<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Jakob Külzer &#187; Tutorial</title>
	<atom:link href="http://www.jakusys.de/blog/tag/tutorial/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.jakusys.de/blog</link>
	<description>Ninja Coding Monkey goes Canada</description>
	<lastBuildDate>Sun, 02 Jan 2011 20:12:51 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.3</generator>
		<item>
		<title>Grails Scaffolding In-Depth</title>
		<link>http://www.jakusys.de/blog/2008/12/grails-scaffolding-in-depth/</link>
		<comments>http://www.jakusys.de/blog/2008/12/grails-scaffolding-in-depth/#comments</comments>
		<pubDate>Thu, 11 Dec 2008 15:12:51 +0000</pubDate>
		<dc:creator>Jakob Külzer</dc:creator>
				<category><![CDATA[Grails]]></category>
		<category><![CDATA[Guide]]></category>
		<category><![CDATA[Scaffolding]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://www.jakusys.de/blog/?p=487</guid>
		<description><![CDATA[Much of Grails power and ability to crank out applications can be accounted to its scaffolding mechanism for creating CRUD interfaces within no time. However, the default scaffolding templates provide only a simple boilerplate and fail to convince for more sophisticated forms. I spent quite some time in the previous weeks writing scaffolding templates. A [...]]]></description>
			<content:encoded><![CDATA[<p>Much of Grails power and ability to crank out applications can be accounted to its scaffolding mechanism for creating <a title="Wikipedia: CRUD" href="http://en.wikipedia.org/wiki/Create,_read,_update_and_delete" target="_blank">CRUD</a> interfaces within no time. However, the default scaffolding templates provide only a simple boilerplate and fail to convince for more sophisticated forms. I spent quite some time in the previous weeks writing scaffolding templates. A lot of this process was trial and error, browsing source code and bothering <a title="Tomás Lin's Blog about Flex &amp; Grails" href="http://fbflex.wordpress.com/" target="_blank">Tomás Lin</a>. I still have to find good documentation on this, so I'm posting my findings here in the hope to help people leveraging Grails even more. If you are just trying to understand how scaffolding works to building something more advanced, this is for you.</p>
<p><span id="more-487"></span></p>
<h2>Scaffolding in a Nutshell</h2>
<p>I assume that you know what Grails and its scaffolding mechanism is about, but I'll just summarize it here.</p>
<p>In a nutshell scaffolding is Grails ability to create controllers and views for domain classes. It analyzes the structure of the domain objects and creates all the files and logic required for simple CRUD functionality. If you have some domain classes all you have to do is type the following from within your project directory:</p>
<pre>$ grails generate-all</pre>
<p>This will create controllers and views for all domain classes found. Note that there are generate-views and generate-controller commands as well.</p>
<p>However you'll soon find out that the default templates which are used to create all the files may not fit your needs. Grails offers a separate <a title="Grails install-template" href="http://grails.org/doc/1.0.x/ref/Command%20Line/install-templates.html" target="_blank">command to copy the default templates</a> into your project directory:</p>
<pre>$ grails install-templates</pre>
<p>This will create a new folder src/templates in your project, holding an copy of the default templates, all yours to modify and adapt.</p>
<h2>Grails Scaffolding Templates</h2>
<p>Before we dive into the details of scaffolding, you need to understand the different templates and what they are for. Running the install-templates command will give you the following files withing your project directory:</p>
<pre>src/templates
|-- artifacts
|   |-- Controller.groovy
|   |-- DomainClass.groovy
|   |-- Script.groovy
|   |-- Service.groovy
|   |-- TagLib.groovy
|   |-- Tests.groovy
|   `-- WebTest.groovy
|-- scaffolding
|   |-- <span style="color: #000000;"><strong>Controller.groovy</strong></span>
|   |-- <strong>create.gsp</strong>
|   |-- <strong>edit.gsp</strong>
|   |-- <strong>list.gsp</strong>
|   |-- <strong>renderEditor.template</strong>
|   `-- <strong>show.gsp</strong>
`-- war
    `-- web.xml</pre>
<p>The files relevant for the scaffolding process are in the scaffolding directory and have been highlighted with <span style="color: #000000;"><strong>bold font</strong></span>. So, what are those files for? Let's examine them one by one.</p>
<p>The first one is <strong>Controller.groovy</strong>. This file is used to create the controllers for your domain classes. The syntax in this file may appear a bit weird in the beginning but after all it's just a <a title="Groovy Templates" href="http://groovy.codehaus.org/Groovy+Templates" target="_blank">groovy template</a> (I really encourage you to read this!). With this in mind reading the templates gets very easy. In the Controller.groovy you basically will find all the actions you would expect from your scaffolded controllers and some groovy template markup.</p>
<p>Next are the GSP files, <strong>create.gsp</strong>, <strong>edit.gsp</strong>, <strong>list.gsp</strong> and <strong>show.gsp</strong>. Those are obviously used to render the GSP markup required for your CRUD views. At a first glance lots of magic happen in those files. We'll cover the details in just a minute.</p>
<p>Finally there is the <strong>renderEditor.template</strong>. This file is used when rendering the HTML forms. Basically what happens in here is a translation of a type like Date or byte[] to their according form elements like a date picker or a file upload button.</p>
<h2>The Scaffolding Process</h2>
<p>Alright, so what happens when you issue generate-all for a domain class? There are a couple of players involved in this game. As most obvious besides the templates we just saw there are the actual scripts,  generate-all, generate-views or generate-controller which reside under $GRAILS_HOME/scripts. These scripts instantiate a DefaultGrailsTemplateGenerator which basically is a wrapper around Groovy's <a title="Groovy Template" href="http://groovy.codehaus.org/api/groovy/text/Template.html" target="_blank">Template</a> and <a title="Groovy TemplateEngine" href="http://groovy.codehaus.org/api/groovy/text/TemplateEngine.html" target="_blank">TemplateEngine</a> and binds together all the pieces we've encountered so far. You won't find any Javadocs about this class, so you'll have to browse the Grails sourcecode if you're interested. The DefaultGrailsTemplateGenerator then calls the actual templates.</p>
<p>One key aspect for creating really powerful scaffolding code is to understand what is handed into the templates by the DefaultGrailsTemplateGenerator. It took me quite some time and some source code browsing to figure this out. First there is a variable called propertyName. There isn't anything magical about it, just the name for a variable. However you will encounter this variable all over the templates. For example if scaffolding is run for a class called "User" propertyName would be "user" (note the lower case "u") and all variables of type "User" would be called "user" in the scaffolded output.</p>
<p>Then there is an instance of <a title="Grails DefaultGrailsDomainClass" href="http://grails.org/doc/1.0.3/api/org/codehaus/groovy/grails/commons/GrailsDomainClass.html" target="_blank">DefaultGrailsDomainClass</a> which is handed into the template as a variable called <strong>domainClass</strong>. This class variable plays a major role in scaffolding as it allows you to access all kinds of information about the domain class the scaffolding process is handling. You can get information about the GORM mappings, the associations the class has and even the other side of the associations, which is crucial when building more complex forms and more. And yes, i really encourage you to read the Javadocs for this class.</p>
<p>Depending on whether views or controllers are generated either the create.gsp, list.gsp, edit.gsp and show.gsp or Controller.groovy are used as template.</p>
<h3>Generating a Controller</h3>
<p>When generating controllers the Controller.groovy file is used as template. What you will end up with is a new file named after your Class containing the usual actions required for CRUD. There is not much magic happening in here; the template is pretty straight forward and just creates calls for the different GORM methods. Read it to get a feeling for this.</p>
<h3>Generating Views</h3>
<p>However when generating views, things get more interesting. In the views and the renderEditor.template the domainClass property is actually used to determine information about collections.</p>
<p>So let's dive into the details of how the views are generated. If you look at the templates you'll see that all of them create a list of properties available for a domain class by querying the domainClass variable:</p>
<pre>props = domainClass.properties.findAll { !excludedProps.contains(it.name) }</pre>
<p>All that remains to do now is to iterate over those properties, determine whether they should be visible and call the renderEditor to actually render the required code. The following block of code has been copied from the edit template and has been commented by me to clarify:</p>
<pre>props.each { p -&gt;
    cp = domainClass.constrainedProperties[p.name]
    display = (cp ? cp.display : true) <strong>// Determine visibility</strong>
    if(display) { %&gt;
    &lt;tr class="prop"&gt;
        &lt;td valign="top" class="name"&gt;
            &lt;label for="${p.name}"&gt;${p.naturalName}:&lt;/label&gt;
        &lt;/td&gt;
        &lt;td valign="top" class="value \${hasErrors(bean:${domainClass.propertyName},field:'${p.name}','errors')}"&gt;
            ${renderEditor(p)}  <strong>// Call render editor to render correct form element</strong>
        &lt;/td&gt;
    &lt;/tr&gt;</pre>
<p>This is basically what happens in all the templates. A list of properties is generated and iterated over. One piece is still missing: the renderEditor.template.</p>
<p>As stated earlier, the renderEditor.template translates the type of a property into the appropriate form control. The way this happens is disappointingly simple; open up the file in your favorite editor and you will find a big block of if-statements like this:</p>
<pre>&lt;%  if(property.type == Boolean.class || property.type == boolean.class)
        out &lt;&lt; renderBooleanEditor(domainClass,property)
    else if(Number.class.isAssignableFrom(property.type) || (property.type.isPrimitive() &amp;&amp; property.type != boolean.class))
        out &lt;&lt; renderNumberEditor(domainClass,property)
    else if(property.type == String.class)
        out &lt;&lt; renderStringEditor(domainClass,property)
    else if(property.type == Date.class || property.type == java.sql.Date.class || property.type == java.sql.Time.class)
        out &lt;&lt; renderDateEditor(domainClass,property)
...</pre>
<p>and further below the methods called by the if-statements:</p>
<pre>...
    private renderByteArrayEditor(domainClass,property) {
        return "&lt;input type=\"file\" id=\"${property.name}\" name=\"${property.name}\" /&gt;"
    }

    private renderManyToOne(domainClass,property) {
        if(property.association) {
            return "&lt;g:select optionKey=\"id\" from=\"\${${property.type.name}.list()}\" name=\"${property.name}.id\" value=\"\${${domainClass.propertyName}?.${property.name}?.id}\" ${renderNoSelection(property)}&gt;&lt;/g:select&gt;"
        }
    }
...</pre>
<p>So in the rendering process for each property the type will be matched in the if statements and the appropriate function is called to render out some HTML/GSP code.</p>
<h2>Conclusion</h2>
<p>Creating scaffolding templates is not hard. It requires some knowledge about the involved technologies and concepts but I hope this post gives you a fair understanding of what is going on. If you still have any questions, feel free to comment or drop me an email.</p>
<p>As always, comments are welcome.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jakusys.de/blog/2008/12/grails-scaffolding-in-depth/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Grails and LiquiBase &#8211; How to use</title>
		<link>http://www.jakusys.de/blog/2008/09/grails-and-liquibase-how-to-use/</link>
		<comments>http://www.jakusys.de/blog/2008/09/grails-and-liquibase-how-to-use/#comments</comments>
		<pubDate>Fri, 19 Sep 2008 03:07:51 +0000</pubDate>
		<dc:creator>Jakob Külzer</dc:creator>
				<category><![CDATA[Cool Tech]]></category>
		<category><![CDATA[Grails]]></category>
		<category><![CDATA[LiquiBase]]></category>
		<category><![CDATA[Database]]></category>
		<category><![CDATA[Guide]]></category>
		<category><![CDATA[Tutorial]]></category>

		<guid isPermaLink="false">http://www.jakusys.de/blog/?p=313</guid>
		<description><![CDATA[In my current project I'm now at a point where the application has come pretty far but is still far from finished. The domain model is not perfect, but very stable at this point -- changes however, are still possible. To get going with the application we are planning to perform tests with some real [...]]]></description>
			<content:encoded><![CDATA[<p>In my current project I'm now at a point where the application has come pretty far but is still far from finished. The domain model is not perfect, but very stable at this point -- changes however, are still possible.</p>
<p>To get going with the application we are planning to perform tests with some real data. The problem at this point is that entering real data into a database that might be wiped due to changes in the domain model is a very tedious task, at least for the person responsible for entering the data. And the reason for running such a test is to find problems with the domain model which lead to the dreaded changes in the domain model. This cat bites her own tail...</p>
<p>As wiping out the database and re-entering the data is not an option at this point, I decided to look into <a title="LiquiBase" href="http://www.liquibase.org/home" target="_blank">LiquiBase</a> which as been sitting on my delicious list for quite a while.</p>
<p>This post is an attempt to write down my experiences and learned lessons with LiquiBase. The <a title="LiquiBase Manual" href="http://www.liquibase.org/manual/home" target="_blank">documentation of LiquiBase</a> is technically complete and extensive but lacks more information about how to use it in a real project. This is an attempt to create a guide on how to leverage LiquiBase in a real world project.</p>
<p><span id="more-313"></span></p>
<h2>What is this LiquiBase anyways?</h2>
<p>For starters LiquiBase is a tool that helps developers to track and apply changes to database schemas. Basically what it does is storing all changes that are made to a database in a special XML file, called a database changelog file. This changelog file can be used to determine if there are any changes between the schema in the changelog file and the schema found in a database. The nice thing about LiquiBase is that it is database neutral so you can use with any database Java is able to connect to, and that are a lot...</p>
<p>But there is more to LiquiBase that just tracking changes. The outstanding feature of LiquiBase is that it is able to migrate data using the information stored in the database changelog file. This doesn't sound like very much when you are starting a project from scratch, but as soon as you start entering data in your evolving application, you'll understand. And as every application evolves, this is a feature handy for every developer, especially for Grails developers as Hibernate as ORM basically supports only two modes of operation to handle the database schema (configured via the <tt class="literal"><a title="Hibernate Configuration" href="http://www.hibernate.org/hib_docs/v3/reference/en-US/html/configuration-optional.html" target="_blank">hibernate.hbm2ddl.auto</a> option</tt>): wiping out the database and applying a new schema (called create or create-drop) or attempting to update the schema (simply called update). The update option looks like a good way to go at first but as it turns out it has its drawbacks, especially if there is data in the database.</p>
<h2>How does it work?</h2>
<p>The hub of all activity in LiquiBase is the changelog file. Basically there are two possible ways to create and maintain the changelogs, the first is to use the generated changelogs as far as possible and the other is to write changelogs by hand. I'm sticking mostly to the first one as the generated changelogs are sufficient most of the time and writing changelogs manually is way to tedious though easy as there is a complete XSD.</p>
<p>Each entry in the changelog file is called a changeset and has a unique id. The id is used to refer to specific datasets. But how does LiquiBase know which changesets have been applied to the database? The answer is simple, it creates a table called DATABASECHANGELOG into which it will insert a row for each applied changeset. So make sure you start using LiquiBase early because you really want to have these tables in your database when changes have been incorporated into a running system.</p>
<p>Applying changesets against the database is called migration but more on this later.</p>
<h2>Setting the Scene</h2>
<p>The work flow to push in changes may depend on your project. The work flow I'm describing can be applied to team of couple of Grails developers and has been tested on a real world project.</p>
<p>As an example for the rest of the post let's assume a project that is developed by a couple of code monkeys. The change the domain classes and to monkey stuff. On the other hand there is a data entry system deployed so real data can be inserted into the database and the software can be demoed. I will refer to this system as the demo system. The demo system and the data entered into it has several purposes. First to see if the domain model is adequate for real data and second to provide the developers with real testing data.</p>
<p>Problems arise quickly in this scenario, for example changes are made to the domain model and the database schema of the demo system must be updated, preferably without wiping out all the data that has been entered. At this point LiquiBase comes in.</p>
<h2>Grails and LiquiBase - Getting Started</h2>
<p>Ok, now how to use LiquiBase in a Grails Project? Easy: there is a <a title="Grails LiquiBase Plugin" href="http://www.liquibase.org/manual/grails" target="_blank">LiquiBase grails plugin</a> for grails which can easily be installed using the following command:</p>
<pre>grails install-plugin liquibase</pre>
<p>This will install a copy of LiquiBase in your application and set up a <a title="Grails LiquiBase Commands" href="http://www.liquibase.org/manual/grails" target="_blank">couple of new commands</a> for the grails command line interface. Before you can do anything useful with LiquiBase you have to create a database changelog file for your current database, preferably using the generate-changelog command:</p>
<pre>grails generate-changelog grails-app/migrations/changelog.xml</pre>
<p>Note: if you omit the filename the changelog will be dumped to the console. You can dump the changelog into any file but grails-app/migrations/changelog.xml is the default and LiquiBase will keep looking for this file. With the changelog file in place you should add it to your version control system.</p>
<h2>Tracking Changes</h2>
<p>So the next step is to make some changes to the domain model which result in a change of the database schema. You now have two possibilities for updating your changelog file. Either manually or using some of the neat tools LiquiBase offers. I won't go into the details for creating the files manually, the LiquiBase manual does a good job at this. So let's talk about the tools.</p>
<p>LiquiBase ships with a very powerful command: diff. What this does is it looks at the current database and at <span style="text-decoration: line-through;">the changelog</span> (<strong>I have to correct myself here, see next section! Sorry about this!</strong>) another database and outputs the difference between them. As LiquiBase changelog XML! So this is awesome because you can make changes to your Grails domain model, run it against a database and pull out the changes. All that is then to do is to add the newly generated changesets to your database changelog file.</p>
<h2>The db-diff Tool</h2>
<p>The db-diff tool in the Grails plugin is kind of mysterious. The LiquiBase documentation for the Grails plugin does not even mention it and I got it wrong in the first run. I had to reading the <a title="DB DIFF " href="http://www.liquibase.org/manual/diff" target="_blank">section about the database diff</a> provided by LiquiBase and dig through the Groovy scripts of the LiquiBase Grails plugin to understand what it does.</p>
<p>The diff utility of LiquiBase compares two databases with each other, which kind of explains its name (doh). When using the LiquiBase command line interface you have to provide two different connection strings for two databases. When using the Grails plugin however, you cannot specify two databases (not yet?); so what happens is that: the database for the current environment ist compared to the database of the test environment. This behaviour is hardcoded into plugins/liquibase-1.8.0.0/scripts/DbDiff.groovy and limits the usefulness of the tool. So what I did is every time a database has been migrated the new schema gets propagated to the testing database. If the domain model changes the schema of the dev database, the changes can easily be determined by diff'ing it against the testing database.</p>
<p>This is not exactly a perfect solution as you manually have to keep the testing database in sync with the changelog. So I am currently playing around with a modification of the Grails LiquiBase plugin which adds a compareToChangelog command which populates a separate database from the current changelog and then compares this to the database of the currently used environment. Using this tool makes updating the changelog really easy as you get the changesets just for those changes you made to the domain model. If there is interest I will publish this to the LiquiBase plugin.</p>
<h2>Migrating a Database</h2>
<p>Finally your changelog has been updated and you now need to update your demo database. The first thing you should do: <strong><span style="color: #ff0000;">Make a backup of your database</span></strong>! Although LiquiBase has matured to some extent, migrating a database full of data is a risky endeavor. So make sure you are on the safe side before touching a database with real data.</p>
<p>The easiest way to migrate the database is to set up a copy of your project and modify the datasource to point at the demo database. The first thing you might want to do is to check which changesets have to be executed by running the following command:</p>
<pre>grails status</pre>
<p>This will generate a list of changesets which have to be applied, assuming there is a DATABASECHANGELOG table in the database. If you are happy with what you see, you can either migrate the database directly or do a dry run. I prefer to do a dry run before touching the database by running:</p>
<pre>grails migrate-sql</pre>
<p>This will output a sequence of SQL statements that LiquiBase will issue to migrate the database. This is quite handy as you can see what will happen. Then, finally the database is migrated by issuing the following command:</p>
<pre>grails migrate</pre>
<p>When everything goes fine your database has just been updated. If something goes wrong, you can either use the rollback commands provided or fall back to the backup of your database.</p>
<h2>Gotchas</h2>
<p>The following points present pitfalls you want to avoid (its enough that I hit them <img src='http://www.jakusys.de/blog/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> . Please note that this is a living section, I keep adding new points I encounter.</p>
<h3>Use LiquiBase early!</h3>
<p>Make sure you start using LiquiBase early. Insert the DATABASECHANGELOG table as soon as possible and ensure that changesets are run against the databases.</p>
<h3>Backups, Backups, Backups...</h3>
<p>Backup your database before migrating! Really, do it!</p>
<h3>Stick to one Database Flavor</h3>
<p>Do not switch database flavors, e.g. from HSQLDB to MySQL. I tried this and I've encountered  a couple of issues with this. For example a changelog created from a HSQLDB may not run on a MySQL and vice versa due to different named datatypes (e.g. MySQL MEDIUMBLOB vs. HSQLDB VARBINARY). Further the changelog generated from a MySQL can cause problems on other databases as it names all primary keys "PRIMARY" per default. This leads to erroneous SQL that cannot be run.</p>
<p>Those problemes are nothing that couldn't be solved with a little bit of search and replace and even might be necessary to create the schema for a production database; but it is definitively nothing you want to do very often.</p>
<h3>How to Start Using LiquiBase in the Middle of a Project</h3>
<p>When you start to use LiquiBase in the middle of a project where there already is a database filled with precious production data, things can easily become complicated. The key to success here is to freeze the project or at least the part which affects the database schema for some time, generate a database changelog file from the current state and propagate this to all database instances. The reason why this is so important is that you need the DATABASECHANGELOG table on those databases; without this table and its entries  LiquiBase does not know which changes to apply. You could use the db-diff tool here, but the far more elegant approach is to simply propagate those changes to all databases once.</p>
<p>As soon as you have the DATABASECHANGELOG on all database instances, updating the schema becomes so easy that you will almost get addicted to it!</p>
<p>So, step by step:</p>
<ul>
<li>freeze your project for half an hour, maybe you can do this in the evening</li>
<li>create a new changelog file from the current schema with the <em>grails generate-changelog</em> command</li>
<li>mark all those changesets as imported with the <em>grails changelog-sync</em> command</li>
<li>push those changes to ALL databases associated with the project. If you fail to do so, migrating the schema of a database without those tables is almost impossible. Depending on the size of your database this requires a massive amount of time.</li>
<li>With the DATABASECHANGELOG table in place, migrating LiquiBase to the next version is as simple as entering grails migrate.</li>
</ul>
<h2>Conclusion</h2>
<p>LiquiBase is a great addition to Grails and you should really really think about using it. Otherwise managing changes to the database can easily become a big problem and im talking out of experience here. Hopefuly this post helps you to get started with LiquiBase. As always if you have any comments please feel to post.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jakusys.de/blog/2008/09/grails-and-liquibase-how-to-use/feed/</wfw:commentRss>
		<slash:comments>22</slash:comments>
		</item>
	</channel>
</rss>

