How Groovy Helps JavaFX: Farewell Pure Java Code?
One of the many cool sample applications known to those trying out JavaFX is the JavaFX Weather application, which is now bundled with the NetBeans IDE 6.5.1/JavaFX 1.2 bundle. In short, it connects to a weather service and then displays the results for selected cities in an impressive JavaFX GUI:
In a technical session at JavaOne on Wednesday, entitled "JavaFX Programming Language + Groovy = Beauty + Productivity", Dierk König showed a number of powerful ways in which Groovy and JavaFX can interact. One of those ways is outlined below, with all the code and the results. It is really quite impressive and earned Dierk a round of applause from his audience when he demoed it in his session.
The JavaFX Weather application creates the above GUI, while using this massive Java class to connect to Yahoo's weather service. The RSS feed that the Java class connects to is displayed in full below:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<rss version="2.0" xmlns:yweather="http://xml.weather.yahoo.com/ns/rss/1.0" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#">
<channel>
<title>Yahoo! Weather - Prague, EZ</title>
<link>http://us.rd.yahoo.com/dailynews/rss/weather/Prague__EZ/*http://weather.yahoo.com/forecast/EZXX0012_f.html</link>
<description>Yahoo! Weather for Prague, EZ</description>
<language>en-us</language>
<lastBuildDate>Fri, 05 Jun 2009 8:00 pm CEST</lastBuildDate>
<ttl>60</ttl>
<yweather:location city="Prague" region="" country="EZ"/>
<yweather:units temperature="F" distance="mi" pressure="in" speed="mph"/>
<yweather:wind chill="54" direction="60" speed="3" />
<yweather:atmosphere humidity="58" visibility="6.21" pressure="29.8" rising="0" />
<yweather:astronomy sunrise="4:56 am" sunset="9:06 pm"/>
<image>
<title>Yahoo! Weather</title>
<width>142</width>
<height>18</height>
<link>http://weather.yahoo.com</link>
<url>http://l.yimg.com/a/i/us/nws/th/main_142b.gif</url>
</image>
<item>
<title>Conditions for Prague, EZ at 8:00 pm CEST</title>
<geo:lat>50.1</geo:lat>
<geo:long>14.28</geo:long>
<link>http://us.rd.yahoo.com/dailynews/rss/weather/Prague__EZ/*http://weather.yahoo.com/forecast/EZXX0012_f.html</link>
<pubDate>Fri, 05 Jun 2009 8:00 pm CEST</pubDate>
<yweather:condition text="Partly Cloudy" code="30" temp="54" date="Fri, 05 Jun 2009 8:00 pm CEST" />
<description><![CDATA[
<img src="http://l.yimg.com/a/i/us/we/52/30.gif"/>
<b>Current Conditions:</b>
Partly Cloudy, 54 F
<b>Forecast:</b>
Fri - Partly Cloudy. High: 58 Low: 42
Sat - PM Rain. High: 58 Low: 49
<a href="http://us.rd.yahoo.com/dailynews/rss/weather/Prague__EZ/*http://weather.yahoo.com/forecast/EZXX0012_f.html">Full Forecast at Yahoo! Weather</a>(provided by The Weather Channel)<br/>
]]>
</description>
<yweather:forecast day="Fri" date="5 Jun 2009" low="42" high="58" text="Partly Cloudy" code="29" />
<yweather:forecast day="Sat" date="6 Jun 2009" low="49" high="58" text="PM Rain" code="12" />
<guid isPermaLink="false">EZXX0012_2009_06_05_20_00_CEST</guid>
</item>
</channel>
</rss>
Now, whenever you hear "Groovy", you should think "grunt work". That's what Groovy is particularly good at. A very strong case in point is that of web services. Also, that of parsing HTML and XML. Therefore, when you need to interact with web services in your Java application, the most obvious helper language you should think of is Groovy.
Look again at the RSS above and then look at line 11 in the Groovy code below. Here's that line:
def channel = new XmlParser().parse(url).channelThat line gets you the "channel" element in the RSS feed above! Awesome, right? And from there on, the Groovy script below parses the RSS feed, identifying exactly those pieces that are of interest to the JavaFX GUI, resulting in EXACTLY the same result, in approximately 20 lines, as the original does in approximately 250.
Take a look at the Groovy snippet below to see how it works, by comparing it to the RSS feed above. Note that this isn't even a snippet! It is the WHOLE Groovy web service class. Now that's just plain cool, especially after comparing it again to the original monstrosity.
package weatherfx.service
class YahooWeatherServiceG {
static YW = new groovy.xml.Namespace("http://xml.weather.yahoo.com/ns/rss/1.0")
def forecasts
YahooWeatherServiceG(String code, boolean celsius) {
def url = "http://weather.yahooapis.com/forecastrss?u=f&p=$code"
println url.toURL().text
def channel = new XmlParser().parse(url).channel
cityName = channel[YW.location].@city
def wind = channel[YW.wind].first()
windSpeed = wind.@speed.toInteger()
windDirection = wind.@direction.toInteger()
def cond = channel.item[YW.condition].first()
temp = cond.@temp.toInteger()
forecasts = channel.item[YW.forecast]
}
String cityName
int temp
int windSpeed
int windDirection
int getConditionCode(int day=0) { forecasts[day].@code.toInteger() }
int getLowsTemp (int day=0) { forecasts[day].@low.toInteger() }
int getHighsTemp (int day=0) { forecasts[day].@high.toInteger() }
}
Now, take a moment to imagine how much simpler, effective, and less error-prone it will be to (a) test and (b) maintain the above code, compared to its original pure Java version.
However, there isn't a JavaFX/Groovy cross-compiler yet. So, how to replace your Java web service code with the above in Groovy? Create a separate project in which you create your Groovy web service. Then add that project to your JavaFX application's classpath. Next, replace the two or three references in your JavaFX application to refer to the Groovy class (which, after compilation, is now a Java class) instead of the original Java class.
In a single picture, the above paragraph gets you the following:

