So you’re happily browsing the web, watching Alpaca’s approach on YouTube. They approach in all their furry bliss and you rejoice. You chuckle and think “awesome, now let’s close this tab…”.

*BOOM*

Aaaargh… you aimed for ⌘W but skimmed right past the W and briefly hammered the Q key. Result: browser session dead. Game over.

“Now if only there was a way to remap this key, just for my browser…”, you think. Well, it turns out there is a way.

On Snow Leopard, go to System Preferences, open “Keyboard” and move to the “Keyboard Shortcuts” tab.

Go to “Application Shortcuts” and click on the small “+” button. Locate your browser’s .app file in the Applications directory.

Hmmm…. what’s this “Menu Title”?

Open your browser and have a look at the menu. Look for ⌘Q.

Right. Head back to the “Keyboard Shortcuts” window and enter “Quit Google Chrome” as the Menu Title. Next, choose a shortcut and click “Add”. Result:

Now back to YouTube.

Guice Book Released!

March 28, 2008

I should really get some sleep, but I can’t wait to get the word out. The book I was working on “Google Guice: Agile Lightweight Dependency Injection Framework” has gone live! It’s available in ebook and print-on-demand formats.

Guice Book

Apart from the title, I think the book reflects the fact that I’m a no-nonsense guy. I’m just like you, interested in new technology and I want to see this Guice thing in action. They did that with dependency injection? Hell yes; let’s see why they did it, and who they killed to get there (just kidding :-)).

So, months later I look on Amazon, and see this:

You can get my humble work together with the best Java book ever. That alone was so worth it :-)

Thanks again to Apress, Bob, Dhanji and the Guice community: I couldn’t have done it without you.

The Last Lecture

February 5, 2008

All the advice you will ever need. This talk is worth the hour of your time, trust me.

More information here. Thanks to John Lam for the link!

Guice Debug Output

December 8, 2007

Guice has a dirty little secret: it logs timing information to its JDK Logger. A while ago I created a simple utility class for myself to enable or disable the logging of Guice’s debug output to the console. Here goes nothing.

/**
* Enable or disable Guice debug output
* on the console.
*/
public class GuiceDebug {
    private static final Handler HANDLER;
    static {
        HANDLER = new StreamHandler(System.out, new Formatter() {
            public String format(LogRecord record) {
                return String.format("[Guice %s] %s%n",
                                  record.getLevel().getName(),
                                  record.getMessage());
            }
        });
        HANDLER.setLevel(Level.ALL);
    }

    private GuiceDebug() {}

    public static Logger getLogger() {
        return Logger.getLogger("com.google.inject");
    }

    public static void enable() {
        Logger guiceLogger = getLogger();
        guiceLogger.addHandler(GuiceDebug.HANDLER);
        guiceLogger.setLevel(Level.ALL);
    }

    public static void disable() {
        Logger guiceLogger = getLogger();
        guiceLogger.setLevel(Level.OFF);
        guiceLogger.removeHandler(GuiceDebug.HANDLER);
    }
}

Output looks something like:

[Guice FINE] Configuration: 51ms
[Guice FINE] Binding creation: 53ms
[Guice FINE] Binding indexing: 0ms
[Guice FINE] Validation: 131ms
[Guice FINE] Static validation: 0ms
[Guice FINE] Static member injection: 2ms
[Guice FINE] Instance injection: 2ms
[Guice FINE] Preloading: 1ms

Listen to the Logger, it’s making sense. Guice is fine! :-)

Communicating Technology

November 23, 2007

More than a year ago I watched this Channel 9 interview in which Don Box shares some tips on how to give a great technical presentation. I often catch myself using his advice in areas beyond tech talks. I’m not sure if these are all from that interview, but here’s a list of things that I find useful.

  • The Goal: probably a universal truth, but if I’m working on something that will be heard or read by other people, it’s surprising to see how quick I lose track of the initial goal of the work. Do sanity checks. Will this serve the goal?
  • The Font: code needs to be readable. I’d say the right code font is Consolas on Windows, or Monaco on the Mac. For God’s sake, don’t use Courier New. The font is the first thing I configure in a fresh IDE install.
  • The Size: use the smallest possible example to explain a concept. Have slides with only a few words on them. Say more with less. It’s amazing how good that works.
  • The Puzzle: give the audience something to look for. A hidden joke. A mistake on the slides.
  • The Humor: nobody is that serious
  • The Story: people like stories. They don’t have to be true.

Go Javapolis! :-)

Builder Pattern Deluxe

July 12, 2007

Update: code available at http://code.google.com/p/garbagecollected/

