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:

Groovy Gaining Traction (Andrew Binstock)

June 9th, 2007

Andrew Binstock writes the “Integration Watch” column for SD Times and is a senior contributing editor at InfoWorld where he reviews middleware and enterprise software development tools. For the past 16 years, he has also been a judge for the Jolt awards. He wrote the following blog entry on Groovy’s traction after JavaOne 2007.

Java developers suddenly have a wealth of choices when it comes to dynamic languages that run on the JVM. There’s JavaFX, which Sun announced at JavaOne this year, and JRuby, which Sun expects to complete sometime this year, and then, of course, there’s my favorite: Groovy. Groovy makes writing Java programs far easier. It essentially takes Java and removes the syntactical cruft, leaving a neat language that makes you terrifically productive.

Because Groovy took a long time getting out of the gate, it’s taken some licks in the press. However, it’s clear that Java developers are catching on to its benefits. The JavaOne bookstore published its daily top-10 sales during the show. The picture on this post, shows the Day 2 list with two Groovy titles in the top 10 (at places 5 and 8). Overall, the Groovy bible, Groovy in Action, came in at number 5 for the show. Interest is definitely growing.

If you haven’t tried Groovy yourself, it’s definitely worth a look. Here are a couple of good overviews:

Dierk König followed up that:

Groovy in Action was #2 bestseller through day 3 of JavaOne and would have finished even better that #5 overall if it wouldn’t have been sold out by Thursday noon ;-)

Tags:

Krugle (The Code Search Engine) Adds Support for Groovy & Erlang

June 9th, 2007

We just rolled out an update to our public site, with some key improvements:

  • Better code index We added over 20,000 new projects, including many that are archive-only (no code available in a public SCM) from repositories such as SourceForge.net and Tigris. We now have over 2 billion lines of code in our index.
  • New languages We now support Erlang and Groovy. I’m guessing Yonatan and Al, among others, will be very excited about this. I know, we’re still missing ABAP, Forth, SCL, LabVIEW, etc, etc. Good God there are a lot of programming languages out there!
  • Revised Eclipse IDE plug-in The Eclipse plug-in is now at version 1.0.5.2, and recently passed the Ready for Rational gauntlet. You can download the latest version here. This link is still to the beta program page, but we’re transitioning to general availability.
  • Open API A big part of this release was cleaning up the RESTful API to our services, in preparation for public availability. If you’re interested, send email to support@krugle.com and request to be added to the documentation seed list.
  • Lots of cleanup For example, our code query parser is smarter about quoted terms. You can click on language graphs in a project page (like KDE). And many more fixes and features requested by our users - so keeping clicking that feedback link…it really works!
  • Top Projects As always, we continue to expand our list of top projects.

While the size of the index isn’t so important (see my early blog post on 1,563,644,824 reasons why size doesn’t matter), the fact that it’s grown by over 35% in the past 6 weeks is an important data point. We’re finding that the long tail of public code is longer and fatter than we thought. The rate at which we find new repositories and projects, as well as the rate at which new projects get added to existing repositories, isn’t slowing down. And as more companies decide to open up their source code, I expect to see an accelleration in the growth of public code.

Notice that I’m using the term “public code” instead of “open source software”. Another trend (for a future blog) is that we’re seeing an increasing amount of code released under what I call “look but don’t touch” licenses. Or maybe a better term would be “antique store” licenses, as in “you use it, you pay for it”. More on that later.

Getting back to the recent update to Krugle, I’m excited about opening up our API. You’ve been able to send in search requests and project links (via URLs) for quite a while - see this blog post by Chris Burmester from last October. What we’re doing now is providing public access to the back end APIs that actually power the Krugle web site and our Eclipse IDE plug-in. Using this API, you’ll have access to the same code, tech pages, and project data that you see on the public web site and via the Eclipse IDE plug-in.

So send us email if you’d like to get added to the documentation seed list (once again, that’s support@krugle.com), and include a short description of how you’re thinking of using the API.

Thanks,

– Ken, Krugle Blog

Tags:

Ruby/Rails vs. Groovy/Rails - I’ll Bite Just This Once

June 8th, 2007

I never intended to do a long-ish explanation of my position on the whole Groovy/Grails vs Ruby/Rails thing, but Migs’ and Graeme’s comments on my previous post prompted me to respond. I originally intended to answer them in another comment after Graeme’s, but my comment turned out longer, so I’m putting it up as a separate post instead.

