Inside Guice 2: exercising elements

Part 3 in a Series. Background: modelling configuration One of the most distinct features of Guice is our fluent embedded domain specific language (DSL). By chaining method calls, Guice supports a wide combination of binding sources, targets and scopes: bind(PaymentService.class) .annotatedWith(Names.named("creditCard")) .to(VisaPaymentService.…

Inside Guice 2: injecting null

Part 2 in a Series. Background: marking nulls Null is bad. Most of the time, use of null indicates clumsy modeling. Instead of null collections, use empty ones. Instead of a null service, use a no-op implementation. The JDK gets this wrong for comparators by using null as a stand-in…

Inside Guice 2: binder sources

To celebrate the release of Guice 2.0, I'd like to showcase my favourite parts of the new code. In this N-part series, I'll go deep into the implementation details to explain the clever and interesting code within the project. I'll focus on general techniques that you can use in…

My perspective on Atinject

Back in February, a discussion flared up over Guice's lack of support for industry-standard annotations. James Strachan described the problem succinctly: So my show stopper issue with ever adopting & recommending Guice is to be able to use IoC framework agnostic annotations for lifecycle & injection (JSR 250/EJB3 for…

Java Minutiae - Reflex

Pop Quiz The following is a method from a very decent implementation of Java SE. I've substituted x and y for the actual method name and parameter type. What are the values of x and y ? public static boolean x(y z)isNaN(float z) { return z != z; } PS -…

Some talks for your JavaOne Schedule

JavaOne is coming up, and now is the time to convince your boss to send you. You only need to learn a few productive tools for the conference to pay for itself. In addition to the Guice talk, here's some sessions I'm excited about... Developing LimeWire: Swing for the Masses…

Two simple classes for text processing in Java

FileCharSequence adapts a java.io.File as a CharSequence which has nice consequences. For example, you can run Java regular expressions directly against a File. And you can easily send part or all of a file to a StringBuilder or Writer: /** * Adapts a text file as a character sequence so…

Upcoming Guice talks

Dhanji and I are doing some Guice talks over the next two months. First, we'll be presenting at Google I/O. This conference is fast, web-focused, and cutting edge. It's also affordable: $300 if you register before May 1. Big Modular Java with Guice Learn how Google uses the fast,…

Jesse and Kevin B help out with Java Posse #239

I love listening to The Java Posse. Back when they mentioned Glazed Lists on episode 76, I was majorly psyched. I ran home and played the relevant clip for my wife, who's usually annoyed at the amount of time I spend programming, "See Jodie? See, see? I feel so…

Read your address bar carefully

Internet addresses are no longer stuck with ASCII and English. If you're Greek, you can have a Greek domain name; if you're Japanese you can have a Japanese domain name. To make international characters work on the existing ASCII system, you encode the address in Punycode: As an example of…

Preprocessing .java with Munge

In the rare situation that you need to preprocess .java files, Munge is a pretty decent tool for getting it done. From Tom Ball's blog, So a combination preprocessor and string translator, Munge, was created to address [supporting Java 1.1 and Java 2] (source). Since its requirements were that…

Always use jarjar to package implementation dependencies

jarjar is a sweet Java packaging tool that allows you to embed one .jar file in another. But rather than just smashing the jars together in one big archive, jarjar renames the embedded .jar's classes so that they live in the main jar's namespace. For example, Guice's ProxyFactory.java file…

howmanyspacesafteraperiod.com

Inspired by the URL-as-question meme sites http://has the large hadron collider destroyed the world yet.com and http://should I use tables for layout.com, I present http://how many spaces after a period.com:…

Audible on Android (and other devices)

I love my new G1, but it doesn't work with Audible yet. Fortunately, I have a workaround. This guide describes how to get audiobooks onto a G1. You'll need a Mac and $40 worth of software. Download and install Tune4Mac. This app creates a virtual CD burner on your Mac,…

Guice punches erasure in the face!

Java 5 Type Erasure is frustrating. I'm coding along, enjoying the glorious type safety of generics. And then I try to do a little more with the Ts, and erasure shows up, "You can't do that!" I can't test an object if it really is a T. I can't inspect…

Just checked in: PrivateModules

Dependency injection is addictive. The pattern allows our applications to grow without harming developer productivity. But we have seen technical hurdles... Sometimes our modules have competing dependencies. For example, we have a BillingModule and a PermissionsModule, each of which has a private database. If we configure two PersistenceModules to talk…

Rip.java: stream manipulation for Java programmers

I never learned sed or awk. Or even Perl. But I'm pretty good with Java's regex, and I'm familiar with the new text formatting facilities in Java 5. So rather than tricking myself into learning sed and awk, I wrote my own stream processor that uses Java's regex and pattern…

Coding in the small with Google Collections: AbstractIterator

Part 17 in a Series. I really like the Java Collections API. So much so, that I use 'em when I'm doing work that isn't particularly collectioney. For example, I recently wrote a quick-n-dirty app that rewrote some files line-by-line. Instead of using a Reader as input, I used an…

Google Collections talk, Aug 6 at the Googleplex

The Google Tech Users Group is hosting a talk that will interest Java developers: Overview: How the Google Collections Library builds on java.util to provide more building blocks for doing your job. Where: Building 42 of the Googleplex, Mountain View, California When: 6:00pm Food, social, demos and announcements…

Correctness and my wife

I do this really annoying thing when I'm hanging out with my wife. I correct her when she uses the "wrong" words... We're walking around town when we see something out of the ordinary - like a humongous fat dog or a friendly hobo or a police chase.…

Two use cases - two names?

Today I did something I've never done before - I created a method that's an 'alias' to another method. I still think this is the right thing to do, but I still find it kind of weird... Getting Providers Binder.getProvider() allows your module to get a Provider<…

Don't create multiple annotations with the same simple name

Nobody reads imports. Good IDEs do their best to pretend imports don't even exist - they'll hide 'em from you, and manage them for you. They'll even add imports on demand when you're writing new code. Suppose you create your own, say @Inject or @RequestScoped annotation. In the code, it's…

TypeResolver tells you what List.get() returns

It's diminishingly rare that I get to write code that improves the internals of both Glazed Lists and Guice... Glazed Lists' BeanProperty BeanProperty is a convenient utility class that can expose a JavaBeans getter/setter property as its own object. You give it a class (like Baz.class) and a…

The reasons I'm not on iPhone

It's really tempting. As far as devices go, iPhone 3G is the best there is. It's a generation ahead of its competitors, and the gap is growing. The app store is great for both developers and for its users. But I'm not gonna get one: **Amazon MP3. ** Lots of good…

Strict vs. Forgiving APIs

Suppose it's the early 1990's and you're James Gosling implementing String.substring(int, int) for the first time. What should happen when the index arguments are out-of-range? Should these tests pass? Or throw? public void testSubstring() { assertEquals("class", "superclass".substring(5, 32)); assertEquals("super"…

What's a Hierarchical Injector?

Our application has two implementations for one interface. EnergySource is implemented by both Plutonium and LightningBolt: class DeLorean { @Inject TimeCircuits timeCircuits; @Inject FluxCapacitor fluxCapacitor; @Inject EnergySource energySource; } interface FluxCapacitor { boolean isFluxing(); } @Singleton class RealFluxCapacitor implements FluxCapacitor { @Inject TimeCircuits timeCircuits; boolean isFluxing; public boolean isFluxing() { return isFluxing; } } class TimeCircuits { Date whereYouveBeen;…

Wanted: Guice Injector Graphing

One of the nice new features of Guice 2.0 is the new introspection API. It's the equivalent of java.lang.reflect for Guice - it lets you inspect your application at runtime. Our goal is to make it easy to write rich tools for Guice. A natural use case…

Integer.class and int.class as Guice Keys

Shortly after fixing arrays, I've found another multiple representations bug. This problem is probably familiar - I'm confusing primitive types (like int) with wrapper types (like Integer). It's one binding The critical question: should these tests pass? assertEquals(Key.get(int.class), Key.get(Integer.class)); assertEquals(TypeLiteral.get(int.…

Wanted: javax.interceptor extension for Guice

I'm feverishly preparing Guice for the 2.0 release later this summer, and tonight I scanned through our issues list. There's a whole bunch of good features that I won't get to before our release. So I'm looking for Guice users to help out with development! Introducing javax.interceptor javax.…

Bug pattern: multiple ways to represent the same data

There's a class of bugs that come up when one logical datatypes has representations in multiple classes. The best example of this is 1 vs. 1L. Both ones represent the same data. But new Integer(1) is not equal to new Long(1) according to the corresponding equals() methods. Calling…

Guice talk, tomorrow morning at Google I/O

Bob and I are giving a talk at Google's developer conference tomorrow. From the session summary: Wed 11:15am - 12:15pm Bob Lee, Jesse Wilson Guice (pronounced 'juice') is a Jolt award-winnning, lightweight dependency injection framework for Java 5 and above. Put simply, Guice alleviates the need for factories…

Calling a method that always throws

Kasper complains that it's hard to call methods that always throw. In particular, code like this won't compile because findGetter is missing a return statement: public Method findGetter() throws CsvException { try { return type.getMethod("get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1)); } catch(SecurityException e) { noSuchGetter(e)…

Overriding Bindings in Guice

In our functional tests, we prefer to launch an application that closely resembles the production one. This means using the production modules in a proper staging environment. Even with automating scripts, setting up the environment is time consuming and tedious - it requires database install and configuration, permissions, SSL certificates,…

MapBinder checked in!

Building out the Multibindings extension, David P. Baker has written a new class that simplifies Map binding. MapBinder uses an API that's consistent with Multibinder: public class SnacksModule extends AbstractModule { protected void configure() { MapBinder<String, Snack> mapBinder = MapBinder.newMapBinder(binder(), String.class, Snack.class); mapBinder.addBinding(…

Elite Guice 3: Private Bindings

In the first and second parts of this series, I discussed hooks for extending Guice. In this post I introduce private bindings. Don't emulate Guice The key to a good extension is tight integration with Guice. In particular, the extension shouldn't copy functionality from Guice; doing so can lead to…

Why no Multibindings for Lists or Arrays?

The Multibindings code I checked in last week has been well received. There's even a screencast introducing the new code. But there are missing features. We're still figuring out exactly what's the right balance of functionality and simplicity. One particular omission is the lack of support for Lists and arrays.…

Elite Guice 2: Binding de-duplication

In part one, I showed how to initialize a Guice extension using the @Inject tag on a method. In this post I'm going to demonstrate a Guice for deduplicating bindings. What is binding duplication? One of the features of the Multibindings Extension is that there's no central coordination. Each module…

Elite Guice 1: Initialize your extension

I recently wrote some fairly, um, extreme code for the Guice Mutibindings extension. That code makes use of several tricks that you might find useful in your own Guice extensions. In this series I'm going to show-and-tell the various clever code tricks from Multibinder.java. Initialize an extension Guice doesn't…

Guice Multibindings extension checked in!

As previously alluded to, I've started work on the Multibindings API. I've checked in the initial implementation, and I'm pretty excited about it. You can grab it from svn. This feature is ideal for lightweight plugin-type architectures, where you've got multiple modules each contributing Servlets, Actions, Filters, Components or even…

Future Guice: Providers that throw unchecked exceptions

As previously mentioned, I'm cataloging Guice's changes since 1.0. Suppose you have a provider that throws an unchecked exception: class PhaseOfTheMoonProvider implements Provider<PhaseOfTheMoon> { @Inject Observatory observatory; public PhaseOfTheMoon get() { if (observatory.isNighttime()) { return observatory.getCurrentPhase(); } throw new IllegalStateException("Can't see the moon unless…

Glazed Lists talk at JavaOne: Friday at 2:50pm

Details on this year's Glazed Lists tech session: Simply Sweet Applications with Glazed Lists Ken Orr, The MathWorks Session TS-6047 Friday May 9 at 14:50, Hall E 135 From Ken's Abstract, Glazed Lists fosters data-centric design, which promotes decoupling of components and increases the testability of your code. This…

Guice Multibinder API proposal

Multibindings is an idea to allow multiple independent modules to contribute elements to a collection. There's lots of proposed APIs to add multibindings to Guice. Unlike almost all of the existing proposals, this strategy can be used to add multibindings as an extension to Guice. Therefore we don't increase the…

Future Guice: injecting inner classes

As previously mentioned, I'm cataloging the differences in Guice since 1.0. This test passes in Guice 1.0, but how it does so is surprising: public class InjectTest extends TestCase { public void testFoo() { Foo foo = Guice.createInjector().getInstance(InnerFoo.class) } class InnerFoo implements Foo { @Inject InnerFoo() {} } } The problem is…

Future Guice: More aggressive error detection

For the past month, I've been cataloging the various changes since Bob & Kevin released version 1.0 back in March 2007. For a 1.0, it's held up remarkably well. We've been using it on my team without many problems and we've quite enjoyed it. Good News! Guice has…

Quine Programs in Java

Michael Kölling blogged about Quines - programs that print themselves. Here's my best effort in Java (prettyprinted for readability): class A { static { String a="class A{static{String a=%s%s%1$s;System.out.printf(a,'%1$s',a);}}"; System.out.printf(a,'"',…

Amazon MP3 works good

I just bought the new Panic At The Disco album on Amazon MP3. It was easy! And I don't have the DRM-guilt that I usually get whenever I buy stuff from iTunes. The price is right, the quality is high, and I don't have to do the Deregister Computer bullshit…

Don't do this: Share names

The following program is valid Java, even though the Runnable on line 1 is a completely different symbol than Runnable on line 3: public class Refrigerator implements Runnable { public void run() { new Runnable().freeze(); } public class Runnable { void freeze() { System.out.println("cold and refreshing"); } } public static void…

Discovering the platform profile from Java

What's the simplest way to get CPU speed, amount of RAM, OS version, and other hardware details from the running JVM? I'm putting together a yet-to-be-announced tool that will include hardware specs in its reporting. So far, I've been able to get the hardware profile on Mac OS X using…

Coding in the small with Google Collections: ImmutableSet

Part 15 in a Series. The Google Collections project has released an impressive new collection of features. The new release has prompted me to continue this series. My favourite feature of the new release is ImmutableSet. It's a top-level implementation of Set that's full of features - this class alone…