Archive for the ‘Groovy’ Category
“Holy Crap, That Worked!”: Running JRuby/Cucumber from Gradle October 31, 2009 | 07:23 pm

I’m working on some code for my book and I’m trying out Swinger, which is a Cucumber library for Swing. I wanted to integrate it into my build (which is Gradle), but was running into issues. The problem is that I was pulling JRuby-Embed from the central Maven repo, which meant that I could only use the JRuby classes by way of Gradle’s fancy classloader stunts. The issue is that JRuby does some of its own classloader stunts, so there were classloader issues. The issue resulted in error messages that looked like this:

Caused by: org.jruby.exceptions.RaiseException: library `enumerator' could not be loaded:
java.lang.ClassNotFoundException: org.jruby.libraries.EnumeratorLibrary
	at (unknown).new(:1)
	at (unknown).(unknown)(:1)

After tracking through the JRuby source code, I found that RubyInstanceConfig was grabbing the thread context classloader instead of the classloader used to load itself. I don’t know what that classloader was set to, but resetting it solved the issue.

Here’s the resulting Gradle script, which at least runs the gem installs and a Cucumber run:

import org.jruby.Main as JRuby
 
buildscript {
  repositories {
    mavenCentral()
  }
  dependencies {
    classpath "org.jruby.embed:jruby-embed:0.1.2"
  }
}
 
task checkGradle << {
  println "OK"
}
 
task gems << {
  def gemsDir = "./build/gems"
  if(!new File(gemsDir).exists()) {
    runJRuby("gem install -i $gemsDir --no-rdoc --no-ri cucumber")
  }
}
 
task runTest(dependsOn:gems) << {
  def cukeHome = new File('./build/gems/gems').listFiles().find {
    it.name.startsWith('cucumber-')
  }
  runJRuby("$cukeHome/bin/cucumber src/test/features")
}
 
def runJRuby(cmdArg) {
  Thread.currentThread().setContextClassLoader(JRuby.class.classLoader)
  println "Running JRuby: $cmdArg"
  JRuby.main("-S $cmdArg".split())
}

null Sucks: A Case in Point October 17, 2009 | 02:30 pm

Take a look at this API: ClassNode#addProperty. Turns out that if you pass null into getterBlock and setterBlock, you get the default implementations. Maybe1. Normally passing null around blows up in unhelpful ways, but here null is a useful value. How is a programmer to know?

I’m increasingly convinced that immutability2 and strong type systems in languages aren’t just about concurrency or letting the computer optimize or catching bad code early. Increasingly, I’m convinced that the key value they provide is clear, meaningful, and maintainable code. Which is really the key problem in software development these days, isn’t it?

1 As of this writing, it’s an outstanding question if the compile phase of the AST transformation impacts whether or not the null values are translated: mailing list conversation.
2 See this nice presentation from Rich Hickey, author of Clojure.

The @WithLog Annotation and Groovy ASTTransforms July 23, 2009 | 05:47 pm

I’ve just released a @WithLog annotation to GitHub under RobertFischer/Groovy-WithLog. The goal of @WithLog is to reduce the boilerplate associated with using Log4J.

Normally, using Log4J looks like this:

import org.apache.log4j.Logger
 
class Foo { 
  static log = Logger.getLogger(Foo)
  /* ... */
}

I’ve now said Logger three times and my class name twice. And there’s absolutely no useful value to having it clogging up the body of my class. This burns my eyes, and needs to stop. Read the rest of this entry

Groovy version of Neal Ford’s JRuby “Recorder” June 17, 2009 | 10:35 am

In Neal Ford’s JavaOne 2009 “‘Design Patterns’ for Dynamic Languages” talk1, he presented a record/playback object as an example of a decorator. He did so in JRuby, which is probably a good call since JRuby is more slide-friendly than Groovy (more on this later), but in presenting the recorder he said something in passing about Groovy having a problem because of operators and how they correspond to methods. This struck me as odd, since (as a once and future Groovy DSL hacker) I regularly work with operators. So I decided to check it out. Read the rest of this entry

Salted and Hashed Passwords in Grails via the Crypto Plugin March 27, 2009 | 08:54 pm

I wanted to share this tidbit n how to do salted and hashed passwords in Grails. If you don’t know why you want to do this, read Never store passwords in a database!. More on salting is available at Wikipedia’s article on Password Cracking.

To be smarter about passwords than the Reddit developers, first install the Crypto plugin via: grails install-plugin crypto. More information on the Crypto plugin is available on the Grails website: Grails Crypto Plugin Documentation.

I tend to then structure the password part of my application user class to look something like this:

import static cr.co.arquetipos.password.PasswordTools.*
 
class AppUser {
 
  static transients = ['password']
 
  String passwordHash
 
  boolean checkPassword(String password) {
    checkDigestBase64(password, passwordHash)
  }
 
  void setPassword(String password) {
    passwordHash = saltPasswordBase64(password)
  }
 
}

Once that’s done, you can execute code like this:

def user = new AppUser()
user.password = "foo"
assertTrue user.checkPassword("foo")

Note that this won’t work:

   assertEquals "foo", user.password // Fails because the 'password' property can't be found

Using this approach, the password is not stored in the database, or even in a transient property in the domain object. This minimizes the tendency to do something stupid (like e-mail the password in cleartext).

OS-X Shortcuts for Grails (and Other Stuff) February 12, 2009 | 08:24 pm

I use bash and vi basically as my IDE, so here are a few of my favorite functions. Hopefully people out there can use these functions as a basis to customize their own shell to really be maximally productive.

This is a straightforward Hamming encoding of one of my most common commands.

alias g='grails'

This prints out the bytecode of a Java class file, along with all the extra noise possible.

alias bytecode="javap -c -l -private -s -verbose"

And shorthand for opening a file read-only, because sometimes you don’t want to break stuff.

alias vir="vi -R"

Open a file that’s not the SVN copy or the compiled *.class file that starts with the given name.

function vif {
  FIND_ME="$1*"
  vi `find . -iname $FIND_ME -and -not -iname '*.svn*' -and -not -ipath '*/.svn/*' -and -not -iname '*.class'`
}

This fires off testing for the app. This will be a lot easier in Grails now that plugins can hook into the test-app command: looking forward to that.

function gta {
  rm -rfv stacktrace.log ./test/reports ./test/reports-functional
  grails clean
  #time grails functional-tests
  #mv ./test/reports ./test/reports-functional
  #open ./test/reports-functional/html/index.html
  time grails run-webtest
  time grails test-app $@
  open ./test/reports/html/index.html
}

This prints out the error codes, as documented by errno.

function errcodes {
  perl -MErrno -e 'my %e= map { Errno->$_()=>$_ } keys(%!); print grep !
    +/unknown error/i, map sprintf("%4d %-12s %s".$/,$_,$e{$_},$!=$_), 0..
    +127'
}

And, courtesy of Ruby.MN, this one looks up a word in Apple’s Dictionary.

function dict {
  open "dict://$1"
}

And this one (for OCaml) looks up the interface for a library.

function mli {
    TARG=`ocamlfind query $1`
    vi -R $TARG/$1.mli
}

Developing Grails Plugins with GitHub October 31, 2008 | 01:47 pm

Editor’s Note: New capabilities of Grails make this a much more useful approach: Github Grails Plugin 2.
Read the rest of this entry

Functional Programming, Typing, and Closures October 9, 2008 | 06:51 am

Back when I was giving my Ruby.MN and Groovy.MN* presentations on OCaml (blog post with video and handouts), one of the questions that came up (from Jesse of Refactr) was why I saw static typing and functional programming as being so tightly connected. After all, Erlang is a dynamically typed functional language, so what’s with the whole static typing hang-up?

At the time, I had an answer, but it isn’t the whole story. That answer was that dynamic typing doesn’t get rid of types, it just moves the type checks runtime (see Ruby’s “No such method” exception/”nil when you didn’t expect it” exception), you still have to be wrestling with type information in your code. When you start working at the higher level of abstraction that is functional programming, tracking types “in your head” becomes tricky, and so static typing helps identify bugs.

One of the big examples is point-free programming, which simple implementations of can be done in Groovy by chaining together functional operators.

results*.foo.collect { 
    [it.bar, it.size() / 2]
}.sort({ a,b -> a[1] <=> b[1] }).findAll { 
    it[1] > 0 || it[0].name == "EMPTY"
}.collect { [it[0].baz, it[1]] }.inject([:]) { hash,entry -> 
    log.debug("Processing ${entry[0]}")
    hash[entry[0]] = entry[1]
}

And so on. As you build up these kinds of constructs, it becomes easy to lose track of what you’re doing and where you’re at — they’re maintenance nightmares in a dynamically typed language, but they’re wonderfully succinct ways of expressing business processes. The dynamic typing situation gets even worse if you try to use closures which aren’t defined straight in-line, or which had previous processing (e.g. curry) done on them.

There’s another reason, though, which I’ve just recently bumped into while developing the BackgroundThread plugin for Grails. Consider this scenario.

let foo = "foo";;
let x = (^) foo;;

The same thing (within handwave) in Groovy is:

def foo = "foo"
def x = { foo + it }

So far, no big deal. Here’s a key difference, though — in Groovy, you could define x this way:

def x = { "$foo" + it } // Stringify foo

Or, if “foo” was a property on the owner:

def x = { owner."$foo" + it } // Access "foo" property in enclosing context

So, in Groovy, when you define a closure, you’re required to hold onto the entire surrounding context — the garbage collector won’t clean up any of those variables, because they may happen to be used. In the OCaml code, the only thing being stored with the closure is the “foo” variable itself, because OCaml knows you won’t be able to use anything outside of it. This difference becomes extremely relevant when you start dealing with long-lived closures (like in the BackgroundThread plugin), because a context that throws off a number of background tasks won’t be cleaned up until after all of those tasks have resolved themselves. And if you’ve got a list of 3000 domain objects in that context, that’s a non-trivial amount of memory you’re hanging onto.

So, if you’re going to be throwing off a closure which may be long-lived in a dynamically typed language, it is important that you try to use consume as much of the context as you can to minimize your memory footprint and allow the garbage collector to do its thing.

*BTW: I’m bummed that the .NC domain name registrar requires you to live in New Caledonia. So much for my dreams of Groovy.NC…

Functional (Meta)?Programming Stunts for Ruby and Groovy (and a Little Perl) June 24, 2008 | 11:04 am

After I learned OCaml, my coding mindset was totally distorted. I started writing Java code that looked like this:

  public Collection<foo> getCertainFoos() {
    return
      CollectionUtils.select(getFoos(), new Predicate() { 
         public boolean evaluate(Object o) {
            return SOME_CONSTANT.equals(((Foo)o).getProperty());
         }
      });
  }
</foo>

This is kinda ugly in Java, but it’s simply what comes out when I was thinking this in OCaml:

List.find_all (fun i -> SOME_CONSTANT = i#getProperty()) #getFoos()

I also started slapping final everywhere — see Yet Another Reason final Is Your Friend. A ubiquitous use of final actually gave some nice patterns (in the “macro” sense of patterns), but raised all kinds of eyebrows and made my code unmistakable. This lead up to a unique coding style which you can see in my most involved open source project, JConch. Meanwhile, my co-blogger was talking about “The Hole in the Middle” Pattern, which is also a lay-up within FP circles but required some backflips to implement in Java (functional interfaces) and C# (delegates).

It wasn’t until the advent of Ruby and Groovy, though, that functional programming skills really became easier to use. Basically, because of the inline closure’s succinct syntax (and ability to access non-final variables), I could suddenly do all kinds of really fun stuff. This “fun stuff” was exactly the kind of stunts I was pulling in Perl back in the day (see the BEGIN block in my Text::Shift code for a reasonably accessible example), and it was part of the reason I loved Perl so much at the time.

So, I thought I’d share some more of these cute stunts with you.
Read the rest of this entry