Jul 14

Simple gotchas with debugging Groovy SQL

Groovy, Tech 3 Comments »

Here is another little gotcha that I have run into (again, due to not thinking and being dumb).

I would use Groovy SQL and start testing in the script leaving me with:

sql.eachRow(”SELECT userpk FROM users where email=’[email protected]’”) { user |
… do stuff
}

then at some point I would want to use a variable for the email and would end up with:

sql.eachRow(”SELECT userpk FROM users where email=’${email}’”) { user |
… do stuff
}

What is wrong with this? The quotes around the variable are wrong. You don’t think of it as “put in this variable here” as Groovy SQL can be smart and will make a prepared statement with question marks ? ? ?

So, taking out the quotes does the trick:

sql.eachRow(”SELECT userpk FROM users where email=${email}”) { user |
… do stuff
}

There is talk on allowing $email as well as ${email}. Bring it on :)

Jul 13

Simple gotchas with debugging Groovy

Groovy, Tech 3 Comments »

As I write more Groovy, I find that simple errors come… and my brain does the usual:

It reads what it thinks is there, NOT what is on the screen

One example is:

The misplaced ${ }

As I move things in and out of strings, I sometimes forget to get rid of the ${ } escapes:

name = “Dion”

println ${name}

# should of course be println name

It would be great if you had the error:

“${ } out of escaped string at ‘${name}’ on line 3″

however you get something like:

Caught: groovy.lang.MissingMethodException: No signature of method test.$() is applicable for argument types: (test$_run_closure1) values: [test$_run_closure1@a9c09e]groovy.lang.MissingMethodException: No signature of method test.$() is applicable for argument types: (test$_run_closure1) values: [test$_run_closure1@a9c09e]

NOTE: I know that the Groovy guys haven’t gotten to the “get the debugging stuff working” phase yet… or as James calls it “debug hell” :)

Jun 29

Good news for Groovy: Session Full

Groovy, Tech No Comments »

James was worried that the Groovy session would be packed today, especially as it was mentioned in a keynote :)

I popped over to the session and was faced with:

Session Full

This is great news for Groovy, and shows that people are interested in different languages and approaches, even at JavaOne.

May 31

Throwing away code again with Groovy

Groovy, Tech No Comments »

I run into a task now and then in which the effort of manually doing something is more than writing a script to do the task for me.

However, at the same time, this task may be a one off, so I don’t want to spend a lot of time worrying about:

  • How elegant the design is
  • How the program handles its memory
  • How readable the code is
  • How generic and reusable it is
  • … and the other many things that you often worry about …

When I was hacking a lot of Perl, I would not think twice… and would open up a doFoo.pl and get going. As soon as it worked, I was done.

When in the Java world though, I often found myself spending more time thinking about things, and how I could make it generic etc etc. I had a suddent oversion to writing code that I would maybe rm after it was used.

Now, I can still use Perl (and do), but now with Groovy I am getting the best of both worlds.

  1. I feel that I can throw away code again
  2. I can utilize my large set of Java libraries from with my “script”
  3. I am having fun :)

It is refreshing to have my mind back in the mode of throwing away code. Be-gone!

May 20

Consilidating scripts with Groovy (Merging .sh/.pl/main()/etc to .groovy)

Groovy, Tech 2 Comments »

One small side effect of embedding groovy into a project is that I have noticed the cleanup of some scripts.

In the past I would often have:

  • Foo.java: This would have a main(…) to do something
  • foo.sh/.cmd/.pl: These would munge a few things, and then call java … Foo …

Now we just have Foo.groovy. The script will itself do some munging, and will just call into the Java packages which have business logic.

So fresh and so clean.

Well, it is a small thing… but still a pleasure :)

May 16

When is Groovy (or something like it) better than XML?

Groovy, Tech 1 Comment »

Mike has written his first bile (although a bit more tame than Hani): Groovy scripting madness – don’t get fooled!

There certainly seem to be a lot of blog entries on how XML is suddenly evil, and that we need to move to something else instead.

As with everything there are pro’s and con’s involved here.

I like Groovy when…

I really like moving away from XML as soon as I need some kind of logic. An obvious example is Ant, and the build.xml file. If you want to do a simple if() test you have to have a target which sets up properties, then have targets with the right depends=”" and if=”property”. What a hack.

I much prefer being able to have the power of a real agile language here. I can modularize my build system as much as I want (not just with <import> and co.)

I like XML when….

XML isn’t suddenly evil. It is often a good choice for a document format. We have lots of tools that can work on it, and if you keep your document fairly simple then you won’t be in tears just because it has angle brackets.

It *does* go crazy when you look at documents that use 10 namespaces, and especially when people try to write programming languages out of it!

So, in the Spring example, I agree with Mike. There isn’t enough of a difference for me to care. I don’t tear up at the sight of angle brackets, so why do something else. If the requirements change and I need to do some smart things with the xml I have the choice of:

a) Writing something that builds the xml file
b) Use something like Groovy where it kinda IS the xml file

Apr 27

New Groovy “use” method added by Sam

Groovy, Tech 1 Comment »

Sam Pullara has added a cool new feature to Groovy. There is a new method use which allows you to introduce methods to existing class.

At the moment this works just for the duration of closure, but in the future you will be able to use it elsewhere.

This is pretty cool. I also would love to see:

  • Feature plugin/out: It would be great to use this mechanism to allow “features” of the language to be plugged in and out. It could enable backwards compatibility in the future, allowing changes to the language as experience shows us what to do (one worry wrt standardizing before a real impl is out there!)
  • Flush out AOP-isms: Mixin’s are great, but I would love to see a PointCut language, and rich support

From Sam’s Email:

excerpt from src/test/groovy/xml/dom/DOMTest.groovy:

xml = new StringReader(”<html><head><title class=’mytitle’>Test</title></head><body><p class=’mystyle’>This is a test.</p></body></html>”);
doc = DOMBuilder.parse(xml);
html = doc.documentElement;
use (groovy.xml.dom.DOMCategory) {
assert html.head.title.textContent == “Test”;
assert html.body.p.textContent == “This is a test.”;
assert html.find { it.tagName == “body” }.tagName == “body”;
assert html.getElementsByTagName(”*”).findAll { if (it["@class"] != “”) { return it } }.size() == 2;
}

Apr 26

Feeling Groovy again

Groovy, Tech 2 Comments »

Ahh, some of the old feelings are coming back. I was on the phone with someone… asking me if I could put together a program that munged some database data and split it out into a file.

I would normally use Perl, but I am feeling Groovy at the moment. So, as I was being explained the problem at hand, I opened up a new file and got to work.

At the end of the explanation, when asked “when could it get done by?”, I was able to say “how about now?”.

import groovy.sql.Sql
import java.io.File

sql = Sql.newInstance(”jdbc:postgresql://dbhost/dbname”, “user”, “pass”, “org.postgresql.Driver”)

new File(”mungeddata.log”).withWriter { writer |
writer.writeLine “Foo, Bar, Baz”

sql.eachRow(”select foo, bar, baz from thetable”) {
writer.writeLine([it.foo, it.bar, it.baz].join(’, ‘));
}
}

All wasn’t perfect though.

I really wanted to reuse a utility class that gets a DB connection by doing the Right Thing (gets a datasource if possible, plays nice with the pool, etc).

So I tried to do:

import groovy.sql.Sql
import mypackage.DBUtil

sql = Sql.newInstance(DBUtil.getConnection())

Unfortunately I got:

groovy.lang.MissingMethodException: No such method: newInstance for class: groovy.sql.Sql with arguments: [org.postgresql.jdbc2.Jdbc2Connection@2a15cd]

UPDATE: James kindly pointed out that I am a moron, and that I just need to use new Sql(Connection). So I changed my code:

//sql = Sql.newInstance(”jdbc:postgresql://dbhost/dbname”, “user”, “pass”, “org.postgresql.Driver”)
sql = new Sql(DBUtil.getConnection())

and it all worked like a charm!

The fact that (in practice) I can easily tie my “scripts” into my Java code is great.

Sometimes you have to write a script that takes in some data, and plugs it into your domain. Often you do that with brute force and shove it into the DB, however it is really nice that now you can:

  1. Munge data in groovy
  2. Package data in a nice way in preparation for …
  3. Accessing your service facade, passing in the nicely packaged data

Great stuff. I do have a couple of frustrations though:

  • Bad error reporting: When things go wrong (compile time) I often get a mega-stacktrace from hell. Really I just want a nice message “couldn’t compile script due to X”. Instead you end up with something like:

    … many lines …
    at groovy.lang.MetaClass.invokeStaticMethod(MetaClass.java:350)
    at org.codehaus.groovy.runtime.Invoker.invokeMethod(Invoker.java:124)
    at org.codehaus.groovy.runtime.InvokerHelper.invokeMethodInvokerHelper.
    ava:101)
    at dumpmetadata.run(dumpmetadata.groovy:13)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invokeNativeMethodAccessorImpl.
    ava:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invokeDelegatingMethodAcces
    orImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:324)
    at org.codehaus.groovy.runtime.ReflectionMetaMethod.invoke(ReflectionMetMethod.java:56)
    at groovy.lang.MetaClass.doMethodInvoke(MetaClass.java:846)
    at groovy.lang.MetaClass.invokeMethod(MetaClass.java:268)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    … many lines …

  • Some things just don’t work like I want them to. For example I really wish the following would work:

    println [1, 2].join(’ ‘)

    What do you think you get back? A “sorry old chap, put some parens around will you?”. Nope. java.lang.NullPointerException at groovy.lang.MetaMethod.(MetaMethod.java:84) … add many lines …

    I know I just need to make this println([1, 2].join(’ ‘)), but if you want to make parens optional, do it right :)

Don’t get me wrong…. I know these are growing pains. Hopefully we can take a leaf out of Howards book, and have line-precise errors ;)

Apr 26

Howard boils the ocean. Use GroovyMarkup! :)

Groovy, Tech 1 Comment »

Howard is trying to boil the ocean :)

Mate, I think that going with YAML is a good idea…. or GroovyMarkup

Your markup:

module (id=foo.bar.baz version=”1.0.0″)
{
service-point (id=Startup interface=java.lang.Runnable)
{
create-object (class=foo.bar.baz.StartupImpl);
}
}

looks a lot like the following GroovyMarkup:

someBuilder.module (id:’foo.bar.baz’, version:’1.0.0′) {
service-point (id:’Startup’ interface:’java.lang.Runnable’) {
create-object (class:’foo.bar.baz.StartupImpl’)
}
}

:)

Apr 20

Re: Re: Maintenance matters

Groovy, Tech 1 Comment »

I got a lot of interest comments to my post Maintenance matters: How should we change our designs to show we care?.

Anthony Eden replied, and had some good comments.

The posting wasn’t meant to discuss the pro’s and con’s of using new technologies.

Even if the newest technology makes you a little more productive, that doesn’t mean that it actually makes sense to go ahead and use it, if you take the other considerations into account:

  • Price
  • Developer knowledge and skill set
  • Your History
  • Business decisions (e.g. who your VP plays golf with)
  • and many more

Skill set is always a big one. I was working on a project where the team were TOP NOTCH when it came to the database tier. For them, throwing an abstraction of the DB in front of them that made it hard to get in there and make the tweaks was painful. So in that case, we didn’t care so much about making that abstraction, but simply hid the implementation behind interfaces, and let them do their magic. If they were doing wacky PL/SQL behind that object that you got back, so be it (as long as that skill set remains).

I love the idea of using scripting languages combined with Java, in the same project. I find that there is a place for nice static interfaces, and a place where it is nicer to just be dynamic and let it flow.

However, even here, I have to stop myself on some projects. What if the team doesn’t know a Groovy/Jython/[insert other scripting language]. Does it really make sense to train everyone? Especially for the maintenence cycle too?

There is no right and wrong to all of these questions…. just interesting to think about, and to know that “bleeding-edge and cool != the best solution all the time”.