Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Friday, March 16, 2012

Converting Forms in Restlet to POJOs with Jackson and Guava

Punchline first. This article presents code that you can use to convert HTML forms into POJOs, mapping property names in the natural way, with support for compound objects and arrays/lists. A long-winded set-up for that punchline follows.

Many of my Restlet resources are designed to support both JSON and HTML representations with resource interfaces that look like this:

public interface PersonResource {
    @Get Person getPerson();
}

where Person is a POJO that might look like this:

public class Person {
    public String getName() { ...}
    public List<Address> getAddresses() { ... }
    ... other bean stuff: setters, fields ...
}

and the implementation of the resource looks like this:

public class PersonServerResource 
        extends ServerResource implements PersonResource {
    @Override public Person getPerson() {
        return ... construct Person from domain data ...
    }
}

I register custom ConverterHelpers with the Restlet Engine. One of them knows how to use Jackson to convert Person into JSON, one knows how to obtain a Freemarker HTML template associated with the Person type and render it with the Person as its data model.

It works like magic. When I use a browser to point to the resource, it returns the HTML generated with Freemarker. When I ask for it with, say, jQuery, requesting JSON, I get ... JSON. When I get a Restlet ClientResource proxy for PersonResource at that URI, I get a Person object back when I call getPerson() on the client side; the value returned by getPerson() on the server is serialized to JSON, sent over the wire, and deserialized back into a Person object.

The only problem I had was for PUT and POST method handlers, because there was no automatic way to convert form data to my domain types. I had to create an additional method to handle forms as parameters:

public interface PeopleResource {
    @Post("json:json") Person addPerson(Person person);
    @Post("form:html") Person addPersonForm(Form person);
}

public class PeopleServerResource 
        extends ServerResource implements PeopleResource {


    @Override public Person addPerson(Person person) {
        ...
    }
    @Override Person addPersonForm(Form personForm) {
        Person person = new Person();
        // Extract values from personForm and set
        // them to person.
        return addPerson(person);
    }
}

I suffered this for a long time, and then I began to think that the application/www-form-urlencoded media type was, at least for simple types, not far from JSON. Could I translate form data to JSON and then use Jackson to deserialize that? Of course I could. In fact, it wasn't too hard to define some conventions whereby sequences (lists/arrays) and nested structures could be modeled. An encoded form for Person as produced  by an HTML page might look like this, in part:

name=Tim&address.1.street=Main&address.1.city=Anytown...
     ...&address.2.street=Elm&address.2.city=Smallton...

and the corresponding JSON would be:

{
    "name":"Tim",
    "address":[{
        "street":"Main",
        "city":"Anytown",
        ...
    },{
        "street":"Elm",
        "city":"Smallton",
        ...
    },
    ...
    ]
}

I wrote FormDeserializer to do this. It takes a Jackson ObjectMapper to do the heavy lifting. Here's the Javadoc for the deserialization method:


public  T deserialize(Form source, Class targetType)
Converts a Form to a Java object of the target type, using each name=value pair to set the corresponding property on the target object.

Compound names, using period (.) as the delimiter, are treated as pseudo-dereferences (a la JavaScript or Groovy) to set properties of sub-objects, e.g., a.b=c for bean targets is treated like a call to target.getA().setB(c).

Numeric components of compound names are treated as indices into a sequence named by the preceding components, e.g., a.1=c is treated as target.getA()[1] = c (or target.getA().set(1, c), if the "a" property of the target is a list rather than an array). Unless an element with index 0 is set, the indices are origin 1.

Sequences are also created by names with multiple values, e.g., a=x&a=y is equivalent to a.1=x&a.2=y, with the value of the "a" property in the target being a sequence of two values.
When a name appears both indexed and non-indexed, the last assignment wins: a=x&a.1=a1&a.2=a2 will set the "a" property to a sequence of values [a1, a2], but a.1=a1&a.2=a2&a=xwill set the "a" property to x.

If the top level consists only of integer indices, the subobjects will be interpreted as elements of a sequence (and T must be a List or List subtype instead).

The values are deserialized using the Jackson ObjectMapper that was used to construct this FormDeserializer. Any type that can be deserialized from a string can be used. While it is possible for Jackson to deserialize object graphs that have internal references, it is not possible for the form values to refer outside of themselves.

Runtime exceptions from Jackson conversion are propagated without exception translation. This could be considered a bug.
Parameters:
source - the Restlet Form object to be deserialized
targetType - the type of the target object into which the form is to be deserialized.
Returns:
the deserialized object of the target type


The converter class that uses this machinery is FormConverter. It uses a marker annotation, FormDeserializable, that signals when a class is suitable for deserialization from a form.

The upshot is that I can now write:

public interface PeopleResource {
    @Post Person addPerson(Person person);
}
// And no need for additional method in implementation!


Big reduction in the amount of boilerplate I have to write, and the code is easier to read.

Here are the links to the code in one place:


I have @Inject tags on some constructors, but you can ignore them unless you want to use them for dependency injection.

The implementation makes heavy use of Guava. If you don't or can't use Guava, then you'll have to roll your own machinery. (Good luck!)

Thursday, March 15, 2012

Restlet Guice extension considered ... unnecessary

I wrote some code back in 2008 to help inject my Restlet resources using Guice and then blogged about it. In 2009, the Restlet team added it to their "incubator" as a potential Restlet extension. (Calling it a Guice extension is a bit of a misnomer, since part of it is independent of Guice and applies to any JSR-330-compliant DI framework.) They've talked about promoting it out of the incubator as early as release 2.2. Update: It's now part of Restlet 2.2 and I've updated code references to point to the 2.2 branch.

More recently, I argued (and Restlet's Jérôme Louvel seemed to accept the argument) that Restlet needs a uniform way to create a non-standard Finder for all the Restlet classes that have methods accepting a Class<? extends ServerResource> in place of a Restlet. This would make the use of the Guice extension invisible when wiring up the routing structure: Currently you have to convert the resource type to a Restlet explicity,
    router.attach("/path/to/resource", finderFactory.finder(MyResource.class));

and the extra support would let you write:
    router.attach("/path/to/resource", MyResource.class);

It's all very gratifying, except I realized suddenly this week that for
most people who just want to inject their 
ServerResource 
subclasses it's completely unnecessary. 
It's much simpler to define 
doInit()
to inject the resource's members, and then you can just use the second, simpler form above.
I wrote an abstract base class extending ServerResource that does just that:


SelfInjectingServerResource.java

Notice that SelfInjectingServerResource uses only the standard @Inject annotation and nothing specific to Guice. In order to make it actually work with Guice, you need to tell Guice that you want self-injecting server resources. The following class is a Guice Module that accomplishes this by requesting static injection of the SelfInjectingServerResource class and providing an implementation of its nested MembersInjector interface to perform the injection.

SelfInjectingServerResourceModule.java

Install this module when creating the top-level injector, make sure that the server resources you want injected inherit from SelfInjectingServerResource, and it just works. Here's a JUnit test class that shows a trivial example of the idea in practice:

SelfInjectingServerResourceModuleTest.java

We'd like this technique to co-exist with other techniques that manage resource injection differently (e.g., the current Guice extension), without worrying about whether it's OK to extend SelfInjectingServerResource, so this code uses an atomic boolean to prevent multiple injections. (AtomicBoolean is probably overkill, but it can't hurt to be safe.)

[Deleted obsolete discussion of how to use prior to adoption as part of Restlet.]

I said that the old Guice extension was unnecessary for most users, but there are a few things the old code does that the new code doesn't do:
  1. It does constructor injection, letting you have final fields with injected values.
  2. It lets you create a Finder for a resource interface, decoupling the target of the routing from the resource implementation.
  3. It lets you use qualifiers when looking up resource types, further decoupling the target of an attachment from the implementation.
  4. It doesn't require inheritance from a common abstract base class.
  5. You don't have to remember to call super.doInit() when you override doInit
As it happens, I'm taking advantage of #2 in my current work. (Note that there's no way to avoid the explicit finder call in this case, even with added Restlet support, because the Restlet signatures expect a ServerResource subclass.) So I'm stuck with my mistake for the foreseeable future. But no one else need be, now.

Update (2013 July 9)

I got rid of my dependency on #2 above, and I am now using the new approach exclusively, and I strongly recommend others do the same.

Further update (2014 Sep 1)

The Restlet Guice extension package docs discuss how to use each of three approaches, so you aren't forced to use the approach that I prefer.

Monday, March 12, 2012

Further distributed CacheLoader developments

Updated 2012-Mar-13 and 2012-Mar-20; see notes at end.

In a discussion on the Guava mailing list after my previous post, Charles Fry and Louis Wasserman had some great ideas that spurred me to rewrite the distributed CacheLoader functionality from scratch.

The first part is static factory methods to turn an AsyncFunction into a CacheLoader:

CacheLoaders.java

This is independent of any mention of Hazelcast; it works with any AsyncFunction. The Iterable-ness of the keys passed to loadAll is preserved all the way through, so asynchronous processing can start before the keys have been completely iterated. This could be handy if, for example, the keys themselves are being generated asynchronously.

The other piece is a class with methods to create an AsyncFunction out of a Hazelcast-based Executor:

HazelcastAsyncFunction.java

Note that the public API of this class does not use any Hazelcast types.

The whole implementation is much cleaner and takes full advantage of existing Guava machinery. Here's what it looks like in use in my code:

    AsyncFunction asyncLookup =
        HazelcastAsyncFunction
            .from(syncLookup());
            .onExecutor(hazelcastExecutor())
            .withTaskKeyFunction(mapAccountToServer());

    LoadingCache cache = CacheBuilder.newBuilder().build(
        fromAsyncFunction(asyncLookup, 30L, TimeUnit.SECONDS));
    ...
    // Later on, this call causes the account lookups to be
    // magically distributed across the cluster:
    Map accountNameToInfo = cache.get(accountNames);

Update 2012-Mar-13: Louis Wasserman pointed out (in comments to this post) a race in the implementation of CacheLoaders. I've updated the code to remove the race. It doesn't use as many cool Guava tricks, but it's quite a bit simpler now.

Update 2012-Mar-20: Unpacked the example to make it less frightening.

Saturday, March 10, 2012

An invokeAll for Hazelcast ExecutorServices and a distributed CacheLoader

[A more recent posting describes a much cleaner implementation of the functionality described in this article.]

The ExecutorService returned by Hazelcast[Instance].getExecutorService() does not support invokeAll, but I needed this functionality for work I'm doing, so I rolled my own restricted version:

ExecUtil.java

ExecUtil has several variants of invokeAll. The generic variants take these values:

  • an ExecutorService, which is must have been returned by a Hazelcast getExecutorService call;
  • an Iterable of DistributedTasks<T>, where T is the common result type; and
  • a FutureCallback<T>, which is a Guava interface for specifying what to do with each returned result (and what to do, if anything, with exceptions thrown during task execution).
The non-generic variants use the Void result type. Generic and non-generic have two variants each, one that waits indefinitely and one that waits a given amount of time for all the results to finish.

The use of Iterable<DistributedTask<T>> allows lazy provision of the tasks. (Supporting this feature prevented a simpler implementation with just a CountDownLatch initialized to the number of tasks, because we don't know the number of tasks in advance.)

The main awkwardness is that both the Callable<T> used to create the DistributedTask and T itself must be Serializable, but this is, of course, a requirement imposed by DistributedTask.

Update (2012-Mar-11): I added a static method to ExecUtil that wraps an ExecutorService, implementing invokeAll in terms of ExecUtil.invokeAll if the argument was created by Hazelcast. Also added a ConcurrentFuction that wraps an existing Function for concurrent or distributed application.

A concurrent Guava CacheLoader

I then realized that this machinery could be used to provide a nice implementation of Guava's CacheLoader, used to build LoadingCache instances with CacheBuilder. LoadingCache has a getAll(Iterable<? extends K> keys) method that returns a Map<K, V> from keys to cached values. It calls CacheLoader.loadAll(Iterable<? extends K> keys) -- if it's implemented -- to load the values in order to cache them. If loadAll isn't implemented, it just loads the keys sequentially.

I wrote a CacheLoader implementation that can use ExecUtil.invokeAll to load the values using DistributedTasks. While I was at it, I made it so that if you don't have a Hazelcast-based ExecutorService, you can use a normal ExecutorService to load the values concurrently (in the same JVM).

The result is ConcurrentCacheLoader:

ConcurrentCacheLoader.java

It has a nested Builder class that allows you to specify:

  • the ExecutorService used (including shortcuts for default HazelcastInstance ExecutorServices),
  • a time limit for loadAll,
  • a function to map a cache key to a key object for the DistributedTask, and
  • the actual function that maps cache keys to values.
There's a minimal set of tests here:

ConcurrentCacheLoaderTest.java

Here's how I'm using it:

Sample usage

That's a ConcurrentCacheLoader.Builder used to build an argument to a CacheBuilder method.

The upshot is that my call to getAll runs on all the nodes in my Hazelcast cluster.

Addendum:

The motivation for all this was the desire to make dozens of calls to JClouds' BlobStore.getBlob() in the space of a single HTTP request. The standard for-loop approach was taking too long, and I suddenly realized I could be asking the Hazelcast cluster to do the work.

Monday, January 23, 2012

Deploying Restlet components in Elastic Beanstalk

I spent some time finding a way to deploy a Restlet component in ElasticBeanstalk without giving up the option of deploying it as a standard Java executable for local development and testing. People have expressed interest in seeing the approach, but I don't have the time to create a full-fledged framework, so I've extracted the following template instead (links to code embedded in the prose). Just copy to your own environment, changing package and class names as you see fit, add your Guice Modules, define your Restlet applications and resources, and you should be able to run the resulting component both standalone and (by bundling everything in a WAR) via Elastic Beanstalk. I make no claims that this code is correct, that it is safe to use, or even that it will compile. You have to read it, compile it, and judge for yourself.

The code depends on Restlet, Guice, Rocoto, Guava, and (minimally) SLF4J. I've included commented-out code that uses the Restlet-Guice extension, which is in incubator status in the Restlet codebase.

The Main class is a GuiceServletContextListener and it has a main method. When you run com.example.server.Main from the command line, the GuiceServletContextListener methods are ignored. When you deploy a WAR that contains the associated web.xml file, the main routine is never called. You can inject the current DeploymentMode into your classes if you want to change behavior depending whether you're running standalone or in Elastic Beanstalk (i.e., as a servlet).

The MainComponent class is where your Restlet component logic goes. Its lifecycle is managed by the MainService class, which is where you can manage other services with lifecycles. (If you use JClouds BlobStores, for example, you can ensure that a singleton BlobStoreContext is closed when the MainService is stopped. Another example: a LifecycleService for the Hazelcast data grid) There is some trickiness to handling shutdown in various cases; make sure you nest try-finally clauses so that every one of your services gets a chance to shut down even if the previous shutdown attempt throws an exception or error.

The MainServletModule and MainServlet classes deal with the details of embedding the component in a servlet (which is necessary in order to use Elastic Beanstalk).

AwsCredentialsModule is an example of how you can inject AWS credentials from either of two sources: system properties defined on the command line (or via Ant invocation) and system properties defined by an Elastic Beanstalk configuration.

The flow of control when running standalone is that the main routine creates an instance of Main with the STANDALONE deployment mode, creates the injector, gets the singleton MainService, and starts it, which causes (in a different thread), the MainComponent to be started.

The flow of control when running as a servlet is that a default instance of Main is created (due to the web.xml directive) and gets the SERVLET deployment mode. Its contextInitialized call creates the injector, which injects the MainService and starts it, causing (in a different thread), the MainComponent to be started. 

Files:
  • web.xml - web application descriptor
  • Main - has main() routine for standalone; is context listener for servlet mode
  • MainComponent - the Restlet component we want to be able to deploy in both modes
  • MainService - manages lifecycle of MainComponent and (optionally) other services
  • MainServletModule - included in module list in Main; configures Restlet-Servlet bridge
  • MainServlet - injects MainComponent and returns it as the component it wraps
  • DeploymentMode - enum with two values: STANDALONE and SERVLET
  • AwsCredentialsModule - example of passing AWS credentials for binding with @Named

Tuesday, December 06, 2011

Overriding common bindings with test bindings in Jukito

This post is about how to get common bindings for Jukito tests without having to write too much boilerplate. (Obviously not a general interest post!)

A recent conversation on the Jukito newsgroup discusses various proposals for reducing the amount of boilerplate involved in setting up common bindings for tests that have a common superclass. I've noticed that the underlying assumption to these proposals is that bindings in modules are inheritable in the same way that methods are, but that's not generally the case. You can override methods by defining a new version in a subclass, but to override the bindings in a module, you need to use Modules.override, which doesn't work via inheritance.

I've written a template to illustrate how to override with test bindings; it uses Jukito 1.1 as is:

http://pastebin.com/BLQnMEqx

The key is to declare a static method in a common test superclass that returns a single module, which is easy to do with Modules.combine. Then in the concrete test class, use

  Modules.override(commonBindings).with(testBindings)

This strikes what I think is the right balance between compactness and clarity: You have one place in the concrete test class that says what the basic bindings are (commonBindings) and what test bindings are being used to override for the purposes of this test (testBindings). There's no hunting around through the inheritance hierarchy for modules with the right characteristics.

Because the Modules.combine/override approach is so simple, the case for adding special Jukito support (based on inheritance alone, annotations alone, or on a combination of inheritance and annotations) for auto-installing commonly-used modules becomes much weaker. Jukito is already pretty magical; it doesn't need to add mystery to its magic.

Tuesday, October 26, 2010

Vote for Bob Lee and prove Doug Lea wrong!

In explaining why he is not seeking another term on the JCP SE/EE Executive Committee, Doug Lea encourages us to prove him wrong about the growing irrelevance of the Java Community Process.

The best hope for proving Doug wrong lies with folks who have experience working on JSRs that weren't simply rubber stamps — and Bob Lee is the best of those folks. Bob is running for one of two open seats on the SE/EE EC against Azul, Eclipse, Google, and three others, and (if you're a member of the JCP) I urge you to vote for him.

Bob is running as an individual, which means that his votes will not be tied to the commercial and legal interests of a large corporation, but will instead reflect his personal expertise and judgment about the best interests of the Java community.

There's no denying that the JCP has been moribund for too long, and that Oracle's ham-handed moves have made the prospect of a true revitalization far less likely than anyone expected a year or so ago. But it's worth a shot, and I don't know anyone better equipped to help make that shot than Bob Lee. (Except Doug Lea, of course, but that's water under the bridge.)

Monday, August 30, 2010

Friday, November 27, 2009

Concurrently initialized singletons in Guice

William Pietri asked whether it would be possible to take advantage of concurrency and Guice's knowledge of dependencies to provide interdependent (and expensive to create) singleton services in parallel.
For example, say that service A depends on services B and C and that B and C don't know about each other (and so could be constructed concurrently). Obviously, you could explicitly construct B and C in separate tasks running in a thread pool, then construct A once B and C exist.
class A {
    A(B b, C c) { /* ... use b and c ... */ }
}

class B {
    B() { /* ... takes a long time ... */ }
}

class C {
    C() { /* ... takes a long time ... */ }
}

class Services {
    A a; B b; C c;
    void init() throws InterruptedException {
        final CountDownLatch ready = new CountDownLatch(2);
        Executor pool = Executors.newCachedThreadPool();
        pool.execute(new Runnable() {
            public void run() { b = new B(); ready.countDown(); }
        })
        pool.execute(new Runnable() {
            public void run() { c = new C(); ready.countDown(); }
        })
        ready.await();
        a = new A(b, c);
        // Now publish a, b, and c safely -- not shown.
    }
}
But it's a pain to have to orchestrate this yourself. You have to know the dependencies intimately and write a lot of tricky code. If the dependencies change, the code has to be completely rethought. Wouldn't it be nice if Guice could do this for you automatically without giving up on the opportunities for concurrency? Well, it turns out that it can.
The idea is to use a variant of singleton scope that runs the providers of all bindings for that scope in separate threads. Naturally some of these providers block in their own thread while their dependencies finish in other threads, but those services that can be constructed in parallel will be.
Here's what the Guice version looks like:
@ConcurrentSingleton
class A {
    @Inject A(B b, C c) { /* ... use b and c ... */ }
}

@ConcurrentSingleton
class B {
    @Inject B() { /* ... takes a long time ... */ }
}

@ConcurrentSingleton
class C {
    @Inject C() { /* ... takes a long time ... */ }
}
No special initialization code needed, just inject A, B, and C wherever they are needed. (Note that if you have circular dependencies, this probably won't work. So don't have circular dependencies.)
ConcurrentSingleton is just a scope annotation. The actual scope implementation is ConcurrentSingletonScope. I have a fleshed-out version of the A, B, C example, ConcurrentSingletonExample, that is slightly different from the code above; it uses Providers for B and C so that A can do some work before getting B and C in the constructor.
You aren't forced to do all the expensive work in the constructor. You could also inject a start method with injected parameters to provide needed dependencies.
In the same thread that provoked the ConcurrentSingleton response, Jesse Wilson suggested the use of the experimental lifecycle facility in Guava. This could prove useful in the current context if, for example, you have singleton services that take a while to stop and could benefit from being stopped in parallel.

Update 2009-11-30

I added a call to pool.shutdown() in the scope implementation to make sure the pool threads don't prevent the JVM from exiting. It might not be necessary, but I don't think it hurts.

Update 2010-7-3

Added explicit notice that the sources are in the public domain.

Update 2018-10-16

Added a GitHub repository with the concurrent singleton code and other utilities, as the old links to code weren't working any more. Now using MIT open source license.

Tuesday, May 12, 2009

Dependency injection in Restlet 2.0 with Guice

I'm very excited about Restlet 2.0, which is in testing now and scheduled for release at the end of 2009. Among other things, the newly refactored Resource API encourages more readable code through the use of a small number of annotations. Here's a very simple server-side resource:
public class DefaultResource extends ServerResource {
    @Get public String represent() {
        return "Default resource, try /hello/resource or /hello/handler";
    }
}

ServerResource has a no-arg constructor, so you don't need to pass Context, Request, and Response objects to super().

Nice as this is, I still want to inject my resources using Guice, so I've updated the Restlet-Guice classes from my previous post to support both the new ServerResources and the old Handlers. It incorporates the enhancement mentioned in the updates: You can override methods to use different providers for Application, Context, Request, and Response, although for most purposes the default providers should suffice.

Update 2009-Dec-11


I've been working on a Guice extension for Restlet as an incubator project that uses the ideas in this posting. My goal is to make this extension independent of Guice at the interface level, so that people can provide implementations for different DI frameworks, of which Guice is only the first.

Thursday, July 24, 2008

Resource dependency injection in Restlet via Guice

(See a more recent posting on this subject.)

I have a body of code that already benefits from Guice dependency injection, and I want to migrate it from a servlet-based architecture to Restlet without losing those benefits. I've had some success, and I figured I'd report on it.

I don't mean that I wanted to use Guice to wire up an object graph of Restlets (Components, VirtualHosts, Applications, etc.). It's straightforward enough to use the builder-like API of Restlet, and such code is nicely confined in a few places where it doesn't bother the meat of the application, its resources.

What I do want is to have those resources created by Guice, so that they can be constructed with dependencies injected into them. With the Finder approach, resource constructors get a Context, a Request, and a Response, but that's it. I suppose I could find a way to stash an Injector in one of these so that resources could look up the dependencies they need, but I wanted something more direct. I came up with the following scheme, which seems to be working pretty well:

I use a custom Finder that knows how to look up a Handler/Resource by class or Guice key -- instances of these custom Finders are provided by a FinderFactory:
public interface FinderFactory {
    Finder finderFor(Key<? extends Handler> key);
    Finder finderFor(Class<? extends Handler> cls);
}

The class RestletGuice has static methods named createInjector that parallel those of the Guice class. The difference is that it adds bindings for Context, Request, Response, and FinderFactory. In my Guiced version of the FirstStepsApplication from restlet.org, the following lines create an Injector with some bindings and then look up the FinderFactory that will produce Finders that will be able to make use of those bindings. (These bindings are not necessarily good practice; they just demonstrate the technique.)
    Injector injector = RestletGuice.createInjector(new AbstractModule() {
        public void configure() {
            bind(Handler.class)
                .annotatedWith(HelloWorld.class)
                .to(HelloWorldResource.class);
            bindConstant()
                .annotatedWith(named(HelloWorldResource.HELLO_MSG))
                .to("Hello, Restlet-Guice!");
        }
    });
    FinderFactory factory = injector.getInstance(FinderFactory.class);

HelloWorldResource is slightly changed. It has a private final field, msg, that is used to generate the text representation. The msg field is initialized via an injected value.
    @Inject public HelloWorldResource(@Named(HELLO_MSG) String msg,
                                      Request request,
                                      Response response,
                                      Context context) {
        super(context, request, response);
        this.msg = msg;
        getVariants().add(new Variant(MediaType.TEXT_PLAIN));
    }
    static final String HELLO_MSG = "hello.message";

This all comes together in the Application class when attaching a Finder for the default routing.
    Finder finder = factory.finderFor(Key.get(Handler.class, HelloWorld.class));
    Router router = new Router(getContext());
    router.attachDefault(finder);
    return router;

I read this as "Route any request for this application to whatever resource is bound to @HelloWorld-annotated Handlers, injecting that resource's dependencies," which was exactly what I wanted.

For those who don't want to have to call a special RestletGuice method, there is a public class FinderFactoryModule extending AbstractModule that can be used with Guice.createInjector(...) to get the same effect.

FinderFactoryModule also implements FinderFactory, so you can construct an instance in your Restlet wiring code and use it right away. You can then use the FinderFactoryModule to create an injector explicitly.

As a special convenience, if you don't use a FinderFactoryModule to create an injector, one will be created implicitly the first time one of its Finders is used to find a target Handler/Resource. This encourages a style where each Application gets its own implicit Injector by creating a local FinderFactoryModule and using it to create Finders.

That's basically it. It works with plain Guice 1.0 and Restlet 1.1 (since it uses Handler as the base type for all Resources). I haven't had time to package it nicely, but you can follow the links below for the actual code.

Sources (links are out of date, use this instead):
FinderFactory.java
FinderFactoryModule.java
RestletGuice.java

Example (links are out of date, use this instead):
FirstStepsApplication.java
HelloWorld.java
HelloWorldResource.java
Main.java

Update (August 2008)


Chris Lee discovered that Context.getCurrent() doesn't work reliably as of 1.1m5; the workaround is to use Application.getCurrent().getContext(). A more comprehensive fix, that I hope to post soon, would involve letting subclasses of FinderFactoryModule override the methods that create the Providers for Request, Response, and Context.

Update (2009-Feb-3)


Leigh Klotz has a workaround for using Guice Finders with WadlApplication. And I still haven't had time to package any of this more nicely. (Feb 7: Jérôme Louvel took Leigh's suggestion and checked it in on the Restlet trunk.)

Monday, November 05, 2007

Concurrency issues in Restlet

Issue #368 in the Restlet issue tracker was originally focused on the Guard class. Since then, I've taken a look at the rest of the org.restlet package and found that the fields of most classes are accessed without appropriate synchronization. [Update 2008-Feb-6: All of these have been fixed as of Restlet 1.1 M1.]

Most of these problems would disappear if the fields could be final, but that would mean taking away setter-injectability.

There is hope, however: Methods that are used only for setter injection (and not, for example, used to reconfigure an instance dynamically), should be documented as setter-injection-only, meaning they must not be called after the instance has been (safely) published. Fields set by such methods get their values before publication, and those values never change; such fields are effectively immutable. I don't know of any standard documentation conventions for this, but the important thing is to decide for each non-final, non-volatile field whether it is truly mutable or only setter-injected before publication.

I have a long-standing gripe about the Spring documentation that it doesn't state, at least not in terms that I recognize, under what conditions beans are safely published. The vanilla use cases (standard ApplicationContext implementations) are almost certainly fine, but if you have any doubts about whether your dependency injection framework can guarantee safe publication, then you should either guard your setter-injected fields with a lock or make them volatile. I have a personal preference for using volatile in this case, but most of my Java Concurrency in Practice co-authors have the opposite preference.

Even if you're fairly confident about your DI framework's guarantees, it is never wrong to guard field access or make a field volatile, only potentially wasteful. For a framework like Restlet that should be usable in any DI context, I think it would be prudent to assume the worst of that context.

But is setter injection really necessary? Most of the injected fields are of distinct types, so constructor injection in Spring would be straightforward. Getting rid of setter injection entirely would allow most, if not all, fields to be final, which would greatly reduce the risk of concurrency problems in Restlet.

Tuesday, October 09, 2007

Basic rules for @ThreadSafe classes

Some rules for classes to be annotated with @ThreadSafe:
  1. All non-final, non-volatile fields (and final references to non-thread-safe state) must be annotated with @GuardedBy(x), where x is usually this, meaning that all access to the field -- reads and writes -- is performed within a synchronized (this) block or synchronized method. [This is probably the hardest rule for people to accept; it's not intuitive that reads must be performed with a lock held. See amplification below.]

  2. If two fields annotated with @GuardedBy participate in the same class invariant, they must be annotated with the same argument to @GuardedBy. [This is trivially satisfied if you only use @GuardedBy("this").]

  3. All compound actions with atomic semantics (e.g., check-then-act and read-modify-write sequences) must be performed completely within a synchronized block or method. [This is what many people incorrectly think is the only reason to use synchronized.]

  4. Do not make calls to code whose synchronization properties you don't know or control from inside a synchronized block or method; prefer open calls (calls made with no locks held). [This is a strategy for deadlock avoidance.]

  5. Prefer final fields. For collection fields, prefer thread-safe collections. (But don't bother using a thread-safe collection if the field needs to be @GuardedBy for some other reason.)

  6. Prefer final atomic variables to volatiles. Volatile fields cannot be modified atomically without a synchronized block.

  7. There need be no special relationship between x and y in "@GuardedBy(x) Type y;" as long as all access to y is made while holding x's lock.

  8. Don't be too clever: even if your clever reasoning is correct right now, it will be harder in the future for others (and you) to understand and maintain the code that relies on that reasoning.

Amplification


Brian Goetz suggests that I make this point more strongly: Not only do you need to declare such fields @GuardedBy(lock), you have to acquire lock every time you access the field in any way.

Concurrency discussion in Restlet community

I started a thread on concurrency issues in the Restlet framework, and it led to a several people saying nice things about Java Concurrency in Practice.

Jérôme Louvel's responsiveness to these issues is gratifying. A far cry from the huffiness I provoked when I had the temerity to question the concurrency guarantees in Spring!

Sunday, September 16, 2007

Java Concurrency in Practice news

I'm told that Java Concurrency in Practice is going into its fifth printing!

Custom Matcher and MethodInterceptor for DWR-Guice

I wanted a way to intercept calls to public methods of a remoted interface so I could replace my use of bindFilter with bindInterceptor, as described in an earlier posting.

At first I thought I could just use the static methods in Matchers:

bindInterceptor(
only(MyService.class),
any(),
myInterceptor
);

This doesn't intercept anything, because MyService is an interface. What I needed was to intercept calls to a method of a subclass of MyService for which there exists a method of the same name and argument types in MyService.

bindInterceptor(
subclassesOf(MyService.class),
declaredBy(MyService.class),
myInterceptor
);

The subclassesOf matcher is already provided in com.google.inject.matcher.Matchers, but I had to roll my own declaredBy method matcher. Here's the heart of the implementation (cls is a final Class<?> field, initialized from the argument to declaredBy):

public boolean matches(Method method) {
try {
// Matches if the method is from a subclass
// of the given class (or the class itself)
// and the given class declares a method
// with the same name and parameter types.
if (cls.isAssignableFrom(
method.getDeclaringClass())) {
// Return value of getDeclaredMethod
// is ignored. It throws an exception
// if the method is not found.
cls.getDeclaredMethod(
method.getName(),
method.getParameterTypes());
return true;
}
// fall through
} catch (NoSuchMethodException e) {
// fall through
} catch (SecurityException e) {
// fall through
}
return false;
}

This still didn't work quite right; the implementation of one method called another public method of the interface, and that call was intercepted even though it wasn't a remote call. To mimic AjaxFilter, I want to able to intercept only the outermost call. I wrote a MethodInterceptor-decorator:

public class OutermostCallInterceptor
implements MethodInterceptor {
/**
* Decorates a MethodInterceptor so that only the
* outermost invocation using that interceptor will
* be intercepted and nested invocations willbe
* ignored.
*/
public static MethodInterceptor outermostCall(
MethodInterceptor interceptor) {
return new OutermostCallInterceptor(interceptor);
}

/** Ensure underlying interceptor is injected. */
@Inject void injectInterceptor(Injector injector) {
injector.injectMembers(interceptor);
}

public Object invoke(MethodInvocation invocation)
throws Throwable {
int savedCount = count.get();
count.set(savedCount + 1);
try {
if (count.get() > 1)
return invocation.proceed();
else
return interceptor.invoke(invocation);
} finally {
count.set(savedCount);
}
}

private OutermostCallInterceptor(
MethodInterceptor interceptor) {
this.interceptor = interceptor;
}

private final MethodInterceptor interceptor;

private final ThreadLocal count =
new ThreadLocal() {
@Override protected Integer initialValue() {
return 0;
}
};
}

So now my binding looks like this:

bindInterceptor(
subclassesOf(MyService.class),
declaredBy(MyService.class),
outermostCall(myInterceptor)
);

and myInterceptor is injected. It's not as compact as using bindFilter, but I can apply multiple interceptors without having to resort to FluentConfigurator. The use of subclassesOf is probably redundant, since declaredBy checks that the method is from a subclass of MyService, but I think it helps to clarify what's going on.

Saturday, September 15, 2007

Replacing AjaxFilter with MethodInterceptor

I wrote the previous posting without referring to DWR-Guice integration but in practice I extended org.directwebremoting.guice.AbstractDwrModule, not com.google.inject.AbstractModule.

For DWR-Guice users, the nice thing about injectable method interceptors is that you can use them to replace most uses of AjaxFilter, which is a good thing because the AjaxFilter support in the DWR-Guice stuff is weak (mea culpa).

I had to write some support utilities to get the right effect, but now I can do something like this:

bindInterceptor(
subclassesOf(VulnerableService.class), // class matcher
declaredBy(VulnerableService.class), // method matcher
// prevent nested interception
outermostCall(new AuthenticationInterceptor()),
outermostCall(new AuthorizationInterceptor())
);
and AuthenticationInterceptor is injected, so that it can look like
this:
class AuthenticationInterceptor 
implements MethodInterceptor {
@Inject Provider<RequestParameters> reqParmsProvider;
@Inject Provider<AuthenticationService> authSvcProvider;
public Object invoke(MethodInvocation invocation)
throws Throwable {
RequestParameters reqParms = reqParmsProvider.get();
AuthenticationService authSvc = authSvcProvider.get();
if (authSvc.authenticate(reqParms))
return invocation.proceed();
else
throw new AuthenticationException(reqParms);
}
}
The subclassesOf matcher is part of Guice. The declaredBy matcher and the outermostCall interceptor decorator are custom implementations that I'll describe in a later posting.

Friday, September 14, 2007

Injecting method interceptors in Guice 1.0

Guice 1.1 will probably have injected method interceptors, but until then those of us who need this kind of thing will have to roll our own.

[Update 2009-1-3] Guice 2 has (or will have, depending on how you view its release status) a requestInjection facility.

The way I've been doing it is similar to the way Stuart McCulloch suggested, but more automatic: I extend AbstractModule by
  1. adding a registerForInjection method that takes a varargs array of objects that should be injected and
  2. overriding bindInterceptor to call registerForInjection(interceptors) before calling the superclass implementation.
The implementation of registerForInjection adds the elements of the array argument to a set of objects to be injected. There is a private method, injectRegisteredObjects, marked with @Inject; all it does is call Injector.injectMembers on every element of this set.

To ensure that injectRegisteredObjects is called, I bind the module class to the module instance. Since I want to be able to do this for every instance of the module, I bind with a unique annotation instance each time. The private method ensureSelfInjection does this binding once only for each module instance, so I can safely call it in registerForInjection.

Here's the code:

/**
 * An extension of AbstractModule that provides
* support for member injection of instances
* constructed at bind-time; in particular,
* itself and MethodInterceptors.
*/
public abstract class ExtendedModule extends AbstractModule {

/**
* Overridden version of bindInterceptor that,
* in addition to the standard behavior,
* arranges for field and method injection of
* each MethodInterceptor in {@code interceptors}.
*/
@Override public void bindInterceptor(Matcher<? super Class<?>> classMatcher,
Matcher<? super Method> methodMatcher,
MethodInterceptor... interceptors) {
registerForInjection(interceptors);
super.bindInterceptor(classMatcher, methodMatcher, interceptors);
}

/**
* Arranges for this module and each of the given
* objects (if any) to be field and method injected
* when the Injector is created. It is safe to call
* this method more than once, and it is safe
* to call it more than once on the same object(s).
*/
protected <T> void registerForInjection(T... objects) {
ensureSelfInjection();
if (objects != null) {
for (T object : objects) {
if (object != null) toBeInjected.add(object);
}
}
}

@Inject private void injectRegisteredObjects(Injector injector) {
for (Object injectee : toBeInjected) {
injector.injectMembers(injectee);
}
}

private void ensureSelfInjection() {
if (!selfInjectionInitialized) {
bind(ExtendedModule.class)
.annotatedWith(getUniqueAnnotation())
.toInstance(this);
selfInjectionInitialized = true;
}
}

private final Set<Object> toBeInjected = new HashSet<Object>();

private boolean selfInjectionInitialized = false;

/**
* Hack to ensure unique Keys for binding different
* instances of ExtendedModule. The prefix is chosen
* to reduce the chances of a conflict with some other
* use of @Named. A better solution would be to invent
* an Annotation for just this purpose.
*/
private static Annotation getUniqueAnnotation() {
return named("ExtendedModule-" + count.incrementAndGet());
}

private static final AtomicInteger count = new AtomicInteger();
}

There's a follow-up posting on DWR-Guice applications.

Thursday, April 12, 2007

A Guice utility for binding to legacy classes

You're going along, happily Guicing your world, when you run into a snag. There's a class Legacy that you'd like to be able to bind things to, but you can't edit the source to add the @Inject annotations. It looks like this:


public class Legacy implements SomeInterface {
public Legacy(LegacyDependency dep, String str) {
...
}
public void initialize(LegacyConfig cfg) {
...
}
...
}

And you wish it looked like this:


public class Legacy implements SomeInterface {
@Inject public Legacy(LegacyDependency dep,
@MyAnnotation String str) {
...
}
@Inject public void initialize(LegacyConfig cfg) {
...
}
...
}

You're used to Guice by now, so right away you think, "No problem, I'll use a Provider!"


public class LegacyProvider
implements Provider<Legacy> {

public Legacy get() {
Legacy result = new Legacy(dep, str);
result.initialize(cfg);
return result;
}

@Inject LegacyDependency dep;
@Inject @MyAnnotation String str;
@Inject LegacyConfig cfg;
}

...

protected void configure() {
bind(SomeInterface.class)
.toProvider(LegacyProvider.class)
.in(WEB_APPLICATION_SCOPE);
}

So you've written a Provider<Legacy>, and it works. But now you have this extra class to maintain. It's not complicated, in fact it's quite trivial. It seems like something you shouldn't have had to write. You'd rather write something like this:


bind(SomeInterface.class)
.toProvider(

fromConstructor(Legacy.class,
Key.get(LegacyDependency.class),
Key.get(String.class, MyAnnotation.class))

.injecting("initialize",
Key.get(LegacyConfig.class))

)

.in(WEB_APPLICATION_SCOPE);

If this looks like something you want, check out my implementation in the DWR-Guice integration sources. The javadocs are there, too, but they aren't complete. It doesn't have anything to do with DWR, but it seems like a nice convenience to provide.

There are also several flavors of factory-method-based providers, so you don't have to write a special provider just to call a factory method.

I wrote it because even though I've been able to jettison a lot of baggage as I migrate from Spring to Guice, there are still Spring things I want to keep using, like JavaMailSender. I don't want to have to write provider implementations for each one.

Thursday, April 05, 2007

Guice support in DWR

Guice is the hot new dependency injection framework from Bob Lee and others at Google. DWR is a system for remoting Java server-side objects as JavaScript client-side objects in a way that is natural on both the client and server sides.

I'd been using DWR with Spring to wire together all the components of the Seat Yourself on-line ticket sales web application for almost a year and I was pretty happy with the combination. Then a few weeks ago, just as I was considering how to make the webapp more easily configurable, to support rapid administration and self-configuration of many customers, Josh Bloch suggested I take a look at Guice, and I suddenly realized just how fragile and unmaintainable was all that XML I had written for DWR and Spring.

Of course I could use Guice without integrating it with DWR, but one of the things that had always bothered me about DWR (and many other tools, not just DWR) was that everything -- remoted objects, data transfer objects, extension classes -- has to be concrete and public, with a public parameterless constructor, and everything works through setter injection, which makes things difficult. I want to work in terms of interfaces, with implementation classes that have final fields for injected state.

Guice looked like a way to have it all: easy remoting with type-safe (pure Java) configuration. I wrote a Guice integration package for DWR, and Joe Walker signed me on as a DWR contributor so I can help maintain it as part of the DWR distribution. The package Javadoc describes how to use it along with a simple example.

I'm still in the early stages of applying it to the Seat Yourself web sales application, but already the power of Guice has made things simpler. Each customer (where a customer is ticket-selling entity, like a theater) is associated with a domain where all their data -- seat charts, performance information, pricing information, patrons and their reservations, and holds on seats -- is maintained. When a user visits the web store to buy tickets, the link contains a domain name, e.g., "t3" for Theatre Three. Before Guice support, I had devised a complicated system using reflection and proxying to route the user request to the appropriate service object. It was so involved that I had trouble explaining it to my partners, both smart people. Not being able to explain something is a bad code smell.

With Guice-injected remoted objects, I can define a new scope, domain scope, where the details of providing the appropriate domain-specific service object are neatly encapsulated and managed by Guice. All I have to do is write something like this in my binding code:

bindRemotedAs("Tix", WebstoreService.class) // interface
.to(WebstoreServiceImpl.class) // impl
.in(DomainScopes.DOMAIN); // scope

where the interface looks like this:

public interface WebstoreService {
PerformanceAvailability getPerformanceAvailability();
...
}


Only the methods of WebstoreService are exposed to the world, even though the implementation class might have other public methods. With the Guice support, I don't need to specify which methods to expose. As usual with DWR, on the JavaScript side I can write things like:

Tix.getPerformanceAvailability({
callback : function(availability) {
notifyPerformanceAvailabilityReceived(availability)
},
exceptionHandler : ...
});


Because Guice has Spring integration, I can migrate my existing Spring-based code smoothly. Because it has JNDI integration, I can rewrite the code that manages the domain-specific configuration to use whatever LDAP back-end I like, instead of having to maintain an assortment of XML files and registry settings. We've already had problems with syntax errors in the XML configuration files, so this will save us a lot of heartache.

Guice also has support for AOP Alliance method interceptors, which means that on most of the occasions when I would feel most tempted to use AspectJ, I can stick to pure Java. Not that I have anything against AspectJ, but it's a different language and one more thing to worry about. I want to save it for the occasions when I really need it (as was the case for another submodule of our project).