Before going further, I have to warn everyone — I have ZERO tolerance for flames. Long convoluted debates to get to some technical ‘truth’ (or any other kind of ‘truth’ for that matter) are nothing but mental and intellectual masturbation, period. Consider yourselves warned.

Now then…

Actually, having a scripting language that compiles to bytecode from its inception has been something on my wishlist for the longest time, ever since I first fell in love with Python many years ago. If I recall correctly, for instance, Jython’s development lagged somewhat behind mainstream Python, and more so Java. Much as I loved Python (and Java), I couldn’t bring myself to bother with Jython.

Now, here comes Ruby. I’m sure its a great language; I ran through a tutorial article in a magazine and it seemed as simple as Python to learn, maybe even simpler. But, it was designed from the get-go to be interpreted, and when I started hearing about JRuby, I figured this would be the same story as with Python — development would always lag somewhat behind mainstream Ruby and/or Java; whether or not anybody admits it, Ruby will always be a second-class citizen on the Java platform.

I haven’t tried Groovy yet, but I find the idea of a [scripting language that is a] first-class Java platform citizen very appealing. Nobody doesn’t really claim that Ruby or Rails had no influence on the initial inspiration for Groovy and Grails, and I have no problem with that. Progress based on or inspired by something that came before, is not unheard of, even in the world of scientific research; in fact its only natural, I think, “standing on the shoulders of giants” and all that, as Einstein said.

As of now, I have no real scientific reason to judge which is ‘better’ or not, and I’m not inclined to do any exhaustive benchmarks on either side. There are other people on both sides of the fence who would only be too happy to do that, and probably do a much better job of it than I ever could. With no ‘real’ technological benchmark to base my judgement on, I’m left with only what ‘appeals’ to my own personal geek sensibilities.

I’m still, therefore, going to give Groovy/Grails a whirl one of these days. And when I say that, I mean just that — I’m not saying everybody else should be getting into Groovy/Grails too. I’m only saying I’m going to give Groovy/Grails a try. It’s not a moral statement of right or wrong, and its not a judgement of what’s better or not. It’s only a statement about what I’m going to do. Let everybody else go into benchmarks and long arguments on mailing lists if they want.

Joel at ThoughtForge

Tags:

Simple Avatar Uploader in Groovy (Clay Luther)

June 6th, 2007

Many collaborative websites allow the user to upload small images or avatars to visually represent the user on the website. Grails makes the upload and display of these images almost trivial.

In this example, we will not specify an exact size for the avatar, but use CSS scaling and assume a width-to-height ratio of 4:5.

To start, you need to add two fields to your User domain class, a byte[] to hold the raw image and a String to hold the mime-type of the image:

Domain Class: User.groovy

class User {
  String userid
  byte[] avatar
  String avatarType

