NLGUG Announced (Marcel Overdijk)

, , , August 8th, 2008

Marcel Overdijk has announced the creation of NLGUG (Netherland’s Groovy User Group) group site hosted at Google groups. The intention of this effort to start building up a network of Groovy & Grails developers in The Netherlands. If the group grows and people are interested in meeting up the better. Please consider joining the group if you are local to The Netherlands and you find Groovy & Grails to be among your favorite topics.

Tags: , , ,

Official Groovy/Grails Support in NetBeans 6.5 (Vladimir Vivien)

, , July 2nd, 2008

Original Source

Vladimir Vivien confirms what we previously announced: NetBeans 6.5 comes with official support for Groovy and Grails. He found a link to NetBeans 6.5m1’s notes that explain with small detail what is to be expected on that release in terms of Groovy/Grails support.

Judging from the list of features that will be included in NetBeans 6.5, Groovy and Grails will be officially supported by the NB team. From the wiki text, Groovy and Grails will be first-class citizen in NB65 with features that will include:
- Editor support (code completion, color highlights, etc)
- Two-way Java / Groovy class integration
- Seamless Grail project support (support for all Grails artifacts and commands)
- Jetty integration for development-time deployment/testing.

It remains to be seen if NB65 Groovy support will be as comprehensive as IntelliJ which currently has the most extensive support for Groovy / Grails development.

Considering the 3 major IDEs, other popular editors as TextMate (and clones), jEdit, Vi(m), Emacs; comand line tools like Ant, Gant, Maven, and even CI servers like Bamboo and Hudson, there are plenty of options to get you started with Groovy and Grails.

Tags: , ,

Custom Implicit Variables in GSPs (Kevin Burke)

, , June 1st, 2008

Kevin Burke writes:

I really should start every post with “groovy is a really swell language”. You can do some pretty cool things with it.

Anyway, I had a desire to have an variable implicitly available in all of my GSP’s so that I didn’t have to wrap certain blocks in a tag that made the variable available. There were a couple of reasons for this. The first is that if an exception was thrown in the block of code, the stack trace would indicate that it was coming from my custom tag. More importantly however it was a real pain in the tuckus to have to litter my GSP’s with a tag that simply introduced a variable into the scope. After several attempts to hijack the page scope before the page was rendered I settled on the following:

  1. GroovyPage.metaClass .getCurrentUser = { -> ctx.authenzedManager .currentUser ( ) }

As it turns out every page extends GroovyPage which is just a groovy script. So you can add methods using it’s metaClass to add all kinds of functionality. This might be a good way for plugins to add sort of helper methods, since, unlike tags, it will actually return a value and not write it to out. Anyway, by adding getCurrenUser I can now call ${currentUser.whatever} from my GSP. It makes me happy.

Rock over London. Rock on Chicago.

5 Responses to “Custom implicit variables in GSP’s”

  1. Graeme Rocher Says:
    Nice. Just one note, tags actually return their value when they’re called as a method such as createLink(action:’foo’)
  2. Shawn Hartsock Says:
    Nice trick, that MOP stuff is really powerful.
  3. Kevin Burke Says:
    Graeme: That’s very true. Sorry for spreading misinformation. Oh well, still fun stuff anyway.

    Shawn: I don’t know what I’d do without it.

  4. esbium Says:
    Where do you put this code in a Grails app? In the config.groovy? maybe bootstrap.groovy?
  5. Kevin Burke Says:
    esbium: BootStrap would be a good place to put it. I happen to be using a plugin in this example.

Tags: , ,

Nothing Makes You Want Groovy More Than XML (Ken Kousen)

, March 12th, 2008

I’m in Delaware this week teaching a course in Java Web Services using RAD7. The materials include a chapter on basic XML parsing using Java. An exercise at the end of the chapter presented the students with a trivial XML file, similar to:


<library>
  <book isbn="1932394842">
    <title>Groovy in Action</title>
    <author>Dierk Koenig</author>
  </book>
  <book isbn="1590597583">
    <title>Definitive Guide to Grails</title>
    <author>Graeme Rocher</author>
  </book>
  <book isbn="0978739299">
    <title>Groovy Recipes</title>
    <author>Scott Davis</author>
  </book>
</library>

(with different books, of course) and asked the students to find a book with a particular isbn number and print it’s title and author values.

I sighed and went to work, producing a solution roughly like this:


import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ParseLibrary {
    public static void main(String[] args) {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        Document doc = null;
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            doc = builder.parse("books.xml");
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
        NodeList books = doc.getElementsByTagName("book");
        for (int i = 0; i < books.getLength(); i++) {
            Element book = (Element) books.item(i);
            if (book.getAttribute("isbn").equals("1932394842")) {
                NodeList children = book.getChildNodes();
                for (int j = 0; j < children.getLength(); j++) {
                    Node child = children.item(j);
                    if (child.getNodeType() == Node.ELEMENT_NODE) {
                        if (child.getNodeName().equals("title")) {
                            System.out.println("Title: "
                                + child.getFirstChild().getNodeValue());
                        } else if (child.getNodeName().equals("author")) {
                            System.out.println("Author: "
                                + child.getFirstChild().getNodeValue());
                        }
                    }
                }
            }
        }
    }
}

The materials didn’t supply a DTD, so I didn’t have any ID attributes to make it easier to get to the book I wanted. That meant I was reduced to continually using getElementsByTagName(String). I certainly didn’t want to traverse the tree, what with all those whitespace nodes containing the carriage-return/line-feed characters. So I found the book nodes, cast them to Element (because only Elements have attributes), found the book I wanted, got all of its children, found the title and author child elements, then grabbed their text values, remembering to go to the element’s first child before doing so.

What an unsightly mess. The only way to simplify it significantly would be to use a 3rd partly library, which the students didn’t have, and it would still be pretty ugly.

One of the students said, “I kept waiting for you to say, ‘this is the hard way, now for the easy way,’ but you never did.”

I couldn’t resist replying, “well, if I had Groovy available, the whole program reduces to:


def library = new XmlSlurper().parse('books.xml')
def book = library.books.find { it.@isbn == '1932394842' }
println "Title: ${book.title}\nAuthor: ${book.author}"

“and I could probably shorted that if I thought about it. How’s that for easy?”

On the bright side, as a result I may have sold another Groovy course. :) For all of Groovy’s advantages over raw Java (and I keep finding more all the time), nothing sells it to Java developers like dealing with XML.

 

Ken Kousen

Tags: ,

Mastering Grails: Changing the view with Groovy Server Pages (Scott Davis)

, , March 11th, 2008

Groovy Server Pages (GSP) puts the Web in the Grails Web framework. In the third installment of his Mastering Grails series, Scott Davis shows you the ins and outs of working with GSP. See how easy it is to use Grails TagLibs, mix together partial fragments of GSPs, and customize the default templates for the automatically generated (scaffolded) views.

The first two articles in this series introduced you to the basic building blocks of the Grails Web framework. I’ve told you — repeatedly — that Grails is based on the Model-View-Controller (MVC) architectural pattern (see Resources), and that Grails favors convention over configuration for binding the framework’s parts together. Grails uses intuitively named files and directories to replace the older, more error-prone method of manually cataloguing these linkages in an external configuration file. For example, in the first article you saw that controllers have a Controller suffix and are stored in the grails-app/controller directory. In the second article, you learned that domain models can be found in the grails-app/domain directory.

This month, I’ll round out the MVC triptych with a discussion of Grails views. Views (as you might guess) are stored in the grails-app/views directory. But there’s much more to the view story than the intuitively obvious directory name. I’ll talk about Groovy Server Pages (GSP) and give you pointers to many alternative view options. You’ll learn about the standard Grails tag libraries (TagLibs) and find out how easy it is to create your own TagLib. You’ll see how to fight the ongoing battle for DRYness (see Resources) by factoring common fragments of GSP code into their own partial templates. Finally, you’ll learn how to tweak the default templates for scaffolded views, thereby balancing the convenience of automatically created views with the desire to move beyond a Grails application’s default look-and-feel.

– See Original @ DeveloperWorks (Scott Davis)

Tags: , ,

My First Impressions of Grails (Tyro Trader)

, , February 22nd, 2008

I’m embarrassed to say that I’ve become a “Java Guy”. It’s fine to know a language well, but when you become defined by a single language, you’ve given up learning. It’s a polite way of saying that you stopped caring. At different points in my life I’d try new languages, new tools and play around, just to learn. In fact, that was how I got interested in Java in the beginning - I was in school and I heard of this new “Java” thing which was only in version 0.6 or 0.7 but already it seemed pretty cool so I printed off the specs and got ahold of the alpha releases from sun and started hacking. What a hoot!

