Thursday, February 17, 2011

How can I provide context to a URLStreamHandler?

Our application defines a URL scheme whose resolution is context-sensitive: The content of the URL depends on the state of an in-progress database transaction. As such, to retrieve the content I cannot, for example, open a new database connection. However, I can't see a way to get at external context from the URLStreamHandler instance.

The documentation is a bit misleading, too: I checked at the java Protocol Handler site and it indicated (in the Implementing URLStreamHandlerFactory section) that the URL class would accept a URLStreamHandlerFactory instance, but the 1.5 JDK indicates that URL accepts only a URLStreamHandler when building a URL.

So, my question is, what is the best way to have context-sensitive URL resolution? Is there any better way than to have a ThreadLocal class variable on my URLStreamHandler implementation, that is set before the calls?

From stackoverflow
  • See URL.setURLStreamHandlerFactory

    This is a static method and:

    Sets an application's URLStreamHandlerFactory. This method can be called at most once in a given Java Virtual Machine.

  • It turns out that for our purposes, at least, the thread-local context object works best.

0 comments:

Post a Comment