Thursday, November 11, 2004

Custom URLs with Java

One of the cool things about the JDK is that it easily supports custom URLs. Say you had a cool object database that returned result sets as XML documents. You could refer to one with odb://user:pass@server/table_name?field1=blah&field2=borf#row_3 which would fetch the third object as an XML document from the query SELECT * FROM table_name WHERE field1 = 'blah' AND field2 = 'borf'. How would you teach Java to recognize the URL and forward it to your clever implementation code?

First, create a protocol handler:

package protocol.odb;

public class Handler extends URLStreamHandler {
    protected URLConnection openConnection(final URL u)
            throws IOException {
        return new OdbURLConnection(u);
    }
}

(Note the package name: the JDK requries that protocol handlers be in a package named the same as the URL scheme. This is how the JDK maps the URL to your handler.)

Second, create the custom connection:

public class OdbURLConnection extends URLConnection {
    /**
     * Constructs a new OdbURLConnection.
     *
     * @param url the input URL
     *
     * @see Handler#openConnection(URL)
     * @see URLConnection#URLConnection(URL)
     */
    public OdbURLConnection(final URL url) {
        super(url);
    }

    public void connect()
            throws IOException {
        if (connected) return; // noop if already connected

        // Connect to the object database here
    }

    // Override the various getters appropriate to the object database
}

For extra credit, you can make the connection bidirectional. You could then read in an XML POST and update the object database accordingly.

See the excellent RFC 2396 for information on URI syntax (and by extension their subset, URLs).

UPDATE: An even better resource, Chapter 24 by Mike Fletcher from Java Unleashed, 2nd Edition by Michael Morrison, et al entitled Developing Content and Protocol Handlers. Very excellent and blends well with A New Era for Java Protocol Handlers.

UPDATE:See Brian McCallister's excellent help.

Post a Comment