Yesterday evening I came up with an interesting approach for implementing Josh Bloch’s revised GoF Builder pattern (warning: PDF). After some late night hacking, I can’t help but feel that this is very useful stuff. Take a look at Josh’s presentation first, and then take a look at this:

package builder; 

public class SomeObject {
  private final String mandatory;
  private final int optional1;
  private final char optional2; 

  private SomeObject (SomeObjectBuilder builder, String mandatory) {
    this.mandatory = mandatory;
    this.optional1 = builder.optional1();
    this.optional2 = builder.optional2();
  } 

  public interface SomeObjectBuilder extends Builder {
    SomeObjectBuilder optional1(int optional1);
    SomeObjectBuilder optional2(char optional2);
    int optional1();
    char optional2();
  } 

  public static SomeObjectBuilder builder (final String mandatory) {
    return BuilderFactory.make (SomeObjectBuilder.class,
        new BuilderCallback () {
          public SomeObject call (SomeObjectBuilder builder) throws Exception {
            return new SomeObject(builder, mandatory);
          }
    });
  } 

  public String toString() {
    return new StringBuilder()
      .append (getClass().getName())
      .append (String.format ("[optional1=%s, ", optional1))
      .append (String.format ("optional2=%s, ", optional2))
      .append (String.format ("mandatory=%s]", mandatory)).toString();
  } 

  public static void main(String[] args) {
    System.out.println(SomeObject.builder("Mandatory!")
        .optional1(35)
        .optional2('A')
        .build()
        .toString()
    );
  }
}

Console output: SomeObject[optional1=35, optional2=A, mandatory=Mandatory!]

Using a dynamic proxy, the BuilderFactory provides the Builder<T> implementation for a given interface, so that you don’t have to write all that horrible boilerplate code. Often you use a builder when constructors get messy, but Builders with many parameters get messy too. Using this approach you not only save time, you also have the advantage of using a static factory method and having your specific builder as an interface instead of a concrete class. Full source code available upon request; feedback/suggestions/improvements appreciated!

Eat that, setter injection ;-)

Guice Thread Scope

June 7, 2007

UPDATE: The reset thing turned out to be a bad idea, I created simple Thread Scope instead. If you somehow seem to need a reset, consider this.

Ever wanted to use Guice‘s request scope outside of a web application? Try out my thread scope implementation and let me know what you think. Cast your vote if you want to see this scope added to Guice.

Here’s an example. Create a Module that looks like this:

Injector i = Guice.createInjector(new Module() {
    public void configure(Binder binder) {
        binder.bindScope(ThreadScoped.class, CustomScopes.THREAD);
        binder.bind(ThreadCache.class).in(Scopes.SINGLETON);
        // add your custom classes
        binder.bind(SomeClass.class).in(CustomScopes.THREAD);
    }
});

Each thread is automatically initialized for the scope. To reset it, use the ThreadCache:

@Inject private ThreadCache threadCache
public void someMethod() {
    try {
        // do stuff in thread scope
    } finally {
        threadCache.reset();
    }
}

I’m thinking about loading this scope’s initialization code lazily (so that you’ll need to execute threadCache.start() or something like that). It currently doesn’t matter for me and the memory overhead is low anyway, but what do you think?

PS: only use field injection for examples ;-)

Scripting Guice

May 6, 2007

I really like Guice, a Java 5 style Dependency Injection framework by the bright guys at Google.

People who are used to Spring’s DI config often complain that they don’t like the “compiled configuration” thing (Java Modules) Guice has. In Spring, all your wiring is usually done in XML. So on one side you have compiled Java Guice Modules, a more natural programming model for Java developers, and on the other side you have XML configuration, nicely externalized. And yes, I know the Spring guys plan on having a Java version of their configuration syntax, but it looks just like the XML, so I don’t see any real advantages there.

Anyway, for the Spring users who want to try out Guice, you could externalize your configuration to a properties file, and load it from that. Or whatever format you’re willing to use. Heck, you could even write some code that parses a Spring config file and translates it into a Guice Module.

But here’s another idea: what about using a scripting language for all your object wiring needs? Why create a configuration file if you could use the highly readable Guice Binder syntax? Well, I tried it, and it works great :-)

Let’s start with an example. This one’s about me drinking some beer. So here’s me:

public class Robbie {
    private Beer myBeer;

    @Inject
    public Robbie(@Strong Beer freshBeer) {
        this.myBeer = freshBeer;
    }
    public void startDrinking() {
        myBeer.drink();
    }
}

And here’s some beer:

