Grails Exchange Demo App coming together...

I thought I would put together a quick demo app that demonstrated all of the things I’m going to be talking about at Grails Exchange so people have a nice “take-away” to play with at home.

Well… it’s a week to go and I’m half done… but a lot can happen on a long flight! For a teaser… here’s the home page… based on a little DZone inspiration..

gzone home page

And it wouldn’t be Web2.0 without CSS rollovers on those images… (technique from here).

gzone home page with mouse rollovers

Hopefully it will be a nice small sample app that can help get people started with some interesting grails features (browser thumbnails, pdf generation, rss feeds, and charting) . Will sort out a download link after the conference (hopefully the thing will actually get finished before then :-)

[Read More]

Implementing a simple toString() with Apache Commons

I think I’m only five years behind the rest of the world, but I’ve recently had need to tinker with Commons BeanUtils and Commons Lang and have found some very nice stuff in there…

I’ve always wanted an easy and generic way to dump out the properties of an object in toString() but never had the passion to follow through… Groovy gives you the super-quick obj.dump() to see all the properties of an object… and I’ve often wished there was a simple way to do that in Java. Well enter the very useful ToStringBuilder and life gets very simple…

If you don’t mind coupling your domain classes to commons-lang, they just use it in your toString() method…

public String toString() {
    return ToStringBuilder.reflectionToString(this);
}

And if you do mind coupling, or it’s a third party object you want to dump out from some client code…

log.info("Current Org: [" +
    ToStringBuilder.reflectionToString(org)
    + "]");

Either way the output is quite tidy… and arrays are handled nicely… (I’ve reformatted to fit here, this is all on one line)

INFO: Current Org: [au.com.bytecode.dto.Org@652295fd[
    groups={Group1,Group2,Group3},
    address=PO Box 123,
    orgName=SampleOrg]]

Top stuff! You can even pass your own formatting objects if there’s a particular way you want ToStringBuilder to format your output. Nice.

Props to the Commons Lang boys.. I’m not sure I’ll need to write a custom toString() method ever again!

[Read More]

My GrailsExchange Slides are in!

Phew! I’m finally done on my slides for my Grails Exchange presento. It’s gonna be a blast.

Outline of my Grails Exchange Talk

I’m packing a ton of stuff into 60 minutes. There’ll be stuff in there around JFreeChart, Rome, ehcache, wiki markup with Textile, scriptaculous, and Yahoo UI. Hopefully something for everyone!

Can’t wait! If you’re coming, make sure you drop by and say hello! It’s a 25 hour flight.. so I’ll be the tired-looking guy with the Aussie accent.

See you there!

[Read More]

Apologies for tonight's groovyblogs outage...

Yes.. Well.. Tonight the server that hosts groovyblogs literally “let the smoke out”. I guess three years of 24x7 operations was too much for no-name whitebox hardware… but it was a stellar effort (I think it was around 250 days of uptime when I last checked).

Anyways… I’ve restored the postgres backup from the night before to some lower end hardware I had lying around… so there might be a little weirdness and slowness until I sort out a replacement.

Took the opportunity to upgrade Glassfish v2 final. My various demo webapps will come back online at time permits.

That was four hours of work that I wasn’t planning on… but it’s almost all back to square. Apologies for the inconvenience.

[Read More]

Generating Browser Thumbnails... at Grails Exchange!

Everything is coming together for Grails Exchange next month in London… it’s a long way for this Aussie to travel, and I’ve never been to the homeland, but I’m super excited about hanging out with all of you over there.

I’m presenting a session title The Whole Nine Yards which will cover 10 things you can do in 10 minutes that your users will just love. I’ll be taking a bunch of ideas from my prod grails apps, along with a few special sauces that I’m yet to reveal..

One funky little tip will centre around a quick way of dynamically generating those funky little website previews that you see on DZone. Here’s the groovyblogs thumbnail which needs less than 10 lines of groovy (and some nice Java library support :-):

A Thumbnail of groovyblogs.org

I’ll also be talking about waycool PDF generation, all things RSS, Charts and Graphs, and lots of other fun UI stuff. If you’re around London, make sure you register and come on over.

[Read More]