Then run the JavaFX application and you'll have the same result as before, with the difference that the web service code is now handled in Groovy. And... there's no pure Java code in your application at all anymore. Oh, dear. JavaFX creates the GUI, while Groovy does the grunt work in the background. So, farewell, pure Java code?
| Attachment | Size |
|---|---|
| fig-1.png | 46.71 KB |
| YahooWeatherService.java | 9.45 KB |
| fig-2.png | 68.64 KB |
- Login or register to post comments
- 8410 reads
- Printer-friendly version
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)










Comments
OtengiM replied on Sun, 2009/06/07 - 8:55pm
Cloves Almeida replied on Sun, 2009/06/07 - 9:45pm
Andrew replied on Sun, 2009/06/07 - 10:26pm
Dean replied on Sun, 2009/06/07 - 10:26pm
jamesjames replied on Sun, 2009/06/07 - 11:40pm
Andres Almiray replied on Sun, 2009/06/07 - 11:57pm
in response to: jamesjames
That depends on your definition of "Java": is it the language or the platform? or both. Frankly I don't care if a JavaFX (or any other alternate JVM language for that matter) post appears from time to time on my Javalobby feed, I can decide to skip it if I want to. Disclaimer: I love Groovy, I don't like JavaFX Script that much, I'm partial to Scala and I'm a total ignorant on Clojure. Tag me as a madman, I prefer polyglot programmer ;-)
Peace.
Andrew replied on Sun, 2009/06/07 - 11:58pm
in response to: jamesjames
Geertjan Wielenga replied on Mon, 2009/06/08 - 12:45am
in response to: jamesjames
jamesjames replied on Mon, 2009/06/08 - 1:01am
in response to: geertjan
Michal Hlavac replied on Mon, 2009/06/08 - 1:11am
in response to: jamesjames
It's interesting, how intolerant readers are here. This article is strongly about java. Why didn't you simply skip this article? (rhetorical question)
jamesjames replied on Mon, 2009/06/08 - 1:18am
in response to: hlavki
Andrew replied on Mon, 2009/06/08 - 1:37am
in response to: hlavki
Michal Hlavac replied on Mon, 2009/06/08 - 1:59am
in response to: andrew.g
jamesjames replied on Mon, 2009/06/08 - 2:50am
in response to: hlavki
Michal Hlavac replied on Mon, 2009/06/08 - 2:51am
in response to: jamesjames
Geertjan Wielenga replied on Mon, 2009/06/08 - 2:56am
in response to: jamesjames
Hmmm. Not in one single place has that argument been made in this article. Not even once. If anything, it's asking you to favor Groovy over Java.
jamesjames replied on Mon, 2009/06/08 - 3:03am
in response to: hlavki
Andrew replied on Mon, 2009/06/08 - 3:04am
in response to: hlavki
Hi Michal,
I agree with you that when you wrote an article about several technologies it is difficult not to rush to publish it on any board possible.
However, I share some concerns with jamesjames that JavaLobby board is being used for preaching JavaFX / Groovy over Java.
Just look at the title "… Farewell Pure Java Code?".
And further the author writes
Quote 1:
"Now that's just plain cool (Groovy), especially after comparing it again to the original monstrosity (Java)."
Quote 2:
"Now, take a moment to imagine how much simpler, effective, and less error-prone it will be to (a) test and (b) maintain the above code, compared to its original pure Java version."
I think to write articles about JavaFX/ Groovy code being "much simpler, effective, and less error-prone" than Java code is more appropriate on Groovy board.
And for articles about JavaFX there is a nice RIA Zone http://ria.dzone.com/.
Geertjan Wielenga replied on Mon, 2009/06/08 - 3:23am
So all you want on Javalobby are articles that are uncritical of Java? What qualifies this article for inclusion on Javalobby is the fact that it is about Java. The fact that it turns out that it doesn't FAVOR Java is completely and utterly irrelevant.
jamesjames replied on Mon, 2009/06/08 - 3:49am
in response to: hlavki
You have gotto be kidding me Michal. Let me rephrase it for you. I wont use JavaFX because I do not need it. And, like JavaScript, JavaFX is not Java. Point here is that a scripting language having a "Java" word in its name does not qualify it to be Java related.
I apologize for being harsh to you. With peace!
Jose Maria Arranz replied on Mon, 2009/06/08 - 3:50am
Groovy is a higher level language on top of "Java as platform", JavaFX is even more higher. Groovy, JavaFX and Java as language are different flavours of "Java as platform", it makes sense Groovy and JavaFX news in JavaLobby. Some day if overwhelming success of Groovy and JavaFX occurs, a javafx.dzone.com and groovy.dzone.com would be necessary to avoid too many news per day, and java.dzone.com would be specialized in Java "as language".
Said this, I can understand JavaFX is the new cornerstone of the Sun (Oracle) offering and it is fine and needed, JavaFX can compete with Flash/Flex/AIR and Groovy has its place, but many people (myself included) think scripting languages are problematic to manage complex applications because of lack of a compiler (yes I know you can compile Groovy). Promoting the mantra "no pure Java code" can be appeling though can drive to bad decisions about the right technology to use.
Scripting has its place, really, in small applications (or applications repeating the same pattern again and again) and highly dynamic applications wich need to read source code from external sources.
I've read again and again examples like:
def channel = new XmlParser().parse(url).channel
"Now that's just plain cool, especially after comparing it again to the original monstrosity (in Java)."
Geertjan is not the language, is the API, the original code in Java is using a SAX parser, a SAX parser is a low level API for markup, using DOM would be shorter (I'm sure Groovy uses DOM behind the scenes), the method Document.getDocumentElement() returns the channel node. Using XPath and/or TreeWalker can help to traverse the DOM in a similar fashion you are doing in Groovy, yes the Java code would be slightly more verbose but who cares? Even more if you wrap some typical DOM code in a custom self made mini-API you have the same productivity as Groovy. There is one problem, you need to compile your Java code, you don't in Groovy and JavaFX, yes definitively Groovy, JavaFX etc are nice if compilation phase is a problem.
By the way, jamesjames, Geertjan works for SunOracle and I'm sure he does not want to kill Java... the language :)
jamesjames replied on Mon, 2009/06/08 - 4:07am
in response to: jmarranz
flex0 replied on Mon, 2009/06/08 - 10:28am
Fabrizio Giudici replied on Mon, 2009/06/08 - 11:01am
I think that it would make sense to *discuss* the creation of a JavaFX zone, but it would mostly for ... promoting JavaFX on its own.
For the rest, JavaFX is the only non-Java language that I'm using on the Java platform. I don't have any particular interest in Groovy, JRuby, Scala; nevertheless I regularly read articles about that stuff, generically because looking at things in different perspectivesis inspiring; because who knows, sooner or later I could change my mind (unlikely) or because I would have a better awareness in motivating my decision of sticking with Java (likely).
My point is that it's important that the title (or the first lines) describes the article content. In this case it does and if I'm not in the mood of reading about Groovy I don't find it hard to skip it.
Osvaldo Doederlein replied on Mon, 2009/06/08 - 11:22am
Groovy is Java. JavaFX is Java. Scala is Java. JRuby is Java. Repeat after me 100 times, "Java is a Platform".
Yes we have a Groovy Zone, and we should have a JavaFX Zone, at least if JavaFX content and interest are already big enough. But this particular article belongs here, exactly because it's a "language mashup" article. Notice: We don't have separated "Java Language Zone" and "Java Platform Zone", so the "Java Zone" must obviously accept any material that is relevant to Java-as-a-Platform. Perhaps we should have that separation, to avoid such stupid discussions.
What' next, people complaining of Java Zone articles that cover any API/framework that's not included in the ME/SE/EE platforms and not an official JCP API? "Move this crap to the Hibernate Zone", I can already hear...
OtengiM replied on Mon, 2009/06/08 - 4:01pm
Calm down people, This article is about Java and Groovy. It happend that JavaFX is the front end it could be JSF or JSP or GWT or even Flex. The point here is between Java and Groovy and as I said if I will replace Java will be with Scala but I think the article is fine and critique Java flaws so we Java developers can learn from Groovy and apply those to Java. I dont see anything bad about this article because also Groovy is Java behind the scenes.
For JavaFX and Flex and even GWT there is a RIA zone, that zone is for that topics but sometimes we need a front end to explain the excersise of the article and happend to be in this article is JavaFX.
Personaly I dont like much JavaFX I prefer Flex but it is not bad to learn something new sometimes.
OtengiM replied on Mon, 2009/06/08 - 4:19pm
phil swenson replied on Mon, 2009/06/08 - 8:52pm
leonelag replied on Tue, 2009/06/09 - 9:34am
Guys, doesn't it strike you that users will also have to download Groovy's 1.6 MB jar file in order to get this simple app working ?
Also, this simple line of code:
def channel = new XmlParser().parse(url).channel
This is possible not because Groovy the language is cool (it is), but because its accompanying classes (the GDK) are awesome.
There are a lot of classes in the JDK for XML, but they aren't as simple to use.
This is a class I could easily see implemented in Java.
Instead of promoting language changes, we could wish for easier to use classes in the JDK.
Andres Almiray replied on Tue, 2009/06/09 - 12:10pm
in response to: leonelag
In plain Java you would go as far as
calling .channel requires metaprogramming techniques that are simply not available in Java, so this is really a combination of language features and libraries. The thing is that both are so tighly integrated that a library feature can be mistaken for a language feature, like the following example demonstrates http://www.transentia.com.au/flatpress/index.php/2009/03/11/inventing-a-new-statment-for-groovy-in-10-minutes/ ;-)