Archive for the 'Code Hints' Category

05th Mar 2008

HOW TO: Better JavaScript Templates

JavaScript Templates (Jst) is a pure Javascript templating engine that runs in your browser using JSP-like syntax. If that doesn’t sound familiar, check out the live working example on this site and download the code. It’s Free Open Source Software.

Better JavaScript Templates

Posted by Posted by Mark Turansky under Filed under Code Hints, Engineering, HOW TO, Technology Comments 3 Comments »

11th Jan 2008

HOW TO: Bootstrap Java programs in isolated classloaders

Bootstrapping is the process by which you load a very small and very simple pure java program with no dependencies that, in turn, loads, configures, and runs more complex programs with varying dependencies. Bootstrapping lets you run your container without polluting the system classpath. This allows you to run your deployed applications with the unpolluted system classpath as its parent. You’ve achieved classloader isolation.

When would you want to bootstrap? Any time you want an unpolluted system classpath, which I’m finding is often convenient.

Let’s say you want to write some kind of middleware product, a container of some sort that deploys other applications within it. You will run into classloading issues. The dependencies that your container has (say, Spring 2.0.6) may not be what your deployed application requires (maybe, Spring 1.2.6). You will find that you cannot have commons-logging in both applications (container and child). There are many ways to encounter java.lang.LinkageErrors. It’s very easy to cross the streams when running in a mutli-app environment.

What you want to do is load your container and deployed apps in splendid isolation from each other. How do you do that? Bootstrapping!

Here’s how you bootstrap…


import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.List;

public class Bootstrap {

    public static void main(String[] args) throws Exception {

        /*
            Assume your application has a "home" directory
            with /classes and /lib beneath it, where you can put
            loose files and jars.

            Thus,

            /usr/local/src/APP
            /usr/local/src/APP/classes
            /usr/local/src/APP/lib
         */

        String HOME = "/usr/local/src/YOURAPP";
        String CLASSES = HOME + "/classes";
        String LIB = HOME + "/lib";

        // add the classes dir and each jar in lib to a List of URLs.
        List urls = new ArrayList();
        urls.add(new File(CLASSES).toURL());
        for (File f : new File(LIB).listFiles()) {
            urls.add(f.toURL());
        }

        // feed your URLs to a URLClassLoader!
        ClassLoader classloader =
                new URLClassLoader(
                        urls.toArray(new URL[0]),
                        ClassLoader.getSystemClassLoader().getParent());

        // relative to that classloader, find the main class
        // you want to bootstrap, which is the first cmd line arg
        Class mainClass = classloader.loadClass(args[0]);
        Method main = mainClass.getMethod(”main”,
                new Class[]{args.getClass()});

        // well-behaved Java packages work relative to the
        // context classloader.  Others don’t (like commons-logging)
        Thread.currentThread().setContextClassLoader(classloader);

        // you want to prune the first arg because its your main class.
        // you want to pass the remaining args as the “real” args to your main
        String[] nextArgs = new String[args.length - 1];
        System.arraycopy(args, 1, nextArgs, 0, nextArgs.length);
        main.invoke(null, new Object[] { nextArgs });
    }

}

You can try this code out for yourself. Cut & paste the bootstrap code above into your favorite IDE, put that single Bootstrap.class onto your classpath, and run it like so:


java -cp . Bootstrap sample.HelloWorldMain Hello!
.

Click here to download the sample /usr/local/src/YOURAPP application.
Tip for Windows users, you can make the path c:\usr\local\src\YOURAPP it’ll work.

Posted by Posted by Mark Turansky under Filed under Code Hints, Engineering, HOW TO Comments 15 Comments »

09th Dec 2007

Horses for courses

A friend/programmer/co-worker of mine recently bemoaned my use of the term “pick the right tool for the job.” Apparently, he thinks it’s a tired metaphor. And so in deference to my friend, this blog entry is about choosing the right horse for the course.

Some horses are mudders, some are good at short-distance sprints, still others are the ones you want for the long race. If you’re eying the race’s purse, you choose the right horse for the course.

So, how do you choose the right horse? I’m guessing it has something to do with experience, breadth of knowledge, and understanding when a functional program makes more sense than an imperative one or knowing when a script is better than a fully engineered OO implementation. Here’s an example to fan the Java vs. Python flames.

Not too long ago, in my previous life working for a consulting company, I wrote a small Java application to monitor our many web applications. The requirements were simple: the server page should return “OK” (text/plain) else the contents of the entire page would be mailed to a list of interested recipients. This technique allows a developer to put whatever test they want in their server page (database connectivity, unit tests, whatever) knowing that any exception they write to the page would be mailed to them.

Not hard, right? Easy implementation? It was both times I wrote it, but one of them was a much better horse for the course.

The configuration file in Java was XML, natch, which required an XSD. The XSD required Castor (or its equivalent) to generate bindings for the XML. The Main program was well factored in that each class did one thing well. As a result, I had a class to poll a site, one of load the configuration, a class to send email, etc. Between Main and classes from Castor, I was up to a dozen .java files. Main, of course, required libraries (Castor, mail.jar, activation.jar, etc.), and those libraries required a script (.cmd in our case) to load them all onto the classpath. Oh, let’s not forget about building with Ant. Add a build file to the heap.

It worked, but damn, that’s a lot of files and jars and complexity for a simple monitoring program!

I rewrote it in Python in less than 40 lines of code. Two files. There are more comment lines than executable code.

Choose the right horse for the course. Occam’s Razor says the 40 line solution is the right one, but you can decide for yourself.

Here’s the python program and configuration file.

Many developers learn one or two mainstream languages and always run their favorite horse, irrespective of course. The best developers will be those that love learning new languages and techniques. I’m a better Java programmer today because of what I’ve learned from Python. I’m a better web developer today because of what I’ve learned from Ruby on Rails.

Learn more. Broaden your horizons. Try new things and new styles of development. Learn to pick the best horse for the course. Always use the right tool for the job.

Posted by Posted by Mark Turansky under Filed under Code Hints, Engineering Comments 1 Comment »