I’ve only done something like that a handful of times and in each case, real life work ground me down. The last time was when I got interested in AspectJ and Aspect Oriented Programming. It seemed very cool and I talked a lot about it with my co-workers and then made the mistake of pushing to get it adopted on a big project. Next thing I new, every bug and every question that arose in any one of a dozen different teams spread across three countries would arrive at my desk and I quickly grew to loathe the whole process. Now that I’m working independently, I’ve had a chance to look into a number of different toolkits and languages, but I never drifted too far from Java.

On a whim, I started playing with a language called Groovy and Grails which compile down to Java bytecode which was “safe” and smart as it let me use all the libraries I’ve already written, but wow, what an difference! To start, here’s what I had in mind for the application.

I want something which can centralize a lot of the swing trading related tasks that I perform regularly and I thought it would be interesting to place them all into a single webapplication. It would let me import all of the executions from Interactive Brokers into a database, define my trades with stoplosses, handle reporting and generate charts (all things I do now using a fat client I wrote in SWT a couple years back), but it would also display an updating list of the most active stocks on the exchanges, compare the different sectors, list some of my watchlists and gather together the different scans that I run during the week.

Over the years, I’ve written dozens of web apps and I’ve grown to hate them. So bloody tedious. If you want to add a page which does something slightly different like say search for trades within a certain date range, then you’ve got to code the new command, register the new command in three different configuration files so the servlet engine knows how to handle it, add new search methods to your DAO, write new SQL to retrieve the data and splatter it throughout your configuration files, handle errors and on and on. I grew to accept it, but I never liked it which is why I wrote my first application for trading as a fat, desktop application - I’d had it with web apps.

But Groovy on Grails is different. It’s founding principle is “Don’t Repeat Yourself” and it does it excellently. It takes some of the strongest features of Groovy and pushes them hard. The domain objects just declare their fields and their constraints and Grails maintains all of the database tables, the CRUD methods (Create, Retrieve, Update, Delete) and a boggling-array of retrieval methods. It also has the simplest way of adding new web services I’ve seen - you just add a new method (”Closure”, really) to a controller class and Grails will do all the wiring for rendering the page. For instance, my domain object “Executions” comes with list functionality by default, but I really want to list the Executions that haven’t been added to a trade, and I wanted to list the results. It wouldn’t be complicated to do using Struts or other frameworks, but it would be tedious and require changing a lot of files.

In Grails, it takes exactly two changes. I added one line to my gsp (”Groovy Server Page”) to link to the new search page:

    <g:link action="searchUnassigned">Search for Unassigned</g:link>

Then in the controller, I added a new “closure” matching this action:

def searchUnassigned = {
    render(view:'list',
        model:[exs: Execution.findAllByTradeIsNull()])
}

It builds a list of executions which do not have trades associated, and sends them to the list view. I didn’t even have to write any of the SQL, all the necessary information is in the function name and Grails is smart enough to handle it properly. And it works, first try!

I then went on to look at adding new Trades and found a line of code which really highlights why Groovy kicks so much ass over Java. The “saveTrade” method would have to extract all of the params from the request object, convert them to the correct object type, munge the order and pass it to the constructor, something like:

public void saveTrade(Request req, Response resp) {
try {
    Map<string,string> params = req.getHttpParameters();
    String symbol = (String)params.get("symbol");
    Date lastupdate = pstDateFormatter.parse((String)params.get("lastupdate"));
    double stoploss = Double.parseDouble((String)params.get("stoploss"));
    boolean isComplete = Boolean.parseBool((String)params.get("isComplete"));
} catch( Exception e ) {
    resp.redirect("error.jsp");
    return;
}
if( symbol == null || symbol.size()<> 6 ) {
    // invalid size
    resp.redirect("error.jsp");
    return;
}
// [...  more error checking ...]

Trade trade = new Trade(symbol, lastupdate, stoploss, isComplete);
if( !WebDAO.saveTrade(trade) ) {
    resp.redirect("error.jsp");
}

resp.put("trade", trade);
resp.redirect("show.jsp");
}

And that’s the short version without all the error checking (and no flames if the syntax isn’t quite correct - that should illustrate how hard it is to get this working properly). To make matters fun, all this stupid error checking has to be done everywhere that a trade is created. It’s bloody irritating and it’s hard to maintain. And this doesn’t even go into the depth of coding the freaking saveTrade() method, which is a pain in itself.

