Archive for the ‘Groovy’ Category
Dependency Injection with Guice and GuiceJumper May 10, 2014 | 10:14 pm

When a lot of people discussion static vs. dynamic typing, they are really discussing Java vs. Ruby typing: they simply don’t know any better than to think that Java is representative of static typing. In a similar way, when people hear “dependency injection”, they think Spring. I was one of these people: after getting caught on one too many angle brackets, I was generally put off Spring. The dynamic language features of Groovy made Spring a bit more tolerable within Grails, but I still found it more annoying and obscure than helpful.

For a while, I considered dependency injection to be an informative failure, but something kept nagging at me: the magical variables in Rails are effectively involuntary dependency injection—this pattern is half-jokingly called “dependency ejection” or “dependency secretion”. So there’s something to dependency injection, even if Spring got it wrong.

Then, at JavaOne, I bumped into some of the Google devs, and they pitched me Guice. Some of the pitch points hit home: compile-time type checking; actionable error messages; configured through code; works with immutable classes. However, it still used annotations (which I was busy hating on), and dependency injection was not a popular point with me, so it took me a while to get around to checking Guice out.

I wish I hadn’t waited so long.

Guice does dependency injection as right as I’ve seen, and it makes working within Java and Groovy much nicer. Its simplicity sometimes leads people to underestimate it, however. Recently, I released GuiceJumper, which is my extension to the Guice core library. The code in there demonstrates some of the power of Guice.

For instance, there’s the ExecutorModule. Its primary purpose is to enable classes to ask for an ExecutorService—the core class for concurrency—by specifying the kind of tasks that will be passed to it. The context will provide an appropriately-configured implementation of the ExecutorService, which (if appropriate) is shared throughout the system.

// Groovy code so it's short enough to read
class Busy {
   @Inject @Background ExecutorService executor
   ...
}
 
def injector = Guice.createInjector(new ConcurrentModule())
def busy = injector.getInstance(Busy)
busy.executor.submit {-> ... }

The @Background annotation means the ExecutorService will be appropriate for background task processing. The other options are @Process (CPU-limited processing); @Read (work production and I/O input); and @Write (work consumption and I/O output).

But that’s no big deal: that’s basically a step above rudimentary dependency injection. Slightly cooler: load your application configuration up into your favorite properties file (through, say, Properties.load(Reader)), provide it to the PropertiesModule, and then those properties will be available throughout your system. You can convert them to any primitive type, BigInteger, BigDecimal, Charset, File, URL, URI, or any enum…with actionable errors if the conversion fails. So all those magic constants can now be stored up front in a single configuration step, loaded later, and you will get an early error if they are badly formatted or otherwise bogus. It’s a beautiful thing.

class Configured {
   @Inject @Named("my.config.prop") int value
   @Inject @Named("my.awesome.blog") URL blogUrl
   ...
}
 
def injector = Guice.createInjector(new PropertiesModule(["my.config.prop":"42", "my.awesome.blog": "http://enfranchisedmind.com"]))
def confed = injector.getInstance(Configured)
assert confed.value == 42
assert "$confed.blogUrl" == "http://enfranchisedmind.com"

The I18nModule pulls a similar stunt, but uses annotations that look like @Localized("i18n.key") and loads localized values from the ResourceBundle, enabling super-simpler localization of the application and centralization of the messaging.

I’ve got another module to be released which provides all the wiring necessary for the AWS Java SDK objects, but that’s not released to the public yet.

Guice gives you the ability to have a distinct configuration phase to your application, which is entirely under the control of your application, and which need not be at the very beginning. In fact, I have systems that have multiple configuration phases, generating child injectors with new modules as more information becomes available: for instance, my hybrid of Groovy/Guice/Restlet (working title: Restling) creates a new injector for each request. The request injector can provide the request itself, the response, the user, and other request-scoped information.[1] It is worth emphasizing that all of this is configured and controlled by code, which means that you can have precise control over what is going on when, and in the unlikely situation that there is a problem, you can apply your standard debugging tactics. It’s great.

