<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Groovy Landscape</title>
	<atom:link href="http://groovyland.wordpress.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://groovyland.wordpress.com</link>
	<description>All you want to know about Groovy, Grails and modern programming</description>
	<lastBuildDate>Wed, 17 Jun 2009 06:07:33 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='groovyland.wordpress.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Groovy Landscape</title>
		<link>http://groovyland.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://groovyland.wordpress.com/osd.xml" title="Groovy Landscape" />
	<atom:link rel='hub' href='http://groovyland.wordpress.com/?pushpress=hub'/>
		<item>
		<title>Google Wave Tips: catching robot exceptions</title>
		<link>http://groovyland.wordpress.com/2009/06/17/google-wave-tips-catching-robot-exceptions/</link>
		<comments>http://groovyland.wordpress.com/2009/06/17/google-wave-tips-catching-robot-exceptions/#comments</comments>
		<pubDate>Wed, 17 Jun 2009 06:07:33 +0000</pubDate>
		<dc:creator>groovyland</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://groovyland.wordpress.com/?p=38</guid>
		<description><![CDATA[Almost trivial code, which I found very useful debugging my robots public void processEvents(RobotMessageBundle bundle) { try { processEventsInternal(bundle); } catch (Throwable t) { final StringWriter stringWriter = new StringWriter(); t.printStackTrace(new PrintWriter(stringWriter)); bundle.getWavelet().getRootBlip().getDocument().append(stringWriter.getBuffer().toString()); } }<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=groovyland.wordpress.com&#038;blog=1197720&#038;post=38&#038;subd=groovyland&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Almost trivial code, which I found very useful debugging my robots</p>
<pre><strong>public void processEvents(RobotMessageBundle bundle) {
   try {
      processEventsInternal(bundle);
   }
   catch (Throwable t) {
      final StringWriter stringWriter = new StringWriter();
      t.printStackTrace(new PrintWriter(stringWriter));
      bundle.getWavelet().getRootBlip().getDocument().append(stringWriter.getBuffer().toString());
   }
}</strong></pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/groovyland.wordpress.com/38/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/groovyland.wordpress.com/38/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=groovyland.wordpress.com&#038;blog=1197720&#038;post=38&#038;subd=groovyland&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://groovyland.wordpress.com/2009/06/17/google-wave-tips-catching-robot-exceptions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cfd952707ed6ccf42f822f91e359c582?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">groovyland</media:title>
		</media:content>
	</item>
		<item>
		<title>Groovy+Scala+Java</title>
		<link>http://groovyland.wordpress.com/2009/03/03/groovyscalajava/</link>
		<comments>http://groovyland.wordpress.com/2009/03/03/groovyscalajava/#comments</comments>
		<pubDate>Tue, 03 Mar 2009 06:33:11 +0000</pubDate>
		<dc:creator>groovyland</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://groovyland.wordpress.com/2009/03/03/groovyscalajava/</guid>
		<description><![CDATA[Almost to years ago I&#8217;ve invented and then wrote joint compiler for Groovy and Java. The idea was pretty simple &#8211; we do compilation in 3 steps 1) Generate Java stubs from Groovy sources 2) Compile all Java code with generated stubs 3) Compile Groovy code with already compiled Java classes First implementation was done [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=groovyland.wordpress.com&#038;blog=1197720&#038;post=37&#038;subd=groovyland&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Almost to years ago I&#8217;ve invented and then wrote joint compiler for Groovy and Java. The idea was pretty simple &#8211; we do compilation in 3 steps<br />
1) Generate Java stubs from Groovy sources<br />
2) Compile all Java code with generated stubs<br />
3) Compile Groovy code with already compiled Java classes</p>
<p>First implementation was done as part of IntelliJ and later another one was written to contribute in Groovy compiler infrastructure. Thanks a lot to Jochen and other guys who improved and incorporated it in to groovyc and ant tasks. It became probably last cornerstone for 100% interoperability between Groovy and Java and now understood by everybody as natural as if it was in Groovy from day one.</p>
<p>But now my arsenal includes Scala as well. Obviously I want to have Groovy and Scala and of course Java together. Isn&#8217;t it natural wish?</p>
<p>Fortunately scala compiler is smart as well and knows how to do joint compilation with Java. Scala does it a bit differently than Groovy &#8211; by parsing Java source during Java compilation. So the process looks like following<br />
1) Compile Scala code using Java sources on the way<br />
2) Compile Java sources using already compiled scala classes</p>
<p>Unfortunally (but not surprisingly) scala has no clue about Groovy.</p>
<p>Today I realized that the small modification of my original algorythm + scala compiler can create joint compiler for all three languages together. The complete algorithm is following<br />
1) Generate Java stubs from Groovy sources<br />
2) Compile Scala code using Java sources and generated stubs on the way<br />
3) Compile all Java code with generated stubs and compiled Scala classes<br />
4) Compile Groovy code with already compiled Java classes</p>
<p>I believe you will not be surprised that when I knew what I want to do it was pretty easy to implement. In fact it was mostly refactoring of what we did before. So now in my working copy I can compile Groovy+Java+Scala together. Of course all references in all three languages are resolved correctly in all possible direction.</p>
<p>I think it opens many amazing opportunities of Groovy becoming orchestration language for people who needs both static and dynamic typing plus functional programming. Of course I would like to see it as part of Groovy Core.</p>
<p>I would like to learn what other people think about it. Please let me know.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/groovyland.wordpress.com/37/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/groovyland.wordpress.com/37/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=groovyland.wordpress.com&#038;blog=1197720&#038;post=37&#038;subd=groovyland&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://groovyland.wordpress.com/2009/03/03/groovyscalajava/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cfd952707ed6ccf42f822f91e359c582?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">groovyland</media:title>
		</media:content>
	</item>
		<item>
		<title>GroovyGrid DSL poll: what is right way to implement branching control structures in Groovy</title>
		<link>http://groovyland.wordpress.com/2008/12/12/groovygrid-dsl-poll-what-is-right-way-to-implement-brunching-control-structures-in-groovy/</link>
		<comments>http://groovyland.wordpress.com/2008/12/12/groovygrid-dsl-poll-what-is-right-way-to-implement-brunching-control-structures-in-groovy/#comments</comments>
		<pubDate>Fri, 12 Dec 2008 11:35:11 +0000</pubDate>
		<dc:creator>groovyland</dc:creator>
				<category><![CDATA[Grid]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[How-To]]></category>
		<category><![CDATA[Methodology]]></category>
		<category><![CDATA[Add new tag]]></category>

		<guid isPermaLink="false">http://groovyland.wordpress.com/?p=30</guid>
		<description><![CDATA[It is well-known that you can&#8217;t implement if/else type control structure in Java. Another useful example of such control structure is continuations. It is much less know that you can implement such kind of structure in Groovy. In this short article I will show several options how it can be done. Our use case will [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=groovyland.wordpress.com&#038;blog=1197720&#038;post=30&#038;subd=groovyland&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>It is well-known that you can&#8217;t implement if/else type control structure in Java. Another useful example of such control structure is continuations. It is much less know that you can implement such kind of structure in Groovy. In this short article I will show several options how it can be done. Our use case will be the same: check point definition for GroovyGrid. The main quesion of the post is which option is better from readability point of view. I will appreciate any comments from Groovy user, which way do they prefer.</p>
<h2>Usecase</h2>
<p>GroovyGrid is Groovy DSK for <a href="http://gridgain.com" target="_blank">GridGain framework</a>. I develop GroovyGrid with idea to simplify coding of grid applications using Groovy instead of Java. Our use case for this article will be checkpoint definition.</p>
<p>So what is checkpoint? Checkpoint is possibility for extensive computing jobs can save their intermidiate state, so if job failed and was started by GridGain again it can continue not from scratch but using previously save state. In general logic of such job looks like following pseudo-code<br />
<em> </em></p>
<pre><em><span style="color:#800000;"><strong>Check if saved state exist
If it doesn't
     Execute first part of the job
     Save result of first part on checkpoint
Execute second part of job using either loaded or calculated result of first part</strong></span>
</em></pre>
<p>Now we are redy to start with implementation options</p>
<h2>Option I: Closure after closure</h2>
<p>We can use following syntax</p>
<pre><span style="color:#800000;"><strong>checkPoint ("checkpoint") {
     // first part calculation
}
{ state -&gt;
    // second part calculation
}</strong></span></pre>
<p>As you can see we put two closures one after another without any syntactical indication of connection between closures. Fortunately for us Groovy parser understand such construction as call of &#8216;checkpoint&#8217; method with one parameter of type String and two parameters of type closure. So our implementation of &#8216;checkPoint&#8217; method is pretty trivial (avoiding of course exception handling and such)</p>
<pre><strong><span style="color:#800000;">def checkPoint(String name, Closure before, Closure after) {
    Serializable state = gridTaskSession.loadCheckpoint(name)
    if (state == null) {
       state = before ()
       gridTaskSession.saveCheckpoint("checkpoint", state)
    }
    after(state)
}</span></strong></pre>
<p>What I like in this option is that it is extremly simple in implementation and very straight forward. Important to note here that if we want to use several checkpoints it is very easy to nest it.</p>
<pre><strong><span style="color:#800000;">checkPoint("state2") {
    checkPoint("state1") {
        // step1
     }
     { state1 -&gt;
       // step2
     }
}
{ state2 -&gt;
   // step3
}</span></strong></pre>
<h2>Option II: Control object</h2>
<p>What I don&#8217;t like in Option I is the fact that closure are not &#8216;visually&#8217; connected in the code. So here are improved syntax</p>
<pre><span style="color:#800000;"><strong>checkPoint ("checkpoint") {
    // first part calculation
}.andContinue { state -&gt;
    // second part calculation
}
</strong></span></pre>
<p>What we gain is &#8216;andContinue&#8217;, which probably improves readability. What we complicate is implementation &#8211; now &#8216;checkPoint&#8217; method returns not value but control object to be called to complete the calculation</p>
<pre><span style="color:#800000;"><strong>def checkPoint(String name, Closure before) {
    [
      andContinue : { Closure after -&gt;
          Serializable state = gridTaskSession.loadCheckpoint(name)
          if (state == null) {
              state = before ()
              gridTaskSession.saveCheckpoint("checkpoint", state)
          }

          after (state)
      }
    ]
}
</strong></span></pre>
<p>There is nice trick we can use to variate the same idea &#8211; use &#8216;rightShift&#8217; of &#8216;rightShiftUnsigned&#8217; name instead of &#8216;andContinue&#8217; It allows us to write code like this (&#8216;rightShiftUnsigned&#8217; case)</p>
<pre><span style="color:#800000;"><strong>checkPoint ("checkpoint") {
    // first part calculation
}  &gt;&gt;&gt; { state -&gt;
    // second part calculation
}
</strong></span></pre>
<p>Again nesting is pretty simple</p>
<pre><strong><span style="color:#800000;">checkPoint("state2") {
    checkPoint("state1") {
        // step1
     } &gt;&gt;&gt; { state1 -&gt;
       // step2
     }
} &gt;&gt;&gt; { state2 -&gt;
   // step3
}</span></strong></pre>
<h2>Option III: No after-brunch at all</h2>
<p>Careful reader might notice for our particular use case special syntax for &#8216;after brunch&#8217; is not necessary because we will always execute it. So we can simply write</p>
<pre><span style="color:#800000;"><strong><strong><strong><strong>def state = checkPoint ("checkpoint") {
    // first part calculation
}
// second part calculation</strong></strong></strong></strong></span></pre>
<p>There main reason I consider other options here is because the article is more about methodology and not about particular use case. For example, in case if we want to execute first part asynchronously on grid or thread pool and and continue with second part only after first one completed (of course without waiting) the current option will not work at all.</p>
<p>Anyway for completeness here is implementation</p>
<pre><strong><span style="color:#800000;">def checkPoint(String name, Closure before) {
    Serializable state = gridTaskSession.loadCheckpoint(name)
    if (state == null) {
       state = before ()
       gridTaskSession.saveCheckpoint("checkpoint", state)
    }
    state
}</span></strong><span style="color:#800000;"><strong><strong>
</strong></strong></span></pre>
<h2>Main questions</h2>
<ol>
<li>Which option do you prefer?</li>
<li>What are other options?</li>
</ol>
<p>Please let me know and Enjoy Groovy!</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/groovyland.wordpress.com/30/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/groovyland.wordpress.com/30/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=groovyland.wordpress.com&#038;blog=1197720&#038;post=30&#038;subd=groovyland&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://groovyland.wordpress.com/2008/12/12/groovygrid-dsl-poll-what-is-right-way-to-implement-brunching-control-structures-in-groovy/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cfd952707ed6ccf42f822f91e359c582?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">groovyland</media:title>
		</media:content>
	</item>
		<item>
		<title>GroovyGrid: grid computing with Groovy and GridGain</title>
		<link>http://groovyland.wordpress.com/2008/12/09/groovygrid-grid-computing-with-groovy-and-gridgain/</link>
		<comments>http://groovyland.wordpress.com/2008/12/09/groovygrid-grid-computing-with-groovy-and-gridgain/#comments</comments>
		<pubDate>Tue, 09 Dec 2008 16:19:49 +0000</pubDate>
		<dc:creator>groovyland</dc:creator>
				<category><![CDATA[Grid]]></category>
		<category><![CDATA[Groovy]]></category>
		<category><![CDATA[How-To]]></category>
		<category><![CDATA[Methodology]]></category>

		<guid isPermaLink="false">http://groovyland.wordpress.com/?p=24</guid>
		<description><![CDATA[Grid computing is complicated field. Even with perfect GridGain framework, which helps a lot in developing and testing distributed applications, it still require writing some auxilary Java code, which mostly serves framework itself and not application logic (like defining classes for tasks and jobs). Today I want to talk a bit about small Groovy DSL [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=groovyland.wordpress.com&#038;blog=1197720&#038;post=24&#038;subd=groovyland&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Grid computing is complicated field. Even with perfect <a href="http://gridgain.com" target="_blank">GridGain framework</a>, which helps a lot in developing and testing distributed applications, it still require writing some auxilary Java code, which mostly serves framework itself and not application logic (like defining classes for tasks and jobs). Today I want to talk a bit about small Groovy DSL for GridGain, which I develop with purpose to simplify the story.</p>
<p>It is important to notice that GroovyGrid is still to be experimental project and one of the main purposes of this post is to collect opinions if it can be useful for other people.</p>
<p>The task we gonna solve is pretty standard &#8211; given directory (let us assume on shared file system) and we want to calculate how many times each character occurs in all Groovy and Java source files recursively. Solution of this problem should help us to see GroovyGrid in action.</p>
<p>For purpose of this post I wrote trivial Groovy class, which will help us to accumulate statistics. It is a bit lengthy but in reality everything it does is definition of several &#8216;leftShift&#8217; methods, which allow us write something like <strong>statistic &lt;&lt; data</strong>, where <strong>data</strong> can be list of files, or file, or String or char or even another statistic accumulator. You can easily skip following code.</p>
<pre><span style="color:#800000;"><strong>class CharStatisticAccumulator extends HashMap {
    private CharStatisticAccumulator add (char ch, counter = 1) {
        if (!this[ch])
          this [ch]  = counter
        else
          this [ch] += counter
        this
    }

    CharStatisticAccumulator leftShift (char ch) {
        add ch
    }

    CharStatisticAccumulator leftShift (Map.Entry e) {
        add e.key, e.value
    }

    CharStatisticAccumulator leftShift (Collection coll) {
        coll.each {
            this &lt;&lt; it
        }
        this
    }

    CharStatisticAccumulator leftShift (String line) {
        this &lt;&lt; Arrays.asList(line.chars)
    }

    CharStatisticAccumulator leftShift (File file) {
        file.eachLine {
            this &lt;&lt; it
        }
        this
    }

    CharStatisticAccumulator leftShift (CharStatisticAccumulator statistic) {
        this &lt;&lt; statistic.entrySet ()
    }
}</strong></span></pre>
<p>Now we are back to our main task of calculation statistic. Standard map/reduce approach nicely implemented by GridGain advice us how to do it:<br />
1) split files by groups</p>
<p>2) assign calculation of statistic for each group as job to different grid nodes</p>
<p>3) combine results calculated by all jobs in to final statistic.</p>
<p>Here is final code for calculation of our statistic. It is richly commented and I hope self-explaining. I am not trying to be lazy here but found that commented code probably the best way to demonstrate what&#8217;s going on.</p>
<pre><span style="color:#800000;"><strong>    <span style="color:#000080;">/**
     * Recursively calculates number of character usage in
     * .java and .groovy files of given directory
     */</span>
    static def calculateCharStatistic (File dir) {

        <span style="color:#000080;">// In GridGain each task consist of one or several jobs.
        // Two main operations of task
        // - map - which split task to jobs and assigned jobs to grid nodes
        // - reduce - which combains result of jobs to result of task
        //
        // In GroovyGrid body of closure solves both task.
        // It will be called in 'map' method </span></strong></span><span style="color:#800000;"><strong><span style="color:#000080;"> with both purposes</span></strong></span><span style="color:#800000;"><strong><span style="color:#000080;">
        // of creating jobs and define useful callbacks
        // like 'reduce', 'onJobResult' etc.</span>
        GroovyGrid.mapReduce {

            <span style="color:#000080;">// recursively collect all .java and .groovy files
            // it is usual Groovy and has nothing to do with grid computing
</span>            def files = []
            dir.eachFileRecurse { File innerFile -&gt;
                if (!innerFile.directory
                 &amp;&amp; ( innerFile.name.endsWith(".java")
                   || innerFile.name.endsWith(".groovy"))) {
                    files &lt;&lt; innerFile
                }
            }

            <span style="color:#000080;">// group files in to groups by 64 files
            // again usual Groovy iteration/grouping
</span>            int groupIndex = 0
            Map groups = files.groupBy { (groupIndex++) &gt;&gt; 6 }

            </strong></span>
<span style="color:#800000;"><strong><span style="color:#000080;">            // iterate groups
            </span></strong></span><span style="color:#800000;"><strong>groups.each { groupId, groupFiles -&gt;
               <span style="color:#000080;"> // define grid job for each group
                // It is important to note that closure below will be
                // called not immediately </span></strong></span><span style="color:#800000;"><strong><span style="color:#000080;">but later </span></strong></span><span style="color:#800000;"><strong><span style="color:#000080;">
                // on some (possibly different) grid node.</span>
                def job = job {
                    println "Job $groupId started"
                    CharStatisticAccumulator jobResult
                        = new CharStatisticAccumulator()
                    groupFiles.each { File jobFile -&gt;
                        jobResult &lt;&lt; jobFile
                        println "processed $jobFile.absolutePath"
                    }
                    println "Job $groupId ended"

                    <span style="color:#000080;">// result of job execution</span>
                    jobResult
                }

                <span style="color:#000080;">// Usually it is not necessary to map jobs to grid nodes
                // </span></strong></span><span style="color:#800000;"><strong><span style="color:#000080;">manually </span></strong></span><span style="color:#800000;"><strong><span style="color:#000080;">but if needed it is possible to do
                // by assigning of 'gridNode' property of job
                // 'gridGrid' property of type Grid and
                // 'gridLoadBalancer' of type GridLoadBalancer
                // are injected in each task.
                //
                // In fact, this demostration is only purpose of 'job' variable -
                // you usually don't do it in normal life.
</span>                if (groupId % 5 == 0)
                    job.gridNode = gridGrid.localNode
                else
                    job.gridNode = gridLoadBalancer.getBalancedNode (job)
            }

            <span style="color:#000080;">// here we will collect statistic</span>
            def taskResult = new CharStatisticAccumulator()

            <span style="color:#000080;">// defines callback to be called when result
            // of a job becomes available</span>
            onJobResult { GridJobResult jobResult
                      /*, List&lt;GroovyJobResult&gt; receivedBefore */ -&gt;
                <span style="color:#000080;">// Interesting to notice that we are able
                // to access 'groupId' of the job here</span>
                println "Result of job $jobResult.job.groupId obtained"

                <span style="color:#000080;">// normally GridGain process all partial results in 'reduce' method
                // It is possible with GroovyGrid as well but here
                // for demonstration purposes we do differently -
                // partial result added immediately in to result statistic</span>
                taskResult &lt;&lt; jobResult.data

                <span style="color:#000080;">// as we don't need result of the job anymore we can forget it</span>
                jobResult.data = null
            }

            <span style="color:#000080;">// defines callback to be called to calculate task result
            // after results of all jobs became available</span>
            reduce { List&lt;GridJobResult&gt; results -&gt;
                <span style="color:#000080;">// Let us print IDs of all jobs to make sure
                // that we've calculated everything
                // Of course, here we are also able to access 'groupId' of the job</span>
                println results*.job*.groupId.sort ()

                <span style="color:#000080;">// result of task calculation</span>
                taskResult
            }

</strong></span><span style="color:#800000;"><strong><strong>            <span style="color:#000080;">// defines callback to be called when task finished
</span></strong></strong></span><span style="color:#800000;"><strong>            onTaskFinished { GridTaskFuture future -&gt;
                println "Task completed"
            }
        }
    }
</strong></span></pre>
<p>I will appreciate comments and advices from everybody &#8211; especially from people familiar with both Groovy and GridGain.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/groovyland.wordpress.com/24/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/groovyland.wordpress.com/24/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=groovyland.wordpress.com&#038;blog=1197720&#038;post=24&#038;subd=groovyland&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://groovyland.wordpress.com/2008/12/09/groovygrid-grid-computing-with-groovy-and-gridgain/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cfd952707ed6ccf42f822f91e359c582?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">groovyland</media:title>
		</media:content>
	</item>
		<item>
		<title>Groovy dynamic stateful mixins</title>
		<link>http://groovyland.wordpress.com/2008/07/09/groovy-dynamic-stateful-mixins/</link>
		<comments>http://groovyland.wordpress.com/2008/07/09/groovy-dynamic-stateful-mixins/#comments</comments>
		<pubDate>Wed, 09 Jul 2008 13:04:38 +0000</pubDate>
		<dc:creator>groovyland</dc:creator>
				<category><![CDATA[Groovy]]></category>
		<category><![CDATA[How-To]]></category>

		<guid isPermaLink="false">http://groovyland.wordpress.com/?p=18</guid>
		<description><![CDATA[My last post was dedicated to Groovy dynamic stateless mixins. Today I want to talk about stateful ones, which are now presented in Groovy trunk. The main difference is obvious &#8211; additionally to providing new method stateful mixins can also keep state. Here is non-trivial sample. First of all let us use EMC to add [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=groovyland.wordpress.com&#038;blog=1197720&#038;post=18&#038;subd=groovyland&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>My last post was dedicated to <a href="http://groovyland.wordpress.com/2008/06/07/groovy-dynamic-stateless-mixins/">Groovy dynamic stateless mixins</a>. Today I want to talk about <em>stateful</em> ones, which are now presented in Groovy trunk.<br />
The main difference is obvious &#8211; additionally to providing new method stateful mixins can also keep state.</p>
<p>Here is non-trivial sample. First of all let us use EMC to add convinient method to JDK class ReentrantLock.</p>
<pre style="padding-left:30px;"><strong><span style="color:#993300;">ReentrantLock.metaClass {
  withLock { Closure operation -&gt;
     lock ()
     try {
        operation ()
     }
     finally {
       unlock ()
     }
  }
}</span>
</strong></pre>
<p>Now we are able to implement Groovy ConcurrentQueue like this</p>
<pre style="padding-left:30px;"><strong><span style="color:#993300;">
class ConcurrentQueue {
   private LinkedList list = new LinkedList ()
   private ReentrantLock lock = new ReentrantLock ()

   def get () {
      lock.withLock () {
        list.removeFirst ()
      }
   }

   void put (def obj) {
      lock.withLock () {
         list.addLast (obj)
      }
   }
}
</span>
</strong></pre>
<p>So far, we didn&#8217;t use any mixins. Let us rewrite last sample using ones</p>
<pre style="padding-left:30px;"><strong><span style="color:#993300;">
class ConcurrentQueue {
   static {
     ConcurrentQueue.metaClass.mixin LinkedList, ReentrantLock
   }

   def get () {
      withLock {
        removeFirst ()
      }
   }

   void put (def obj) {
      withLock {
         addLast (obj)
      }
   }
}
</span>
</strong></pre>
<p>What we did is we replace private fields with mixins, which we assign in static initialization of the class. Of course, this sample is a little bit artificial because what we do is emulating compile time mixins with static initializer. I will discuss compile time mixins separately but now let us modify our sample to be more dynamic.</p>
<pre><strong><span style="color:#993300;">
        def queue = new Object ()
        queue.metaClass {
            mixin LinkedList, ReentrantLock

            get { -&gt;
               withLock {
                 removeFirst ()
               }
            }

            put { obj -&gt;
               withLock {
                  addLast (obj)
               }
            }
        }
</span>
</strong></pre>
<p>Instead of creating special class for our concurrent queue we use combination of mixin and per instance meta class to create what we need. Isn&#8217;t it lovely?</p>
<p>Now you may wish to ask me several interesting question, which I try to answer below.</p>
<p>How to access instance of mixed-in object if needed? Well, it is very easy. Let us add one more method to implementation of our queue, which will demonstrate how to do that.</p>
<pre><strong><span style="color:#993300;">
        queue.metaClass {
            duplicateEachElement {
               withLock {
                  LinkedList newList = new LinkedList ()
                  <span style="color:#0000ff;"><strong>mixedIn[LinkedList]</strong></span>.each {
                     newList &lt;&lt; it
                     newList &lt;&lt; it
                  }
                  <span style="color:#0000ff;">mixedIn[LinkedList]</span> = newList
               }
            }
        }
</span>
</strong></pre>
<p>How to access owner object from mixed-in instance if needed? This is a little bit more tricky. To understand why is it so we need to understand how mixins are implemented. Obviously, where is no magic here &#8211; mixed in references kept separately from objects in weakly referenced map. It means that if mixed in instance keeps reference to owner, then owner has zero chances to be collected. So in the perfect world mixed in instance should never keep reference for owner. But in pragmatic world it might make sense to do it time to time. Here is example how to do that</p>
<pre><strong><span style="color:#993300;">
class NoDuplicateCollection {
    void put (def obj) {
        def clone = (<span style="color:#0000ff;">mixinOwner as Collection</span>).find {
            it == obj
        }

        if (!clone)
          mixinOwner.add obj
    }
}

def list = new Object ()
list.metaClass.mixin NoDuplicateCollection, LinkedList

list.put 1
list.put 1
list.put 2
list.put 2
list.put 3
list.put 3

assertEquals (3, list.size ())
assertEquals 1, list [0]
assertEquals 2, list [1]
assertEquals 3, list [2]
</span>
</strong></pre>
<p>NoDuplicateCollection class designed to be used with any JDK Collection as owner. In example above we use it with LinkedList but any other Set or List will work as well. Property &#8216;mixinOwner&#8217; is magically (via delegating per instance meta class) inserted in to instance of NoDuplicateCollection and&#8230; Voila! Of course, internally mixedOwner is week reference so it will not prevent owner from being collected.</p>
<p>One more interesting thing to notice is &#8216;as operator&#8217; used to cast our object to Collection. Yes, it is true &#8211; we cast instance of Object to Collection. Again, there is no magic here &#8211; if our object can&#8217;t be casted itself we try mixed-ins. Simple as that.</p>
<p>Enjoy it in the Groovy 1.6 trunk</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/groovyland.wordpress.com/18/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/groovyland.wordpress.com/18/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/groovyland.wordpress.com/18/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/groovyland.wordpress.com/18/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=groovyland.wordpress.com&#038;blog=1197720&#038;post=18&#038;subd=groovyland&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://groovyland.wordpress.com/2008/07/09/groovy-dynamic-stateful-mixins/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cfd952707ed6ccf42f822f91e359c582?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">groovyland</media:title>
		</media:content>
	</item>
		<item>
		<title>Groovy dynamic stateless mixins</title>
		<link>http://groovyland.wordpress.com/2008/06/07/groovy-dynamic-stateless-mixins/</link>
		<comments>http://groovyland.wordpress.com/2008/06/07/groovy-dynamic-stateless-mixins/#comments</comments>
		<pubDate>Sat, 07 Jun 2008 12:26:47 +0000</pubDate>
		<dc:creator>groovyland</dc:creator>
				<category><![CDATA[Groovy]]></category>
		<category><![CDATA[How-To]]></category>
		<category><![CDATA[Opinion]]></category>

		<guid isPermaLink="false">http://groovyland.wordpress.com/?p=17</guid>
		<description><![CDATA[Last week I wrote about per-instance meta-classes and ExpandoMetaClass DSL. At that point it was just prototyped code in my working copy and I was not even sure if it will come to Groovy 1.6 trunk. Now it is there. If you didn&#8217;t read this previous post I recommend to have quick look on it [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=groovyland.wordpress.com&#038;blog=1197720&#038;post=17&#038;subd=groovyland&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Last week I <a href="http://groovyland.wordpress.com/2008/06/02/groovy-per-instance-meta-classes-and-expandometaclass-dsl/" target="_blank">wrote about per-instance meta-classes and ExpandoMetaClass DSL</a>. At that point it was just prototyped code in my working copy and I was not even sure if it will come to Groovy 1.6 trunk. Now it is there. If you didn&#8217;t read this previous post I recommend to have quick look on it as it might help to understand current one.</p>
<p>Today I want to talk about another part of the same commit, which is kind of side-effect of ability to have per-instance meta classes. Now we able to have per instance dynamic stateless mixins.</p>
<p>But let me start we explanation of what is mixin for me.</p>
<blockquote><p>Mixin is either static or dynamic way to extend <em>class</em> or <em>instance</em> behavior by adding methods and/or state defined in another class.</p>
<p><em>Static</em> here means defined at compile time and <em>dynamic</em> means defined on runtime. This two types of mixins are totally different.</p>
<ul>
<li>Static mixins applied to <em>class</em> but dynamic one to <em>meta class</em> (either class one or instance one)</li>
<li>Static mixins always effect hierarchy, dynamic ones may or may not effect it depending on nature of meta class under effect (if meta class is the one associated with the class it does, if not it does not</li>
<li>Static mixins always effect type information, dynamic ones never does that.</li>
</ul>
<p><em>Stateless</em> or <em>stateless</em> mixins means ability of mixins to extend object behavior not only with methods but with state as well. Stateful compile time mixins can be understand as kind of multiple inheritance.</p></blockquote>
<p>Groovy has no compile time mixins yet. I think Groovy has to have something similar to Scala traits but it is subject to different discussion.</p>
<p>Groovy has no stateful mixins yet as well and below I will talk a bit about my idea how they should look like. So main subject for today is <em>dynamic stateless mixins</em></p>
<p>Let me show simple example. First of all we define usual category class, which will be used to mix in.</p>
<pre><span style="color:#993300;"><strong>class DeepFlattenToCategory {
    static Set flattenTo(element) {
        LinkedHashSet set = new LinkedHashSet()
        element.flattenTo(set)
        return set
    }
    // Object - put to result set
    static void flattenTo(element, Set addTo) {
        addTo &lt;
           element.flattenTo(set);
        }
    }
    // Map - flatten each value
    static void flattenTo(Map elements, Set addTo) {
       elements.values().flattenTo(addTo);
    }
    // Array - flatten each element
    static void flattenTo(Object [] elements, Set addTo) {
        elements.each { element -&gt;
           element.flattenTo(set);
        }
    }
}</strong>
</span></pre>
<p>This category does pretty obvious thing &#8211; deep flattening of complex data structure as demonstrated by following code snippet.</p>
<pre><span style="color:#993300;"><strong>
        // mixin Category to meta class
        Object.metaClass.mixin DeepFlattenToCategory
        // and here we are
        assertEquals ([8,9,3,2,1,4], [[8,9] as Object [], [3,2,[2:1,3:4]],[2,3]].flattenTo () as List)
</strong>
</span></pre>
<p>Careful reader may notice probably that we modify only meta class for Object but methods for Collection, Object [] and Map becomes available as well. Such behavior is usual for categories but a bit uncommon for ExpandMetaClass &#8211; in the past he had to call ExpandoMetaClass.enableGlobally () to ask meta classes to look for missed methods. Such approach had several downsides &#8211; to name a few: unnecessary memory footprint for creation ExpandoMetaClass for each class (both modified and non-modified) and lack of &#8220;good place&#8221; where to call ExpandoMetaClass.enableGlobally (). It means that if you developed library, which requires it &#8211; you should call it somewhere, because nobody can guarantee that user application will do that. Fortunately, now ExpandoMetaClass can define methods for sub classes and if sub class missed some method he will try to find it in hierarchy. Obviously such behavior is must for mixins &#8211; otherwise our sample will look much less nicer(which is still to be valid code but creating four ExpandoMetaClasses instead of one)</p>
<pre><span style="color:#993300;"><strong>
        // mixin Category to meta classes
        Object.metaClass.mixin DeepFlattenToCategory
        Collection.metaClass.mixin DeepFlattenToCategory
        Object[].metaClass.mixin DeepFlattenToCategory
        Map.metaClass.mixin DeepFlattenToCategory
        // and here we are
        assertEquals ([8,9,3,2,1,4], [[8,9] as Object [], [3,2,[2:1,3:4]],[2,3]].flattenTo () as List)
</strong>
</span></pre>
<pre><span style="color:#993300;"><strong>
        Object.metaClass.foo(ArrayList){ -&gt; .... }
</strong>
</span></pre>
<p>BTW, ExpandoMetaClass has new syntax to define methods for subclasses</p>
<pre><span style="color:#993300;"><strong>
        Object.metaClass.foo(ArrayList){ -&gt; .... }
</strong>
</span></pre>
<p>OR</p>
<pre><span style="color:#993300;"><strong>
        Object.metaClass {
           foo(ArrayList){ -&gt; .... {
        }
</strong>
</span></pre>
<p>OR</p>
<pre><span style="color:#993300;"><strong>
        Object.metaClass {
           define(ArrayList){
              foo{ -&gt; .... }
           }
        }
</strong>
</span></pre>
<p>OK, back to mixins. So far, it seems very similar to normal categories, so let us make our sample more interesting</p>
<pre><span style="color:#993300;"><strong>
        class NoFlattenArrayListCategory {
           // ArrayList - put to result set
           static void flattenTo(ArrayList element, Set addTo) {
              addTo &lt;&lt; element;
           }
        }

        def x = [2,3]
        x.metaClass.mixin NoFlattenArrayListCategory
        assertEquals ([x, 8,9,3,2,1,4], [x, [8,9] as Object [], [3,2,[2:1,3:4]],[2,3]].flattenTo () as List)
</strong>
</span></pre>
<p>What we do here is create category, which does not flatten array lists and mix it in instance meta class. Voila!<br />
Of course the same can be achieved with ExpandoMetaClass without mixing in category</p>
<pre><span style="color:#993300;"><strong>
        def x = [2,3]
        x.metaClass.flattenTo = { Set addTo -&gt; addTo &lt;&lt; delegate }
        assertEquals ([x, 8,9,3,2,1,4], [x, [8,9] as Object [], [3,2,[2:1,3:4]],[2,3]].flattenTo () as List)
</strong>
</span></pre>
<p>but please remember that category can be easily implemented in Java and provide much better performance compare to closure-based meta methods. And now we can use it as mixins.</p>
<p>The last thing I want to talk about is some features, which is missing and which I would love to see in Groovy. All below is just imagination and I don&#8217;t know exact implementation details and underwater stones but here are problems to be addressed.</p>
<ul>
<li>Stateful mixins</li>
<li>Mixing in objects</li>
<li>Better syntax to define categories in Groovy</li>
<li>Compile time mixins</li>
</ul>
<p>Stateful mixins</p>
<p>Imagine that category class defines not only static methods but also some fields and these fields magically becomes available as properties when we mix these category in. Probably if object already has such properties the one defined by category should be ignored, but if not&#8230; we have extremely powerful tool.</p>
<p>The main technical problem here is that we don&#8217;t want to define these new properties via ExpandoMetaClass, which will be very slow, but if we created instance of category class to associated it with original object&#8230; well, we have no good place to store this association. For Groovy compiled objects we of course can store refernence(s) directly in the object and for Java one in WeakHashMap. But what will happen if this mixed in instance keeps strong reference for original Java object&#8230; It will never be collected. Believe me, it will happen very often. So far I don&#8217;t know any good solution for that.</p>
<p>Mixing in objects</p>
<p>If we had solution for stateful mixin most probably it will lead us to ability to mix in not only category class but any object. I can imagine fantastic possibilities for that.</p>
<p>Better syntax to define categories in Groovy</p>
<p>Well static methods with additional parameter &#8216;self&#8217; are so ugly. We definitely need something better. So far we have @Category annotation, which solves only part of the problem.</p>
<p>Compile time mixin</p>
<p>Having stateful mixins with good syntax to define category methods will lead us to ability mixin category classes on runtime. As result we will have probably the strongest mixin story between all dynamic languages and as powerful as Scala traits in the world of staticly compiled ones.</p>
<p>So it goes.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/groovyland.wordpress.com/17/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/groovyland.wordpress.com/17/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/groovyland.wordpress.com/17/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/groovyland.wordpress.com/17/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=groovyland.wordpress.com&#038;blog=1197720&#038;post=17&#038;subd=groovyland&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://groovyland.wordpress.com/2008/06/07/groovy-dynamic-stateless-mixins/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cfd952707ed6ccf42f822f91e359c582?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">groovyland</media:title>
		</media:content>
	</item>
		<item>
		<title>Groovy per instance meta classes and ExpandoMetaClass DSL</title>
		<link>http://groovyland.wordpress.com/2008/06/02/groovy-per-instance-meta-classes-and-expandometaclass-dsl/</link>
		<comments>http://groovyland.wordpress.com/2008/06/02/groovy-per-instance-meta-classes-and-expandometaclass-dsl/#comments</comments>
		<pubDate>Mon, 02 Jun 2008 11:55:11 +0000</pubDate>
		<dc:creator>groovyland</dc:creator>
				<category><![CDATA[Groovy]]></category>
		<category><![CDATA[How-To]]></category>
		<category><![CDATA[Opinion]]></category>

		<guid isPermaLink="false">http://groovyland.wordpress.com/?p=15</guid>
		<description><![CDATA[So far Groovy allow per instance meta classes only for objects, which implements GroovyObject interface (like any class defined in Groovy). It can be illustrated by following simple test case: // for java.lang.String "test string".metaClass.toString = { "modified string" } assertEquals( "modified string", "test string".toString() ) // but any other string will have the same [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=groovyland.wordpress.com&#038;blog=1197720&#038;post=15&#038;subd=groovyland&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>So far Groovy allow per instance meta classes only for objects, which implements GroovyObject  interface (like any class defined in Groovy). It can be illustrated by following simple test case:</p>
<pre><strong><span style="color:#993300;">   // for java.lang.String
   "test string".metaClass.toString = { "modified string" }
   assertEquals( "modified string", "test string".toString() )
   // but any other string will have the same behavior
   assertEquals( "modified string", "any other string".toString() )</span></strong></pre>
<p>At the same time</p>
<pre><span style="color:#993300;"><strong>   // for GroovyObject
   class MyBean {
      String toString () { "bean" }
   }

   def bean = new MyBean ()
   def emc = new ExpandoMetaClass(MyBean,false,true)
   emc.toString = { -&gt; "modified bean" }
   bean.metaClass = emc
   assertEquals("modified bean", bean.toString())
   // but any other bean will keep default behavior
   assertEquals("bean", new MyBean().toString())
   // if we want to modify behavior of all MyBean objects
   MyBean.metaClass = emc
   assertEquals("modified bean", new MyBean().toString())
</strong></span></pre>
<p>Notice that we use different technique to add methods to Java and Groovy objects. As <em>getMetaClass ()</em> for Java object always returns the same meta class we can use <em>.metaClass</em> notation, each GroovyObject has it is own meta class (of course, it is the same object by default) so we act differently depending on what we want to modify (whole class or just one Object)</p>
<p>Now I have patch which solves all these problems.</p>
<p>First of all we can assigned per instance meta class for any object. Of course, for Java objects it kept in WeakHashMap which involves some performance penalties. But now our first sample looks much more natural</p>
<pre><strong><span style="color:#993300;">   // for java.lang.String
   "test string".metaClass.toString = { "modified string" }
   assertEquals( "modified string", "test string".toString() )
   // but any other string will have natural behavior
   assertEquals( "any other string", "any other string".toString() )</span></strong></pre>
<p>Groovy objects also has benefits &#8211; we don&#8217;t need to create ExpandoMetaClass manually.</p>
<pre><span style="color:#993300;"><strong>
   def bean = new MyBean ()
   bean.metaClass.toString = { -&gt; "modified bean" }
   assertEquals("modified bean", bean.toString())
   // but any other bean will keep default behavior
   assertEquals("bean", new MyBean().toString())
   // if we want to modify behavior of all MyBean objects
   MyBean.metaClass = bean.metaClass
   assertEquals("modified bean", new MyBean().toString())
</strong></span></pre>
<p>But now, when we have unified behavior for Java and Groovy objects we can use simply and powerful ExpandoMetaClass DSL. Here is example</p>
<pre><span style="color:#993300;"><strong>
        // add behavior to meta class for Integer
        Integer.metaClass {
           // block of static methods
           'static' {
                fib { Number n -&gt;
                    n.fib ()
                }
                // we can use both = or &lt;&lt; if needed
                unusedStatic &lt;&lt; { -&gt; }
            }

            // one more syntax for static methods
            static.unusedStatic2 = { -&gt; }

            // property definition
            ZERO = 0

            // method definition
            fib { -&gt;
                def n = delegate
                if (n == ZERO)
                  return 1;
                if (n == 1)
                  return 1
                else
                  return fib(n-1) + fib(n-2)
            }

            // of course we can use both = or &lt;&lt; if needed as well
            unusedMethod &lt;&lt; { -&gt; }
        }
        // and now we have it
        assertEquals( 3, 3.fib())

        // but we can also modify meta class for particular number
        4.metaClass {
            fib { -&gt;
                10
            }
        }

        // and it works!
        assertEquals( 13, Integer.fib(5))
</strong></span></pre>
<p>You know what&#8230; I like it. And thanks a lot for Graeme for inspirations and advices while I worked on that. Hope it will be accepted well and commited to the trunk.</p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/groovyland.wordpress.com/15/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/groovyland.wordpress.com/15/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/groovyland.wordpress.com/15/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/groovyland.wordpress.com/15/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=groovyland.wordpress.com&#038;blog=1197720&#038;post=15&#038;subd=groovyland&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://groovyland.wordpress.com/2008/06/02/groovy-per-instance-meta-classes-and-expandometaclass-dsl/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cfd952707ed6ccf42f822f91e359c582?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">groovyland</media:title>
		</media:content>
	</item>
		<item>
		<title>Groovy testing: 3 lessons from 1 test case</title>
		<link>http://groovyland.wordpress.com/2008/05/25/groovy-testing-3-lessons-from-1-test-case/</link>
		<comments>http://groovyland.wordpress.com/2008/05/25/groovy-testing-3-lessons-from-1-test-case/#comments</comments>
		<pubDate>Sun, 25 May 2008 10:54:16 +0000</pubDate>
		<dc:creator>groovyland</dc:creator>
				<category><![CDATA[Groovy]]></category>
		<category><![CDATA[Methodology]]></category>

		<guid isPermaLink="false">http://groovyland.wordpress.com/?p=14</guid>
		<description><![CDATA[As Groovy Core developer involved in compiler and language runtime I am always worried for broken tests in the trunk. Especially when it happened after my commit. But even if it is not a case I have big problem with broken trunk because to test any of my changes in the local copy I need [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=groovyland.wordpress.com&#038;blog=1197720&#038;post=14&#038;subd=groovyland&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>As Groovy Core developer involved in compiler and language runtime I am always worried for broken tests in the trunk. Especially when it happened after my commit. But even if it is not a case I have big problem with broken trunk because to test any of my changes in the local copy I need to re-run whole Groovy test suite.</p>
<p>So when after update this morning I found that one test is broken I decided to have a look what&#8217;s going on. Especially strange was the fact that test was broken on Windows build server but passed well on Linux one. We had such problem recently, which was probably caused by different default stack size on different VMs and forced me to improve compiler a bit. So I start to look on the test.</p>
<p>It is relatively simple</p>
<pre style="padding-left:30px;"><strong><span style="color:#993300;">class Groovy1759_Bug extends GroovyTestCase {
   void testInterception() {
      def benchmarkInterceptor = new BenchmarkInterceptor()
      def proxy = ProxyMetaClass.getInstance(A.class)
      proxy.setInterceptor(benchmarkInterceptor)
      proxy.use {
         def a = new A()
         a.a()
         a.b()
      }

      def actual = benchmarkInterceptor.statistic()
      def expected = [['b', 2, 0],['ctor', 1, 0],['a', 1, 0]]
      assert expected == actual
   }
}

class A{
   void a(){ b() }
   void b(){}
}</span></strong></pre>
<p>We test BenchmarkInterceptor, which records all calls to different methods and record number of executions and accumulated time spent inside methods. Then we compare actual results with our expectations.</p>
<p>Here is piece of code, which actually does the job:<br />
<code><br />
def actual = benchmarkInterceptor.statistic()<br />
def expected = [['b', 2, 0],['ctor', 1, 0],['a', 1, 0]]<br />
assert expected == actual<br />
</code></p>
<p>But it was failing with following not very helpful message:<br />
<em><span style="color:#993300;">java.lang.AssertionError: Expression: (expected == actual). Values: expected = [[b, 2, 0], [ctor, 1, 0], [a, 1, 0]], actual = [[Ljava.lang.Object;@cc06e0, [Ljava.lang.Object;@d7643a, [Ljava.lang.Object;@f52a1d]</span></em></p>
<p><strong>Lesson 1: If you provide diagnostic try to provide useful one.</strong></p>
<p>I had quick look to compiler and immediately found that instead of call to <em>stringBuffer.append(obj) </em>during generation of assert statement it would be much better better to use <em>stringBuffer.append(InvokerHelper.toString(obj)).</em> Fast check and &#8230; voila! It works and I have much better error message:</p>
<p><span style="color:#993300;"><em>java.lang.AssertionError: Expression: (expected == actual). Values: expected = [[b, 2, 0], [ctor, 1, 0], [a, 1, 0]], actual = [[ctor, 1, 0], [a, 1, 0], [b, 2, 0]]</em></span></p>
<p>OK, content of expected and actual lists are the same but the order of elements is wrong. Fortunately, I had this lesson many times before</p>
<p><strong><span style="color:#000000;">Lesson 2: Never expect any particular order of elements in a hash map. Or either sort or use linked one if you need an order.</span></strong></p>
<p>What hash map one can ask? Really, I had no idea but I could imagine that BenchmarkInterceptor use internal one to record calls. And it is was exactly the case &#8211; method names as keys and list of current time before and after the call as values.<br />
So the fix was almost trivial &#8211; replace HashMap by LinkedHashMap in BenchmarkInterceptor and put expected values in order how calls happen</p>
<p style="padding-left:30px;"><code><strong><span style="color:#993300;"><br />
def expected = [['ctor', 1, 0],['a', 1, 0],['b', 2, 0]]<br />
assert expected == actual</span></strong></code></p>
<p>At that point I run clean build, checked that all tests passed and commited my changes. In fact before commit I also run remote build on TeamCity, where test failure was reported from. In two minutes I had beautiful surprise from build server. Test was failing!</p>
<p>It took me another 5 or 6 local runs tio reproduce failure on my environment. Some time execution time was 1 instead of 0.</p>
<p><strong>Lesson 3: Never expect particular execution time of piece of code</strong></p>
<p>Do I need to explain? Probably not.</p>
<p>Thanks to Groovy here is final code snippet.</p>
<pre><span style="color:#993300;"><strong>      def actual = benchmarkInterceptor.statistic().collect{ [ it[0], it[1] ] }
      def expected = [['ctor', 1],['a', 1],['b', 2]]
      assert expected == actual
</strong>
</span></pre>
<p>And it works much better.</p>
<p><strong>Bonus Lesson: Analize your tests we have a lot to learn from our failures</strong></p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/groovyland.wordpress.com/14/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/groovyland.wordpress.com/14/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/groovyland.wordpress.com/14/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/groovyland.wordpress.com/14/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=groovyland.wordpress.com&#038;blog=1197720&#038;post=14&#038;subd=groovyland&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://groovyland.wordpress.com/2008/05/25/groovy-testing-3-lessons-from-1-test-case/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cfd952707ed6ccf42f822f91e359c582?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">groovyland</media:title>
		</media:content>
	</item>
		<item>
		<title>Grails Trainings in Scandinavia</title>
		<link>http://groovyland.wordpress.com/2008/05/21/grails-trainings-in-scandinavia/</link>
		<comments>http://groovyland.wordpress.com/2008/05/21/grails-trainings-in-scandinavia/#comments</comments>
		<pubDate>Wed, 21 May 2008 12:35:46 +0000</pubDate>
		<dc:creator>groovyland</dc:creator>
				<category><![CDATA[Grails]]></category>
		<category><![CDATA[Groovy]]></category>

		<guid isPermaLink="false">http://groovyland.wordpress.com/?p=13</guid>
		<description><![CDATA[We were asked about that very often and now it happened. G2One, Inc., company behind both Grails and Groovy, and Callista Enterprise AB announce today series of public trainings in Scandinavia. Göteborg 2008-09-08 Stockholm 2008-09-15 Malmö 2008-09-22 This 3 day course covers both Groovy language and Grails framework. After an introduction to the basics of [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=groovyland.wordpress.com&#038;blog=1197720&#038;post=13&#038;subd=groovyland&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>We were asked about that very often and now it happened.</p>
<p><a href="http://www.g2one.com">G2One, Inc.</a>, company behind both Grails and Groovy, and <a href="http://www.callistaenterprise.se/">Callista Enterprise AB</a> announce today series of public trainings in Scandinavia.</p>
<p>Göteborg   2008-09-08<br />
Stockholm 2008-09-15<br />
Malmö      2008-09-22 </p>
<p>This 3 day course covers both Groovy language and Grails framework.  After an introduction to the basics of the Groovy language, Students are taken through a step-by-step lab-driven experience on how to build a solid Grails application learning from the people who created the technology. We will start from basic but will go very deeply.</p>
<p>Full description of course can be found <a href="http://www.callistaenterprise.se/download/18.146c1a30118e9c69ac680005494/GroovyGrails.pdf">here</a></p>
<p>BTW, thanks to our friends from <a href="http://www.jetbrains.com">JetBrains</a> each student will receive free 12 month license for <a href="http://www.jetbrains.com/idea/">IntelliJ IDEA</a></p>
<p>If you are interested to participate in one of these courses please <a href="http://www.callistaenterprise.se/tjanster/utbildningar/agilutvecklingmedgroovyovhgrails.4.146c1a30118e9c69ac680005470.html">register here</a> or email to us on <b>training at g2one dot com</b>. Group discounts and discounts for students coming from non-Scandinavian countries are available, so we have what to talk about <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>And I totally forgot &#8211; many other European and North American locations of trainings will be announced very soon. </p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/groovyland.wordpress.com/13/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/groovyland.wordpress.com/13/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/groovyland.wordpress.com/13/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/groovyland.wordpress.com/13/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=groovyland.wordpress.com&#038;blog=1197720&#038;post=13&#038;subd=groovyland&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://groovyland.wordpress.com/2008/05/21/grails-trainings-in-scandinavia/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cfd952707ed6ccf42f822f91e359c582?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">groovyland</media:title>
		</media:content>
	</item>
		<item>
		<title>TeamCity saved my day</title>
		<link>http://groovyland.wordpress.com/2008/05/17/teamcity-saved-my-day/</link>
		<comments>http://groovyland.wordpress.com/2008/05/17/teamcity-saved-my-day/#comments</comments>
		<pubDate>Sat, 17 May 2008 12:59:16 +0000</pubDate>
		<dc:creator>groovyland</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://groovyland.wordpress.com/?p=12</guid>
		<description><![CDATA[I had crazy problem this morning &#8211; Groovy Core build was failing with StackOverflowException on some Windows configurations but not on Linux or Mac. Unfortunately, it happen after my commit several days ago, so I was somehow responsible for that. I have only Mac. No Linux. No Windows. So my first idea was to ask [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=groovyland.wordpress.com&#038;blog=1197720&#038;post=12&#038;subd=groovyland&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I had crazy problem this morning &#8211; Groovy Core build was failing with StackOverflowException on some Windows configurations but not on Linux or Mac. Unfortunately, it happen after my commit several days ago, so I was somehow responsible for that.</p>
<p>I have only Mac. No Linux. No Windows. So my first idea was to ask someelse to take care for the bug. But you know what&#8230; It is somehow not very professional.</p>
<p>Fortunately, I found very simple solution. TeamCity Remote Build. 45 minutes and 15 builds and problem was located. I even was able to create test case, which also failing on my Mac. Really cool.</p>
<p>Now I have more serious problem &#8211; to understand how to fix it. But it is kind of more regular work. </p>
<br /><img alt="" border="0" src="http://feeds.wordpress.com/1.0/categories/groovyland.wordpress.com/12/" /> <img alt="" border="0" src="http://feeds.wordpress.com/1.0/tags/groovyland.wordpress.com/12/" /> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/groovyland.wordpress.com/12/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/groovyland.wordpress.com/12/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=groovyland.wordpress.com&#038;blog=1197720&#038;post=12&#038;subd=groovyland&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://groovyland.wordpress.com/2008/05/17/teamcity-saved-my-day/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/cfd952707ed6ccf42f822f91e359c582?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">groovyland</media:title>
		</media:content>
	</item>
	</channel>
</rss>