Goodnight SyncTheMilk: Just not fast enough to market....

This blog has been pretty quiet lately since I’ve been beavering hard on SyncTheMilk, my little Groovy app for syncing Outlook to Remember The Milk.

Sadly, though, SyncTheMilk will never make to 1.0, since the guys at RTM have released their own client called MilkSync which uses their own private SyncML interface. So it’s definitely time to call it a day. I came pretty close:

SyncTheMilk in action at 0.3

Anyways, I’ll leave 0.3 for download posterity. It was certainly a lot of fun to work on, and gave me a whole new perspective on how tricky the corner cases can be around syncing.

From a learning perspective I had a chance to put Groovy through its paces in the Business Domain and was really happy. Using Groovy greatly accelerated the XML/http stuff, and made the Outlook/COM integration easy. I also discovered some of the sync logic was probably better suited to a Java solution (I think Java’s static typing could have saved me a lot of time in there and saved me from a couple of hard to track down bugs where I was putting the wrong things into some of the collections).

From the Java side, I also had a chance to learn a little about SWT Progress Bars, Custom Field Editors, and Checkbox Listviewers.

Oh well… On to the next big idea… I’ve got a swag full of Grails ideas that are needing some attention… :-)

[Read More]

Dealing with Win32 Dates from Java (and Groovy)

I’ve been working hard on the Sync engine behind SyncTheMilk, which means doing tons of work with the Outlook COM model… it also means getting up to speed with Win32 scripting dates.

If you’re in the market for a good discussion of how Win32 scripting dates work, check out Chip Pearson’s article. If you thought Java dates were ugly..

Win32 dates are kept as an offset from an epoch of Jan 0, 1900. Yep, that’s no typo. January Zero. They have an integer part which represents the number of days since epoch, and then a fractional part that represents the percentage of the current day. So… in Canberra local time…

39220.54722673611 == Fri May 18 13:08:00 EST 2007

I know what you’re thinking… How about a little code so I can google for this later? Sure… Here’s a little quick and dirty Groovy for converting Win32 dates to Java dates:

Date winToJavaDate(BigDecimal d) {

    if (!d) return null

    def daysSinceEpoch = d.intValue()
    def percentOfDay = d - daysSinceEpoch		

    Calendar jCal = Calendar.getInstance()
    jCal.set(1900, 0, 0, 0, 0, 0)
    jCal.add(Calendar.DATE, daysSinceEpoch-1)

    def msPerDay = 1000 * 60 * 60 * 24
    def msOffset = msPerDay * percentOfDay

    jCal.add(Calendar.MILLISECOND, msOffset.intValue())
    return jCal.getTime()

}

And you’re off and running. A little more work on my Syncing robustness and I’ll have my first little rich UI Groovy-powered app to set free…

Stay tuned…

[Read More]

SyncTheMilk: Business logic in Groovy, UI in Java

I’m getting close to my first release of SyncTheMilk, my little Outlook and RememberTheMilk task synchronisation tool. Most of the business logic is done, and I’m starting work on the UI makeover right now.

One of the interesting features of the app is that while the UI is written completely in Java, and all of the core business logic is in Groovy.

SyncTheMilk in progress GUI makeover

One of the things that I truly love about the Groovy community is that we are, on the whole, a bunch of pragmatists. We’re mostly practitioners. We use Groovy where is makes sense, and makes our life simpler, and drop back to Java when it doesn’t.

For SyncTheMilk, the business logic does tons of xml/http to the RTM API service (XmlSlurper rocks so hard!), a little bit of Crypto, lot of work with the Outlook COM model (via Scriptom), and has pluggable Sync drivers, so I should, in theory, be able to Sync RememberTheMilk to just about anything!

Groovy makes all of those things simple, so it made sense to write all of the Business Logic in Groovy. But when it came to the UI, I’ve found I’m much more productive with some sort of visual designer, so SWT Designer just made so much sense. (FD: I have a free copy, it’s not cheap but it is just amazing)

Anyways, will have something to show in a couple of weeks. Planning on a free version and a pro version to raise a little money for charity. Not sure if there are other Commercial Groovy desktop apps out there… Should be an interesting experiment!