It’s dependency injection without the pain. I love it.

[1] Yes, I am aware that there is a request scope using the servlet plugin for Guice. I find that plugin more magical than helpful, especially given that I can accomplish the same things with nested injectors.

Executing a MySQL Script through JDBC July 30, 2013 | 03:26 pm

There’s no way to execute a MySQL script through JDBC, and most of the tools (including SimpleJdbcTestUtils) have weird requirements for the script and/or a bunch of overhead to do what you want to do. The big trick is that DELIMITER isn’t actually a SQL command: it’s a pre-processing instruction (at least conceptually). And that makes feeding the script into MySQL a pain.

Groovy and Commons-Lang StringUtils to the rescue. Here’s the short script that will break up a SQL script into a Collection of String objects, which can then be fed to your favorite SQL execution tool.

	static Collection<String> breakUpSqlScript(String loadSql) {
		List<String> statements = []
 
		String delimiter = ";"
		String currentStatement = ""
		loadSql.eachLine { String line ->
			line = line.trim()
			if(StringUtils.startsWithIgnoreCase(line, "--")) {
				// Comment: IGNORE
			} else if(line.endsWith(delimiter)) {
				line = StringUtils.removeEnd(line, delimiter)
				currentStatement = "$currentStatement \n $line".trim()
				statements << currentStatement
				currentStatement = ""
			} else if(StringUtils.startsWithIgnoreCase(line, "DELIMITER")) {
				delimiter = StringUtils.removeStartIgnoreCase(line, "DELIMITER").trim()
			} else {
				currentStatement = "$currentStatement \n $line"
			}
		}
		if(!StringUtils.isBlank(currentStatement)) statements << currentStatement
 
		return statements
	}

PS: If you want to get the contents of a file as a string, use File#getText().

Gaelyk (Groovy/Google App Engine) Persistence in September’s GroovyMag: Announcement and Errata September 9, 2012 | 11:24 am

This month, I have an article on persistence on Google App Engine’s persistence (BigTable/DataStore), viewed through the perspective of Gaelyk. One of the big things I highlight is ways in which this NoSQL engine differs from relational databases, and what that means for structuring your data and optimizing your structures. This is a part of the conversation which is often sorely missing, so I felt the need to highlight it.

Vladimír Oraný read through it, and said he liked it quite a bit, but noticed two things that I have to correct. First, I apparently imply through my example that you need to use @Entity in order to use coercion into Google App Engine’s Entity. This isn’t true: any bean or POGO can be coerced. I knew that, but apparently conflated two steps in a way that might be confusing. Second, despite an error in the documentation implying the contrary, @Unindexed cannot be applied to a class. Instead, you need to pass that as an argument to the @Entity annotation: @Entity(unindexed=true).

Like before, you can get a free copy of this month’s GroovyMag by tweeting me for it.

Grails Database Session Plugin June 6, 2012 | 02:07 pm

I’ve done a fair bit of updating to the Grails Database Session Plugin (originally written by Burt Beckwith), and
it is now released. The plugin solves the problem of cloud services often not having sticky sessions/session affinity, so as soon as you ramp up a second Grails application, you’re losing sessions now and again.

If you want more information on this plugin, check out this month’s GroovyMag (June 2012), where I’ve got an article going over the whole thing, including the differences in implementations, a peak under the hood, and extensive details on how to use the plugin. A summary version of it is available in the README file.

BTW, if you’d like a free copy of this month’s GroovyMag, tweet me and let me know: I have a few coupons to share around.

“Statically Typed Groovy”? Bwuh? I’m confused. August 10, 2011 | 03:21 pm

Hamlet d’Arcy just posted on Groovy getting a static mode, apparently called “Grumpy”. I’m really confused about why Groovy is bothering.

