Archive for the ‘Code Samples’ 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.

JQuery PeriodicalUpdater in JSMag July 4, 2012 | 08:43 pm

The jQuery PeriodicalUpdater, which is undoubtedly my most popular open source project to date, is featured in this month’s JSMag. It’s actually a part of a two-part series, the first on jQuery PeriodicalUpdater in particular, and the second on witing jQuery plugins, using jQuery PeriodicalUpdater as an exemplar. So keep an eye out for that next month, too.

The jQuery PeriodicalUpdater is responsible for long-polling the backend from the client. When people usually write this code, it tends to be like some little kid: “Can I have it now? What about now? How about now? Now? Now? Now? Now?” This leads to exasperated servers. The PeriodicalUpdater handles this with much more grace, leading to happy servers while keeping the client up-to-date.

Like last month’s GroovyMag article, I’m offering a free copy of this month’s JSMag if you drop me a tweet asking for it. (There’s also a few more GroovyMag article codes for those tweets.)

jQuery: Timing of Selector Resolution June 17, 2012 | 07:05 pm

I was curious how eager or lazy jQuery was with its selector resolution. So when you say $(".foo"), does it walk the DOM immediately looking for things of class “foo”, or does it wait? After all, it could wait until a call comes in to modify an element before resolving the elements, which could be an optimization in some cases. This would also handle mutations to the DOM, which would be nice in certain cases (such as the bound version of PeriodicalUpdater). It could also be that that jQuery detected changes to the DoM via jQuery, and perhaps threw signals to keep things in sync.

However, it turns out that selector resolution is eager in jQuery. I checked it twice: once using a timer as a simplified version of what JQuery PeriodicalUpdater does and once using direct DOM modifications. In both cases, you see the straight eager behavior.

So there you have it: selector resolution is eager in jQuery. So don’t ask for elements until you’re sure you want them, and not until you’re sure they exist.

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.

Gradle, Lift, and Google App Engine January 21, 2012 | 08:34 pm

I’m getting back into the game a little bit, and I decided to take a look at Lift for web development. After an initially promising experience, I became totally unhappy with Eclipse (it began forgetting I had Google App Engine libraries on the classpath after every clean). So I moved back to the command line. The recommendation to use Simple Build Tool or Maven for Lift put me off: SBT is pretty weak for a build tool, and Maven is…well…Maven, off to download the Internet. So I went back to Gradle.

For the record, I’m using Objectify for my Google App Engine development, because JPA gets you into that whole ugly ORM conceptual space without need: there’s no “R” in GAE, so you might as well deal with it in a more natural way.

So, given that situation, I came up with this build.gradle script. (Forgive the ugly organization, but this is actually the relevant points extracted from a multi-project build.)

buildscript {
   repositories {
      mavenCentral()
      add(new org.apache.ivy.plugins.resolver.URLResolver()) {
          name = 'GitHub'
          addArtifactPattern 'http://cloud.github.com/downloads/[organisation]/[module]/[module]-[revision].[ext]'
      }
  }
 
  dependencies {
    classpath "bmuschko:gradle-gae-plugin:$gaePluginVersion"
  }
}
 
apply plugin:'java'
 
// Buildscript dependencies and repositories
 
 
repositories {
  mavenCentral()
  mavenRepo name:'scala-releases', url:'http://scala-tools.org/repo-releases/'
  mavenRepo name:'objectify-appengine-releases', url:'http://objectify-appengine.googlecode.com/svn/maven'
  mavenRepo name:'sonatype-releases', url:'http://oss.sonatype.org/content/repositories/releases/'
  mavenRepo name:'sonatype-snapshots', url:'http://oss.sonatype.org/content/repositories/snapshots/'
 
  add(new org.apache.ivy.plugins.resolver.URLResolver()) {
      name = 'GitHub'
      addArtifactPattern 'http://cloud.github.com/downloads/[organisation]/[module]/[module]-[revision].[ext]'
  }
}
 
// Universal dependencies
 
dependencies {
  compile "org.encog:encog-core:$encogVersion",
        "com.google.guava:guava:$guavaVersion",
        "commons-lang:commons-lang:$commonsLangVersion",
        "org.apache.commons:commons-lang3:$commonsLang3Version",
        "commons-io:commons-io:$commonsIoVersion",
        "commons-collections:commons-collections:$commonsCollectionsVersion",
        "org.slf4j:slf4j-api:$slf4jVersion",
        "org.slf4j:slf4j-simple:$slf4jVersion"
 
 
  testCompile "junit:junit:4.5"
}
 