[Read More]

opencsv 1.8 ships - now with Bean binding

For reasons I’ll never understand, my little Apache2 open source CSV parser, opencsv has recently trucked through the 20,000 download mark.

Thanks to some wonderful work from Kyle Miller, I’ve just shipped version 1.8 which includes Kyle’s neat little Bean binding framework. Using one of Kyle’s various binding strategies (column position, column name, custom strategy), you can now bind a CSV file to a list of beans:

      ColumnPositionMappingStrategy strat = new ColumnPositionMappingStrategy();
      strat.setType(YourOrderBean.class);
      String[] columns = new String[] {"name", "orderNumber", "id"};
      strat.setColumnMapping(columns);

      CsvToBean csv = new CsvToBean();
      List list = csv.parse(strat, yourReader);

Great stuff, Kyle!

You can grab the new version from the download page, or checkout the javadoc, or see some sample usage scenarios.

Enjoy!

[Read More]

Cuteness with Commons-Http: proxies and user-agents

I’ve been wanting to add a custom User-Agent to groovyblogs.org for a while, so you know from your logs when I’m coming by to poll. It’s not easy to find sample code on this one, but the API does cover it just fine:

def client = new HttpClient()

def clientParams = client.getParams()
clientParams.setParameter(
    org.apache.commons.httpclient.params.HttpClientParams.USER_AGENT,
    "GroovyBlogs/1.0 (http://www.groovyblogs.org)")

If you need to enable your client for proxy support too, you’ll need to add a couple of more lines:

def hostConfig = client.getHostConfiguration()
hostConfig.setProxy("yourhost", 8080)

If it’s only proxy access you need, and you don’t need to mess with custom user agents or POSTed params, then I’ve found the simple URL class with some groovy enhancements is all I need: (just love that text property!)

System.properties["http.proxyHost"] = "yourhost";
System.properties["http.proxyPort"] = "8080";

def url = new URL("http://www.groovyblogs.org/")
println url.text

Happy proxying with your new User-Agent!

[Read More]

Transparently Feedburning Pebble with UrlRewriteFilter

I’ve been looking for a chance to play with UrlRewriteFilter for a while.. and I’ve finally found my opportunity.

A colleague has been talking up FeedBurner as a very swish feed stats crunching and decoration site, so I was keen to take it for a spin. I was asking how to handle the fact that you would need all your clients to add the new feed address? He mentioned that WordPress can do this with a simple plugin, so I figured I could get Pebble to work the same magic.

Enter UrlRewriteFilter. Catch the old feed address, send a redirect to the FeedBurner address, voila.

Deploying UrlRewriteFilter is a snap. Copy the jar file to your /WEB-INF/lib/ directory, copy a urlwrite.xml to your /WEB-INF/ directory, then hack web.xml to enable the filter. If you’re doing this for Pebble, insert the following entries after the jsp-config section of your web.xml:


   <filter>
        <filter-name>UrlRewriteFilter</filter-name>
        <filter-class>org.tuckey.web.filters.urlrewrite.UrlRewriteFilter</filter-class>
        <init-param>
            <param-name>confReloadCheckInterval</param-name>
            <param-value>3600</param-value>
        </init-param>
    </filter>

Probably don’t need the added “reload every hour” parameter unless you plan on messing with your config. I had it reloading its config file every few seconds when I was messing with pattern matching.

Now to the pattern matching part of the equation. I needed to match a pattern of /glen/rss.xml or /glen/atom.xml and send the user off to http://feeds.feedburner.com/glensmith, but the trick was that I needed to exclude all my category specific feeds in /glen/categories/General/rss.xml. Oh, and I also need to let a User-Agent containing the text “FeedBurner” through to the real feed, while redirecting everyone else. Turns out all that’s supported out of the box. Here’s my urlrewrite.xml:


<rule>
        <note>
            Redirect Root RSS/Atom feed to feedburner
        </note>

        <condition name="user-agent" operator="notequal">FeedBurner</condition>
        <condition type="request-uri" operator="notequal">categories</condition>
        <condition type="request-uri" operator="equal">glen</condition>
        <from>.xml$</from>
        <set type="response-header" name="Location">http://feeds.feedburner.com/glensmith
        <set type="response-header" name="Pragma">no-cache</set>
        <set type="response-header" name="Content-Length">0</set>
        <set type="status">307</set>
    </rule>