First of all, we have to be clear that a statically typed Groovy is going to have to do away with a lot of functionality. After all, this is totally legitimate and well-defined Groovy code:

class Foo {}
new Foo().abjdslkfansdawkejras()

The specified behavior is that it throws a NoSuchMethodException. If this is to be respected, then no method call can ever be identified as erroneous in Grumpy-mode Groovy. My guess is that this is not what they are going for, and that code would be flagged as an error (or at least a very strong warning) in Grumpy mode. So, basically, we aren’t talking about statically typed Groovy. We are talking about a language that looks kinda like Groovy, but doesn’t have all the features, and is statically instead of dynamically typed.

Similarly, though, you’re looking at having to get rid of metaClass mangling, methodMissing/invokeMethod, and getProperty and setProperty. This means basically all builders are out, as are context-sensitive methods (e.g. GORM domain objects). You’re also going to have to get rid of any code that uses any of that functionality, which includes the Groovy SDK: things like List#forEach are metaclass stunts. This means you’re talking about a static mode for Groovy which is not only missing many of the key features of Groovy, but also is not even compatible with non-static mode Groovy code.

At this point, it’s probably fair to point out that a static mode for compiling a subset of Groovy already exists: it’s called Java. Once you get away from chiseling away the dynamic features, I think all you’re left with is post-Coin Java plus closures. If Groovy provided a nicer bridge to Groovy closures from Java, I’m really not sure what they have left to gain. And considering that the Groovy core development team is going to have to support Grumpy, whereas Oracle supports Java, this seems like a bad strategic move.

All in all, I’m just totally confused about what motivates this move. It can’t be functionality, because we’re actually losing functionality in the language. It shouldn’t be performance: Headius seems to have no problem optimizing JRuby like crazy without having to fall to a “static mode”, and GPP seems to be doing okay with plugging static code into Groovy. I suppose it could be error checking, but if that’s the case, then it seems like the Groovy core team is declaring the static vs. dynamic type war over, and static won. If that’s the case, they should shift over to Scala (or fund my Ashlar development), because they’re about to rediscover a lot of the pain of developing a statically typed language, but with the added difficulty of having to be congruent (for some limited meaning) to a dynamic language.

They whole thing is just a really confusing proposition.

Script: Write out ASM Code to Generate Java Class (Mark II) November 14, 2010 | 03:59 pm

Here’s an update to the Java class file to ASM script based on suggestions from Headius and Guillaume Laforge.

 
#!/usr/bin/env groovy
 
import org.objectweb.asm.util.ASMifierClassVisitor as V
 
@GrabResolver(name='ow2.org', root='http://maven.ow2.org/maven2/')
@Grab(group='asm', module='asm-all', version='[3.3,)')
private class JustHereForGrab {}
 
V.main(this.args)

No need to muck with your grapeConfig.xml file with this script.

Script: Write out ASM Code to generate Java class November 5, 2010 | 03:10 pm

Edit: Updated version of the script here.


Here’s a nifty little Groovy script to write out the ASM code to generate a given Java class.

#!/usr/bin/env groovy
 
import org.objectweb.asm.util.ASMifierClassVisitor as V
import org.objectweb.asm.ClassReader as R
 
@Grab(group='asm', module='asm-all', version='[3.3,)')
private class JustHereForGrab {}
 
new R(new File(this.args[0]).newInputStream()).accept(new V(new PrintWriter(System.out)), 0)

You will have to update your ~/.groovy/grapeConfig.xml file to point to a repo with ASM in it. I’ve posted my grapeConfig.xml at http://repo.smokejumperit.com/grapeConfig.xml.

log.debug { “$toStringMe only if necessary!” } March 19, 2010 | 01:02 pm

I’ve just updated the @WithLog AST transform for Groovy. In case you don’t know, that’s my project over at GitHub which allows you to turn:

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

into

@WithLog
class Foo {
  /* ... */
}