So how is this done in Groovy?

def save = {
def trade = new Trade(params)

if(!trade.hasErrors() && trade.save()) {
    flash.message = "Trade ${trade.id} created"
    redirect(action:show,id:trade.id)
}
else {
    render(view:'create',model:[trade:trade])
}
}

Because Groovy’s constructors take a map, you can just pass in the params map. Sweet, there’s a couple dozen lines shrunk down into one. And because the trade object already has a save() method built for you, no need to code it up. What’s especially interesting is that this reduced method (closure, actually) has better error handling than the huge Java method. And all of that work trying to check for valid data in the Java code? Simple, Grails lets you declare that in one place - in the Trade class where it belongs. Here’s what it looks like:

static constraints = {
symbol(maxLength:6,blank:false)
stoploss(min:1.00d, max:100000.00d)
}

How sweet is that? You do it in one place in a simple, declarative fashion without all the messy code and if you ever violate one of these constraints, it even generates friendly error messages telling you what went wrong! It’s just brilliant! It’s exactly how you want to write it, simple and clear and because it’s so simple and clear (and not replicated everywhere) it’s much less likely to have bugs.

AJAX and Plugins

AJAX is one of the Big Things in web sites these days. It’s the technology which allows Google Maps and GMail to act like desktop applications. It decomposes the page into tiny elements and uses JavaScript and custom web services to populate each element separately. That way you can read mail and refresh only the current message, and you can get notifications when new messages arrive without redrawing the entire page, and it lets you scroll Google Maps as if you had downloaded the entire atlas yet still lets pages load quickly. There are a lot of nifty tools to let you develop these applications without having to hand-code all of the JavaScript (like Google’s GWT) and Grails is no exception.

Grails isn’t wedded to a single technology either and lets you pick and choose, but this can lead to potential problems. One of the big failings that I’ve found with these large frameworks is how poorly integrated they are with other tools. Sure you can use JSF or portlets but can you make them work with anything else? Grails has dealt with this issue through the use of “plugins”. The Grails home stores a list of plugins that are vetted to work with the framework and you can automatically download them and all of the associated library versions. There are a lot of cool features of plugins (like integration with the Grails version) but I’ll just show you how easy they are to use.

I had always wanted to have a UI which would show a calendar-based view of my trades, much like Dave’s excellent Stocktickr journal tool but I couldn’t find a way to cram it into my SWT, Swing or AWT tools. But in the web world, MIT has a free tool called SIMILE | Timeline which does just what I want using a goop-load of JavaScript and XML. Fortunately, there is a plugin (”richui”) which simplifies most of the process. In your GSP, you add the tag:

<richui:timeline
    style="border: 1px; height: 450px; width: 100%;"
    startDate="${new Date() - 20}"
    datasource="http://localhost:8080/StockMonitor/reporting/timeEvents" />

and then in the ReportingController, create the “timeEvents” method (really a Closure, but that’s a discussion for another time) which returns the XML data to display. Again, Groovy comes to our aid with the Builder tools, letting us build the XML in a language-friendly fashion.

For my tool, I wanted to query all trades between a user-supplied interval and show my winners in green and losers in red, with incomplete trades marked with an icon and their symbol name:

def timeEvents = {
initParams(params)
   def trades = Trade.findAllByLastupdateBetween(
                        params.startDate, params.endDate)

render(contentType: "text/xml") {
    data() {
       trades.each() { trade ->
         if( trade.isComplete) {
            event('start':dateForm.format(trade.start()),
                  'end':dateForm.format(trade.end()),
                  'title': rForm.format(trade.R())+ "R",
                  )
         } else {
            event('start': dateForm.format(trade.start()),
                  'end':dateForm.format(new Date()),
                  'title': "${trade.symbol}",
                  'color': "blue"
                  )
          }
      }
    }

To non-coders it may look like a mess, but it’s pretty simple. It starts by fetching all matching trades, then builds the XML structure. The event() method declares an node with the attributes “start”, “end”, and “title”. And if you want to change from XML to JSON or other protocols, you just change the content type of the render() method and everything else remains the same!

The result is this:

(Perceptive readers may notice one reason why I’m trading very small size and why I’m not totally stoked with my performance in the market right now.)

So that’s one of the things I’ve been doing in my spare time. I also wrote a Groovy-based API for QuoteTracker which I’m cleaning up and bug testing with the hopes of writing a simple ATS that leverages the charting, studies and alert system of QuoteTracker (this was by far the hardest bit of code that I encountered on my last attempt and I’m trying to learn from my mistakes). I hope to expand this over the coming months and see if I can’t resurrect some day trading ideas.

Tyro Trader (Original)

Tags: , ,

eWeek: Groovy Climbing Programmer Ranks (Darryl Taft)

, , , , February 22nd, 2008

Groovy is what Java would look like if it had been invented in the 21st century, said one developer.

RESTON, Va. – Groovy is getting its groove on and is moving up the charts.

At the 2G Groovy/Grails Experience conference here, Scott Davis, author of several books on Groovy, Java and editor in chief of aboutGroovy.com, said the Groovy language is moving fast up the charts of languages favored by developers.

Groovy now ranks 31 on the list of top programming languages, according to Davis and data from the TIOBE Software BV. Groovy had cracked the top 100 six months ago, moving from 103 to 52, and jumped to its current position in a January poll. Java remains the most popular programming language today, followed by the C language, Visual Basic, PHP, C++, Perl, Python and C#. Fortan, ColdFusion and ActionScript, also rank higher than Groovy.

Groovy, based on Java, is a dynamic language that runs on the Java Virtual Machine, or JVM. James Strachan, the creator of Groovy, first discussed the language on his blog in 2003, but early versions of the language did not appear until 2004, and a 1.0 release came out in January of 2007.

“Groovy is what Java would look like if it had been invented in the 21st century,” Davis said, noting that Groovy is “the next generation of Java.”

Davis, who delivered the opening keynote for the Groovy/Grails Experience, said people often ask whether Groovy will be a replacement for Java.

“It’s like saying do you think icing will ever replace cake,” Davis said. “It’s the same kind of relationship here. What we do is put a nice Groovy facade over Java things like icing over a cake.”

Davis said there is a symbiotic relationship between Groovy and Java. And that makes all the difference between Groovy and other dynamic languages that run on the JVM, he said.

“There’s JRuby out there,” Davis said. JRuby is an implementation of Ruby that runs on the JVM.

“JRuby is a great dynamic language if you already know Ruby,” Davis said. “And Jython is a great dynamic language if you know Python. But when you run JRuby on the JVM you’ve got this weird kind of disconnect.”

However, “Groovy is targeted at us: Java developers,” Davis said. “It is for us by us.”

Moreover, “because of the linguistic similarities between Java and Groovy it’s painless for developers to switch between Java and Groovy,” Davis said.

To implement Groovy, all a Java developer needs to do is “add a single JAR (Java Archive file) to your classpath; you don’t have to rewrite a single line of code,” Davis said.

Groovy runs on Java 1.4, 1.5 or 1.6.

Meanwhile, Grails is a Web application framework based on Groovy that is patterned after Ruby on Rails. Grails co-creator Graeme Rocher said Grails 1.0 shipped earlier this month. Rocher is the project lead for the open-source Grails project.

“Grails is a fully integrated, modern Java Web application in a box,” Davis said.

Grails includes support for Asynchronous JavaScript and AJAX frameworks.

“The plug-in system is really where the strength of Grails comes from,” Davis said. “Grails is a simple core, but it’s infinitely extensible through its plug-in system.”

Salil Deshpande, a partner at Bay Partners, a venture capital firm, said, “what’s cool about Groovy is it’s basically a language that is very Ruby-like, but it’s a superset of Java.”

Further, Deshpande explained that because Groovy is based on Java then “enterprises can preserve their legacy investments in Java” to extend their development to a dynamic language or lightweight Web development framework such as Grails.

“For the six to nine million Java developers out there, it’s easier for these guys to go to Groovy and Grails instead of Ruby and Rails,” Deshpande said.

Indeed, Matthew Porter, founder of Contegix, a managed hosting firm, said Contegix went to Groovy and Grails for several reasons, including being able to use their existing skill set in enterprise Java.

Darryl Taft, eWEEK

Tags: , , , ,

Using Groovy with the Thinwire Ajax Framework (Chris Richardson)

June 16th, 2007

Thinwire, which is an open source Ajax framework, was one of the more interesting technologies that I encountered at JavaOne. It provides a Swing-like API for building a web GUI. Your application code, which runs in the web container, constructs a GUI component hierarchy, which is then rendered by an Ajax client in the browser. See the website for an example. Last year, I helped develop the server-side part of a similar framework along with a demo application. I found it to be an extremely compelling way of building a web application: nice server-side Java code with no messy HTML or JavaScript. It’s great to see that Thinwire are offering something similar.

In order to see whether Thinwire lives up to it’s promise I decided to build a Thinwire front-end to Project Track , which is a sample JSF, Spring, Hibernate and Acegi application developed by myself and Kito Mann. To make it a little more interesting I decided to use Groovy as the implementation language.

A major part of using Thinwire consist of building hierarchies of GUI components using code like this

  Dialog dialog= new Dialog(..)
  Button button = new Button(...)
  dialog.getChildren().add(button)

One of the neat things about Groovy is that has the concept of builders, which can simplify this kind of code. Here is what I came up with:

 class ThinwireBuilder extends BuilderSupport {

    def components = new ComponentContainer()

    public Object createNode(Object name, Map attributes) {
        def component = attributes.type.newInstance(attributes.label)
        components.put(name, component)
        if (attributes.bounds) {
            component.setBounds(*attributes)
        }
        if (attributes.click) {
            component.addActionListener("click", new MyActionListener(attributes.click));
            attributes.click.delegate = components
        }
        return component

    }

    public void setParent(parent, child) {
        parent.getChildren().add(child);
    }

....
}

The createNode() method instantiates a component using the attributes passed in as a Map (attributes.x is shorthand for attributes.get(”x”)). The builder also lets the click listener for a button be a Groovy closure, which eliminates the clutter of anonymous inner classes. The builder maintains a map of names to components using the components property, which is an instance of this class:

class ComponentContainer {

    def components

    ComponentContainer() {
        this.components = new HashMap()
    }

    public Object getProperty(String name) {
        return components.get(name)
    }

    public Object get(name) {
        return components.get(name)
    }

    public void put(name,value) {
        components.put(name, value)
    }

}

With this builder in place I was then able to rewrite Thinwire’s Hello World example like this:

public class Main {
    public static void main(String[] args) {

        def builder = new ThinwireBuilder()

        builder.dialog(type: Dialog, label: "Hello World, ThinWire Style!", bounds: [25, 25, 215, 120])  {
            label(type: Label, label: "Hello, what is your name?", bounds: [5, 5, 200, 25])
            input(type: TextField, bounds: [5, 35, 200, 25])
            button(type: Button, label: "Ok", bounds: [55, 65, 100, 25 ], click: {
               MessageBox.confirm("Hello " + input.getText() + "!");
               dialog.setVisible(false)
            } )
        }

        def dialog = builder.components.dialog
        dialog.setVisible(true);
    } 

}

Note that the closure that handles the click event references the input and dialog properties even though they have not been explicitly defined. That’s accomplished in the builder by setting the closure’s delegate to components. Quite slick!

The Main program is then specified as an init-param of the Thinwire Servlet:

  <servlet>
    <servlet-name>thinwire</servlet-name>
    <servlet-class>thinwire.render.web.WebServlet</servlet-class>

    <init-param>
      <param-name>mainClass</param-name>
      <param-value>net.chrisrichardson.thinwire-example.Main</param-value>
    </init-param>
  <//servlet>

I also had to add groovy support to the maven project, which is accomplished by using the maven groovy plugin:

            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>groovy-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

With that in place I could then type ‘mvn clean package cargo:start’ to run my Thinwire web application. This is what it looks like in the browser:

Hello World - Thinwire style

Next time, I’ll write about the Thinwire front-end for Project Track

Chris Richardson

Tags:

Grooovier Ways to Iterate Through Lists (Mark Palmer)

June 16th, 2007

There’s been a lot of people asking for a Java loop syntax in groovy. A lot if not almost all usages however are cleaner without it, once you know some idiomatic groovy.

Here are just some of the examples of looping constructs available in groovy:

def results = []
10.times { results << it }
assert results == [0,1,2,3,4,5,6,7,8,9]

results = []
0.step(10, 2) { results << it }
assert results == [0,2,4,6,8]

results = []
(1..10).each { results << it }
assert results == [1,2,3,4,5,6,7,8,9,10]

results = []
(1..10).step(2) { results << it }
assert results == [1,3,5,7,9]

def items = [‘one’, ‘two’, ‘three’, ‘four’]
results = []
items.eachWithIndex { item, idx ->
results << idx
}
assert results == [0,1,2,3]

There are a whole range of Groovy features at work here, from inline lists to ranges, GDK methods added to JDK classes such as step() on numeric types and of course closures.

Mark Palmer

Tags:

Using Groovy with the Thinwire Ajax Framework (Chris Richardson)

June 16th, 2007

Thinwire, which is an open source Ajax framework, was one of the more interesting technologies that I encountered at JavaOne. It provides a Swing-like API for building a web GUI. Your application code, which runs in the web container, constructs a GUI component hierarchy, which is then rendered by an Ajax client in the browser. See the website for an example. Last year, I helped develop the server-side part of a similar framework along with a demo application. I found it to be an extremely compelling way of building a web application: nice server-side Java code with no messy HTML or JavaScript. It’s great to see that Thinwire are offering something similar.

In order to see whether Thinwire lives up to it’s promise I decided to build a Thinwire front-end to Project Track , which is a sample JSF, Spring, Hibernate and Acegi application developed by myself and Kito Mann. To make it a little more interesting I decided to use Groovy as the implementation language.

A major part of using Thinwire consist of building hierarchies of GUI components using code like this

  Dialog dialog= new Dialog(..)
  Button button = new Button(...)
  dialog.getChildren().add(button)

One of the neat things about Groovy is that has the concept of builders, which can simplify this kind of code. Here is what I came up with:

 class ThinwireBuilder extends BuilderSupport {

    def components = new ComponentContainer()

    public Object createNode(Object name, Map attributes) {
        def component = attributes.type.newInstance(attributes.label)
        components.put(name, component)
        if (attributes.bounds) {
            component.setBounds(*attributes)
        }
        if (attributes.click) {
            component.addActionListener("click", new MyActionListener(attributes.click));
            attributes.click.delegate = components
        }
        return component

    }

    public void setParent(parent, child) {
        parent.getChildren().add(child);
    }

....
}

The createNode() method instantiates a component using the attributes passed in as a Map (attributes.x is shorthand for attributes.get(”x”)). The builder also lets the click listener for a button be a Groovy closure, which eliminates the clutter of anonymous inner classes. The builder maintains a map of names to components using the components property, which is an instance of this class:

class ComponentContainer {

    def components

    ComponentContainer() {
        this.components = new HashMap()
    }

    public Object getProperty(String name) {
        return components.get(name)
    }

    public Object get(name) {
        return components.get(name)
    }

    public void put(name,value) {
        components.put(name, value)
    }

}

With this builder in place I was then able to rewrite Thinwire’s Hello World example like this:

public class Main {
    public static void main(String[] args) {

        def builder = new ThinwireBuilder()

        builder.dialog(type: Dialog, label: "Hello World, ThinWire Style!", bounds: [25, 25, 215, 120])  {
            label(type: Label, label: "Hello, what is your name?", bounds: [5, 5, 200, 25])
            input(type: TextField, bounds: [5, 35, 200, 25])
            button(type: Button, label: "Ok", bounds: [55, 65, 100, 25 ], click: {
               MessageBox.confirm("Hello " + input.getText() + "!");
               dialog.setVisible(false)
            } )
        }

        def dialog = builder.components.dialog
        dialog.setVisible(true);
    } 

}

Note that the closure that handles the click event references the input and dialog properties even though they have not been explicitly defined. That’s accomplished in the builder by setting the closure’s delegate to components. Quite slick!

The Main program is then specified as an init-param of the Thinwire Servlet:

  <servlet>
    <servlet-name>thinwire</servlet-name>
    <servlet-class>thinwire.render.web.WebServlet</servlet-class>

    <init-param>
      <param-name>mainClass</param-name>
      <param-value>net.chrisrichardson.thinwire-example.Main</param-value>
    </init-param>
  <//servlet>

I also had to add groovy support to the maven project, which is accomplished by using the maven groovy plugin:

            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>groovy-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

With that in place I could then type ‘mvn clean package cargo:start’ to run my Thinwire web application. This is what it looks like in the browser:

Hello World - Thinwire style

Next time, I’ll write about the Thinwire front-end for Project Track

Chris Richardson

Tags: