Java URL Handlers

There are two ways to register your own URL scheme handler in Java, but they both kind of suck. The first is to set a system property to a list of packages, and then name subpackages and classes therein just right, the second is to register a handler factory. The handler factory approach seems great, except that you can register one, once, ever – and, oh yeah, Tomcat registers one. Given the complete brokeness of the factory registration the sane way is to align packages and class names perfectly, though this is annoying to do, so like all good programmers, I wrote a library to put a nice facade on the process: URL Scheme Registry .

Using it is about as simple as I could figure out – because URL handlers need to be global (given how URL works) there is a single static method. To register the dinner scheme handler you just do like:

UrlSchemeRegistry.register("dinner", DinnerHandler.class);

Et voila, you can now use dinner://okonomiyaki and an instance of DinnerHandler, which must implement URLStreamHandler, will be used if you retrieve the resource.

Note that you can only register a given scheme once, and your handler must have a no-arg constructor.

Under the covers the library adds a particular package to the needed system property for the package/class lookup method and creates a subclass of the class you pass it, using the super convenient CGLib. This way it can leave the handler factory setting alone (so you can use it in Tomcat or others that register the url handler factory), and don’t need to manually set system properties.

You can fetch it via Maven ( search for current version ) in two forms. The first has a normal dependency on cglib:

<dependency>
    <groupId>org.skife.url</groupId>
    <artifactId>url-scheme-registry</artifactId>
    <version>0.0.1</version>
</dependency>

The second puts cglib into a new namespace and bundles it in case there are still cases of colliding cglib versions in the same namespace out there:

<dependency>
    <groupId>org.skife.url</groupId>
    <artifactId>url-scheme-registry</artifactId>
    <version>0.0.1</version>
    <classifier>nodep</classifier>
</dependency>

Have fun!