<?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>The Kaptain on ... stuff &#187; Hibernate</title>
	<atom:link href="http://www.kellyrob99.com/blog/tag/hibernate/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.kellyrob99.com/blog</link>
	<description>Tales of development, life and the folly that goes along with both</description>
	<lastBuildDate>Sun, 04 Dec 2011 21:51:34 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=</generator>
		<item>
		<title>Groovy and Hibernate Validator for Dynamic Constraints</title>
		<link>http://www.kellyrob99.com/blog/2010/04/17/groovy-and-hibernate-validator-for-dynamic-constraints/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=groovy-and-hibernate-validator-for-dynamic-constraints</link>
		<comments>http://www.kellyrob99.com/blog/2010/04/17/groovy-and-hibernate-validator-for-dynamic-constraints/#comments</comments>
		<pubDate>Sun, 18 Apr 2010 06:17:50 +0000</pubDate>
		<dc:creator>TheKaptain</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Grails]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[JBoss Seam]]></category>
		<category><![CDATA[kellyrob99.com]]></category>
		<category><![CDATA[Languages]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Source code]]></category>
		<category><![CDATA[theKaptain]]></category>
		<category><![CDATA[User interface]]></category>
		<category><![CDATA[validator]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">http://www.kellyrob99.com/blog/?p=1263</guid>
		<description><![CDATA[I was reading this article about hibernate validator today and it inspired me to apply a little Groovy to the problem of validating a bean. More specifically, finding out how hard it would be to apply different validation rules to the same classes at runtime. Turns out it&#8217;s really pretty simple. Hibernate validator, if you [...]
Related posts:<ol>
<li><a href='http://www.kellyrob99.com/blog/2010/07/01/groovy-and-csv-how-to-get-your-data-out/' rel='bookmark' title='Groovy and CSV: How to Get Your Data Out?'>Groovy and CSV: How to Get Your Data Out?</a></li>
<li><a href='http://www.kellyrob99.com/blog/2009/12/16/jira-grails-plugin/' rel='bookmark' title='Jira Grails Plugin'>Jira Grails Plugin</a></li>
<li><a href='http://www.kellyrob99.com/blog/2010/03/14/breaking-weak-captcha-in-slightly-more-than-26-lines-of-groovy-code/' rel='bookmark' title='Breaking Weak CAPTCHA in&#8230; slightly more than 26 Lines of Groovy Code'>Breaking Weak CAPTCHA in&#8230; slightly more than 26 Lines of Groovy Code</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>I was reading <a href="http://java.dzone.com/articles/using-hibernate-validator">this article about hibernate validator</a> today and it inspired me to apply a little <a class="zem_slink" href="http://groovy.codehaus.org" title="Groovy (programming language)" rel="homepage">Groovy</a> to the problem of validating a bean.  More specifically, finding out how hard it would be to apply different validation rules to the same classes at runtime. Turns out it&#8217;s really pretty simple.<br />
<a href="http://www.hibernate.org/subprojects/validator/download.html">Hibernate validator</a>, if you didn&#8217;t already know, is the reference implementation of <a href="http://jcp.org/en/jsr/detail?id=303">JSR-303</a> and it provides the ability to specify by xml or annotation configuration validation rules for pojos.</p>
<p></p>
<h2>Where Hibernate Validator Shines</h2>
<p>Annotations on domain classes allow for easily validating object state at the time of persistence. Excellent integration with frameworks like <a class="zem_slink" href="http://www.seamframework.org" title="JBoss Seam" rel="homepage">JBoss Seam</a> allow this same ability to be utilized for validating web forms on the client-side with little more than an <a href="http://docs.jboss.org/seam/1.2.1.GA/reference/en/html/validation.html">&lt;s:validateAll/&gt; tag</a>. Seam practically hides the entire interaction with validation components from the developer. Since validation rules are defined directly in the domain class, you can (almost) guarantee that no objects with inconsistent state will ever end up being saved in your database.  There are certain validations that aren&#8217;t possible to verify without actually looking in the database, unique constraints for example, but generally in my experience hibernate validator is extremely easy to configure and work with. Implementing <a class="zem_slink" href="http://en.wikipedia.org/wiki/Create%2C_read%2C_update_and_delete" title="Create, read, update and delete" rel="wikipedia">CRUD</a> functionality is pretty trivial, and UIs can achieve consistency since all validations are applied equally.<br />
Alternatively, if you can&#8217;t or don&#8217;t want to use annotations for some reason, you can specify your validation rules in an xml file. Usually a singleton validation.xml file is made available on the classpath and picked up automagically when a ValidationFactory is created. A simple xml configuration looks like this:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;constraint-mappings xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemalocation=&quot;http://jboss.org/xml/ns/javax/validation/mapping validation-mapping-1.0.xsd&quot; xmlns=&quot;http://jboss.org/xml/ns/javax/validation/mapping&quot;&gt;
    &lt;default-package&gt;org.kar.test&lt;/default-package&gt;
    &lt;bean class=&quot;ValidateTestableClass&quot;&gt;
        &lt;field name=&quot;name&quot;&gt;
            &lt;constraint annotation=&quot;javax.validation.constraints.NotNull&quot;&gt;
        &lt;/constraint&gt;
    &lt;/field&gt;
&lt;/bean&gt;
</pre>
<p>and is meant to be applied to this simple class:</p>
<pre class="brush: groovy; title: ; notranslate">
class ValidateTestableClass
{
    int id
    String name
    String description
    boolean enabled
}
</pre>
<p></p>
<h2>Comparing with <a class="zem_slink" href="http://grails.org" title="Grails (framework)" rel="homepage">Grails</a> Validation</h2>
<p>Grails automatically provides <a href="http://www.grails.org/doc/latest/guide/7.%20Validation.html">validation capabilities</a> for domain classes and command objects, and enables adding the same behavior to any pogo through a combination of the @Validateable annotation and a static constraints closure. Adding validation support to arbitrary classes also requires specifying which packages to scan for the annotation.<br />
Plugin support from projects like <a href="http://www.grails.org/plugin/bean-fields">bean-fields</a> simplifies the handling of client-side validation and rendering error markers in the UI, an ability which the Grails framework provides natively by adding an &#8216;errors&#8217; field directly onto the domain or command object class instances bound to a web form.</p>
<p></p>
<h2>Dynamic Constraints</h2>
<p>Both the hibernate validator and the Grails strategies for applying validation described here have the same limitation: both are universally applied to all instances of a class. There&#8217;s no easy apparent way to override those constraints at runtime, although I suspect that some fancy MOP&#8217;ing or configuration could probably be used to accomplish overrides at runtime.<br />
Hibernate validator also supports creation of ad hoc validators by seeding with one or more xml documents. Or if you&#8217;re like me and hate hand editing xml, you can leverage Groovy to take a bit of the pain away. Here&#8217;s the same xml snippet from above in a Groovy Closure, generated simply by turning the DomToGroovy class loose on the raw xml:</p>
<pre class="brush: groovy; title: ; notranslate">
looseConstraint = {
        mkp.declareNamespace(xsi: 'http://www.w3.org/2001/XMLSchema-instance')
        'constraint-mappings'(xmlns: 'http://jboss.org/xml/ns/javax/validation/mapping',
                'xsi:schemaLocation': 'http://jboss.org/xml/ns/javax/validation/mapping validation-mapping-1.0.xsd') {
            'default-package'('org.kar.test.objects')
            bean('class': 'ValidateTestableClass') {
                field(name: 'name') {
                    constraint(annotation: 'javax.validation.constraints.NotNull')
                }
            }
        }
    }
</pre>
<p>Losing all the angle brackets is a good start, but we really haven&#8217;t saved a lot of typing. Until you start taking advantage of the ability to define more complicated structures. Note the use of a list structure here to apply NotNull constraints to multiple fields.</p>
<pre class="brush: groovy; title: ; notranslate">
strictConstraint = {
        mkp.declareNamespace(xsi: 'http://www.w3.org/2001/XMLSchema-instance')
        'constraint-mappings'(xmlns: 'http://jboss.org/xml/ns/javax/validation/mapping',
                'xsi:schemaLocation': 'http://jboss.org/xml/ns/javax/validation/mapping validation-mapping-1.0.xsd') {
            'default-package'('org.kar.test.objects')
            bean('class': 'ValidateTestableClass') {
                ['name', 'description'].each {
                    field(name: it) {
                        constraint(annotation: 'javax.validation.constraints.NotNull')
                    }
                }
                field(name: 'id') {
                    constraint(annotation: 'javax.validation.constraints.DecimalMin') {
                        element(name: 'value', '2')
                    }
                }
                field(name: 'enabled') {
                    constraint(annotation: 'javax.validation.constraints.AssertTrue')
                }
            }
        }
    }
</pre>
<p></p>
<h2>Applying Dynamic Constraints</h2>
<p>Applying constraints is as simple as converting Closures to xml and mapping them to a Configuration object, which then supplies a Validator to use. StreamingMarkupBuilder is utilized to create the xml behind the scenes.</p>
<pre class="brush: groovy; title: ; notranslate">
    /**
     * Create a configuration object passing closures as validation mapping documents.
     * @param closures closures to render into validation mapping documents
     * @return config
     */
    public Configuration createConfig(Closure... closures)
    {
        Configuration config = Validation.byDefaultProvider().configure()
        closures.each {
            config.addMapping(new ByteArrayInputStream(GroovyXmlConversionUtil.convertToXml(it).bytes))
        }
        config
    }
</pre>
<p>I haven&#8217;t tested the use of multiple mappings extensively, but minimally each class you&#8217;re configuring must be confined to a single mapping &#8211; you can&#8217;t extend the validations by layering configurations on top of one another. You should however be able to map constraints for different classes in separate Closures.</p>
<p></p>
<h2>Crying out for a Builder!</h2>
<p>Going from Closures to xml is a quick and dirty way to test out this functionality, but what would really be nice is a Builder that could create an appropriate validation environment more directly. At the least it would allow for removing the namespace declarations and explicit package naming that make up the bulk of the content.</p>
<h2>So what do you get?</h2>
<ol>
<li>1. Ability to declare validations against any existing <a class="zem_slink" href="http://java.sun.com" title="Java (programming language)" rel="homepage">Java</a> or Groovy class without changing the source code</li>
<li>2. Programmatic ability to create the configuration of validations</li>
<li>3. A choice of which validations to apply at runtime</li>
<li>4. Consistency with the behavior of domain class validation</li>
</ol>
<p>And what&#8217;d I get? A fun bit of quick coding on a Saturday afternoon. Nice! Source code is <a href="http://github.com/kellyrob99/groovy-hibernate-validator">available on git-hub</a> if you want to check it out.</p>
<div class="zemanta-pixie"><a class="zemanta-pixie-a" title="Reblog this post [with Zemanta]" href="http://reblog.zemanta.com/zemified/c83e9a1b-1079-49a8-80cb-95c76b967f69/"><img class="zemanta-pixie-img" src="http://img.zemanta.com/reblog_c.png?x-id=c83e9a1b-1079-49a8-80cb-95c76b967f69" alt="Reblog this post [with Zemanta]" /></a><span class="zem-script more-related pretty-attribution"><script src="http://static.zemanta.com/readside/loader.js" type="text/javascript"></script></span></div>
<!-- AdSense Now! V1.95 -->
<!-- Post[count: 2] -->
<div class="adsense adsense-leadout" style="float:right;margin: 12px;"><script type="text/javascript"><!--
google_ad_client = "pub-6955914197200080";
/* 728x90, created 8/3/09 */
google_ad_slot = "4051815125";
google_ad_width = 728;
google_ad_height = 90;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p>Related posts:<ol>
<li><a href='http://www.kellyrob99.com/blog/2010/07/01/groovy-and-csv-how-to-get-your-data-out/' rel='bookmark' title='Groovy and CSV: How to Get Your Data Out?'>Groovy and CSV: How to Get Your Data Out?</a></li>
<li><a href='http://www.kellyrob99.com/blog/2009/12/16/jira-grails-plugin/' rel='bookmark' title='Jira Grails Plugin'>Jira Grails Plugin</a></li>
<li><a href='http://www.kellyrob99.com/blog/2010/03/14/breaking-weak-captcha-in-slightly-more-than-26-lines-of-groovy-code/' rel='bookmark' title='Breaking Weak CAPTCHA in&#8230; slightly more than 26 Lines of Groovy Code'>Breaking Weak CAPTCHA in&#8230; slightly more than 26 Lines of Groovy Code</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.kellyrob99.com/blog/2010/04/17/groovy-and-hibernate-validator-for-dynamic-constraints/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Groovy and Bash &#8211; can scripting get much easier?</title>
		<link>http://www.kellyrob99.com/blog/2009/04/14/groovy-and-bash-can-scripting-get-much-easier/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=groovy-and-bash-can-scripting-get-much-easier</link>
		<comments>http://www.kellyrob99.com/blog/2009/04/14/groovy-and-bash-can-scripting-get-much-easier/#comments</comments>
		<pubDate>Wed, 15 Apr 2009 03:25:02 +0000</pubDate>
		<dc:creator>TheKaptain</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Apache Camel]]></category>
		<category><![CDATA[Bash]]></category>
		<category><![CDATA[dependency management]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Hibernate]]></category>
		<category><![CDATA[Ivy]]></category>
		<category><![CDATA[Java]]></category>
		<category><![CDATA[maven]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Scripting language]]></category>

		<guid isPermaLink="false">http://www.kellyrob99.com/blog/?p=292</guid>
		<description><![CDATA[The ability to execute pretty much any bash statement embedded in a Groovy script is great, don&#8217;t get me wrong, but with the advent of Grape &#8211; and provided that you&#8217;re an Ivy/Maven user &#8211; adding the abilities of just about any Java library to your scripting language is easy. So what does Groovy add [...]
Related posts:<ol>
<li><a href='http://www.kellyrob99.com/blog/2009/04/03/griffon-bash-completion/' rel='bookmark' title='Griffon bash completion&#8230;'>Griffon bash completion&#8230;</a></li>
<li><a href='http://www.kellyrob99.com/blog/2009/08/09/using-the-testng-dataprovider-with-groovy/' rel='bookmark' title='Using the TestNG DataProvider with Groovy'>Using the TestNG DataProvider with Groovy</a></li>
<li><a href='http://www.kellyrob99.com/blog/2010/04/17/groovy-and-hibernate-validator-for-dynamic-constraints/' rel='bookmark' title='Groovy and Hibernate Validator for Dynamic Constraints'>Groovy and Hibernate Validator for Dynamic Constraints</a></li>
</ol>]]></description>
			<content:encoded><![CDATA[<p>The ability to execute pretty much any bash statement embedded in a Groovy script is great, don&#8217;t get me wrong, but with the advent of <a href="http://groovy.codehaus.org/Grape">Grape</a> &#8211; and provided that you&#8217;re an <a href="http://ant.apache.org/ivy/">Ivy</a>/Maven user &#8211; adding the abilities of just about any Java library to your scripting language is easy.</p>
<p>So what does <a href="http://groovy.codehaus.org">Groovy</a> add to the mix to make it an attractive option on top of(or instead of) bash on its own? Dependency management, lean distribution and testability all jump to mind.</p>
<h3 style="text-align: center;">Dependency Management</h3>
<p>Grape gives you the same stability that Maven provides. Any script can load any Java library is wants to utilize into the classpath at runtime using your existing repository or an available internet connection.</p>
<h3 style="text-align: center;">Lean Distribution</h3>
<p>Because Grape utilizes a central repository, all dependencies are shared across the entire system. Scripts with extremely small footprints can do some pretty big things. Recently I&#8217;ve seen examples of <a href="http://www.infoq.com/articles/groovy-1-6">parsing html using TagSoup</a>(I swear I originally saw that example somewhere else but for the life of me can&#8217;t find it now), <a href="http://mrhaki.blogspot.com/2009/04/poll-for-e-mail-with-groovy-and-apache.html">Apache Camel integration</a>(<a href="http://java.dzone.com/news/groovy-example-activemq-broker?mz=7893-progress">and again</a>) and even spawning a local HSQL database, <a href="http://groovy.codehaus.org/Using+Hibernate+with+Groovy">complete with Hibernate</a>. Within a very sparse number of lines, you can do more than you could ever imagine with plain Java, and I&#8217;m more than willing to admit that I wouldn&#8217;t know where to start with bash to do any of the stuff I just mentioned.</p>
<h3 style="text-align: center;">Testability</h3>
<p>The only thing that separates a stand-alone Groovy script from a Groovy class on the command line is the #!. If you&#8217;re willing to launch the script on the command line explicitly using the &#8216;groovy&#8217; executable you can abandon that. So now the difference becomes &#8216;./groovyScript&#8217; versus &#8216;groovy groovyScript&#8217;. But&#8230;. that same script is now ripe and ready to be included in the test framework you use everyday for regular project development. You can easily compose it into unit-testable methods and treat it like any other part of a large and rapidly evolving software project &#8211; things that I&#8217;ve always found inherently difficult with a command line script. Mostly I find that the truly useful scripts and snippets &#8211; the ones that are used regularly by developers on a day to day basis &#8211; are the ones that also never end up under source control, and don&#8217;t get the benefit of evolutionary change that most code gets.</p>
<p>Building upon the example included in the <a href="http://www.infoq.com/articles/groovy-1-6">InfoQ Groovy 1.6 launch notice</a>, here&#8217;s the quick and dirty addition of a JXTable component for showing the results of parsing all links from an html page with TagSoup. A text field is used to bind the url and a click of the button starts it off.  It&#8217;s not pretty, but it did take less than 10 minutes to do so judge for yourself. Run this script from the command line using the groovy command (V1.6+).</p>
<pre class="brush: groovy; smart-tabs: true; title: ; notranslate">
import org.jdesktop.swingx.JXTable
import javax.swing.*

@Grab(group='org.swinglabs', module='swingx', version='0.9.3')
@Grab(group='org.ccil.cowan.tagsoup', module='tagsoup', version='0.9.7')
def getHtml(url) {
       def parser = new XmlParser(new org.ccil.cowan.tagsoup.Parser())
       parser.parse(url)
}
def data = [ ]

def my = groovy.swing.SwingBuilder.build {
       frame = frame(title:'Groovy Grab Test', size:[800,500], show:true, pack:true, defaultCloseOperation: WindowConstants.DISPOSE_ON_CLOSE) {
       actions(){
             action(name:'Fetch', id:'fetchAction')
             {
                   data.clear
                   getHtml(urlField.text).body.'**'.a.@href.each{ data &lt;&lt; [url:it] }
                   frame.repaint()
             }
       }
       boxLayout(axis: BoxLayout.Y_AXIS)
       scrollPane() {
             myTable = table(new JXTable(columnControlVisible:true)){
                   tableModel(list:data){
                   propertyColumn(header: 'URL', propertyName: 'url')
             }
       }
 }
       textField(id:'urlField')
       button(fetchAction)
 }
}
</pre>
<p>Since I work for an organization that uses maven extensively for dependency management, most of the libraries that come to mind as handy bash replacements are already available in my local repository. Apache commons, Google collections, and most importantly &#8211; any libraries that are specifically dealing with your own products &#8211; all are at your fingertips! Even better, since most of the tasks that commonly fall to scripting are pretty low level (moving files around, etc), there are easy alternatives.</p>
<p>AntBuilder, for instance, is baked into Groovy, and provides a great abstraction around most of the desired functionality you want in a scripting environment. Moving files, doing text replacement,tarring files, sending mail &#8211; anything that Apache Ant can do, AntBuilder can do. But without all of that infuriating and frustating xml. An example(complete with exception handling!) courtesy of <a href="http://thediscoblog.com/">Andrew Glover</a>, <a href="http://www.ibm.com/developerworks/library/j-pg12144.html">in this article</a>.</p>
<pre class="brush: groovy; title: ; notranslate">
ant = new AntBuilder()
ant.mkdir(dir:&quot;/dev/projects/ighr/binaries/&quot;)

try{
       ant.javac(srcdir:&quot;/dev/projects/ighr/src&quot;,
       destdir:&quot;/dev/projects/ighr/binaries/&quot; )

}catch(Throwable thr){
       ant.mail(mailhost:&quot;mail.anywhere.com&quot;, subject:&quot;build failure&quot;){
             from(address:&quot;buildmaster@anywhere.com&quot;, name:&quot;buildmaster&quot;)
             to(address:&quot;dev-team@anywhere.com&quot;, name:&quot;Development Team&quot;)
             message(&quot;Unable to compile ighr's source.&quot;)
       }
}
</pre>
<p>Where you REALLY need it, you of course are still able to call on any and all of the *nix powertools you might like in a Groovy script. Personally, more and more I find that building and testing the script in my chosen IDE, and using the libraries I&#8217;m most comfortable with to do it, is a much more productive and enjoyable experience.</p>
<p>P.S. Gotta apologize about the code formatting &#8211; if anyone knows a wordpress syntax highlighting plugin that DOESN&#8217;T blow away your formatting or randomly replace the text with html entities, gimme a shout please!</p>
<p>Related posts:<ol>
<li><a href='http://www.kellyrob99.com/blog/2009/04/03/griffon-bash-completion/' rel='bookmark' title='Griffon bash completion&#8230;'>Griffon bash completion&#8230;</a></li>
<li><a href='http://www.kellyrob99.com/blog/2009/08/09/using-the-testng-dataprovider-with-groovy/' rel='bookmark' title='Using the TestNG DataProvider with Groovy'>Using the TestNG DataProvider with Groovy</a></li>
<li><a href='http://www.kellyrob99.com/blog/2010/04/17/groovy-and-hibernate-validator-for-dynamic-constraints/' rel='bookmark' title='Groovy and Hibernate Validator for Dynamic Constraints'>Groovy and Hibernate Validator for Dynamic Constraints</a></li>
</ol></p>]]></content:encoded>
			<wfw:commentRss>http://www.kellyrob99.com/blog/2009/04/14/groovy-and-bash-can-scripting-get-much-easier/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