Fantastic. I’m now transparently redirecting clients to the new location, and with those pragma settings, I’m able to switch everything off in a flash. And it’s a ton more configurable than any ServletFilter that I could have whipped up for the task.

Great stuff UrlRewriteFilter folk!

[Read More]

Less is More: Migrating from Grails 0.2 to 0.5.6

My very first grails app was a simple SMS gateway called CyaThen.com. It was mostly developed on Grails 0.1 and then later migrated to 0.2 beta before the go live in August 2006 . It’s proved very useful for SMSing workmates to remember their squash gear.

Anyways, I did a rebuild on the app with Grails 0.4.2 so I could deploy it to Glassfish, but it was pretty unchanged from it’s 0.1 Grails glory. I’ve recently been updating it to 0.5.6 and uncovered some Gems from the “good ol’ days”…

Don’t you remember when every GORM class need hibernate ids embedded…

Long id
Long version

Back then, men were men, and there was one and only one ApplicationDataSource and log4j.properties

Back in the old days, if you wanted to def a taglib, you wanted to let the world know with an @Property

@Property welcome = { attrs ->
...
}

All the standard taglibs have been banished to plugins now anyways. And who could forget the best friend of every Domain class was a nice hashCode()… and equals()… and toString()…

String toString() { "${this.class.name} :  $id" }

    boolean equals(other) {
        if(other?.is(this))return true
        if(!(other instanceof Account)) return false

        if(!id || !other?.id || id!=other?.id) return false

        return true
    }

    int hashCode() {
        int hashCode = 0
        hashCode = 29 * (hashCode + ( !id ? 0 : id ^ (id >>> 32) ) )
    }
[Read More]

Upgrade to Glassfish 2, slash your bandwidth usage by half

I’m a couple of days into making the switch from Glassfish v1 UR1 to Glassfish v2 beta-2 and I’ve gotta say that, even at beta level, this is a compelling upgrade.

There are tons of improvements in v2 (including first class clustering support), but there were two compelling features for me personally in v2 to make me move over to the new beta:

  • Http Compression Support
  • Much improved Virtual Domain support

The Http Compression support was a big step up. Tomcat users have had this for a while, but it was only introduced to Glassfish in v2. Jean-Francois has documented this ages ago, and you can do it all via the GUI in beta 2 (just put in “compression” equals “on” in the properties of your http-listener-1 page). This has been a killer for me as I creep closer and closer to my ADSL allowance. Check this out:

Graph showing compression effectiveness

The first two days were before enabling compression (and are representative of my standard traffic profile) at just under 400Mb/day, the next two days are once I turned on compression - just under 200Mb/day. Awesome! My traffic cut in half! If I tune the default compressibleMimeTypes I might even be able to improve on that!

The other killer feature for me in v2 is much improved Virtual Domain management. I host about 5 different domains on my current server and I had all sorts of issues with default apps on virtual servers under v1.0. I would often get my “default application” for a particular server starting up twice - which led to all sort of dramas (hibernate concurrency issues, excess memory usage, etc). All that has gone away under V2.0 - and I can see from the logs everything is just starting up once! Under v2, I can also bind multiple apps to the “/“ context - since they each run on different virtual servers. Awesome!

One thing I have also noticed in V2 is much snappier performance on both startup and render times. All my Grails apps continue to run just fine - and I took the opportunity to move to Grails 0.5 which is also much faster to startup.

The only real gotcha was the need to enable access logs (which are turned off by default), and needing to tune my log format, but once that was done my awstats continued working just fine. Also need to add -Djava.awt.headless=true to my JVM params to keep my charting stuff working happily.

Big props to the Glassfish guys. They’ve done an awesome job with this upgrade.

[Read More]

Setting up a WebDAV Server on Glassfish

