<?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>JT Dev &#187; grails</title>
	<atom:link href="http://www.jtict.com/blog/tag/grails/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.jtict.com/blog</link>
	<description>About programming stuff</description>
	<lastBuildDate>Sun, 11 Jul 2010 14:23:16 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Shorter Grails textField</title>
		<link>http://www.jtict.com/blog/shorter-grails-textfield/</link>
		<comments>http://www.jtict.com/blog/shorter-grails-textfield/#comments</comments>
		<pubDate>Thu, 24 Jul 2008 15:53:59 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Web programming]]></category>
		<category><![CDATA[grails]]></category>

		<guid isPermaLink="false">http://www.jtict.com/blog/?p=23</guid>
		<description><![CDATA[Making textFields in Grails is a bit verbose, at least if you want error highlighting and returned values on errors. This post shows a quick solution.
Problem
A full textField would be:
&#60;g:textField class=&#34;${hasErrors(bean:user, field:&#039;name&#039;, &#039;errors&#039;)}&#34; value=&#34;${fieldValue(bean:user,field:&#039;name&#039;)}&#34; name=&#34;name&#34;/&#62;
Which clearly is very verbose; you have to specify &#8220;user&#8221; twice, and &#8220;name&#8221; even three times. This verbosity also makes the [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Making textFields in Grails is a bit verbose, at least if you want error highlighting and returned values on errors. This post shows a quick solution.</strong></p>
<h3>Problem</h3>
<p>A full textField would be:</p>
<pre class="brush: xml">&lt;g:textField class=&quot;${hasErrors(bean:user, field:&#039;name&#039;, &#039;errors&#039;)}&quot; value=&quot;${fieldValue(bean:user,field:&#039;name&#039;)}&quot; name=&quot;name&quot;/&gt;</pre>
<p>Which clearly is very verbose; you have to specify &#8220;user&#8221; twice, and &#8220;name&#8221; even three times. This verbosity also makes the view less readable. </p>
<p>Googling for this problem resulted in: <a href="http://docs.codehaus.org/display/GRAILS/Smarter+grails+tags">Smarter Grails Tags</a> (a proposal). Funny that the writer exactly sees the same problem in it, also uses the &#8220;user&#8221; domain model, and also knows Stripes where you could just use something like</p>
<pre class="brush: xml">&lt;stripes:text name=&quot;name&quot;/&gt;</pre>
<p> and specify the bean name in the form. (Stripes has a very good <a href="http://www.stripesframework.org/display/stripes/Quick+Start+Guide">Quick Start Guide</a>, which also shows error highlighting.)</p>
<p>One of the less verbose proposed formats of textField is:</p>
<pre class="brush: xml">&lt;g:textField bean=&quot;user&quot; field=&quot;username&quot; /&gt;</pre>
<h3>Implemented Solution</h3>
<p>I found that implementing a quick version of this is surprisingly easy in Grails, it only takes for a few statements. Here is the code:</p>
<pre class="brush: java">
import org.codehaus.groovy.grails.plugins.web.taglib.FormTagLib

// file: project/grails-app/taglib/MyTagLib.groovy
class MyTagLib {
    // tagname &quot;myTextField&quot; within the &quot;g&quot; namespace
    def myTextField = {attrs -&gt;
        // If a controller returned the bean, and the field has an error,
        // then &quot;errors&quot; will be returned as HTML class, otherwise the class will be empty.
        attrs.class = hasErrors(bean:attrs.bean, field:attrs.field, &#039;errors&#039;)
        // Retrieves the field value of the given bean to be rendered in the view.
        // Note: specify the bean and not the bean name. So &quot;${user}&quot; instead of &quot;user&quot;
        attrs.value = fieldValue(bean:attrs.bean, field:attrs.field)
        // Required for textField taglib. attrs.name is a keyname of the params map
        attrs.name = attrs.field
        // renders the HTML tag
        out &lt;&lt; new FormTagLib().textField(attrs)
    }
}
</pre>
<h3>Usage</h3>
<pre class="brush: xml">&lt;g:myTextField bean=&quot;$user&quot; field=&quot;name&quot; /&gt;</pre>
<p>And ofcourse some CSS to highlight the error in a color. This can be put in the HTML head (or better, a seperate CSS file) :</p>
<pre class="brush: xml">
&lt;style type=&quot;text/css&quot;&gt;
   .errors {
      background-color: red;
   }
&lt;/style&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.jtict.com/blog/shorter-grails-textfield/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Grails and existing Java Hibernate DAO&#8217;s</title>
		<link>http://www.jtict.com/blog/grails-existing-hibernate-dao/</link>
		<comments>http://www.jtict.com/blog/grails-existing-hibernate-dao/#comments</comments>
		<pubDate>Sun, 20 Jul 2008 16:02:57 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Web programming]]></category>
		<category><![CDATA[grails]]></category>
		<category><![CDATA[hibernate]]></category>

		<guid isPermaLink="false">http://www.jtict.com/blog/?p=22</guid>
		<description><![CDATA[If you have some existing Java Hibernate entity classes (outside Grails), you only have to add one line in Datasource config, and you can use them immediately. However, if you have some exising POJO (Plain Old Java Object) Hibernate DAO&#8217;s (classes that implement a Data Access Object pattern), you&#8217;ll have to do some additional steps [...]]]></description>
			<content:encoded><![CDATA[<p><strong>If you have some existing Java Hibernate entity classes (outside Grails), you only have to add one line in Datasource config, and you can use them immediately. However, if you have some exising POJO (Plain Old Java Object) Hibernate DAO&#8217;s (classes that implement a Data Access Object pattern), you&#8217;ll have to do some additional steps to make it a bit suitable.</strong></p>
<p>(The solution described in this post can also be handy when you need data access on places where GORM is NOT available. GORM not available? Yes, GORM is not fully available when you access collections via a taglib that is accessed via a Sitemesh layout. (A scenerio that isn&#8217;t rare.) (Should be considered as a bug?) In that case you will get a <em>lazily initialize a collection</em> error. If you use HibernateUtil, you can get around this by just opening new session yourself.)</p>
<h3>Existing Hibernate entities and GORM</h3>
<p>You can use existing Hibernate Java entities directly in Grails. The only thing that you&#8217;ll have to configure is:</p>
<ol>
<li>define mappings in hibernate.cfg.xml</li>
<li>set GrailsAnnotationConfiguration as configClass in DataSource.groovy</li>
</ol>
<p>For example:<br />
webapp/grails-app/conf/hibernate/hibernate.cfg.xml :</p>
<pre class="brush: xml">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;!DOCTYPE hibernate-configuration PUBLIC
		&quot;-//Hibernate/Hibernate Configuration DTD 3.0//EN&quot;
		&quot;http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd&quot;&gt;
&lt;hibernate-configuration&gt;
    &lt;session-factory&gt;
        &lt;mapping class=&quot;myPackage.Product&quot;/&gt;
        &lt;mapping class=&quot;myPackage.Customer&quot;/&gt;
        &lt;mapping class=&quot;myPackage.Supplier&quot;/&gt;
    &lt;/session-factory&gt;
&lt;/hibernate-configuration&gt;
</pre>
<p>webapp/grails-app/conf/DataSource.groovy :</p>
<pre class="brush: java">
import org.codehaus.groovy.grails.orm.hibernate.cfg.GrailsAnnotationConfiguration

dataSource {
    configClass = GrailsAnnotationConfiguration.class
    pooled = true
    driverClassName = &quot;com.mysql.jdbc.Driver&quot;
    url = &quot;jdbc:mysql://localhost/mydb&quot;
    username = &quot;myusername&quot;
    password = &quot;mypass&quot;
    dbCreate = &quot;create&quot; // one of &#039;create&#039;, &#039;create-drop&#039;,&#039;update&#039;
    dialect= org.hibernate.dialect.MySQLInnoDBDialect
}
hibernate {
    cache.use_second_level_cache=true
    cache.use_query_cache=true
    cache.provider_class=&#039;com.opensymphony.oscache.hibernate.OSCacheProvider&#039;
}
</pre>
<p>Now you can put your existing Hibernate java entities in <em>webapp/src/entities</em> (or any other package), and they will work immediately and have GORM functionality.<br />
For example, in the Grails controller classes, you can direcly use Product.get(100) (to get a Product instance that has id 100). Hibernate sessions and transactions are created/invoked automatically.</p>
<h3>Exising Hibernate DAO&#8217;s</h3>
<p>If you don&#8217;t need any GORM functionality and you don&#8217;t want Grails to touch sessions, then you can use your existing unaltered full hibernate.cfg.xml.</p>
<p>However, if you have some POJO DAO&#8217;s that use the HibernateUtil helperclass, you will have to do some additional steps to make it a bit suitable. (In this example, I use the configurations above.)</p>
<p><strong>By default Grails injects a SessionFactory</strong><br />
First, your DAO&#8217;s will need a HibernateSession to perform work. By default Grails injects a SessionFactory into Grails controllers that have a &#8220;sessionFactory&#8221; variable defined. So the following controller will automatically have a SessionFactory available:</p>
<pre class="brush: java">
import org.hibernate.*;

class ProductController {
    // This one will be injected
    SessionFactory sessionFactory

    def index = {
        Session session = sessionFactory.getCurrentSession()
        println session.createQuery(&quot;from Product&quot;).list()
    }
}
</pre>
<p>(You can also use Gorm in this controller example and don&#8217;t use the SessionFactory yourself, but this just to show that a SessionFactory will be injected.)</p>
<p><strong>HibernateUtil used by the DAO&#8217;s</strong><br />
In the example, the DAO&#8217;s use HibernateUtil to get a SessionFactory. By default HibernateUtil create a SessionFactory itself, but the SessionFactory provided by Grails is needed instead, so we alter HibernateUtil slightly:</p>
<pre class="brush: java">
package persistence;

import org.hibernate.*;

public class HibernateUtil {
    private static SessionFactory sessionFactory;

    public static SessionFactory getSessionFactory() { return sessionFactory; }
    public static void setSessionFactory(SessionFactory sf) { sessionFactory = sf; }

    public static void shutdown() { sessionFactory.close(); }
}
</pre>
<p><strong>Set SessionFactory for HibernateUtil</strong><br />
We want HibernatUtil to be ready with a SessionFactory after booting, so we configure HibernateUtil during the bootstap. We alter webapp/grails-app/conf/BootStrap.groovy to:</p>
<pre class="brush: java">
import persistence.HibernateUtil
import org.springframework.web.context.support.WebApplicationContextUtils

class BootStrap {

     def init = { servletContext -&gt;
        def ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext)
        def sf  = ctx.getBean(&#039;sessionFactory&#039;)
        HibernateUtil.setSessionFactory(sf)
     }

     def destroy = {
         HibernateUtil.shutdown()
     }
}
</pre>
<p>Now the DAO&#8217;s can use HibernateUtil.getSessionFactory().getCurrentSession() to get a HibernateSession.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.jtict.com/blog/grails-existing-hibernate-dao/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Grails &amp; Jetty with multiple contexts</title>
		<link>http://www.jtict.com/blog/grails-jetty-multiple-contexts/</link>
		<comments>http://www.jtict.com/blog/grails-jetty-multiple-contexts/#comments</comments>
		<pubDate>Sat, 12 Jul 2008 18:39:33 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[grails]]></category>

		<guid isPermaLink="false">http://www.jtict.com/blog/?p=12</guid>
		<description><![CDATA[A webapp usually contains both dynamic resources (scripts, config files, html files) and static resources (jpg, zip files, data etc). These resources can be deployed all together as one package, but when you have a lot of static resources, you usually want them to be seperate from the dynamic resources. Reasons might be that you [...]]]></description>
			<content:encoded><![CDATA[<p><strong>A webapp usually contains both dynamic resources (scripts, config files, html files) and static resources (jpg, zip files, data etc). These resources can be deployed all together as one package, but when you have a lot of static resources, you usually want them to be seperate from the dynamic resources. Reasons might be that you have that much static resources that it will slow down deployment or testing when packaged as a single unit, or you might want static resources to be served by a seperate service to improve performance, or you might want them to be in seperate filesytem hierarchy because the static resources might also be needed outside the webapp. In this post I describe two methods to solve the problem of seperating dynamic from static resources when using Grails and Jetty.</strong></p>
<p>The methods are tested using:</p>
<ul>
<li>Grails 1.0.3</li>
<li>Jetty 6.1.4 (default Jetty for Grails 1.0.3)</li>
<li>Static Resources 0.5 plugin</li>
</ul>
<h3>Method 1: Static Resources plugin &amp; symbolic links</h3>
<p>The Grails <a href="http://grails.org/Static+Resources+Plugin">Static-Resources</a> plugin is designed to separate dynamic from static resources.</p>
<p>Install:</p>
<ol>
<li>open a cmd/shell prompt and go into the directory of your Grails webapp project. I will call this directory &lt;myapp-grails-project-base&gt;.</li>
<li>type: grails install-plugin static-resources<br />
The plugin will now be installed for the current webapp only.</li>
</ol>
<p>I&#8217;ll show by example how the Static-Resources plugin works. Suppose you have a website called example.com and a webapp called myapp, then the webapp is available at <em>http://example.com:8080/myapp/</em>. When you have the plugin installed, everything under the <em>/static/</em> (filesystem directory) will be available under <em>http://example.com:8088/</em> when run in dev environment. Notice that port 8088 is used instead of port 8080. The plugin does this by starting a <a href="http://elonen.iki.fi/code/nanohttpd/">NanoHTTPD</a>, which is a lightweight single class Java HTTP server. The plugin calls this the <em>resource server</em>.<br />
When you go to <em>http://example.com:8088/</em>, you will get a directory listing of all the files located in the <em>static</em> directory, so you can start using them and linking to them, but there is a better way (read on).</p>
<p>If you put a pdf file at <em>&lt;myapp-grails-project-base&gt;/static/archive/catalog2005.pdf</em> (filesystem) then it will be available automatically and directly at <em>http://example.com:8088/archive/catalog2005.pdf</em> in a dev env.<br />
You can hardcode links to <em>http://example.com:8080/archive/catalog2005.pdf</em> manually in the view, but you can also use the plugins dedicated <em>resourceLinkTo</em> tag for this. For the pdf link, this tag is used as: <em>&lt;g:resourceLinkTo dir=&#8221;archive&#8221; file=&#8221;catalog2005.pdf&#8221;/&gt;</em></p>
<p>When running in prod env instead of dev, the resourceLinkTo tag will link to the URI <em>/resources/archive/catalog2005.pdf</em> instead of <em>http://example.com:8080/archive/catalog2005.pdf</em>. And this time it won&#8217;t start a NanoHTTPD server, it only changes the link. So in a prod env, you have to map <em>/resources/</em> to <em>&lt;myapp-grails-project-base&gt;/static/</em> yourself, in whatever production HTTP server you are using. You could do this in Tomcat 6 by putting something like <em>&lt;Context docBase=&#8221; &lt;myapp-grails-project-base&gt;/static/&#8221; path=&#8221;/resources&#8221;/&gt;</em> in the host element of server.xml, or better, in context.xml.</p>
<p>If you don&#8217;t want your resources to be located in the &lt;myapp-grails-project-base&gt;/static/ directory, you can use symbolic links in the static directory, and map them to elsewhere. Note that symbolic links are not only available on POSIX systems (Linux etc), but <a href="http://en.wikipedia.org/wiki/Symbolic_link">also on Windows systems</a> using special tools. (I&#8217;m not talking about Windows Shortcuts, but Windows symbolic links, hard links or junctions.)</p>
<p>Another way is to change the <em>static</em> directory location by modifying <em>&lt;myapp-grails-project-base&gt;\plugins\static-resources-0.5\grails-app\services\ExternalResourceServerService.groovy</em>.</p>
<h3>Method 2: a second Jetty webapp context</h3>
<p>The static resources method (described above) doesn&#8217;t have a complete built-in solution for a production environment; you have to make/map the <em>/resources/</em> URI yourself.</p>
<p>If want you to use Jetty in both dev and prod env, or if you want to have a separate static resources directory without using the Static-Resources plugin, then read on:</p>
<p>1) Open %GRAILS_HOME%\scripts\RunApp.groovy<br />
2) change</p>
<pre class="brush: java">
    target( configureHttpServer : &amp;quot;Returns a jetty server configured with an HTTP connector&amp;quot;) {
    def server = new Server()
    grailsServer = server
    def connectors = [new SelectChannelConnector()]
    connectors[0].setPort(serverPort)
    server.setConnectors( (Connector [])connectors )
    setupWebContext()
    server.setHandler( webContext )
    event(&amp;quot;ConfigureJetty&amp;quot;, [server])
    return server
}
</pre>
<p>to</p>
<pre class="brush: java">
    target( configureHttpServer : &amp;quot;Returns a jetty server configured with an HTTP connector&amp;quot;) {
    def server = new Server()
    grailsServer = server
    def connectors = [new SelectChannelConnector()]
    connectors[0].setPort(serverPort)
    server.setConnectors( (Connector [])connectors )
    setupWebContext()

    server.addHandler( webContext )
    WebAppContext resourceContext = new WebAppContext(&amp;quot;D:/myapp-grails-project-base/static&amp;quot;, &amp;quot;/resources&amp;quot;)
    server.addHandler(resourceContext);

    event(&amp;quot;ConfigureJetty&amp;quot;, [server])
    return server
}
</pre>
<p>Now, everything under <em>D:/myapp-grails-project-base/static</em> will be mapped to <em>http://&#8230;../resources</em>, in both dev and prod evironment, and will be served seperate from the webapp.</p>
<p>A drawback of placing this in RunApp.groovy is that every Grails app will have a <em>/resources</em> context running next to it.</p>
<p>Note that Jetty 5 and earlier versions of Grails probably needs different code.</p>
<p>Edit:<br />
Grails maintains a temperary directory for scripts in %userhome%\.grails\1.0.3\scriptCache. I you find that modifications aren&#8217;t visible, then try deleting that directory. </p>
<p>More info:</p>
<ul>
<li><a href="http://www.mortbay.org/jetty-6/apidocs/org/mortbay/jetty/webapp/WebAppContext.html">http://www.mortbay.org/jetty-6/apidocs/org/mortbay/jetty/webapp/WebAppContext.html</a></li>
<li><a href="http://jetty.mortbay.org/jetty5/tut/Server.html">http://jetty.mortbay.org/jetty5/tut/Server.html</a></li>
<li><a href="http://docs.codehaus.org/display/JETTY/Embedding+Jetty">http://docs.codehaus.org/display/JETTY/Embedding+Jetty</a></li>
<li><a href="http://www.mortbay.org/jetty-6/apidocs/org/mortbay/jetty/Server.html">http://www.mortbay.org/jetty-6/apidocs/org/mortbay/jetty/Server.html</a></li>
<li><a href="http://www.nabble.com/Jetty-and-virtual-host-td7505119.html#a7505119">http://www.nabble.com/Jetty-and-virtual-host-td7505119.html#a7505119</a></li>
<li><a href="http://grails.org/Static+Resources+Plugin">http://grails.org/Static+Resources+Plugin</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.jtict.com/blog/grails-jetty-multiple-contexts/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