  static constraints = {
    avatar(nullable:true, maxSize: 16384 /* 16K */)
    avatarType(nullable:true)
}

Next, create a view for the user to select the avatar image to upload:

User View: select_avatar.gsp

<fieldset>
  <legend>Avatar Upload</legend>
  <g:form action="upload_avatar" method="post" enctype="multipart/form-data">
    <label for="avatar">Avatar (16K)</label>
    <input type="file" name="avatar" id="avatar" />
    <div style="font-size:0.8em; margin: 1.0em;">
      For best results, your avatar should have a width-to-height ratio of 4:5.
      For example, if your image is 80 pixels wide, it should be 100 pixels high.
    </div>
    <input type="submit" class="buttons" value="Upload" />
  </g:form>
</fieldset>

Next, in your UserController, you will need to create a handler for the upload:

UserController.groovy:

def upload_avatar = {
  def user = User.current(session)  // or however you select the current user

  // Get the avatar file from the multi-part request
  def f = request.getFile('avatar')

  // List of OK mime-types
  def okcontents = ['image/png', 'image/jpeg', 'image/gif']
  if (! okcontents.contains(f.getContentType())) {
    flash.message = "Avatar must be one of: ${okcontents}"
    render(view:'select_avatar', model:[user:user])
    return;
  }

  // Save the image and mime type
  user.avatar = f.getBytes()
  user.avatarType = f.getContentType()
  log.info("File uploaded: " + user.avatarMimeType)

  // Validation works, will check if the image is too big
  if (!user.save()) {
    render(view:'select_avatar', model:[user:user])
    return;
  }
  flash.message = "Avatar (${user.avatarMimeType}, ${user.avatar.size()} bytes) uploaded."
  redirect(action:'show')
}

The final piece is extracting and displaying the avatar. First, you’ll need to create a handler on User and then some CSS styles to scale the image properly:

UserController.groovy:

def avatar_image = {
  def avatarUser = User.get(params.id)
  if (!avatarUser || !avatarUser.avatar || !avatarUser.avatarType) {
    response.sendError(404)
    return;
  }
  response.setContentType(avatarUser.avatarType)
  response.setContentLength(avatarUser.avatar.size())
  OutputStream out = response.getOutputStream();
  out.write(avatarUser.avatar);
  out.close();
}

Next, add a few classes to your stylesheet:

img.avatar {
  width: 6.0em;
  height: 7.5em;
}

img.avatar_small {
  width: 4em;
  height: 5em;
}

img.avatar_tiny {
  width: 2em;
  height: 2.5em;
}

Notice you don’t specify the precise size of the avatar, rather you use em-scaling and a 4:5 width-to-height ratio. This means the avatars will scale based on the user’s font/screen size preferences (more about em-scaling in CSS).

Finally, you can summon up a user’s avatar in a web page using a pattern similar to:

views/user/show.gsp:

<g:if test="${user.avatar}">
  <img class="avatar" src="${createLink(controller:'user', action:'avatar_image', id:user.ident())}" />
</g:if>

By changing the class of the <img> tag, you can change the size of the avatar on your page.

Clay Luther

Tags:

Groovy Use Case: Mock Business Interfaces with Groovy Implementations (Dewavrin Luc)

June 4th, 2007

I recently discovered Spring’s ability to declare beans that are script-based. This feature can be used to mock business interfaces with Groovy implementations. In a JavaEE container where startup and redeployment can take a while, it can be very useful, in pre-integration tests, to change the behaviour of your business services especially without redeploying the whole EAR or restarting the server.
Here’s an example declaration:

1
2
3
4
5
6
7
<bean id=“MockServiceImpl” class=“org.springframework.scripting.groovy.GroovyScriptFactory”>
<constructor-arg value=“${mocks.path}/MockServiceImpl.groovy”></constructor-arg>
</bean>

<bean class=“org.springframework.scripting.support.ScriptFactoryPostProcessor”>
<property name=“defaultRefreshCheckDelay” value=“2″></property>
</bean>

The “defaultRefreshCheckDelay” parameter sets the delay in seconds between checks for modifications of the script. and the groovy script:

1
2
3
4
5
6
7
public class MockServiceImpl implements Service {
    ProductsReturn returnCase1 = new ProductsReturn(fetchDate:Calendar.getInstance(),products:[new Product(id:1,name:“good”)])
    ProductsReturn emptyReturn = new ProductsReturn(fetchDate:Calendar.getInstance(),products:[])

    ReturnObject listProductsForUser(String userId) {
                 return  returnCase1
    }

I see many benefits in this solution:

  • hot-swapping implementations without redeployment.
  • returned objects can be dynamically generated. For instance if you want to return objects depending only one a given parameter it can be done easily.
  • more concise than XML (see xmlstubs a XML based mocking solution).

On a side note, groovy requires ASM 2.2.2 library so if you use hibernate use the cglib with no dependency library which includes asm classes in renamed packages. Also use Spring 2.0.3+ if you use AspectJ pointcut declarations or you can expect errors.
With maven profiles it ’s easy to build a mock and non-mocked service layer of an EAR.

Note that you can still inject the real implementations if you want to delegate work to it.

1
2
3
4
<bean id=“MockServiceImpl” class=“org.springframework.scripting.groovy.GroovyScriptFactory”>
<constructor-arg value=“${mocks.path}/MockServiceImpl.groovy”></constructor-arg>
<constructor-arg value=“ServiceImpl”></constructor-arg>
</bean>

On an other side note, I like both Groovy and JRuby but now tend to prefer Groovy because it leverages my knowledge of Java API. With Ruby i spend too much time finding the reference web site how to achieve things that i do almost naturally in Java. OTH, Ruby has its core API use closures. Closures are tightly integrated and tend to favor loose coupling.

–  Dewavrin Luc

Tags: