Pathfinder Blog
Topic Archive: Groovy

Grails and JSONP: How Easy is That?

Grails_logo
For all of those Java developers casting longing glances at their buddies doing Rails development, there is hope. Grails, which has just celebrated its 1.0 release, is a Rails-like "convention over configuration" framework that aims to do for the Java world what Rails has done for Ruby. Instead of Ruby, the dynamic programming language of choice is Groovy, which compiles to bytecode (no Groovy to Java translation) and integrates smoothly with just about any Java code you may be using.

I'll stop hyping Groovy and Grails in general here; there's plenty of good informational stuff on the Grails and Groovy home pages. I will note that if you run off the tracks a little bit, you can find yourself reading through 500-odd line stack traces of Groovy, Spring and Hibernate -- there's room for some improvement there.

One of the many nice things about Grails is it's support for JSON and XML. Let me put together a simple example that shows off some of Grails' power.

Continue reading »

Markdown, GWT & Regular Expressions in Groovy

If you haven't been able to tell yet, I like Groovy.

I was playing around with enabling some Markdown support in GWT (attempting to use Markdown-J from inside a TextArea instance widget).  Because Markdown-J relies on java.util.regex classes, it can not be invoked directly by GWT. I decided to take two approaches-- the first being to invoke the Markdown-J processor via an RPC call, and secondly to do it all on the client-side (which I will address later).

The first approach meant I could do some interesting things along the way in Groovy.  First off, I wanted to extend the Markdown processor to support table markup similar to, say, a FitNesse test (i.e turning markup like this):

|com.some.fixture.DummyTestFixturePlusOne|| input | expectedOutput? || 10    | 11              || 44    | 45              |

Into HTML output like this..

com.some.fixture.DummyTestFixturePlusOne
input expectedOutput?
10 11
44 45

Or other alternate (possibly interactive) representations of tabular data using GWT, if you get my drift (but that's another show).

The implementation of Markdown-J is relatively straightforward.  It makes heavy use of regular expressions (java.util.regex can not be referenced by GWT), and thereby serves as a good illustration of the paradox of regular expression support in Java:  You can get the job done, but it's rarely nice to look at.  Groovy makes it so much better.  Here's my first attempt to extend Markdown-J's "MarkdownProcessor" class from a Groovy class.  Nothing special up my sleeve here.

class MarkdownProcessorWithTableSupport extends MarkdownProcessor {    private static final tableRegex = /\|([\d \w\.]+)\|[\n\r](.*\|)(?:[\n\r]?[^\|])/

    public TextEditor runBlockGamut(TextEditor text) {        TextEditor editor = super.runBlockGamut(text)        String content = editor.toString()

        content.eachMatch (tableRegex) { match ->            String headerRow = match[1]            String tableContent = match[2]            // do something with this match..        }        return new TextEditor(content)    }}

This is enough code to extract the first two match groups in the regex and start doing something with them.  The only real item of value in this class is the regular expression.  That regex took me a bit of time to nail down, so obviously it's rewarding to have it represented as closely as possible without any of the double-backslash marks you find with Java strings.  Notice that Groovy avoids the '\\' hell when describing regular expressions with it's "slashy" style strings.  'tableRegex' is still a String, you see.  But unlike the double-quote delimiter, the '/' delimiter allows things like unescaped backslashes.

Other than the regex, everything else in the code is rather boilerplate (iterate over each match, generate some HTML markup, yadda yadda... you get the idea).  Take note of the 'eachMatch' invocation on my String content though.  There's more going on than you might imagine-- Groovy actually takes the regular expression and compiles it down to a java.util.regex.Pattern instance before evaluating the closure.  Isn't that nice?  After all, it's what I would have done in Java anyway.

What's next?  I think it makes sense to try something like Showdown and bake it into a GWT component.  This will be my first attempt to integrate some existing JS library and see how nicely it will play with GWT.  Stay tuned.

Topics: , ,

GWT Testing With Groovy? (Heck yeah!)

Speaking of GroovyTestCase, I experimented a bit with using both it and JMockit
as an alternative to GWTTestCase.  This may sound strange at first-- after all, the point of GWTTestCase is to exercise your code in the way it will eventually execute as JS at runtime.  What
I've effectively done is to run my tests from within Groovy against GWT classes compiled-as-Java.  First I will go through an example of what I'm talking about, then I will summarize some of the thoughts I had as a result of going through this exercise.

Below I have an implementation of KeyboardListener which modifies the contents of a TextArea based on keypress.  I want to test the behavior of this listener.  Here's what I did:

1) Write a test.  I did this using Groovy, but you could just as easily write it in Java using JUnit
TestCase if you prefer.  This particular test verifies that my listener will append an equal amount of whitespace to the next line when the <enter> key is pressed, and position the cursor at the end of that new line.  Very simple stuff, but worth testing even outside of GWTTestCase.  I find that the Groovy style keeps this test case a lot shorter than it would otherwise be in Java.

class SampleTest extends GroovyTestCase {    private static final char KEY_ENTER = (char) KeyboardListener.KEY_ENTER    private static final int NO_MODIFIERS = 0;

    protected void setUp() throws Exception {        Mockit.redefineMethods(GWT, MockGWT)    }

    public void testEnterKey() {        def keyListener = new MyKeyListener()        def textArea = new TextAreaFixture(text: "    abcd", cursorPos: 8) 

        keyListener.onKeyPress(textArea, KEY_ENTER, NO_MODIFIERS)

        assertEquals "Content is incorrect", "    abcd\r    ", textArea.text        assertEquals "Cursor position is incorrect", 13, textArea.cursorPos    }}

class TextAreaFixture extends TextArea {    String text;    int cursorPos;}

2) Mock out com.google.gwt.core.client.GWT.  This ultimately comes
down to mocking out the 'create' method.  Notice below that we make a special case for 'DOMImpl.class'.  The reason for this is that
the actual DOMImpl is decided at runtime.  It is also referenced in the constructors of the widget we are testing (i.e. 'TextArea()').  Note that this class needs to be a Java class (i.e. non-Groovy) due to the way in which JMockit redefines methods on existing Java classes.  As for why I return 'null' for everything else, I do this to fail fast in any cases I'm not testing.  As it turns out, this is all I need for the testcase above.

public class MockGWT {    public static Object create(Class classLiteral) {        try {            if (classLiteral.equals(DOMImpl.class)) {                return new MockDOMImpl();            }            return null;        } catch (Exception e) {            throw new RuntimeException(e);        }    }}

3) Subclass com.google.gwt.user.client.impl.DOMImplAh-hah!  Here's the catch...  This step provides us just enough code to satisfy construction of our Widgets.  For my purposes, I let my IDE generate this subclass for me, and stuck with the default implementations it generated.  I return an instance of it above.

public class MockDOMImpl extends DOMImpl {    public Element createElement(String tag) {        return null;    }    [...]}

The approach to this style of testing intercepts any calls on the
Widgets themselves before anything is allowed to hit the underlying DOM
implementation.  What I provide above is just an example of how this could be done, specifically when testing behavior of custom classes that happen to inherit or reference GWT classes.  Testing things like layout or UI concerns is another matter, but one which I would not consider 'interesting' enough for unit testing, since most of the behavior on the UI can be easily inspected by viewing Widgets as simple beans.

So why would you want to attempt this anyway?  First, I happen to like working in
Groovy, so I crave more reasons to do exactly that.  Second (and
more pertinent), much of behavior I find interesting in GWT apps revolves around simple message passing.  I trust GWT enough to do its job once I leave the Java space.  Beyond this are some philosophical differences I have with GWTTestCase, particularly since GWTTestCase makes it hard to maintain a larger body of unit tests, requires additional configuration in your module file (or as I've done before, constructed a different "test-only" module file that inherited from two module files), did not let me set up tests the way I would like to, etc.  I could go on.  When
unit testing, very little of the logic I write is made less interesting
or less relevant outside of a JS runtime environment, so where possible I would like to gain some benefits from treating everything as Java.

There are other benefits.  There's the
noticeable speedup in execution time when running entirely within the
JVM.  There's also less restrictions on the test class itself with
regards to instance variables, language (i.e. Groovy), dependencies in outside packages, etc.  Why wouldn't I want such flexibility in my test code?  I really want my test code to be as concise and expressive as possible, particularly as my apps get larger and more complex.  I think having alternative ways of approaching this kind of testing brings a lot of these types of benefits.

About Pathfinder

  • We design and build extraordinary applications for companies looking to make the next great idea a reality.
  • learn more

Topics

WordPress

Comments about this site: info@pathf.com