public interface Beer {
    void drink();
}
public class Duvel implements Beer {
    public void drink() {
        System.out.println("Duvel!");
    }
}
public class StellaArtois implements Beer {
    public void drink() {
        System.out.println("Stella Artois");
    }
}

The @Strong annotation basically means I’d like a strong beer, not just some water with taste. So I created a Guice BindingAnnotation for that, and expressed the binding in a module:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
@BindingAnnotation
public @interface Strong {}
public class BeerModule implements Module {
    public void configure(Binder binder) {
        binder.bind(Beer.class).to(StellaArtois.class);
        binder.bind(Beer.class).annotatedWith(Strong.class).to(Duvel.class);
        System.out.println("Configured using Java implemented Guice Module!");
    }
}

So everyone is getting regular beers, unless they specify they want some stronger beer. You could run this code like this:

public class StartGuice {
    public static void main(String[] args) {
        Injector i = Guice.createInjector(Stage.DEVELOPMENT, new BeerModule());
        Robbie robbie = i.getInstance(Robbie.class);
        System.out.print("Robbie starts drinking: ");
        robbie.startDrinking();
    }
}

This prints:

    Configured using Java implemented Guice Module!
    Robbie starts drinking: Duvel!

Hmm… tasty. Now, let’s get us some scripting. I’ll thankfully use the new Java 6 scripting support, you could probably use the BSF as well. Also, I’ll use Jython for scripting, a Java Python implementation. So I throw in jython.jar, jython-engine.jar (from the scripting site), aopalliance.jar next to the guice.jar. By the way, if you want to know how all this scripting support stuff works, check out Jurgen’s excellent introduction.

Anyway, let’s try binding our dependencies in Python. Create a file called BeerBinder.py that looks like this:

import java
from scriptguice import *

    def configure(binder):
        binder.bind(Beer).to(StellaArtois);
        binder.bind(Beer).annotatedWith(Strong).to(Duvel);
        print "Configured Guice using Python method!"

Then we add some scripting magic to our Guice Module, so that we delegate the configure call to the Python script:

public class BeerModule implements Module {
    public void configure(Binder binder) {
        ScriptEngineManager mgr = new ScriptEngineManager();
        ScriptEngine python = mgr.getEngineByName("python");
        Reader reader = ReadUtil.getReaderForClassPathResource("scriptguice/pythonmethod/BeerBinder.py");
        try {
            python.eval(reader);
            Invocable invocablePython = (Invocable) python;
            invocablePython.invokeFunction("configure", binder);
        } catch (ScriptException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }
}

If we run StartGuice again, the output now looks like:

    Configured Guice using Python method!
    Robbie starts drinking: Duvel!

Great, it works! Now let’s take it one step further and get rid of the ugly Java / Python mix. Python all the way! Create a file called BeerModule.py:

import java
from scriptguice import *
from com.google.inject import *

class BeerModule(Module):
    def configure(self, binder):
        binder.bind(Beer).to(StellaArtois);
        binder.bind(Beer).annotatedWith(Strong).to(Duvel);
        print "Configured using Python implemented Guice Module!"

# Factory method that returns new BeerModule
def getBeerModule():
    return BeerModule()

So we created a class called BeerModule, and subclassed the Java class com.google.inject.Module. Jython really starts to shine here. Let’s do some magic to get the thing back in Java:

public class StartGuice {
    public static Module getPythonBeerModule() {
        ScriptEngineManager mgr = new ScriptEngineManager();
        ScriptEngine python = mgr.getEngineByName("python");
        try {
            Reader reader = ReadUtil.getReaderForClassPathResource("scriptguice/pythonclass/BeerModule.py");
            python.eval(reader);
            Invocable invocablePython = (Invocable)python;
            return (Module)invocablePython.invokeFunction("getBeerModule");
        } catch (ScriptException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        Injector i = Guice.createInjector(Stage.DEVELOPMENT, getPythonBeerModule());
        Robbie robbie = i.getInstance(Robbie.class);
        System.out.print("Robbie starts drinking: ");
        robbie.startDrinking();
    }
}

It’s been a long time since my last beer, so here we go:

    Configured using Python implemented Guice Module!
    Robbie starts drinking: Duvel!

Man, how cool is this? Now we have defined the entire Guice module in Python code, and I got drunk in the process. Life just doesn’t get any better, does it ;-)

Now you could take it even further and return an array of Modules or what not, which is probably what you want in a real world app. Oh and one final note: don’t just copy paste this code. Close the Reader and stuff. I’m just being lazy for the sake of the example.

Thanks to Bob Lee and Kevin Bourrillion for creating Guice, the coolest DI framework on the planet.

Follow

Get every new post delivered to your Inbox.