<?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>Blog</title>
	<atom:link href="http://blog.andresteingress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.andresteingress.com</link>
	<description>Groovy, Grails, Java, Stuff. Mostly.</description>
	<lastBuildDate>Wed, 20 Mar 2013 07:15:11 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.4</generator>
		<item>
		<title>GContracts 1.2.11 Released!</title>
		<link>http://blog.andresteingress.com/2013/03/20/gcontracts-1-2-11-released/</link>
		<comments>http://blog.andresteingress.com/2013/03/20/gcontracts-1-2-11-released/#comments</comments>
		<pubDate>Wed, 20 Mar 2013 07:15:11 +0000</pubDate>
		<dc:creator>andresteingress</dc:creator>
				<category><![CDATA[gcontracts]]></category>
		<category><![CDATA[groovy]]></category>

		<guid isPermaLink="false">http://blog.andresteingress.com/?p=2525</guid>
		<description><![CDATA[I am happy to announce the release of GContracts 1.2.11. The new version comes with a couple of important bug fixes, improved closure expression validation and IDE support for IntelliJ >= 12.1 and GGTS >= 3.2.0. Issue Overview #42 Improved &#8230; <a href="http://blog.andresteingress.com/2013/03/20/gcontracts-1-2-11-released/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I am happy to announce the release of GContracts 1.2.11.</p>
<p>The new version comes with a couple of important bug fixes, improved closure expression validation and <a href="http://blog.andresteingress.com/2013/03/14/gcontracts-1-2-11-sneak-peak-improved-ide-support/">IDE support for IntelliJ >= 12.1 and GGTS >= 3.2.0</a>.</p>
<p>Issue Overview</p>
<ul>
<li>#42 Improved compilation error messages
<li>#41 Fix copyright text
<li>#40 Provide GDSL and DSLD files for improved IDE support Feature
<li>#39 @Grab with GContracts fails in groovyConsole and @CompileStatic Bug
<li>#38 ContractClosureWriter should generate final classes
</ul>
<p>GContracts is available in the central Maven repository [<a href="http://repo1.maven.org/maven2/org/gcontracts/gcontracts-core/1.2.11/">0</a>] and at Github [<a href="http://gcontracts.org">1</a>].</p>
<p>[0] <a href="http://repo1.maven.org/maven2/org/gcontracts/gcontracts-core/1.2.11/">GContracts @ Maven repo</a><br />
[1] <a href="http://gcontracts.org">GContracts @ Github</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.andresteingress.com/2013/03/20/gcontracts-1-2-11-released/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>GContracts 1.2.11 Sneak Peak &#8211; Improved IDE Support</title>
		<link>http://blog.andresteingress.com/2013/03/14/gcontracts-1-2-11-sneak-peak-improved-ide-support/</link>
		<comments>http://blog.andresteingress.com/2013/03/14/gcontracts-1-2-11-sneak-peak-improved-ide-support/#comments</comments>
		<pubDate>Thu, 14 Mar 2013 13:33:12 +0000</pubDate>
		<dc:creator>andresteingress</dc:creator>
				<category><![CDATA[gcontracts]]></category>
		<category><![CDATA[groovy]]></category>

		<guid isPermaLink="false">http://blog.andresteingress.com/?p=2493</guid>
		<description><![CDATA[GContracts [0] is a &#8220;Design-by-Contract&#8221; implementation for Groovy. It adds the concept of programming by contract to the Groovy programming language by adding a single JAR file without third-party dependencies to the class-path. Here is a short preview for the &#8230; <a href="http://blog.andresteingress.com/2013/03/14/gcontracts-1-2-11-sneak-peak-improved-ide-support/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>GContracts [<a href="https://www.github.com/andresteingress/gcontracts">0</a>] is a &#8220;Design-by-Contract&#8221; implementation for Groovy. It adds the concept of programming by contract to the Groovy programming language by adding a single JAR file without third-party dependencies to the class-path.</p>
<p>Here is a short preview for the upcoming 1.2.11 release.</p>
<p>In the very beginning, GContracts was based on a &#8220;hidden&#8221; feature in Groovy 1.7: closure annotation parameters. As this was kind of a hidden trick, there was only accidental support for this feature in IDEs. This changed with the release of Groovy 1.8, which officially released the feature of closure annotation parameters.</p>
<p>Another missing piece besides supporting closure annotation parameters was the possibility to let the IDE know about implicit variables added by GContracts during compile-time. This was especially needed for the <tt>@Ensures</tt> annotation&#8217;s <tt>result</tt> and <tt>old</tt> variables.</p>
<p>With the ongoing support for custom DSLs, I am happy to announce improved support in this area for the Eclipse Groovy/Grails Toolsuite (GGTS) and Intellij 12.1 [<a href="http://youtrack.jetbrains.com/issue/IDEA-98733">1</a>] and upwards.</p>
<h3>Unresolved Variables EVERYWHERE</h3>
<p>As of today, GContracts provides only a small &#8211; yet powerful &#8211; set of annotations: <tt>@Requires</tt>, <tt>@Ensures</tt> and <tt>@Invariant</tt></p>
<p><tt>@Ensures</tt> &#8211; the annotation to define postconditions &#8211; is a special case. It adds two implicit variables to the closure code block: <tt>old</tt> and <tt>result</tt>. <tt>result</tt> is available in the case the target method is a non-void instance method and resembles the method&#8217;s return value. <tt>old</tt> is a map and resembles all parameter and property values before a method call.</p>
<p><a href="http://blog.andresteingress.com/wp-content/uploads/2013/03/Screenshot.png"><img class="aligncenter size-full wp-image-2498" title="Unresolved Variable" src="http://blog.andresteingress.com/wp-content/uploads/2013/03/Screenshot.png" alt="" width="616" height="89" /></a></p>
<p>The problem with implicitly introduced variable names in DSLs is their support in IDEs. Up to now, neither IntelliJ nor Eclipse did recognize the <tt>old</tt> and <tt>result</tt> variables.</p>
<p>With the upcoming 1.2.11 release, GContracts comes with bundled GDSL and DSDL files, to extend the IDE inference mechanisms:</p>
<p><a href="http://blog.andresteingress.com/wp-content/uploads/2013/03/Web_Screen1.png"><img class="aligncenter size-full wp-image-2499" title="IntelliJ Result" src="http://blog.andresteingress.com/wp-content/uploads/2013/03/Web_Screen1.png" alt="" width="357" height="221" /></a></p>
<p>Note, the inferred <tt>result</tt> variable is typed with the declared return type of the corresponding method. In the case of a void method, the variable is not available in the auto-completion dialog.</p>
<p><a href="http://blog.andresteingress.com/wp-content/uploads/2013/03/Web_Screen2.png"><img class="aligncenter size-full wp-image-2500" title="Old Variable IntelliJ" src="http://blog.andresteingress.com/wp-content/uploads/2013/03/Web_Screen2.png" alt="" width="400" height="281" /></a></p>
<p style="text-align: center;"><a href="http://blog.andresteingress.com/wp-content/uploads/2013/03/Web_Screen3.png"><img class="size-full wp-image-2501 aligncenter" title="Old Variable Eclipse GGTS" src="http://blog.andresteingress.com/wp-content/uploads/2013/03/Web_Screen3.png" alt="" width="504" height="240" /></a></p>
<p>At time of writing, the <tt>old</tt> variable is simply typed as being of type <tt>java.util.Map</tt>. I will try to add some more logic to provide this variable only when it makes sense in the current context.</p>
<h3>And now?</h3>
<p>I am looking forward to release 1.2.11 until the next couple of days. There is &#8220;only&#8221; one bug pending being a class-loading issue, d&#8217;oh <img src='http://blog.andresteingress.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </p>
<p>[0] <a href="https://www.github.com/andresteingress/gcontracts">GContracts &#8211; Programming by Contract for Groovy</a><br />
[1] <a href="http://youtrack.jetbrains.com/issue/IDEA-98733">IntelliJ YouTrack &#8211; IDEA 98773</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.andresteingress.com/2013/03/14/gcontracts-1-2-11-sneak-peak-improved-ide-support/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Groovy 2.1: groovyc &#8211;configscript</title>
		<link>http://blog.andresteingress.com/2013/01/25/groovy-2-1-groovyc-configscript/</link>
		<comments>http://blog.andresteingress.com/2013/01/25/groovy-2-1-groovyc-configscript/#comments</comments>
		<pubDate>Fri, 25 Jan 2013 08:41:48 +0000</pubDate>
		<dc:creator>andresteingress</dc:creator>
				<category><![CDATA[ast transformations]]></category>
		<category><![CDATA[groovy]]></category>

		<guid isPermaLink="false">http://blog.andresteingress.com/?p=2325</guid>
		<description><![CDATA[One of the new features in Groovy 2.1 [0] is the -configscript Groovy compiler program option. Compiler Configuration Script with &#8211;configscript The --configscript option can be used to specify a compiler configuration script. Before 2.1, the CompilerConfiguration class could be &#8230; <a href="http://blog.andresteingress.com/2013/01/25/groovy-2-1-groovyc-configscript/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>One of the new features in Groovy 2.1 [<a href="http://jira.codehaus.org/secure/ReleaseNote.jspa?projectId=10242&amp;version=18598">0</a>] is the <tt>-configscript</tt> Groovy compiler program option.</p>
<h3>Compiler Configuration Script with &#8211;configscript</h3>
<p>The <tt>--configscript</tt> option can be used to specify a compiler configuration script. Before 2.1, the <tt>CompilerConfiguration</tt> class could be used to change certain configuration settings:</p>
<pre class="wp-code-highlight prettyprint linenums:1">
def configuration = new CompilerConfiguration()
// apply some configuration settings ...

def shell = new GroovyShell(configuration)
</pre>
<p>Although we could set the <tt>CompilerConfiguration</tt> for a given <tt>GroovyShell</tt>, there was no way to do so for the Groovy compiler <tt>groovyc</tt>. As of Groovy 2.1, <tt>--configscript</tt> can be used to point to an external Groovy DSL script that has access to an implicit <tt>configuration</tt> variable of type <tt>CompilerConfiguration</tt>.</p>
<p>In order to specify a Groovy configuration file we need to create a configuration Groovy script, let&#8217;s call it <tt>config.groovy</tt>:</p>
<pre class="wp-code-highlight prettyprint linenums:1">
import org.codehaus.groovy.control.customizers.ImportCustomizer

def imports = new ImportCustomizer()
imports.addImports(&#039;org.some.*&#039;)

configuration.addCompilationCustomizers(imports)
</pre>
<p>The script above adds package <tt>org.some.*</tt> to the default imports. As you can see, Groovy adds an implicit variable called <tt>configuration</tt>. At runtime, this is the actual compiler configuration our DSL script needs to interact with.</p>
<h3>A New Builder: <tt>CompilerCustomizationBuilder</tt></h3>
<p>Groovy 2.1 comes even with a new DSL for the <tt>--configscript</tt> configuration file. The builder in the background is <tt>CompilerCustomizationBuilder</tt>. For the star import example given above, with the builder the configuration file would look like this:</p>
<pre class="wp-code-highlight prettyprint linenums:1">
import org.codehaus.groovy.control.customizers.ImportCustomizer
import org.codehaus.groovy.control.customizers.builder.CompilerCustomizationBuilder

CompilerCustomizationBuilder.withConfig(configuration) {
    new ImportCustomizer().addImports(&#039;org.some.*&#039;)
}
</pre>
<p>or we could &#8211; due to the fact that Groovy already adds a star import for <tt>import static CompilerCustomizationBuilder.*</tt> &#8211; reduce our code to:</p>
<pre class="wp-code-highlight prettyprint linenums:1">
// implicitly added ...
// import static org.codehaus.groovy.control.customizers.builder.CompilerCustomizationBuilder.*

import org.codehaus.groovy.control.customizers.ImportCustomizer

withConfig(configuration) {
    new ImportCustomizer().addImports(&#039;org.some.*&#039;)
}
</pre>
<p>The compiler customization is not restricted to adding <tt>CompilerCustomizer</tt> implementations. It can be used to add AST transformations on every artifact that is compiled with the <tt>-configscript</tt> option. Let&#8217;s say we wanted to apply the newly introduced static compilation feature with <tt>@CompileStatic</tt> to every class in our project. The compiler configuration script can look like this:</p>
<pre class="wp-code-highlight prettyprint linenums:1">
// implicitly added ...
// import static org.codehaus.groovy.control.customizers.builder.CompilerCustomizationBuilder.*

withConfig(configuration)  {
    ast(groovy.transform.CompileStatic)
}
</pre>
<p>We can even go further. In addition, <tt>CompilerCustomizationBuilder</tt> provides a way to register certain source files with AST transformations.</p>
<p>Let&#8217;s say we wanted to couple all files with a <tt>*.sgroovy</tt> extension to the <tt>@StaticCompile</tt> annotation. This could be done in the configuration script using a <tt>SourceAwareCustomizerFactory</tt>:</p>
<pre class="wp-code-highlight prettyprint linenums:1">
withConfig(configuration) {
    source(extension: &#039;sgroovy&#039;) {
        ast(groovy.transform.CompileStatic)
    }
}
</pre>
<p>When running e.g. <tt>groovyc</tt> with this configuration script and a <tt>*.sgroovy</tt> file we have <tt>@StaticCompile</tt> automatically applied on all newly compiled classes.</p>
<p>There are even more features that can be used with this builder. As a starting point, take a look at the <tt>registerFactories</tt> method in <tt>CompilerCustomizationBuilder</tt>:</p>
<pre class="wp-code-highlight prettyprint linenums:1">
registerFactory(&quot;ast&quot;, new ASTTransformationCustomizerFactory())
registerFactory(&quot;customizers&quot;, new CustomizersFactory())
registerFactory(&quot;imports&quot;, new ImportCustomizerFactory())
registerFactory(&quot;inline&quot;, new InlinedASTCustomizerFactory())
registerFactory(&quot;secureAst&quot;, new SecureASTCustomizerFactory())
registerFactory(&quot;source&quot;, new SourceAwareCustomizerFactory())
</pre>
<p>As you can see, there is even a <tt>ImportCustomizerFactory</tt> predefined. A look at the documentation shows how to use it in the compiler configuration DSL:</p>
<pre class="wp-code-highlight prettyprint linenums:1">
import org.codehaus.groovy.control.customizers.builder.CompilerCustomizationBuilder

def builder = new CompilerCustomizationBuilder()
builder.imports {
    star &#039;org.some&#039;
}
</pre>
<h3>Conclusion</h3>
<p>Groovy 2.1 comes with a new Groovy compiler configuration parameter: <tt>-configscript</tt>. In conjunction with the new <tt>CompilerCustomizationBuilder</tt> it can be used to specify a Groovy script holding the compiler configuration DSL code as supported by the builder. This is good news for AST transformation authors as the hook can be used for embedding AST transformations or registering AST transformations on specific source files.</p>
<p>[0] <a href="http://jira.codehaus.org/secure/ReleaseNote.jspa?projectId=10242&amp;version=18598">Groovy 2.1 Relase Notes</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.andresteingress.com/2013/01/25/groovy-2-1-groovyc-configscript/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Groovy 2.1: The @DelegatesTo Annotation</title>
		<link>http://blog.andresteingress.com/2013/01/25/groovy-2-1-the-delegatesto-annotation/</link>
		<comments>http://blog.andresteingress.com/2013/01/25/groovy-2-1-the-delegatesto-annotation/#comments</comments>
		<pubDate>Fri, 25 Jan 2013 08:41:40 +0000</pubDate>
		<dc:creator>andresteingress</dc:creator>
				<category><![CDATA[groovy]]></category>

		<guid isPermaLink="false">http://blog.andresteingress.com/?p=2306</guid>
		<description><![CDATA[http://docs.codehaus.org/display/GROOVY/Eclipse+Plugin#EclipsePlugin-DevelopmentBuildsGroovy 2.1 comes with a neat feature for DSL and Groovy library others: the @DelegateTo [0] annotation. The Delegate and The Closure Groovy supports the concept of closures [1]. One closure feature is to being able to modifiy the closure &#8230; <a href="http://blog.andresteingress.com/2013/01/25/groovy-2-1-the-delegatesto-annotation/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>http://docs.codehaus.org/display/GROOVY/Eclipse+Plugin#EclipsePlugin-DevelopmentBuildsGroovy 2.1 comes with a neat feature for DSL and Groovy library others: the <tt>@DelegateTo</tt> [<a href="http://jira.codehaus.org/browse/GROOVY-5714">0</a>] annotation.</p>
<h3>The Delegate and The Closure</h3>
<p>Groovy supports the concept of closures [<a href="http://en.wikipedia.org/wiki/Closure_(computer_science)">1</a>]. One closure feature is to being able to modifiy the closure code delegation mechanism. Once a closure is defined, its <tt>delegate</tt> object can be changed by setting the delegate property:</p>
<pre class="wp-code-highlight prettyprint linenums:1">def me = &#039;André&#039;
def closure = { greet me }

closure.delegate = new Greeter()

closure()</pre>
<p>In the code sample above, we change the delegate to an instance of <tt>Greeter</tt>.</p>
<pre class="wp-code-highlight prettyprint linenums:1">class Greeter {
    void greet(def another)  {
        println &quot;Hello, $another&quot;
    }
}</pre>
<p>When executing the code in groovConsole [<a href="http://groovy.codehaus.org/Groovy+Console">2</a>], it prints</p>
<pre class="wp-code-highlight prettyprint linenums:1">No signature of method: ConsoleScript1.greet() is applicable for argument types: (java.lang.String) values: [André]</pre>
<p>Ups, obviously we did forget one little thing: the resolve strategy. By setting the resolve strategy of a single <tt>groovy.lang.Closure</tt> instance, we can chose between the following types:</p>
<ul>
<li><strong>OWNER_ONLY</strong>: delegate method calls to the owner of the closure (e.g. the instance creating the closure instance)</li>
<li><strong>DELEGATE_ONLY</strong>:  delegate method calls to the delegate of the closure</li>
<li><strong>OWNER_FIRST</strong>: delegate to the owner first, then the delegate</li>
<li><strong>DELEGATE_FIRST</strong>: delegate to the delegate first, then the owner</li>
<li><strong>SELF_ONLY</strong>: method calls are resolved against the closure instance only</li>
</ul>
<p>In our example the resolve strategy should be set to <tt>DELEGATE_FIRST</tt> or <tt>OWNER_FIRST</tt>, as we call <tt>Greeter#greet</tt> and have a reference to the script variable <tt>me</tt>.</p>
<pre class="wp-code-highlight prettyprint linenums:1">def me = &#039;André&#039;
def closure = { greet me }

closure.delegate = new Greeter()
closure.resolveStrategy = Closure.DELEGATE_FIRST

closure()</pre>
<h3>What&#8217;s the deal?</h3>
<p>Modifying the closure resolving strategy is a powerful technuique for DSL and Groovy library authors. For example, take a look at GContracts [<a href="https://github.com/andresteingress/gcontracts">3</a>], a Design by Contract extension for Groovy, that uses closure annotations to specify contracts on methods and classes:</p>
<pre class="wp-code-highlight prettyprint linenums:1">@Invariant({ elements != null })
class Stack {

    List elements

    @Ensures({ is_empty() })
    def Stack()  {
        elements = []
    }

    // ...

    @Ensures({ last_item() == item })
    def push(T item)  {
       elements.add(item)
    }

    @Requires({ !is_empty() })
    @Ensures({ last_item() == item })
    def replace(T item)  {
        remove()
        elements.add(item)
    }

    @Requires({ !is_empty() })
    @Ensures({ result != null })
    T remove()  {
        elements.remove(count() - 1)
    }

    String toString() { elements.toString() }
}

def stack = new Stack()</pre>
<p>Another example is definitely Gradle [<a href="http://www.gradle.org">4</a>], the Groovy-based build automation framework:</p>
<pre class="wp-code-highlight prettyprint linenums:1">task hello &amp;lt;&amp;lt; {
    println &#039;Hello Earth&#039;
}
hello.doFirst {
    println &#039;Hello Venus&#039;
}
hello.doLast {
    println &#039;Hello Mars&#039;
}
hello &amp;lt;&amp;lt; {
    println &#039;Hello Jupiter&#039;
}</pre>
<p>When working with one of these libraries in IntelliJ or Eclipse, one shortage becomes immediately apparent: whenever a custom delegate object is set, IntelliJ or Eclipse do not provide code completion for closure code, except the IDE of choice comes with specific framework support.</p>
<p><a href="http://blog.andresteingress.com/wp-content/uploads/2013/01/screen.tiff"><img class="aligncenter size-full wp-image-2348" title="IntelliJ" src="http://blog.andresteingress.com/wp-content/uploads/2013/01/screen.tiff" alt="" /></a></p>
<h3>@DelegatesTo comes into play</h3>
<p>As of version 2.1, Groovy provides a way for DSL, library and framework authors to hint IDEs in the right direction: the <tt>@DelegatesTo</tt> annotation. In its simplest application, <tt>@DelegatesTo</tt> has only a single default argument of type <tt>java.lang.Class</tt>. Back to our previous example, we have to introduce an indirection as <tt>@DelegatesTo</tt> can only be applied on parameters:</p>
<pre class="wp-code-highlight prettyprint linenums:1">class Greeter {
    void greet(def another)  {
        println &quot;Hello, $another&quot;
    }
}

class Marketplace {

    void interactions(@DelegatesTo(Greeter) Closure closure) {
        closure.delegate = new Greeter()
        closure.resolveStrategy = Closure.DELEGATE_FIRST
        closure()
    }
}

def marketplace = new Marketplace()

def me = &#039;André&#039;
marketplace.interactions{
    greet me
}</pre>
<p>We can even provide more meta-data by specifying the <tt>strategy</tt> attribute:</p>
<pre class="wp-code-highlight prettyprint linenums:1">// ...
void interactions(@DelegatesTo(strategy = Closure.DELEGATE_FIRST, value = Greeter) Closure closure) {
// ...</pre>
<h3>The DelegatesTo.Target Annotation</h3>
<p><tt>@DelegatesTo</tt> has one last additional meta-data that can be applied on method paramters: the <tt>@DelegatesTo.Target</tt> annotation.</p>
<p>Whenever an actual parameter will be set as the closure&#8217;s delegate object, the <tt>Target</tt> can be used to document this circumstance:</p>
<pre class="wp-code-highlight prettyprint linenums:1">// ...
void interactions(@DelegatesTo.Target Greeter greeter, @DelegatesTo(Greeter) Closure closure) {
    closure.delegate = greeter // &amp;lt;-- the argument will be set as closure delegate
    // ....
}

// ...</pre>
<p>For the special case of having multiple parameters of the same type, there is a <tt>target</tt> annotation element type that allows for specifying unique <tt>String</tt> ids.</p>
<pre class="wp-code-highlight prettyprint linenums:1">// ...
void interactions(@DelegatesTo.Target(&#039;id&#039;) Greeter greeter, @DelegatesTo(target = &#039;id&#039;) Closure closure) {
    closure.delegate = greeter // &amp;lt;-- the argument will be set as closure delegate
    // ....
}

// ...</pre>
<p>Note, in the example above we did not specify a class for the <tt>closure</tt> parameter. This can be omitted since the type will be inferred from the <tt>greeter</tt> parameter.</p>
<h3>IDE Support</h3>
<p>Besides supporting IDEs the <tt>@DelegatesTo</tt> information is evaluated by <tt>@TypeChecked</tt> and <tt>@StaticCompile</tt>.</p>
<p>As of writing, neither IntelliJ nor the Groovy Eclipse plugin comes with support for <tt>@DelegatesTo</tt>, but it is expected to become supported in the near future:</p>
<p><img class="alignleft size-full wp-image-2356" title="IntelliJ Support " src="http://blog.andresteingress.com/wp-content/uploads/2013/01/screen2.tiff" alt="" /></p>
<h3>Conclusion</h3>
<p>DSL, library and Groovy framework authors should definitely consider adding <tt>@DelegatesTo</tt> to their method meta-data. Besides the benefit of better IDE support (think of code completion), additional meta-data is utilized by Groovy 2.0&#8242;s <tt>@TypeChecked</tt> and <tt>@StaticCompile</tt> to catch even more typing errors.</p>
<p>It&#8217;s a small step for third party authors, but a big step for Groovy IDE support.</p>
<p><strong>Update</strong></p>
<p>As announced today (2013-02-07), <em>@DelegatesTo</em> is supported by the Groovy-Eclipse plugin. Snapshot builds are available at <a href="http://docs.codehaus.org/display/GROOVY/Eclipse+Plugin#EclipsePlugin-DevelopmentBuilds">http://docs.codehaus.org/display/GROOVY/Eclipse+Plugin#EclipsePlugin-DevelopmentBuilds</a></p>
<p>[0] <a href="http://jira.codehaus.org/browse/GROOVY-5714">GROOVY-5714: @DelegatesTo annotation for IDEs/TypeChecker</a><br />
[1] <a href="http://en.wikipedia.org/wiki/Closure_(computer_science)">Wikipedia: Closure</a><br />
[2] <a href="http://groovy.codehaus.org/Groovy+Console">grooovyConsole</a><br />
[3] <a href="https://github.com/andresteingress/gcontracts">GContracts</a><br />
[4] <a href="http://www.gradle.org">Gradle &#8211; Build Automation Framework</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.andresteingress.com/2013/01/25/groovy-2-1-the-delegatesto-annotation/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Groovy 2.1: The @AnnotationCollector Annotation</title>
		<link>http://blog.andresteingress.com/2013/01/25/groovy-2-1-the-annotationcollector-annotation/</link>
		<comments>http://blog.andresteingress.com/2013/01/25/groovy-2-1-the-annotationcollector-annotation/#comments</comments>
		<pubDate>Fri, 25 Jan 2013 08:41:32 +0000</pubDate>
		<dc:creator>andresteingress</dc:creator>
				<category><![CDATA[groovy]]></category>

		<guid isPermaLink="false">http://blog.andresteingress.com/?p=2373</guid>
		<description><![CDATA[Groovy 2.1 comes with another cool addition to the groovy.transform AST package: the @AnnotationCollector [0]. X Annotations -> 1 Annotation The use case for the annotation collector is simple: we want to define a meta-annotation that includes a handful of &#8230; <a href="http://blog.andresteingress.com/2013/01/25/groovy-2-1-the-annotationcollector-annotation/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Groovy 2.1 comes with another cool addition to the <tt>groovy.transform</tt> AST package: the <tt>@AnnotationCollector</tt> [<a href="http://jira.codehaus.org/browse/GROOVY-5821">0</a>].</p>
<h3>X Annotations -> 1 Annotation</h3>
<p>The use case for the annotation collector is simple: we want to define a meta-annotation that includes a handful of other annotations. By the way, it&#8217;s not just &#8220;other annotations&#8221; but we also want to include AST transformation annotations like <tt>@ToString</tt>, <tt>@EqualsAndHashCode</tt>, <tt>@Immutable</tt> etc. (for an introduction to Groovy&#8217;s AST transformation annotations, you might want to start here [<a href="http://groovy.codehaus.org/Compile-time+Metaprogramming+-+AST+Transformations">1</a>]).</p>
<p>Let&#8217;s say we have the use case to apply <tt>@ToString</tt> and <tt>@Immutable</tt> to several classes in our project. With Groovy 2.1 we can use <tt>@AnnotationCollector</tt> to avoid code duplication and create a single annotation alias:</p>
<pre class="wp-code-highlight prettyprint linenums:1">
@AnnotationCollector([ToString, Immutable])
@interface ValueObject {}
</pre>
<p>Our self-defined <tt>@ValueObject</tt> can now be applied on Groovy classes:</p>
<pre class="wp-code-highlight prettyprint linenums:1">
@ValueObject
class UpperLimit {}
</pre>
<p>What happens during compile-time is, the <tt>@ValueObject</tt> is detected to be an <tt>@AnnotationCollector</tt> annotation, thus it is replaced by its meta annotations:</p>
<pre class="wp-code-highlight prettyprint linenums:1">
@ValueObject
class UpperLimit {}
</pre>
<p>becomes</p>
<pre class="wp-code-highlight prettyprint linenums:1">
@ToString
@Immutable
class UpperLimit {}
</pre>
<p>One last thing: <tt>@AnnotationCollector</tt> provides a way to specify annotation type element values. For example, the <tt>@ToString</tt> annotation comes with various attributes to configure the <tt>toString()</tt> output:</p>
<pre class="wp-code-highlight prettyprint linenums:1">
public @interface ToString {

    String[] excludes() default {};
    // ...
    String[] includes() default {};
    // ...
}
</pre>
<p>Let&#8217;s say we want to ignore all <tt>id</tt> properties on our value objects. Although our <tt>@ValueObject</tt> has no attributes defined, we can ignore that fact as the <tt>@AnnotationCollector</tt> AST transformation modifies the custom annotation accordingly:</p>
<pre class="wp-code-highlight prettyprint linenums:1">
@ValueObject(excludes = [&#039;id&#039;])
class UpperLimit {}
</pre>
<p>One special case is when multiple annotation elements have different types and the same names, or just the same names. If they have different types, compilation will fail. Otherwise, the last annotation collect by <tt>@AnnotationCollector</tt> will deemed as appropriate while others being ignored.</p>
<h3>Advanced Features</h3>
<p><tt>@AnnotatioCollector</tt> even supports adding custom AST transformation code by specifying its <tt>processor</tt> annotation element. A custom annotation collector must inherit from <tt>org.codehaus.groovy.transform.AnnotationCollectorTransform</tt> and override the <tt>visit()</tt> method.</p>
<p>A complete example by Guillaume Laforge can be found at Github [<a href="https://gist.github.com/4563430">2</a>].</p>
<h3>Conclusion</h3>
<p>The new <tt>@AnnotationCollector</tt> annotation can be used to group several (AST xform) annotations to a single annotation. Further, its functionality can be extended by custom AST transformation code.</p>
<p>[0] <a href="http://jira.codehaus.org/browse/GROOVY-5821">GROOVY-5821: Provide a way to assemble an annoation consisting of several other</a><br />
[1] <a href="http://groovy.codehaus.org/Compile-time+Metaprogramming+-+AST+Transformations">Compile-time Metaprogramming &#8211; AST Transformations</a><br />
[2] <a href="https://gist.github.com/4563430">Github AnnotationCollectorTransform Example by Guillaume Laforge</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.andresteingress.com/2013/01/25/groovy-2-1-the-annotationcollector-annotation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Groovy 2.1: Type Checking Extensions</title>
		<link>http://blog.andresteingress.com/2013/01/25/groovy-2-1-type-checking-extensions/</link>
		<comments>http://blog.andresteingress.com/2013/01/25/groovy-2-1-type-checking-extensions/#comments</comments>
		<pubDate>Fri, 25 Jan 2013 08:41:25 +0000</pubDate>
		<dc:creator>andresteingress</dc:creator>
				<category><![CDATA[ast transformations]]></category>
		<category><![CDATA[groovy]]></category>

		<guid isPermaLink="false">http://blog.andresteingress.com/?p=2381</guid>
		<description><![CDATA[As of Groovy 2.0, the static type checking and compilation annotations @CompileStatic and @TypeChecked [0][1] can be applied on types and methods. Type checking helps us identify typing errors, or references to undeclared methods as shown in the following code &#8230; <a href="http://blog.andresteingress.com/2013/01/25/groovy-2-1-type-checking-extensions/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>As of Groovy 2.0, the static type checking and compilation annotations <tt>@CompileStatic</tt> and <tt>@TypeChecked</tt> [<a href="http://groovy.codehaus.org/gapi/groovy/transform/CompileStatic.html">0</a>][<a href="http://groovy.codehaus.org/gapi/groovy/transform/TypeChecked.html">1</a>] can be applied on types and methods.</p>
<p>Type checking helps us identify typing errors, or references to undeclared methods as shown in the following code example:</p>
<pre class="wp-code-highlight prettyprint linenums:1">@groovy.transform.TypeChecked
class Greeter {
    void greet(String other)  {
        println &quot;Hello, $oher&quot;.toUppercase()
    }
}</pre>
<p>With <tt>@TypeChecked</tt> we get the following errors during compile-time:</p>
<pre class="wp-code-highlight prettyprint linenums:1">[Static type checking] - The variable [oher] is undeclared.
 at line: 4, column: 26

[Static type checking] - Cannot find matching method groovy.lang.GString#toUppercase(). Please check if the declared type is right and if the method exists.
 at line: 4, column: 17</pre>
<p>If you ever had the case where a typing error caused serious errors on your Grails production system, you will surely value the use of this annotation.</p>
<h3>Custom Type Checking Extensions</h3>
<p>Groovy 2.1 takes the conecpt of type checking even further and introduces a way to add custom type checking extensions. Custom type checking extensions are a great way to add compile-time checks that go beyond standard compile validations.</p>
<p>As an example, let&#8217;s assume we have a type checked <tt>Sql</tt> utility class to access our relational database. The <tt>Sql</tt> class has a method named <tt>eachRow</tt> receiving a SQL query of type String as first argument:</p>
<pre class="wp-code-highlight prettyprint linenums:1">sql.eachRow( &#039;select * from tableName&#039; ) { println &quot;$it.id -- ${it.firstName} --&quot; }</pre>
<p>As you can see in the code above, the SQL query is of type String. Syntactical errors we only occur at runtime.</p>
<p>With a custom type checking extension we can evaluate the specified SQL query at compile-time. The first step is to add a Groovy script to our class-path, let&#8217;s call it <tt>SqlExtension.groovy</tt>. Groovy 2.1 comes with a custom type checking DSL that can be used within these scripts.</p>
<p>Let&#8217;s see how a SQL parsing type checking extension could look like:</p>
<pre class="wp-code-highlight prettyprint linenums:1">@Grab(group=&#039;net.sf.jsqlparser&#039;, module=&#039;jsqlparser&#039;, version=&#039;0.8.0&#039;)
import net.sf.jsqlparser.parser.CCJSqlParserManager

afterMethodCall { mc -&gt;
  def receiver = mc.receiver
  if (!isVariableExpression(receiver)) return

  def method = getTargetMethod(mc)

  if (classNodeFor(groovy.sql.Sql) == getType(receiver) &amp;&amp; method.name == &#039;eachRow&#039;) {
    def argList = getArguments(mc)
    if (argList &amp;&amp; isConstantExpression(argList[0])) {
        def pm = new CCJSqlParserManager();
        def sqlQuery = argList[0].text

        try {
            pm.parse(new StringReader(sqlQuery))
            } catch (e) {
                addStaticTypeError(&quot;SQL query is not valid: &quot; + e, argList[0])
            }
        }
    }
}</pre>
<p>And that&#8217;s it. It has to be noted that the <tt>@Grab</tt> annotation can be used inside type checking extension scripts.  </p>
<p>The example above uses the JSQLParser [<a href="http://jsqlparser.sourceforge.net/">2</a>] library but we could of course use any other third party library.</p>
<p>The <tt>afterMethodCall</tt> is one of the event hooks that can be used in a type checking extension. As can be seen, its only argument is an instance of <tt>MethodCall</tt> which we use to retrieve the target method&#8217;s name and the methods receiver type. Once we&#8217;re sure that it&#8217;s a call to <tt>Sql#eachRow(...)</tt>, we can check the first argument for being a constant expression (ie. a constant <tt>String</tt>). After we retrieved the constant, we can fire up our SQL parser and see if the statement is syntactically correct. Let&#8217;s add the <tt>SqlExtension.groovy</tt> on a test class:</p>
<pre class="wp-code-highlight prettyprint linenums:1">import groovy.sql.Sql

@groovy.transform.TypeChecked(extensions = [&#039;SqlExtension.groovy&#039;])
class SqlTest {

    def test() {
    	def db = [url:&#039;jdbc:hsqldb:mem:testDB&#039;, user:&#039;sa&#039;, password:&#039;&#039;, driver:&#039;org.hsqldb.jdbc.JDBCDriver&#039;]
 	def sql = Sql.newInstance(db.url, db.user, db.password, db.driver)

 	sql.eachRow(&#039;select * frm PROJECT&#039;) { row -&amp;gt;
	    println row
	}
    }
}</pre>
<p>Obviously, the specified SQL argument string is syntactically not correct. Let&#8217;s see if we get a compile error when compiling this class:</p>
<pre class="wp-code-highlight prettyprint linenums:1">org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
SqlTest.groovy: 10: [Static type checking] - SQL query is not valid: net.sf.jsqlparser.JSQLParserException
 @ line 10, column 16.
    		sql.eachRow(&#039;select * frm PROJECT&#039;) { row -&amp;gt;
                  ^</pre>
<p>It worked! We have our first custom type checking extension that checks SQL statements for their syntactical correctness. Cool, isn&#8217;t it?</p>
<h3>GTCES</h3>
<p><tt>GroovyTypeCheckingExtensionSupport</tt> [3] is the class that handles type extension script and therefore defines all available event hooks. During its initialization phase, GTCES adds a custom script base class to our extension script and adds some default imports:</p>
<pre class="wp-code-highlight prettyprint linenums:1">CompilerConfiguration config = new CompilerConfiguration();
config.setScriptBaseClass(&quot;org.codehaus.groovy.transform.stc.GroovyTypeCheckingExtensionSupport.TypeCheckingDSL&quot;);

ImportCustomizer ic = new ImportCustomizer();
ic.addStarImports(&quot;org.codehaus.groovy.ast.expr&quot;);
ic.addStaticStars(&quot;org.codehaus.groovy.ast.ClassHelper&quot;);
ic.addStaticStars(&quot;org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport&quot;);

config.addCompilationCustomizers(ic);</pre>
<p>The <tt>METHOD_ALIASES</tt> constant show all event hooks currently available:</p>
<pre class="wp-code-highlight prettyprint linenums:1">private final static Map METHOD_ALIASES = Collections.unmodifiableMap(
            new HashMap() {{
                put(&quot;onMethodSelection&quot;, &quot;onMethodSelection&quot;);
                put(&quot;afterMethodCall&quot;, &quot;afterMethodCall&quot;);
                put(&quot;beforeMethodCall&quot;, &quot;beforeMethodCall&quot;);
                put(&quot;unresolvedVariable&quot;, &quot;handleUnresolvedVariableExpression&quot;);
                put(&quot;unresolvedProperty&quot;, &quot;handleUnresolvedProperty&quot;);
                put(&quot;unresolvedAttribute&quot;, &quot;handleUnresolvedAttribute&quot;);
                put(&quot;methodNotFound&quot;, &quot;handleMissingMethod&quot;);
                put(&quot;afterVisitMethod&quot;, &quot;afterVisitMethod&quot;);
                put(&quot;beforeVisitMethod&quot;, &quot;beforeVisitMethod&quot;);
                put(&quot;afterVisitClass&quot;, &quot;afterVisitClass&quot;);
                put(&quot;beforeVisitClass&quot;, &quot;beforeVisitClass&quot;);
                put(&quot;incompatibleAssignment&quot;, &quot;handleIncompatibleAssignment&quot;);
                put(&quot;setup&quot;,&quot;setup&quot;);
                put(&quot;finish&quot;, &quot;finish&quot;);
            }}
    );</pre>
<p>If you seek to implement custom type checking extensions, you should have a closer look at <tt>GCTES</tt> as this is starting point for the extension DSL.</p>
<h3>Conclusion</h3>
<p>Groovy 2.1 adds custom type checking extensions to its <tt>@TypeChecked</tt> annotation. Type checking extensions can be used for additional type checks that go beyond standard compiler validations and offer a great way to perform domain-specific compile-time checks in DSLs or, more general, Groovy code!</p>
<p><strong>UPDATE</strong></p>
<p>Cédric Champeau released the <a href="http://docs.codehaus.org/display/GROOVY/Type+checking+extensions">type checking extensions documentation</a>. If you want to implement a type checking extension, this is the place where to get a deeper insight into that topic.</p>
<p>[0] <a href="http://groovy.codehaus.org/gapi/groovy/transform/CompileStatic.html">groovy.transform.CompileStatic</a><br />
[1] <a href="http://groovy.codehaus.org/gapi/groovy/transform/TypeChecked.html">groovy.transform.TypeChecked</a><br />
[2] <a href="http://jsqlparser.sourceforge.net/">JSQLParser Library @ Sourceforge</a><br />
[3] org.codehaus.groovy.transform.stc.GroovyTypeCheckingExtensionSupport</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.andresteingress.com/2013/01/25/groovy-2-1-type-checking-extensions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Groovy 2.1.0 Released!</title>
		<link>http://blog.andresteingress.com/2013/01/25/groovy-2-1-0-released/</link>
		<comments>http://blog.andresteingress.com/2013/01/25/groovy-2-1-0-released/#comments</comments>
		<pubDate>Fri, 25 Jan 2013 08:41:00 +0000</pubDate>
		<dc:creator>andresteingress</dc:creator>
				<category><![CDATA[announcement]]></category>
		<category><![CDATA[groovy]]></category>

		<guid isPermaLink="false">http://blog.andresteingress.com/?p=2383</guid>
		<description><![CDATA[Groovy 2.1.0 has been released today. This release comes with important additions for DSL authors, third party libraries and improved IDE support. Here are the changes as announced at Greach by Guillaume Laforge today [0]: complete invoke dynamic support when &#8230; <a href="http://blog.andresteingress.com/2013/01/25/groovy-2-1-0-released/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://groovy.codehaus.org"><img class="aligncenter size-medium wp-image-2391" title="Groovy 2.1.0 Released!" src="http://blog.andresteingress.com/wp-content/uploads/2013/01/groovy-logo-medium-300x149.png" alt="" width="300" height="149" /></a></p>
<p>Groovy 2.1.0 has been released today. This release comes with important additions for DSL authors, third party libraries and improved IDE support. Here are the changes as announced at Greach by Guillaume Laforge today [<a href="http://glaforge.appspot.com/article/groovy-2-1-is-released">0</a>]:</p>
<ul>
<li>complete invoke dynamic support when running with the &#8220;indy&#8221; JAR on JDK 7</li>
<li><tt>@DelegatesTo</tt> annotation: to help IDEs and the static type checker and compiler to know that method calls in a method parameter closure are delegated to another parameter of the method &#8212; nice for DSLs like in Gradle build files</li>
<li>custom type checking extensions: so you can type check your DSLs at compile-time with your own logic</li>
<li>a meta-annotation system: which allows you to define a new annotation actually combining several others &#8212; which also means being able to apply several AST transformations with a single custom annotation</li>
<li>compiler configuration script: to let you define various configuration options for the Groovy compiler, like specifying custom file extensions, various compilation customizers to apply, etc.<br />
compilation customizer builder: a special builder for specifying compilation customizers</li>
</ul>
<p>I&#8217;ve decided to cover the most important features in separate blog posts:</p>
<p><a href="http://blog.andresteingress.com/2013/01/25/groovy-2-1-type-checking-extensions/">Groovy 2.1: Type Checking Extensions</a><br />
<a href="http://blog.andresteingress.com/2013/01/25/groovy-2-1-the-annotationcollector-annotation/">Groovy 2.1: The @AnnotationCollector Annotation</a><br />
<a href="http://blog.andresteingress.com/2013/01/25/groovy-2-1-groovyc-configscript/">Groovy 2.1: groovyc -configscript</a><br />
<a href="http://blog.andresteingress.com/2013/01/25/groovy-2-1-the-delegatesto-annotation/">Groovy 2.1: The @DelegatesTo Annotation</a></p>
<p>If you wanna get in touch with 2.1 you can either download it at [<a href="http://groovy.codehaus.org/Download">1</a>] or &#8211; and that is a way better alternative &#8211; use GVM, the Groovy enVironment Manager [<a href="http://gvmtool.net/">2</a>].</p>
<p>Keep on Groovying&#8217; <img src='http://blog.andresteingress.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>[0] <a href="http://glaforge.appspot.com/article/groovy-2-1-is-released">Groovy 2.1 Release Notes</a><br />
[1] <a href="http://groovy.codehaus.org/Download">Groovy 2.1.0 Download<br />
</a>[2] <a href="http://gvmtool.net/">GVM &#8211; The Groovy enVironment Manager</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.andresteingress.com/2013/01/25/groovy-2-1-0-released/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Groovy Quickie: Collection#inject([Object,] Closure)</title>
		<link>http://blog.andresteingress.com/2013/01/22/groovy-quickie-collectioninjectobject-closure/</link>
		<comments>http://blog.andresteingress.com/2013/01/22/groovy-quickie-collectioninjectobject-closure/#comments</comments>
		<pubDate>Tue, 22 Jan 2013 10:45:44 +0000</pubDate>
		<dc:creator>andresteingress</dc:creator>
				<category><![CDATA[groovy]]></category>

		<guid isPermaLink="false">http://blog.andresteingress.com/?p=2287</guid>
		<description><![CDATA[Groovy has a nice Groovy default method called inject [0]. Inject can be executed on collection types and is used for algorithms having intermediate results that need to be passed from iteration to iteration. Documentation excerpt: Iterates through the given &#8230; <a href="http://blog.andresteingress.com/2013/01/22/groovy-quickie-collectioninjectobject-closure/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Groovy has a nice Groovy default method called <code>inject</code> [<a href="http://groovy.codehaus.org/groovy-jdk/java/util/Collection.html#inject(groovy.lang.Closure)">0</a>]. Inject can be executed on collection types and is used for algorithms having intermediate results that need to be passed from iteration to iteration.</p>
<p>Documentation excerpt:</p>
<blockquote><p>Iterates through the given Collection, passing in the initial value to the 2-arg closure along with the first item. The result is passed back (injected) into the closure along with the second item. The new result is injected back into the closure along with the third item and so on until the entire collection has been used. Also known as foldLeft or reduce in functional parlance.</p></blockquote>
<p>Let&#8217;s say we wanted to compute the sum of a list of numbers:</p>
<pre class="wp-code-highlight prettyprint linenums:1">
assert 28 == [1, 2, 3, 4, 5, 6, 7].inject(0, { sum, value -&gt; sum + value })
</pre>
<p>The code above iterates over all list elements, and passes the current list element as the second actual argument to the given closure. The first argument resembles the intermediary result. </p>
<p><strong>1. run</strong>: sum == 0 (initial value), value == 1<br />
<strong>2. run</strong>: sum == 1, value == 2<br />
<strong>3. run</strong>: sum == 3, value == 3<br />
<strong>4. run</strong>: sum == 6, value == 4<br />
// &#8230;</p>
<p><tt>inject</tt> does not only work for scalar values, but for arbitrary data types:</p>
<pre class="wp-code-highlight prettyprint linenums:1">
assert [2, 4, 6, 8, 10, 12, 14] == [1, 2, 3, 4, 5, 6, 7].inject([], { list, value -&gt; list &lt;&lt; value * 2; list })
</pre>
<p>In fact, we could even simplify the code above to use the second <tt>inject</tt> without the initial value argument:</p>
<pre class="wp-code-highlight prettyprint linenums:1">
assert 28 == [1, 2, 3, 4, 5, 6, 7].inject { sum, value -&gt; sum + value }
</pre>
<h3>Conclusion</h3>
<p>The <tt>Collection#inject</tt> default Groovy method (DGM) comes in handy whenever we need to iterate over a collection and pass some intermediary result from iteration to iteration. It can be used either be specifying an initial value and a closure, or with just a single closure as argument.</p>
<p>[0] <a href="http://groovy.codehaus.org/groovy-jdk/java/util/Collection.html#inject(groovy.lang.Closure)">DGM: Collection#inject</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.andresteingress.com/2013/01/22/groovy-quickie-collectioninjectobject-closure/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Groovy Quickie: Dumping the Groovy AST</title>
		<link>http://blog.andresteingress.com/2012/12/21/dumping-the-groovy-ast/</link>
		<comments>http://blog.andresteingress.com/2012/12/21/dumping-the-groovy-ast/#comments</comments>
		<pubDate>Fri, 21 Dec 2012 12:46:22 +0000</pubDate>
		<dc:creator>andresteingress</dc:creator>
				<category><![CDATA[ast transformations]]></category>
		<category><![CDATA[groovy]]></category>

		<guid isPermaLink="false">http://blog.andresteingress.com/?p=2307</guid>
		<description><![CDATA[Lately I had a strange bug in a project-specific AST transformation that caused me to look for ways to directly use the Groovy AST browser from within the affected components. Printing the AST tree I came accross this posting [0] &#8230; <a href="http://blog.andresteingress.com/2012/12/21/dumping-the-groovy-ast/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Lately I had a strange bug in a project-specific AST transformation that caused me to look for ways to directly use the Groovy AST browser from within the affected components. </p>
<h3>Printing the AST tree</h3>
<p>I came accross this posting [<a href="http://groovy.329449.n5.nabble.com/AST-Browser-from-code-td4419006.html">0</a>] by Cédric Champeau, himself one of the Groovy core comitters. In the mailing list Hamlet D&#8217;Arcy pointed to <tt>AstNodeToScriptAdapter</tt> [<a href="http://svn.codehaus.org/groovy/trunk/groovy/groovy-core/src/main/groovy/inspect/swingui/AstNodeToScriptAdapter.groovy">1</a>], a class utilized by the AST browser to compile Groovy code to a given compile phase and decompile the result back to Groovy code.</p>
<p>One way to add logging the AST tree to the console with this class would be to introduce a compilation customizer [<a href="http://groovy.codehaus.org/api/org/codehaus/groovy/control/customizers/CompilationCustomizer.html">2</a>] and simply pass the current <tt>ClassNode</tt> instance to the script adapter:</p>
<pre class="brush: groovy; title: ; notranslate">

class LoggingCompilationCustomizer extends CompilationCustomizer {

  final PrintStream out

  LoggingCompilationCustomizer(CompilePhase compilePhase, PrintStream out) {
    super(compilePhase)
    this.out = out
  }

  void call(SourceUnit source, GeneratorContext context, ClassNode classNode) throws CompilationFailedException {

    StringWriter writer = new StringWriter()
    new AstNodeToScriptVisitor(writer).visitClass(classNode)

    out.println writer
  }
}
</pre>
<p>Once the customizer is defined it can be used by registering it with a <tt>GroovyShell</tt> object:</p>
<pre class="brush: groovy; title: ; notranslate">

def config = new CompilerConfiguration()
config.addCompilationCustomizers(new LoggingCompilationCustomizer(CompilePhase.SEMANTIC_ANALYSIS, System.out))

shell = new GroovyShell(config)
</pre>
<h3>Conclusion</h3>
<p>The <tt>AstNodeToScriptVisitor</tt> is a class used by the Groovy AST browser to render Groovy code from a specific compile phase. When debugging AST transformations it can sometimes be an advantage to dump the actual AST source code to immediately see AST issues.</p>
<p>[0] <a href="http://groovy.329449.n5.nabble.com/AST-Browser-from-code-td4419006.html">Nabble: AST browser from code</a><br />
[1] <a href="http://svn.codehaus.org/groovy/trunk/groovy/groovy-core/src/main/groovy/inspect/swingui/AstNodeToScriptAdapter.groovy">groovy.inspect.swingui.AstNodeToScriptAdapter</a><br />
[2] <a href="http://groovy.codehaus.org/api/org/codehaus/groovy/control/customizers/CompilationCustomizer.html">org.codehaus.groovy.control.customizers.CompilationCustomizer</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.andresteingress.com/2012/12/21/dumping-the-groovy-ast/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>GVM &#8211; the Groovy enVironment Manager</title>
		<link>http://blog.andresteingress.com/2012/12/14/gvm-the-groovy-environment-manager/</link>
		<comments>http://blog.andresteingress.com/2012/12/14/gvm-the-groovy-environment-manager/#comments</comments>
		<pubDate>Fri, 14 Dec 2012 20:11:02 +0000</pubDate>
		<dc:creator>andresteingress</dc:creator>
				<category><![CDATA[groovy]]></category>

		<guid isPermaLink="false">http://blog.andresteingress.com/?p=2293</guid>
		<description><![CDATA[Marco Vermeulen [0] created a new tool that supports in keeping track and switching between different versions of Groovy(-influenced) software development kits: GVM [1]. At the time of writing, GVM namely supports Groovy, Grails, Griffon, Gradle and Vert.x. GVM itself &#8230; <a href="http://blog.andresteingress.com/2012/12/14/gvm-the-groovy-environment-manager/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Marco Vermeulen [<a href="https://twitter.com/marcoVermeulen">0</a>] created a new tool that supports in keeping track and switching between different versions of Groovy(-influenced) software development kits: <strong>GVM</strong> [<a href="http://gvmtool.net">1</a>]. </p>
<p>At the time of writing, GVM namely supports Groovy, Grails, Griffon, Gradle and Vert.x. GVM itself is a command-line tool based on the Bash shell, depending on <tt>curl</tt> and <tt>unzip</tt> to be pre-installed on target systems only.</p>
<h3>Get it while its hot</h3>
<p>The installation is actually a single <tt>curl</tt> command-line call. Open your command-line and type the following line:</p>
<pre class="brush: plain; title: ; notranslate">
curl -s get.gvmtool.net | bash
</pre>
<p>the following output should indicate a successful installation</p>
<pre class="brush: plain; title: ; notranslate">
Thanks for using                                                     

_____/\\\\\\\\\\\\__/\\\________/\\\__/\\\\____________/\\\\_
 ___/\\\//////////__\/\\\_______\/\\\_\/\\\\\\________/\\\\\\_
  __/\\\_____________\//\\\______/\\\__\/\\\//\\\____/\\\//\\\_
   _\/\\\____/\\\\\\\__\//\\\____/\\\___\/\\\\///\\\/\\\/_\/\\\_
    _\/\\\___\/////\\\___\//\\\__/\\\____\/\\\__\///\\\/___\/\\\_
     _\/\\\_______\/\\\____\//\\\/\\\_____\/\\\____\///_____\/\\\_
      _\/\\\_______\/\\\_____\//\\\\\______\/\\\_____________\/\\\_
       _\//\\\\\\\\\\\\/_______\//\\\_______\/\\\_____________\/\\\_
        __\////////////__________\///________\///______________\///__

                                       Will now attempt installing...

Looking for a previous installation of GVM...
Looking for JAVA_HOME...
Validating JAVA_HOME...
Looking for unzip...
Looking for curl...
Installing gvm scripts...
Creating candidate directories...
Attempting to update bash profile...
All done!
</pre>
<p>Once this is done and you restart the terminal, the <tt>gvm</tt> script should be available in your path.</p>
<h3>Installing and Switching Between Multiple Groovy Versions (<= awesome)</h3>
<p>Once the <tt>gvm</tt> command is available, we can call <tt>gvm help</tt> to see an overview of the supported commands and arguments:</p>
<pre class="brush: plain; title: ; notranslate">
Usage: gvm &lt;command&gt; &lt;candidate&gt; [version]

   command    :  install, uninstall, list, use, current, version, default, selfupdate, broadcast or help
   candidate  :  groovy, grails, griffon, gradle, vert.x
   version    :  optional, defaults to latest stable if not provided
</pre>
<p>Now let&#8217;s say we wanted to install multiple Groovy versions. With GVM this ain&#8217;t no rocket science anymore. To install the most current version of Groovy (or one of the other supported software kits), you have to execute</p>
<pre class="brush: plain; title: ; notranslate">
gvm install groovy

Downloading: groovy 2.0.5

[...]

Installing: groovy 2.0.5
Done installing!

Do you want to use groovy 2.0.5 now? (Y/n): Y

groovy -version
Groovy Version: 2.0.5 JVM: 1.6.0_37 Vendor: Apple Inc. OS: Mac OS X
</pre>
<p>To install another version of the Groovy programming language, we just have to append the appropriate version number:</p>
<pre class="brush: plain; title: ; notranslate">
gvm install groovy 1.8.8
</pre>
<p>And now comes the crux: switching between Groovy, Grails, Griffon, Gradle or Vert.x versions is done with a single line in the command-line:</p>
<pre class="brush: plain; title: ; notranslate">
gvm use groovy 1.8.8

groovy -version
Groovy Version: 1.8.8 JVM: 1.6.0_37 Vendor: Apple Inc. OS: Mac OS X
</pre>
<h3>Conclusion</h3>
<p>Switching between different development branches with different framework versions (e.g. of Grails) has been with some pain until now. GVM as a great tool for easily keeping track of and switching between multiple software kit versions.</p>
<p>[0] <a href="https://twitter.com/marcoVermeulen">Marco Vermeulen @ Twitter</a><br />
[1] <a href="http://gvmtool.net">GVM &#8211; Project Homepage</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.andresteingress.com/2012/12/14/gvm-the-groovy-environment-manager/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

<!-- Dynamic page generated in 0.640 seconds. -->
<!-- Cached page generated by WP-Super-Cache on 2013-05-22 09:57:03 -->

<!-- Compression = gzip -->