<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
   <title>Danno Ferrin: ... Speling Errors</title>
   <link rel="alternate" type="text/html" href="http://shemnon.com/speling/" />
   <link rel="self" type="application/atom+xml" href="http://shemnon.com/speling/atom.xml" />
   <id>tag:shemnon.com,2008:/speling//2</id>
   <updated>2008-06-11T05:05:39Z</updated>
   <subtitle>Danno Ferrin&apos;s technical blog on software development, Java, and bad speling.</subtitle>
   <generator uri="http://www.sixapart.com/movabletype/">Movable Type 3.33</generator>
   <icon>http://shemnon.com/speling/favicon.png</icon>
   
<entry>
   <title>More than I wanted to know about groovy.lang.Closure</title>
   <link rel="alternate" type="text/html" href="http://shemnon.com/speling/2008/06/more-than-i-wanted-to-know-abo-1.html" />
   <id>tag:shemnon.com,2008:/speling//2.197</id>
   
   <published>2008-06-11T05:02:14Z</published>
   <updated>2008-06-11T05:05:39Z</updated>
   
   <summary>Mind you, I&apos;m not going to tell you everything there is to know about Groovy&apos;s implementation of Closures. The principal reason being I don&apos;t know that much. For the most part I really like Groovy&apos;s closures, because they just magically...</summary>
   <author>
      <name>Danno Ferrin</name>
      <uri>http://shemnon.com/speling/</uri>
      <email>danno&amp;#46;ferrin&amp;#64;gmail&amp;#46;com</email>
   </author>
   
   
   <content type="html" xml:lang="en" xml:base="http://shemnon.com/speling/">
      <![CDATA[<p>Mind you, I'm not going to tell you everything there is to know about Groovy's implementation of Closures.  The principal reason being I don't know that much.  For the most part I really like Groovy's closures, because they just magically work and I don't have to worry about adding <code>final</code> to externally referenced variables under threat of compilation error.  But there comes a time when making a feature work like magic that you just have to know the details of the magical incantation.</p>
<p>It started out innocently enough, with Andres Almiray coming to me at JavaOne 2008 and suggesting the next great idea for the SwingBuilder: make the bind node work with closures.  Well, at least well behaved closures.  Because sometimes terseness adds more to readability and usability than rigor does.  Consider these two lines, which would you prefer to code and read?</p>
<blockquote><pre>label(text: bind(source:model, sourceProperty:'value'))
label(text: bind {model.value})</pre></blockquote>
<p>Certainly, it should be the second line.  Immediately my head started to churn, and my first impression was 'is there some way we can make AST Transformations do this?'  Because (a) the first beta of 1.6 had just gone out with AST Transformations making it's debut and (b) this seemed like a compile time problem.  But quickly things came screeching to a halt.  You see the problem is that in Groovy all method calls and property references are dynamic.  Meaning that they go through the Meta-Object Protocol (MOP) to dispatch the call or resolve the value of the property.  And the actual methods used to resolve these values can be completely altered at runtime (with the right permissions).  This presents a problem with compile time transformations: how do you safely do a transformation on a symbol that may not mean what you think it means at compile time?  The short answer is you don't.  (The longer answer is deserving of another blog post).</p>
<p>So how can I bind to a somewhat arbitrary closure, one who's meaning isn't fully resolved until runtime?  The answer is to use the same mechanisms the closure uses at runtime to resolve it's values, but make a mockery of it instead.  Err.. I mean.. use the mock object pattern.  This is actually where I started to learn more about the incantations of closures than I intended.</p>
<p>In Groovy, each closure creates a separate type, whose name is a mechanical mangling of the owning type: <code>&lt;Class Name&gt;$_run(_closure&lt;number&gt;)+</code> and each of these types extends groovy.lang.Closure.  However, a closure needs to get some access to the methods and properties of the scope in which it was declared and/or in which it is executed.  To this end, it has an <code>owner</code> field, which is always set to the instance it was created in, and a <code>delegate</code> field which can be set to any old object.  The <code>resolveStrategy</code> property on the closure is then used to determine which of the fields to use and the order to address them in to resolve methods and properties not directly know to the closure.  This was simple enough, since I already exploit that knowledge to get any of the builders to work their magic in the first place.  However, once I got the simple case working, the real magic of closures made itself manifest: lexically scoped variables.  Consider this script:</p>
<blockquote><pre>String bar = "long"
def closure = { [bar.length(), baz.length()] }
bar = "longer than long"
closure.delegate = [bar:"short", baz:"short"]
println closure()
</pre></blockquote> 
<p>What will the result be?  Wait for it.... is it <code>[4, 5]</code>, <code>[5, 5]</code>, or <code>[16, 5]</code>?  The correct answer is, of course the last one.  But how can that be?  In Java with an inner class I would be forced to declare <code>bar</code> final, and remove the third line since I cannot alter it, so in Java the first answer would almost always be true.  But to get the second answer instead of the third one I would have to remove the typedeclaration for <code>bar</code>, and this is the point where I started to see some of the deep magic at work.  Whether or not <code>bar</code> is defined as a free variable or a lexically scoped variable is an essential distinction for a Closure.  Properties are not lexically scoped variables, and lexically scoped variables are not pushed through the MOP for resolution like properties are.  Lexically scoped variables basically have a static meaning, even when used in a closure that may leave scope.  (note: the variables <span class="misspelt">themeselves</span> are not subject to the MOP, but the methods or properties on said variable, those are subject to being MOPed up).</p>
<p>So when Groovy compiles a closure and generates bytecodecode it looks over the lexically scoped variables it can see, and compares it against the symbols that the closure is using.  When it encounters a variable that is used by the closure it does two things, first it adds to the closure an argument in the constructor, a field, and a getter method to access the variable within the class.  Java does this for Inner classes so it is not too shocking.  But the second thing it does, which is simple but powerful, is it wraps all access to the variable in the enclosing scope and in the closure inside of a <code>groovy.lang.Reference</code> object.  The code looks like it may be accessing an Object on the stack, but the compiler alters those calls for you so you are actually accessing the reference object and using get and set to read and write to the variable.  This allows the variable to, in essence, outlive the stack frame it was created in and for other closures to act on the variable in a manner that can be shared across other closures.  Consider this slight alteration...</p>
<blockquote><pre>String bar = "long"
def closure = { [bar.length(), baz.length()] }
bar = "longer than long"
def change = {bar = "Doh" }
change()
closure.delegate = [bar:"short", baz:"short"]
println closure() // [3,4]</pre></blockquote>
<p>Providing an alternate value in the delegate still has no effect, but altering it's value inside another closure does affect it.  Knowing this I could now create a separate instance of the Closure and fully mock it up against both lexically scoped variables and free variables in an equivalent fashion.  The simple act of adding a type to a previously unbound variable will now no longer break things in strange and mysterious ways.  Making things work like magic made me learn more than I ever expected to know about how Groovy implements Closures.</p>]]>
      
   </content>
</entry>
<entry>
   <title>What an excellent idea...</title>
   <link rel="alternate" type="text/html" href="http://shemnon.com/speling/2008/06/what-an-excellent-idea.html" />
   <id>tag:shemnon.com,2008:/speling//2.195</id>
   
   <published>2008-06-04T02:11:14Z</published>
   <updated>2008-06-04T02:17:02Z</updated>
   
   <summary>A dynamic language works great when you have a clearly-defined structure of an application, where you know where everything lives, where everything is, and what everything is around you. For example, with a Rails application, you have a very strict...</summary>
   <author>
      <name>Danno Ferrin</name>
      <uri>http://shemnon.com/speling/</uri>
      <email>danno&amp;#46;ferrin&amp;#64;gmail&amp;#46;com</email>
   </author>
   
   <category term="34" label="Griffon" scheme="http://www.sixapart.com/ns/types#tag" />
   <category term="6" label="groovy" scheme="http://www.sixapart.com/ns/types#tag" />
   
   <content type="html" xml:lang="en" xml:base="http://shemnon.com/speling/">
      <![CDATA[<blockquote>A dynamic language works great when you have a clearly-defined structure of an application, where you know where everything lives, where everything is, and what everything is around you. For example, with a Rails application, you have a very strict structure: You have controllers and views and models, and so on. It's all very uniform. You can easily jump into any place of the application and understand what's around you: Here comes the model, and here's the data from the Web request, and so on. That's easy to figure out. [Dmitry Jemerov via <a href="http://www.artima.com/lejava/articles/javaone_2008_dmitry_jemerov.html">Artima</a>]</blockquote>
<p>...hmmmmm.  <a href="http://svn.codehaus.org/groovy/trunk/groovy/modules/griffon/samples/Greet/">What an excellent idea.</a>  Smithers... the hounds are sleeping?  Then release the Falcons!  err, actually release the Cougars...  wait.  Hawks, Cougars, Hawks, Cougars.  Meh.  Release <a href="http://docs.codehaus.org/display/GROOVY/griffon">Both!</a></p>]]>
      
   </content>
</entry>
<entry>
   <title>Greet - A Groovy Twitter Client</title>
   <link rel="alternate" type="text/html" href="http://shemnon.com/speling/2008/05/greet-a-groovy-twitter-client.html" />
   <id>tag:shemnon.com,2008:/speling//2.194</id>
   
   <published>2008-05-13T15:40:06Z</published>
   <updated>2008-05-13T16:50:44Z</updated>
   
   <summary>The demo application from the Groovy SwingBuilder Tech Session at JavaOne 2008 is now runnable via WebStart. (note to self, link to SDN site when the presentaiton goes live). The source code may also be browsed via FishEye. There are...</summary>
   <author>
      <name>Danno Ferrin</name>
      <uri>http://shemnon.com/speling/</uri>
      <email>danno&amp;#46;ferrin&amp;#64;gmail&amp;#46;com</email>
   </author>
   
   
   <content type="html" xml:lang="en" xml:base="http://shemnon.com/speling/">
      <![CDATA[<p>The demo application from the Groovy SwingBuilder Tech Session at JavaOne 2008 is now runnable via <a href="http://docs.codehaus.org/download/attachments/35422231/greet.jnlp">WebStart</a>. (note to self, link to SDN site when the <span class='misspelt'>presentaiton</span> goes live).  The source code may also be browsed <a href="http://fisheye.codehaus.org/browse/~date=2008-05-13T15%3A09%3A00/groovy/trunk/groovy/modules/griffon/src/examples/greet">via FishEye</a>.  There are a couple of points I wish to call out that were touched on in the tech session:</p>
<h3>Model View Controller Separation</h3>
<p>The GUI has a firm model view controller separation.  All of the Twitter API functionality is sequestered into the TwitterAPI.groovy class.  No other class does network functionality.  The GUI code is also handled separate from the controller.  View.groovy is the main class, whereas a couple other classes (ScrollablePanel.groovy, RoundedPanel.groovy) are there to support the view portion.  One other view class, TweetLine.groovy, handles the rendering of the individual tweet line (because I was not satisfied with JList).  Finally there is the controller class, Greet.groovy.  In addition to the main method all Swing events are dispatched to the various controller methods.  State variables are also kept here.</p>
<h3>Use of <code>@Bindable</code> and <code>bind()</code></h3>
<p>A lot of the glue code to manage visual state with the controller has been automated because of the new <code>@Bindable</code> annotation in Groovy 1.6.  This allows me to send notices that the view shouldn't be accepting updates and also notify the view that the backing data model has changed.  Adding these hooks by hand would add at least 100-200 lines to the application and would also introduce repetitive code that is prone to cut and paste errors.  The view code uses the <code>bind()</code> node to easily bind the values of the actions to relevant attributes.</p>
<h3>Actions are your friends</h3>
<p>Less of a Groovy call out and more of a Swing call out.  Use actions, actions are your friends.  All of the buttons, text lines, and list boxes are not hooked directly to the controller, but to the action.  This causes all of the relevant controls to turn off when the action becomes unavailable, and is why the bind to enable occurs in the actions definition and not the control definitions.</p>
<h3>Builder scripts are still Groovy Code</h3>
<p>In line 142 to 147 of View.groovy I do a loop inside of a panel to add the tweet lines individually, calling out to the TweetLine.groovy script.  This is perfectly legal in Groovy, since a builder is actually just executing closures and using meta-programming to intercept the method calls.  It may look like a static declarative XML type file in most cases, but it doesn't have to.  Especially with repeating elements, it's a great way to DRY out code.</p>
<h3>The 'Dynamic Language' part is what makes it possible</h3>
<p>The dynamic language aspect of Groovy code (and in particular the Scripts) is what allows for most of the magic to happen.  It is essential to the builder pattern.  You will also notice that both of the principal view scripts (View and TweetLine) don't create a SwingBuilder, or even imply that one exists.  They also use variables that are not defined in the scope of their script (like the controller object and the tweet).  This provides for a very subtle form of resource injection that requires no ceremony to access.  If this were statically typed I would have to state somehow the methods and fields the controller and tweet have, even if by simple type decleration.  All of that formality is unneeded in this context.</p>

<p>So what is the future of Greet?  I intend it to be one of a few marquee examples for a project I am attempting to get off of the ground with a few others, so the WebStart version may see some changes every once in a while.  But that is also why I am a fan of the promise of WebStart (if not particular shipped versions), new versions can be distributed without the same ceremony as an installer.</p>]]>
      
   </content>
</entry>
<entry>
   <title>Groovy Faster than Ruby?  Apparently.</title>
   <link rel="alternate" type="text/html" href="http://shemnon.com/speling/2008/05/groovy-faster-than-ruby-appare.html" />
   <id>tag:shemnon.com,2008:/speling//2.193</id>
   
   <published>2008-05-04T16:13:25Z</published>
   <updated>2008-05-05T01:09:54Z</updated>
   
   <summary>I kind of brushed over Alex&apos;s speed improvements in the recent Groovy 1.6-beta1 release, but based on some recent benchmarks it looks like it needs some re-iterating. Alex implemented something called call site caching. Here&apos;s what goes on. When we...</summary>
   <author>
      <name>Danno Ferrin</name>
      <uri>http://shemnon.com/speling/</uri>
      <email>danno&amp;#46;ferrin&amp;#64;gmail&amp;#46;com</email>
   </author>
   
   
   <content type="html" xml:lang="en" xml:base="http://shemnon.com/speling/">
      <![CDATA[<p>I kind of brushed over Alex's speed improvements in the recent Groovy 1.6-beta1 release, but based on some recent benchmarks it looks like it needs some re-iterating.  Alex implemented something called call site caching.  Here's what goes on.  When we encounter a call site we look at some notes we left the last time we ran through it, (assuming there are any).  We compare notes, and if nothing changed, we don't recalculate the MOP dispatch and just do what we did last time.  If our notes are different, we do the full MOP dispatch over again.  It's the 'memento' design pattern.  Charles Oliver Nutter has a <a href="http://headius.blogspot.com/2008/05/power-of-jvm.html">great writeup</a> on how this works. I thought it would speed things up, but I was <span class="misspelt">suprised</span> by how much.</p>
<p>Consider these external numbers from <a href="http://shootout.alioth.debian.org/">The Computer Language 
Benchmarks Game</a>.  Left is the comparison implementation, right is Groovy.  White is speed, black is memory consumption.  Measures are relative to each other.</p>
<p>First, <a href="http://shootout.alioth.debian.org/gp4sandbox/benchmark.php?test=all&lang=groovy&lang2=jruby">JRuby 1.1</a>.  (Note: JRuby 1.1.1, wasn't on the alioth site)<br/>
<img src="http://shootout.alioth.debian.org/gp4sandbox/chartvs.php?test=all&lang=groovy&lang2=jruby"><br/>
This surprised me.  Charles Oliver Nutter has been working intently on making the JRuby call sites work very well with the HotSpot optimizations.  Lots of talk about monomorphic branch paths, reflection barriers, and other stuff that makes my head hurt like I'm back in my undergraduate algorithms class.  Groovy beat JRuby in most of the tests (it used to be all but one, but it looks like possibly it got the JRuby 1.1.1 update).  I'm not sure why however.  Possibly better loop optimizations.</p>
<p>I remember that Charles was excited that some JRuby benchmarks had been running faster than Ruby, and that it was running Rails faster, some I compared Groovy against <a href="http://shootout.alioth.debian.org/gp4sandbox/benchmark.php?test=all&lang=groovy&lang2=ruby">Ruby 1.8.6</a>.<br/>
<img src="http://shootout.alioth.debian.org/gp4sandbox/chartvs.php?test=all&lang=groovy&lang2=ruby"><br/>
The first two places Ruby beast groovy are not surprising, calculating the digits of Pi and regular expression searching of DNA sequences.  The last on we get spanked on, printing hello world.  This is partly because the way the test is set up groovy both compiles and executes the test, then there is plain old jvm startup time, even <a href="http://shootout.alioth.debian.org/gp4sandbox/benchmark.php?test=all&lang=ruby&lang2=java">plain old Java</a> loses to Ruby in that one.  There is also the issue of memory consumption.  Generally speaking Ruby has a better story when it comes to these benchmarks.</p>
<p>Ruby gains some ground when using the <a href="http://shootout.alioth.debian.org/gp4sandbox/benchmark.php?test=all&lang=groovy&lang2=yarv">YARV</a> vm in Ruby 1.9, but Groovy still maintains a performance edge, while getting beat on memory for the most part.<br/>
<img src="http://shootout.alioth.debian.org/gp4sandbox/chartvs.php?test=all&lang=groovy&lang2=yarv"></p>
<p>Now I am not claiming that Groovy is the most performant language on the JVM, <a href="http://shootout.alioth.debian.org/gp4sandbox/benchmark.php?test=all&lang=groovy&lang2=java">it isn't</a>.  But it's performance story has improved markedly.  Since groovyc can jointly compile plain old java (which is slightly <a href="http://shootout.alioth.debian.org/gp4sandbox/benchmark.php?test=all&lang=java&lang2=scala">faster than Scala</a>) it provides a nice fallback for performance intensive parts that are critical.</p>
<p>Now it's time to pack for JavaOne.</p>
<p><b>Update:</b> Some of the analysis is off because some of the groovy programs that are missing are being filled in as time goes on.  Some of these are as partial sums and reverse complement (which Groovy stinks at apparently) and more (like k-nucleotide) are to come.  I am also directly linking to their images, so as the other implemetnations get updated, the images will change.</p>
]]>
      
   </content>
</entry>
<entry>
   <title>Consumer JRE - I think they may have pulled it off.</title>
   <link rel="alternate" type="text/html" href="http://shemnon.com/speling/2008/04/consumer-jre-i-think-they-may.html" />
   <id>tag:shemnon.com,2008:/speling//2.192</id>
   
   <published>2008-04-30T16:50:50Z</published>
   <updated>2008-04-30T17:05:00Z</updated>
   
   <summary>On my system I use two browsers: Mozilla and IE. Our customers use IE (its functionally as if they have a law to do so) so whenever I need to tweak web stuff (it happens on occasion) I fire up...</summary>
   <author>
      <name>Danno Ferrin</name>
      <uri>http://shemnon.com/speling/</uri>
      <email>danno&amp;#46;ferrin&amp;#64;gmail&amp;#46;com</email>
   </author>
   
   
   <content type="html" xml:lang="en" xml:base="http://shemnon.com/speling/">
      <![CDATA[<p>On my system I use two browsers: Mozilla and IE.  Our customers use IE (its functionally as if they have a law to do so) so whenever I need to tweak web stuff (it happens on occasion) I fire up IE to test it.  There is also another reason as well, I don't install flash on my Mozilla instance.  Flash ads are extremely annoying, and almost never are relevant to me (lower my rates?  Below 4.375%?).  So I am in the habit of seeing the bevel box and thinking "is it worth firing up IE to watch this YouTube video."  This makes getting <span class="misspelt">RickRoled</span> that much more annoying.</p>
<p> So I am going to this <a href="http://www.benfry.com/salaryper/">Baseball Salary Comparison</a> (via <a href="http://freakonomics.blogs.nytimes.com/2008/04/30/would-a-salary-cap-improve-baseball/">NYT/Freakonomics</a>) in Mozilla and I am scratching my head.  Is AJAX that powerful now?  Did flash sneak into my plugins?  Is Silverlight in XP SP3?  So I view the source and... oh my...  it's referencing a class file.  Where was the browser halting startup?  The grey box?  The orange java logo?  I look down to my system tray and, yep, there's the java logo.  I do have 6u10Beta installed, so all of the consumer oriented goodness is wired in by default, and it worked.</p>
<p>Oh my, I started a Java applet and didn't know it.</p>
<p>About time.</p>]]>
      
   </content>
</entry>
<entry>
   <title>@Bindable - Observable Properties for Groovy</title>
   <link rel="alternate" type="text/html" href="http://shemnon.com/speling/2008/04/bindable-observable-properties.html" />
   <id>tag:shemnon.com,2008:/speling//2.191</id>
   
   <published>2008-04-29T16:10:36Z</published>
   <updated>2008-04-29T16:41:48Z</updated>
   
   <summary>Groovy 1.6 is about to hit it&apos;s first beta here pretty soon, so I thought I&apos;de spend some time writing about an implementation of the second big feature. in 1.6. Call site caching is the first big feature, and that...</summary>
   <author>
      <name>Danno Ferrin</name>
      <uri>http://shemnon.com/speling/</uri>
      <email>danno&amp;#46;ferrin&amp;#64;gmail&amp;#46;com</email>
   </author>
   
   
   <content type="html" xml:lang="en" xml:base="http://shemnon.com/speling/">
      <![CDATA[<p>Groovy 1.6 is about to hit it's first beta here pretty soon, so I thought I'de spend some time writing about an implementation of the second big feature. in 1.6.  Call site caching is the first big feature, and that is really just a technical term for 'faster.'  The second big feature is AST Transformations.  Right now it just triggers off of annotations, but there are already two implementations of it that are slated to ship, <code>@Mixin</code> (which I won't go into here) and <code>@Bindable/@Vetoable</code>.  I'll go into the details of how you could write a transform later, but now I will focus on the most common task, simply using it.</p>
<p><code>@groovy.beans.Bindable</code> is an annotation that can go either on a Groovy class property or a Groovy class itself.  When the annotation is on a class you are telling the transform that all properties declared in the class should be treated as having <code>@Bindable</code> (whether or not they already have it).  When a property has this annotation the AST Transformation will generate (if it doesn't exist) a <code>java.beans.PropertyChangeSupport</code> object, appropriate listener addition methods, and then a setter that uses the property change support.  The end result is a bound JavaBeans property, with a whole lot less boilerplate code.  What was once this:</p>
<blockquote><pre>import java.beans.PropertyChangeSupport;
import java.beans.PropertyChangeListener;

class MyBean {
  private String prop;

  PropertyChangeSupport pcs = new PropertyChangeSupport(this);

  public void addPropertyChangeListener(PropertyChangeListener l) {
    pcs.add(l);
  }

  public void removePropertyChangeListener(PropertyChangeListener l) {
    pcs.remove(l);
  }

  public String getProp() {
    return prop;
  }

  public void setProp(String prop) {
    pcs.firePropertyChanged("prop", this.prop, this.prop=prop);
  }
}</pre></blockquote>
<p>now looks a lot more concise and to the point:</p>
<blockquote><pre>import groovy.beans.Bindable

class MyBean {
  @Bindable String prop
}</pre></blockquote>
<p>This goes hand in hand with the <code>bind()</code> node in swingbuilder, making a model update a text field automatically when it changes is now a simple as <code>textField(text:bind(source:myBeanInstance, sourceProperty:'prop'))</code>.  This is a very sublte thing to grok, but it really goes a long way in cutting down the amount of lines it takes to link the model and the view <span class='misspelt'>togeather</span> in a client application.</p>
<p>The same premise goes for <code>@Vetoable</code>, you know, for all those constrained JavaBeans properties you write.  You know, just in case.  I have seen some code in the wild that uses <code>VetoableChangeListeners</code>, but not indexed JavaBean properties.  It is useful for validation, when architected properly.</p>]]>
      
   </content>
</entry>
<entry>
   <title>SwingBuilder: Tight Groovy and Java Integration</title>
   <link rel="alternate" type="text/html" href="http://shemnon.com/speling/2008/04/swingbuilder-tight-groovy-and.html" />
   <id>tag:shemnon.com,2008:/speling//2.190</id>
   
   <published>2008-04-10T03:52:25Z</published>
   <updated>2008-04-10T04:29:23Z</updated>
   
   <summary>Gregg Bolinger recently wrote a blog post illustratiing how Groovy&apos;s SwingBuilder can have two way integration with Java code. However, Gregg uses the javax.script APIs to integrate with groovy and Java. But the integration between the two can be made...</summary>
   <author>
      <name>Danno Ferrin</name>
      <uri>http://shemnon.com/speling/</uri>
      <email>danno&amp;#46;ferrin&amp;#64;gmail&amp;#46;com</email>
   </author>
   
   
   <content type="html" xml:lang="en" xml:base="http://shemnon.com/speling/">
      <![CDATA[<p>Gregg Bolinger recently wrote a <a href="http://www.greggbolinger.com/blog/2008/04/09/1207778100000.html">blog post</a> illustratiing how Groovy's SwingBuilder can have two way integration with Java code.  However, Gregg uses the javax.script APIs to integrate with groovy and Java.  But the integration between the two can be made even tighter.  How?  Remember: every groovy script and class is also a Java Object.  The GUI layout could be compiled in an entierly separate script, compiled, instantiated at runtime, and fed into the SwingBuilder.  Consider these files...</p>
<blockquote><pre>//Panel.groovy
panel(id:'loginPanel') {
  tableLayout {
    tr {
      td { label(text:'Username') }
      td { textField(id:'usernameTextField', columns: 20) } 
    }
    tr {
      td { label(text:'Password') }
      td { passwordField(id: 'passwordTextField', columns: 20) }
    }
    tr {
      td { panel() }
      td { 
        button(text:'Login', actionPerformed: { 
          println user.username 
          println user.password 
        }) 
      }
    } 
  } 
}

bind(source:usernameTextField, sourceProperty:'text', 
     target:user, targetProperty:'username') 
bind(source:passwordTextField, sourceProperty:'text', 
     target:user, targetProperty:'password') 
</pre></blockquote>
<p>With this model in a separate file (because I'm that kind of coder on occasion)</p>
<blockquote><pre>//User.groovy
class User { 
  String username 
  String password 
} 
</pre></blockquote>
<p>Now before we go any further we will compile these scripts.  Yes, with <code>groovyc</code>.  If you are wondering if these are the complete sources the answer is yes they are.  You are also correct in noticing that there is no import or use of <span class='misspelt'>SwingBuidler</span>. &lt;soapbox&gt;This, my friends, is the power of a dynamic language.  The MOP dispatches these calls, and when the script is actually invoked is when these symbols are resolved.  When the SwingBuilder consumes the script it links itself into the script's metaclass to intercept all unresolved calls.&lt;/soapbox&gt;  Sorry, evangelical tangent there for a moment.  Let's get back on task.  How does the Java code look?</p>
<blockquote><pre>//JavaSwingBuilderDemo.java
import javax.swing.JPanel;
import javax.swing.JDialog;
import groovy.swing.SwingBuilder;

public class JavaSwingBuilderDemo {

  public static void main(String[] args) {
    SwingBuilder swing = new SwingBuilder();
    
    // load all externally referenced variables
    User user = new User();
    swing.setVariable("user", user);
    
    swing.build(new Panel());
    
    // unload the desired components
    JPanel result = (JPanel)swing.getVariable("loginPanel");

    JDialog dialog = new JDialog();
    dialog.getContentPane().add(result);
    dialog.pack();
    dialog.show();
  }

}</pre ></blockquote>
<p>To invoke the script you do it much as you would in groovy, just with a lot more typeing.  Both the keyboarding a casting kind.  The main call is SwingBuilder.build(Script).  This calls the script as though it was being evaluated in one of the builder's content nodes.  Of course, before you call the script you need to load in any external variables, in this case a user object that contains the username and password.  Then after the call you need to unload the variables you want to use.  In Groovy I could just do <code>swing.loginPanel</code> but in Java no implicit meanings are allowed, so that means more typing.</p>
<p>An interesting side note is that this is similar to something we are looking at doing inside my own company: using SwingBuilder to build and wire up the GUI while keeping the core of the application in Java and keeping those who don't have the time to learn Groovy or want to deal with it from having to do so.  And that is what I find great about Groovy: you can use it where it makes sense and adds value, and where you transition it's relatively seamless (unless of course you <i>are</i> using Seam ;) )</p>]]>
      
   </content>
</entry>
<entry>
   <title>Speaking at JavaOne! TS-5098</title>
   <link rel="alternate" type="text/html" href="http://shemnon.com/speling/2008/04/speaking-at-javaone-ts5098.html" />
   <id>tag:shemnon.com,2008:/speling//2.189</id>
   
   <published>2008-04-04T18:22:37Z</published>
   <updated>2008-04-04T18:27:17Z</updated>
   
   <summary>Good news everyone! My submission for a Technical Session at JavaOne has been upgraded from an alternate to an accepted session! TS-5098 - Building Rich Applications with Groovy&apos;s SwingBuilder. This will be given with Andres Alamiray. This is basically an...</summary>
   <author>
      <name>Danno Ferrin</name>
      <uri>http://shemnon.com/speling/</uri>
      <email>danno&amp;#46;ferrin&amp;#64;gmail&amp;#46;com</email>
   </author>
   
   
   <content type="html" xml:lang="en" xml:base="http://shemnon.com/speling/">
      <![CDATA[<p>Good news everyone!</p>
<p>My submission for a Technical Session at JavaOne has been upgraded from an alternate to an accepted session!  TS-5098 - Building Rich Applications with Groovy's SwingBuilder.  This will be given with Andres Alamiray.  This is basically an intro to using Groovy to build Swing applications.  No word on when the session will be however.</p>
<p>This is in addition to my BOF session on Wednsday Night with James Williams: BOF-5110 - Extending Groovy’s Swing User Interface in Builder to Build Richer Applications, which will go over how to add your custom widgets or leverage commercial libraries in the SwingBuilder.</p>

]]>
      
   </content>
</entry>
<entry>
   <title>New Swing Features in Groovy 1.5</title>
   <link rel="alternate" type="text/html" href="http://shemnon.com/speling/2007/12/new-swing-features-in-groovy-1.html" />
   <id>tag:shemnon.com,2007:/speling//2.188</id>
   
   <published>2007-12-08T01:02:55Z</published>
   <updated>2007-12-08T21:17:15Z</updated>
   
   <summary>Groovy 1.5 has been released. Yes, this is the former 1.1-rc line, and a late decision was made to brand it Groovy 1.5. It&apos;s more than the typical incremental improvements, but not quite a major release (by a hair), so...</summary>
   <author>
      <name>Danno Ferrin</name>
      <uri>http://shemnon.com/speling/</uri>
      <email>danno&amp;#46;ferrin&amp;#64;gmail&amp;#46;com</email>
   </author>
   
   
   <content type="html" xml:lang="en" xml:base="http://shemnon.com/speling/">
      <![CDATA[<p><a href='http://docs.codehaus.org/display/GROOVY/2007/12/07/Groovy+1.5+released'>Groovy 1.5</a> has been released.  Yes, this is the former 1.1-rc line, and a late decision was made to brand it Groovy 1.5.  It's more than the typical incremental improvements, but not quite a major release (by a hair), so at the prompting of Alexandru Popescu we went for a release number that shows compatibility with Java 1.5 features.</p>
<p>In addition to the basic language level changes, there are a lot of changes that went into Groovy's Swing support.</p>
<h3>Backend overhaul</h3>
<ul><li>Almost every line in the SwingBuilder was adjusted in some way.  And the whole thing was ported over to Groovy from Java.  Dogfood baby!</li>
<li>FactoryBuilderSupport is a juiced up refactoring of SwingBuilders building pattern.  SwingBuidler is now a subclass of FactoryBuidlerSupport fully using Factories for all of it's classes, and node specific handling has similarly been moved to the factories out of the SwingBuidler core.</li>
<li>At the FactoryBuilderSupport level a new <code>build()</code> method was added, so external Groovy Scripts can be called and executed as though they are builder content directly.</li>
<li>Also at the FBS level nodes that create object that should be disposed are tracked via addDisposalClosure(), which are all called in FILO order from the dispose() method.</li>
<li>Most nodes now accept an object of their own type, providing another point of extension.
  i.e. <code>button(new MyCustomButton())</code> works as expected if MyCustomButton extends JButton</li>
</ul>
<h3>New Nodes</h3>
<ul><li><code>actions()</code>, a simple collection node that is meant to describe actions</li>
<li><code>imageIcon()</code> provides support for ImageIcons</li>
<li>Borders are now supported via buidler nodes.  <code>lineBorder()</code>, <code>loweredBevelBorder()</code>, <code>raisedBevelBorder()</code>, <code>etchedBorder()</code>, <code>loweredEtchedBorder()</code>, <code>raisedEtchedBorder()</code>, <code>titledBorder()</code>, <code>emptyBorder()</code>, <code>compoundBorder()</code>, and <code>matteBorder()</code>.</li>
<li><code>bind()</code> and <code>model()</code>, adding binding support for observable properties.</li>
<li>The passthrough <code>widget()</code> now has two use specific cousins, <code>container()</code> for widgets that can have children (<code>widget()</code> now throws an error when children are added) and <code>bean()</code>, which will not add the resulting object to the parent container.  (Note that the expanded argument support for the basic nodes should reduce the necessity of these nodes.  Just add the new widget as an argument to it's javax.swing type.)</li>
</ul>
<h3>New Methods</h3>
<ul><li><code>edt(Closure)</code>, executes the Closure in the Event dispatch Thread (EDT) and wait for completion (via SwingUtilities.invokeAndWait).  Optimizations are performed for when the method is called in the EDT.</li>
<li><code>doLater(Closure)</code>, executes the Closure in the EDT asynchronously via SwingUtilities.invokeLater()</li>
<li><code>doOutside(Closere)</code>, insures that the closure is executed outside of the EDT.  If the context is not in the EDT it is executed immediately, otherwise a new thread is created</li>
<li><code>shortcut(key [, modifiers])</code>, given a keystroke it adds a platform specific modifier for it (ctrl on Windows and GTK, option on MacOS).</li>
<li><code>dispose()</code> invokes all disposal closures.  Generally these are things such as dialogs, frames, and windows created by the SwingBuilder and unbinds all bindings created by <code>bind()</code>.</li>
<li><code>lookAndFeel()</code> is an easy way to set the look and feel.  Defaults exist for system, metal, nimbus, etc. and a few third party LAFs.</li></ul>

<h3>New static method</h3>
<ul><li><code>build(Closure)</code>, creates and returns a SwingBuilder and executes the closure in context of the Event Dispatch Thread.</li></ul>
]]>
      
   </content>
</entry>
<entry>
   <title>More reasons I am leaving NetBeans for IntelliJ</title>
   <link rel="alternate" type="text/html" href="http://shemnon.com/speling/2007/12/more-reasons-i-am-leaving-netb.html" />
   <id>tag:shemnon.com,2007:/speling//2.187</id>
   
   <published>2007-12-05T22:00:00Z</published>
   <updated>2007-12-05T22:11:47Z</updated>
   
   <summary>Check out this beauty, any decent Swing developer should cringe at this stack trace java.lang.Object.wait(Native Method) java.lang.Object.wait(Object.java:485) org.netbeans.modules.debugger.jpda.JPDADebuggerImpl.waitRunning(JPDADebuggerImpl.java:290) org.netbeans.modules.debugger.jpda.JPDADebuggerImpl.finish(JPDADebuggerImpl.java:1039) org.netbeans.modules.debugger.jpda.actions.KillActionProvider.doAction(KillActionProvider.java:74) org.netbeans.api.debugger.ActionsManager.doAction(ActionsManager.java:158) org.netbeans.api.debugger.Session.kill(Session.java:278) org.netbeans.modules.debugger.ui.models.SessionsActionsProvider$3.perform(SessionsActionsProvider.java:97) org.netbeans.spi.viewmodel.Models$ActionSupport.actionPerformed(Models.java:528) javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995) javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318) javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387) javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242) javax.swing.AbstractButton.doClick(AbstractButton.java:357) javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:1216) javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:1257) java.awt.Component.processMouseEvent(Component.java:6038) javax.swing.JComponent.processMouseEvent(JComponent.java:3265) java.awt.Component.processEvent(Component.java:5803) java.awt.Container.processEvent(Container.java:2058) java.awt.Component.dispatchEventImpl(Component.java:4410) java.awt.Container.dispatchEventImpl(Container.java:2116) java.awt.Component.dispatchEvent(Component.java:4240) java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322) java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)...</summary>
   <author>
      <name>Danno Ferrin</name>
      <uri>http://shemnon.com/speling/</uri>
      <email>danno&amp;#46;ferrin&amp;#64;gmail&amp;#46;com</email>
   </author>
   
   
   <content type="html" xml:lang="en" xml:base="http://shemnon.com/speling/">
      <![CDATA[<p>Check out this beauty, any decent Swing developer should cringe at this stack trace</p>
<blockquote>java.lang.Object.wait(Native Method)<br />
java.lang.Object.wait(Object.java:485)<br />
org.netbeans.modules.debugger.jpda.JPDADebuggerImpl.waitRunning(JPDADebuggerImpl.java:290)<br />
org.netbeans.modules.debugger.jpda.JPDADebuggerImpl.finish(JPDADebuggerImpl.java:1039)<br />
org.netbeans.modules.debugger.jpda.actions.KillActionProvider.doAction(KillActionProvider.java:74)<br />
org.netbeans.api.debugger.ActionsManager.doAction(ActionsManager.java:158)<br />
org.netbeans.api.debugger.Session.kill(Session.java:278)<br />
org.netbeans.modules.debugger.ui.models.SessionsActionsProvider$3.perform(SessionsActionsProvider.java:97)<br />
org.netbeans.spi.viewmodel.Models$ActionSupport.actionPerformed(Models.java:528)<br />
javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)<br />
javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)<br />
javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)<br />
javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)<br />
javax.swing.AbstractButton.doClick(AbstractButton.java:357)<br />
javax.swing.plaf.basic.BasicMenuItemUI.doClick(BasicMenuItemUI.java:1216)<br />
javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(BasicMenuItemUI.java:1257)<br />
java.awt.Component.processMouseEvent(Component.java:6038)<br />
javax.swing.JComponent.processMouseEvent(JComponent.java:3265)<br />
java.awt.Component.processEvent(Component.java:5803)<br />
java.awt.Container.processEvent(Container.java:2058)<br />
java.awt.Component.dispatchEventImpl(Component.java:4410)<br />
java.awt.Container.dispatchEventImpl(Container.java:2116)<br />
java.awt.Component.dispatchEvent(Component.java:4240)<br />
java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)<br />
java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)<br />
java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)<br />
java.awt.Container.dispatchEventImpl(Container.java:2102)<br />
java.awt.Window.dispatchEventImpl(Window.java:2429)<br />
java.awt.Component.dispatchEvent(Component.java:4240)<br />
java.awt.EventQueue.dispatchEvent(EventQueue.java:599)<br />
java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)<br />
java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)<br />
java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)<br />
java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)<br />
java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)<br />
java.awt.EventDispatchThread.run(EventDispatchThread.java:121)<br />
</blockquote>
<p>Yes, Netbeans totally froze up on me, because some overworked programmer thought it would be good to do a blocking wait without timeout in the Swing Event Dispatch Thread.  If a single problem happens you are stuck in limbo <bold>forever</bold>.  Which is why non-timeout wait calls can be so evil, and doing it in the EDT makes it demonic.  Looks like we need to <a href="http://www.cafeaulait.org/quotes2007.html#quote2007February24">get the stick back out</a>, or punish whoever it is that violated their blood oath.</p>
<p>Really, I'm not just being petty.  I've sent may stack traces like this to the bugzilla at NetBeans for years, <i>literally years,</i> and they still are doing messed up things in their action handlers without checking to see if they are in the EDT.  It may have the best GUI designer for Java out there, but the frosting doesn't matter if you cannot stomach the cake.</p>]]>
      
   </content>
</entry>

</feed>
