Tuesday, September 25, 2007

Yo Classpath, It's Globbering Time !

This post isn't rocket science: it is mostly for my own reference, but you might find it useful.

I've written a small, easy Groovy script that scans a directory (recursively) and builds a CLASSPATH from scratch.

We'll call it a jar globber. This really appeals to me:

1. Sometimes, it's great to go 'minimalist' and start from scratch

2. setting the CLASSPATH is the first step to cool scripting with the 'JVM Tunnelers' such as Groovy

In this post, I'll show the Groovy script and then use it to glob jars in the Jini project, and write a tiny script as a demo.


Here's the Groovy version of Jar Globber:


// Usage:
// groovy jarGlobber [targetDir]
//
// e.g. groovy Which c:\YourProject\lib

// Closure: if file is a jar, emit string
myEmitter = { file ->
if( file.isFile() && file.canRead() ) {
fileName = file.getName();

if( fileName.indexOf(".jar") != -1 ) {
// easily changed for Unix
println "set CLASSPATH=%CLASSPATH%;" + file;
}
}
}

////////////////////////////////////////////////
// static void main(String args[])
//
// TODO 1: sanity check arguments
// TODO 2: add param for Windows versus Unix
def fileName
searchDir = args[0]

println "set CLASSPATH=."
new File(searchDir).eachFileRecurse(myEmitter)


Easy stuff, thanks to Groovy's ability to iterate over files. (Yes, you Bash hounds, there are easier ways to do it.) Using Jini's lib directory as the target, the output looks like this:


set CLASSPATH=.
set CLASSPATH=%CLASSPATH%;c:\jini2_1\lib\browser.jar
set CLASSPATH=%CLASSPATH%;c:\jini2_1\lib\checkconfigurationfile.jar
set CLASSPATH=%CLASSPATH%;c:\jini2_1\lib\checkser.jar
set CLASSPATH=%CLASSPATH%;c:\jini2_1\lib\classdep.jar
set CLASSPATH=%CLASSPATH%;c:\jini2_1\lib\classserver.jar

ETC

If I output this to a BAT file and execute it, I'm ready to roll.

Here's a screenshot of a Groovy shell session where I start scripting Jini objects and interacting with them. (Note: I have started the Jini service elsewhere.)



You can click on the screenshot but here's the gist:


def loc = new net.jini.core.Discovery.LookupLocator('jini://localhost')
def registrar = loc.getRegistrar()
println registrar


We shoot, we score! Dynamic Jini objects. So, now it is Game On (or Flame On?) for experimenting with Jini, since the CLASSPATH was clobbered....

The cool part is that there is nothing particular here about Jini. We're ready to roll with any given project. Try your project at work. It is truly amazing to start scripting Java classes.

No comments:

Post a Comment