I’ve always wanted to have a tinker with WebDAV, but never really had a good excuse to have a look at it. Since I’ve had to get up to speed with Maven, I’ve finally had a reason to get a WebDAV server happening locally for a few developers to share a repository. Turns out that running a WebDAV server on Glassfish (or whatever app server you like) is a snack thanks to the good folk at the WebDAV-Servlet project.

Here’s the steps you need to know:

  1. Head on over to the downloads page and grab the .war edition
  2. Unjar the war file and edit /WEB-INF/web.xml. Change the “rootpath” parameter to point to a place on your webserver filesystem where you want to store you WebDAV’d files (eg /data/webdav)
  3. Rejar the war and deploy
  4. Point your fave webdav client at your new site

IE works just fine as a WebDAV client if you just want to browse a repository. Select /File/Open… tick the “Open as Web Folder” setting and point it at your freshly installed WebDAV URL.

Opening a WebFolder WebDAV URL in IE6

Once things fire up, you can happily drag and drop to and from the web folder. Works great!

Browsing a WebFolder WebDAV URL in IE6

Now I’m doing all this on a small intranet, so my security concerns are pretty low… I would be thinking twice before I installed this sort of stuff on my public facing boxes. But very handy for an internal shared Maven repository…

Props to the WebDAV servlet folks for a very cool little app!

[Read More]

A First Look at GroovySWT

I’ve been working on my little app to Sync Outlook to Remember The Milk and having a great time learning GroovySWT along the way. GroovySWT offers a SwtBuilder and JFaceBuilder (simple DSL) for putting together SWT/JFace applications. Now I’m a huge fan of both SWT and JFace, so I was very keen to see what GroovySWT could let me do from straight groovy code.

It’s very early days for the GUI, but I’ve thrown together some scratchy ideas using the Tango Icon Library to get a basic interface underway.

SyncTheMilk in action on OSX

I still think the ideal way to build GUIs is with a tool. Even with the sensational DSLs that SwingBuilder and SwtBuilder give you, nothing beats dragging and dropping stuff around (personal fave is SWT Designer, which is unbelievably good - FD: I managed to get a free copy from the early days).

But if your GUI is very simple (like the one shown above), it really does seems a shame not to be able to throw something together really quickly using straight groovy, and GroovySWT gives you that in spades. How about a little Preferences dialog for your app which automatically persists user entries to a .properties file?

An SWT Preferences dialog

preferenceDialog() {

    preferencePage( title:"Proxy Settings", filename:"syncthemilk.properties" ) {
        booleanFieldEditor( propertyName:"proxyEnabled", title:"Enable Proxy" )
        stringFieldEditor( propertyName:"proxyHost", title:"Proxy Host" )
        integerFieldEditor( propertyName:"proxyPort", title:"Proxy Port" )
    } 		

    preferencePage( title:"RTM Settings", filename:"syncthemilk.properties" ) {
        stringFieldEditor( propertyName:"rtmToken", title:"RTM Token" )
    }
}

I’ve found a few little bugs in the current groovy-swt source which I’ll bundle up in a patch and submit once I have the full GUI for my app done. That should let me exercise a good part of the library.

The only major shortcoming I’ve found so far is there is virtually no documentation. There are, however, a ton of good examples that demonstrate many of the cool and interesting parts of the library (including tray integration, properties dialogs, wizards, and more).

I’ll update the Groovy wiki with some new info once I’ve had a chance to get my own GUI done.

[Read More]

Getting Groovy with Hudson and Cobertura

Gave a talk last night at our local Canberra JUG on using Hudson for continuous integration. (Brief slides available, but it was mostly a “demo” style talk… so not much to show)

But to spice it up a little, I used my latest little Groovy project as the demo. I was reading in Groovy in Action about the support Groovy Unit tests have for both IDE integration and coverage tools, so I thought I’d throw that into the mix. Using JUnit from Eclipse works just great…

Groovy with JUnit in Eclipse

I did have some problems getting my tests running from Ant, getting an error like:

groovyc doesn't support the "srcdir" attribute

Which turns out to mean that I’d defined my groovyc task incorrectly. It needed to be:

<taskdef name="groovyc"
    classname="org.codehaus.groovy.ant.Groovyc"
    classpathref="useful.jars"/>

One thing I have been wanting to try out is Cobertura support for Groovy. Turns out to be a snack. The only gotcha is that you must set fork="true" on your JUnit task. If you don’t, all your coverage reports will appear blank (ie with 0% coverage).

Groovy Cobertura in Action

[Read More]

Scripting the Milk: Powering Outlook from Groovy

I’ve always been a TODO list kinda guy and the only product that I’ve found works well with my PocketPC is Outlook. That’s cool when I’m on client sites (since they all run Outlook), except that I’d like to be able to use some other tool when I’m hacking away on my Macbook.

Well lately I’ve been tinkering with Remember The Milk to see what online TODO managers have to offer. I think RTM is even built by a bunch of Aussies, so it gets extra points. The only thing it doesn’t do yet is Outlook integration… But they do offer a pretty comprehensive REST-based API. You know where I’m heading with this right? How hard could it be?

Ok, so a little bit of XmlSlurper action from Groovy and I’m all set and parsing out my tasks straight from RTM method responses. But how am I going to get to my Outlook tasks? Outlook has got some kinda COM story going on…

I’ve used JNIWrapper in the past for getting to COM based stuff, and it works just great - but the upgrade prices were starting to hurt, so I checked out com4j. Very neat little project - and an almost entire replacement for JNIWrapper. Pointed it at my outlook tlb file and voila! Full set of Java classes to match with Outlook… but then I remembered that Guillaume had done some funky Groovy/COM library that he wrote up for Groovy In Action. Grabbed my copy of GINA and checked it out…

Enter Scriptom. This is the COM integration library that I’ve been looking for. No need to generate any classes, just give it a COM object and start calling methods. Takes advantage of Groovy dynamic typing goodness to make it all very easy.

Need to get to your Outlook tasks? Howse about something like:

import org.codehaus.groovy.scriptom.ActiveXProxy

def outlook = new ActiveXProxy("Outlook.Application")
def namespace = outlook.GetNamespace("MAPI") 

def taskFolder = namespace.GetDefaultFolder(13) // tasks
def tasks = taskFolder.Items

for (i in 1..tasks.Count.value) {
    def task = tasks.Item(i)
    if (task.Complete.value == false) {
        println task.Subject.value
    }
}

Sensational. I'm now in a position where I can get my list of Outlook tasks, and my RTM tasks... now the tricky bit around doing the merge. Both support a "last modified" attribute, so it should be ok to handle the actual time mods, but I'm still not sure how I'm going to handle task renames? I guess I'll need to tag the RTM entries with an Outlook task id... That could get interesting...

Anways, double thumbs up to Scriptom. Guilluame has done some sensational stuff there. Will post some more when I’ve got something working…

[Read More]

Antlr, DSLs and Business Grads....

Truth be known, I’ve never really been very interested in Computer Science. My undergrad is in Business, and my postgrad is in IT. I was busy writing COBOL-80 applications while the Comp Sci guys were building logic gates on patch panels.

For the most part it’s put me in good stead career-wise since the things you pickup in those HR, Marketing, and Stats units are actually quite useful in the IT space. But there are a few things you miss out on…

One unit I never did get a chance to pick up was Compiler design. I’ve often eyed off that dragon book and wondered what interesting stuff lurks beneath. I’ve done a little Flex when I was working as a C systems programmer in the early days, and a ton of Perl regular expressions since, but never really got into hardcore lexer/parser goodness.

Turns out that I haven’t missed out, as the whole space is getting a little resurgence through the whole Domain Specific Language movement. So I’m catching up some missed knowledge in my spare time while tinkering with Antlr.

My first little project is to trying to write a very simple lexer for Textile. I know, I know. There are already a few Java parsers already out there, but it’s pretty tricky to get all the combinations of nesting right in regexps, so I’m keen to see how far I could get with a full blown parser. Plus it’s mainly a learning exercise (but it will end up in a Grail project on my drawing board somewhere down the track).

Antlr is quick a beast. But the documentation is growing and I’ve found a couple of good articles that have been helpful in getting started. Also turns out that Textile is quite like TML, so there are some grammars to kickstart things. And ANTLRWorks is a very cool little IDE.

It’s hard yards… but we’ll see how I go…

[Read More]

Eclipse Tip: Breakpoint on Exception

I’ve been starting to read up on Eclipse Rich Client Platform programming using the excellent RCP Book. Along the way they’ve introduced me to a few things I didn’t know about Eclipse itself.

One of the very cool things that I didn’t know about is that Eclipse will let you set breakpoints based on where an Exception occurs. This is going to be a huge timesaver! You access the option via the “j!” icon in the debugging window.

Getting to the option via the Breakpoing j! icon

And if you click on the “j!” icon on the right you are greeted with the magic dialog:

Adding a Breakpoint based on an exception

Select the exception type you want to breakpoint on, and you’re off and running. You can even choose whether you want to breakpoint on uncaught or caught versions! Very funky stuff.

This whole RCP exploration thing is actually looking quite promising. A lot to learn, for sure, but there’s some very cool stuff in there. I’m also really looking forward to tinkering with Groovy Monkey to do some RCP prototyping once I have a bit of an idea how RCP apps hang together.

Anyways, hope you guys all have a sensational easter! For those of you interested in exploring spirituality over the season, I can recommend Christian City Church as one of many great places to hang out over Easter. I’ll be in Belconnen.

Happy breakpointing!

[Read More]

The Groovy Spaceship Operator

I’ve been digging into Groovy in Action lately. I read the .75 review copy, which was extremely cool. The final release of the book included a ton of even cooler stuff!

One thing that did appear in the final version was a ton of interesting reference information, including very comprehensive tables in the body of the text. One of the operators I hadn’t seen before was the “spaceship operator” <=>. Now I remember this bad boy from my Perl days, but I didn’t know Groovy had an equivalent.

So when might you use this guy? Whenever you need to implementing sorting in a hurry, like implementing a compareTo(). The spaceship will return -1 if the left side is smaller, 1 if the left side is greater, and 0 if both sides are equal. Perfect for sorting, no? Seeing it in action makes it clearer…

println 3 <=> 4
println "glen" <=> "dierk"
def d = new Date()
println d <=> d
println d <=> new Date()

Which gives you....

-1
1
0
-1

Turns out that I have an immediate use for it. I’m working on fixing some nasty bugs in my dodgy chart generation code for groovyblogs. The good old spaceship is going to make some of my sorts one-liners.

How groovy is that? Beam me up!

[Read More]

Getting Groovy with Language Translation APIs

The Groovy community is a very international one… so it’s no surprise that GroovyBlogs ends up getting entries in all sorts of languages, particularly Spanish. As someone with no exposure to non-english applications or any i18n stuff (shame on me, I know) all these UTF-8 issues are quite a head spin…

So I’ve been thinking that some of those non-english entries look pretty interesting, there must be some Java translation APIs out there I can call to do an inplace-translation? Even a webservice would be nice? You’d think, but you’d be wrong. The best I can manage without violating terms of service is to link you off to Google, for now. But how do you work out what language the source document is written in?

At the moment I’m using textcat which is a cute little library for doing just that. Bundles with a small section of languages, but the jar seems to contain signatures for a whole lot more. Just need to work out how to activate them… The API is a one liner:

def guesser = new org.knallgrau.utils.textcat.TextCategorizer()
def category = guesser.categorize(yourString)

which will return the string “spanish”. Combine that with Groovy hashmaps, templates and Google linking goodness, and you get something like:

Translation in action at GroovyBlogs

where that Translate link will send you off to Google translate with the “Spanish to English” option. Still not so accurate for some languages (notable portuguese), but that may just be activating the correct rulesets that come bundled with the jar.

Anyways, kudos to the textcat guys for a great little library. Now back to working out how to get portuguese happening… And sorting out my current UTF8 encoding woes…

[Read More]

Getting Jiggy with JFreeChart

Jim Clark has put together a great little JFreeChart builder for Groovy called GroovyChart. I’ve been thinking for a while that I’d love to add some simple charting to GroovyBlogs, and I figure this was a great way to get into it. I’ve had a play, and could generate the demo charts just fine, but once I wanted to go a little deeper, I got a little lost in the builder semantics. It looks like it’s going to be a great little library, though.

So I retreated to using the standard JFreeChart APIs, working off some of the samples you get with the manual, and I’ve got my first little chart happening. Still a little work to do on the fonts, but it’s travelling very nicely:

Stats Graph with Alpha Blend

That alpha-blending transparency on the png was the only really tricky bit and courtesy of a little of Aaron’s magic, even that is very doable. The final pieces of implementing the magic in my Grails controller ended up being:

chart.setBackgroundPaint(new Color(255,255,255,0))
KeypointPNGEncoderAdapter encoder = new KeypointPNGEncoderAdapter()
encoder.setEncodingAlpha(true)

def cb = encoder.encode(chart.createBufferedImage(170, 150,
     BufferedImage.BITMASK, null))

response.setContentType("image/png")
response.setContentLength(cb.length)
response.getOutputStream().write(cb)

Hope to get it deployed to prod groovyblogs later in the week. I’ve also got some interesting translation functionality in the mix, too. So stay tuned…

[Read More]

Calculating stats for your Grails project

After developing in Grails for a while, I went to a Rails talk by Matt. He demoed developing a little blogging app, and I recognised that I could do most of what he was talking about just as quickly and easily in Grails.

But one cool little thing he demoed was the “rake stats” command. This gave you a bunch of metrics on your project (lines of code, test/code ratios, NCLOC, etc). Check out a sample run.

Anyways, I thought it was a neat feature, and I was keen to run a similar thing for groovyblogs, so I set aside a lunch hour putting together a cheap and cheerful version in Groovy. Certainly not anywhere near as feature complete, but it’ll get us started, and maybe someone out there will pick up the batton and run with it. Here’s my output from a “grails stats” command when run on the groovyblogs source base:


        +----------------------+-------+-------+
        | Name                 | Files |  LOC  |
        +----------------------+-------+-------+
        | Controllers          |     7 |   588 |
        | Domain Classes       |     3 |   101 |
        | Jobs                 |     3 |    66 |
        | Services             |     6 |   618 |
        | Tag Libraries        |     2 |   207 |
        | Tests                |    11 |    66 |
        | Groovy Helpers       |     5 |   179 |
        +----------------------+-------+-------+
        | Totals               |    37 |  1825 |
        +----------------------+-------+-------+

Mine is very rudimentary, simply calculating the number of files and total lines of code (sorry, no smart stuff around whitespace or comments).

The amazing part is how quick is it to whip this sort of thing up in groovy. Building that table I became acquainted with the String.padRight() and String.padLeft() enhancements. Add the File.eachFileRecurse closure and a sprinkling of Expandos, and voila! You’ve saved an incredible amount of mucking about!

Converting to a command that can integrate with Grails commandline was pretty much a drag and drop to the “scripts” directory along with a few scaffold lines to return the name of the target. A snack!

Anyways, I’ll talk to the Grails boys and see if I can get it added to a future release. In the meantime, if you’re keen to use it in your own project, grab Stats.groovy from the downloads directory, and put it in your $GRAILS_HOME/scripts directory. Then you’re only a “grails stats” away from getting a lay of the land.

[Read More]

24 Hours of groovyblogs.org: source now available

Well the first 24 hours of groovyblogs.org was a senssational one. Only one outage due to the most fierce electrical storm we’ve had in Canberra for ages. Note to self: move the router onto the UPS as well.

I’m pleased to announce that the complete source code for the site (including art) is now available, so if you’ve been wondering how much dodgy-ness can be crammed into 22 hours, now’s your chance to find out.

Should be a nice sample app for people to learn about fulltext search, RSS aggregation and generation, caching, and some simple Ajax uses.

Have updated the site with some fixes today based on the first 23 hours. The first fix was to suppress any entries not containing groovy or grails keywords. I think a lot of people may have thought that groovyblogs.org was just a general java aggregator written in groovy/grails. Fair enough.

Decided to make that more clear for people when they test their blog (with checkboxes for groovy related stuff). Incidentally, found a great site for icons in my quest for an open source tick and cross.

Filtering blog entries in the preview screen

Anyways, enjoy the source! And have fun with groovyblogs.org!

[Read More]