Three big changes in the new release. First, I switched to using Gradle for the build system, because Gradle is awesome. Second, I OSGi-ified the archive and released it to the Maven repo at http://repo.smokejumperit.com, so I’m now Java infrastructure compliant (thank you, Gradle, for making that a no-brainer). Third, I provided the ability to use an enhanced Logger implementation (unoriginally called WithLogLogger) — see the README for full details, but basically it means you can save the toString() evaluation on your logging messages if you wrap the logging GString in a Closure. If you use this, though, you’ll have to schlep around the Groovy-WithLog-0.2.jar file with your runtime code. If you’re using Maven/Ivy/Gradle/whatever, see the end of the README for repo information.

The @WithLog code is still released under the WTFPL.

Oh, Gradle, You Made My Heart Skip a Beat November 27, 2009 | 10:28 am

As I just mentioned, I’ve been working on some Gradle plugins. I’ve been using Gradle in my polyglot programming book, and there’s a stunt (namely, running Cucumber in a Java/Groovy/Scala build) that I’d like the user to be able to do without too much hassle. The easiest way is to say, “Hey, use this plugin and let the magic fly”.

In doing development, I’m spending some time pushing through integration tests, and in so doing, I wanted to deploy various versions to a Maven repository and pull them back down.

Creating a Maven repository for SmokejumperIT was pretty simple.

  1. Create a space on the internet for the repository which is accessible via public-key-authenticated SCP. In my case, it’s http://repo.smokejumperit.com.
  2. Create a configuration in the Gradle build file for the JARs needed to deploy:
    configurations {
        deployerJars
    }
     
    repositories {
      mavenRepo urls: "file://${System.properties['user.home']}/.m2/repository/"
      mavenCentral()
    }
    dependencies {
      deployerJars 'org.apache.maven.wagon:wagon-ssh:1.0-beta-2'
    }

    Note: The part in the repositories block is in every build file that I have, so I’m working on a plugin (working title PreconfigPlugin) that will automatically add that in.

  3. Configure the uploadArchives task. I had it delegate to various System properties that I set when I run the build script.
    uploadArchives {
      repositories.mavenDeployer {
        def repoUser = System.properties['sjit.repo.user']
        configuration = configurations.deployerJars
        repository(url: "scp://repo.smokejumperit.com/home/$repoUser/repo.smokejumperit.com/") {
          authentication(
            userName: repoUser,
            privateKey: new File(System.properties['sjit.repo.keyFile']).absolutePath,
            passphrase: System.properties['sjit.repo.passphrase']
          )
          pom {
            groupId='com.smokejumperit'
            artifactId='gradle-plugins'
            version='0.2-SNAPSHOT'
          }
        }
      }
    }
  4. Run gradle upload.

That’s all it took. Even better, it does all the funky snapshot management on its own: see http://repo.smokejumperit.com/com/smokejumperit/gradle-plugins/0.2-SNAPSHOT/ for the beautiful timestamped results!

This is how builds should be: stupid-simple to do the right thing.

Announcing Gradle-Plugins November 25, 2009 | 07:16 pm

A lot of people know that I have contributed a lot of Grails plugin work, even if my take on contributing is somewhat controversial. Well, I’m continuing on with that approach of plugin contributions, but now for Gradle, the world’s most awesome build system. You can check out the plugins at http://github.com/RobertFischer/gradle-plugins/. Be sure to scroll down to see the README file with all of its goodness.

Currently, there are just two plugins: one to get at classloaders and one to execute shell commands. I’ll probably have some JRuby/Cucumber, maybe JAVACC, and almost certainly some conventional development plugins sometime in the future.

Note that I’m releasing the Gradle plugins under the CC0 (which is a classier form of my beloved WTFPL). Here are the details:

CC0
To the extent possible under law, Robert Fischer has waived all copyright and related or neighboring rights to Smokejumper IT Gradle Plugins. This work is published from United States.