// Now the Scala stuff
apply plugin: 'scala'
 
dependencies {
  scalaTools "org.scala-lang:scala-compiler:$scalaVersion",
       "org.scala-lang:scala-library:$scalaVersion"
 
   compile "org.scala-lang:scala-library:$scalaVersion"
 
  testCompile "org.scala-tools.testing:specs:1.6.1",
    "org.scala-lang:scala-compiler:$scalaVersion"
}
 
apply plugin:'war'
 
dependencies {
  compile "net.liftweb:lift-webkit_$scalaVersion:$liftVersion",
        "net.liftweb:lift-mapper_$scalaVersion:$liftVersion",
        "net.liftweb:lift-json_$scalaVersion:$liftVersion",
        "net.liftweb:lift-util_$scalaVersion:$liftVersion",
        "net.liftweb:lift-common_$scalaVersion:$liftVersion"
 
  testCompile 'org.mortbay.jetty:jetty-util:6.1.22',
          'org.mortbay.jetty:jetty-management:6.1.22'
 
  providedCompile 'javax.servlet:servlet-api:2.5'
}
 
apply plugin: 'gae'
 
dependencies {
    compile "com.googlecode.objectify:objectify:$objectifyVersion"
    gaeSdk "com.google.appengine:appengine-java-sdk:$gaeVersion"
}
 
gae {
  downloadSdk = true
  disableUpdateCheck = true // Error with HTTPS
 
  appcfg {
    email = '[email protected]'
    logs {
      append = true
      severity = 1
      ouputFile = file('build/logs.txt')
    }
  }
}

I stash versions in the gradle.properties file, which looks like this (it’s a lot more details than you actually need):

scalaVersion = 2.9.1
liftVersion = 2.4-RC1
gaePluginVersion = 0.5.2
objectifyVersion = 4.0a2
guavaVersion = 11.0.1
commonsLang3Version = 3.1
commonsLangVersion = 2.6
commonsIoVersion = 2.1
commonsCollectionsVersion = 3.2.1
encogVersion = 3.1.0-SNAPSHOT
androidPluginVersion = 1.1.0
slf4jVersion = 1.6.4
gaeVersion = 1.6.1

If you start Lift up at this point (using gradle gaeRun), there are errors about Lift not having permission to mess with the thread pool.

Now, here’s the amazing magic trick which I found documented nowhere but discovered while digging through the Lift source code. It’s an astounding and miraculous trick which is necessary in order to get Lift to work on Google App Engine.

In the file ./src/main/resources/props/default.props, make sure to have this set:

inGAE=true

That’s it. You do that, Google App Engine works. You don’t do that, it won’t. Magic!

“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.

My Experience Installing F# on OS-X August 4, 2011 | 08:46 pm

I’ve been working in .NET for a while now, but the time finally came when I no longer had to be working on a Microsoft workstation via VPN. This meant that I was free to start developing .NET on my Mac, and that meant starting with installing F#.

I presumed I was going to have to do some kind of hardcore magic dance to get this to work, so imagine my surprise when I fired up MacPorts for shits and giggles but actually discovered an fsharp port! It even seemed reasonably up-to-date! What a world!

So I began with the three steps beginning basically every serious endeavor on MacPorts: a selfupdate, an upgrade outdated, and a clean installed. I then dove in: install fsharp.

Unfortunately, the libgdiplus port (a dependency of fsharp) failed to build for me. Some googling around and I found a ticket saying that I failed to build its dependencies with +universal, so I should do that. According to the ticket, the problem was probably cairo, so I fired off upgrade --enforce-variants cairo +universal, and that got me a bit further, but no ultimately it failed again: libsasl (from cyrus-sasl) was apparently also of the wrong architecture. About this time I was having Gentoo flashbacks, so I fired off upgrade --enforce-variants installed +universal, because sometimes the only way to be sure is to take off and nuke the site from orbit. That completed just fine after an hour or so.

Another install fsharp later and I got past libgdiplus. The mono and fsharp ports installed like a breeze. (It was a very slow breeze — more like stagnant air being pushed around by a decrepit fan — but it worked all the same.)

So far, things look pretty good. I have to run the fsi as fsi --no-gui --readline for some reason, but that’s pretty minor.

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.