I'm investigating OSGI-ifying a large codebase, and am trying to pin
down how we're going to do resource loading.  At the bottom of this
message is a bit of code that's called many times in the codebase.  It
can take anything from a filename to a URL string to a resource path,
and turn it into a canonical URL that can be passed to anything in the
Java libraries that take a URL.

Questions:
1. I think ClassLoader.getSystemResource(spec) is going to get me into
trouble in OSGi-land.  I'm not sure the
Thread.currentThread().getContextClassLoader().getResource(spec); is any
better.  However, this is what was recommended by Sun in
http://java.sun.com/j2se/1.5.0/docs/guide/javaws/developersguide/faq.htm
l#211 when trying to make our code work in JNLP-land.  Would
AnyInputStream.class.getResource(spec) work any better?
2. Felix sees the string "C:\dir\file" as a URL with protocol "C:" (and
throws malformed URL exception since it doesn't recognize that protocol)
when it tries to to look it up as a resource.  Moving the attempt to
stat the File to before the resource calls solves that problem, but the
common case is that we store the file in a resource, so we're doing a
lot of extra file stats if I make that change.
3. I'd like to avoid OSGI-specific code in the core codebase and rely on
the classpath-mangling magic to accomplish this... but do I need to move
away from static calls to do it?  Would a singleton pattern work better
here, or are singletons, too, evil in a multi-classloader world?

        --Sam Kass

class AnyInputStream
{
//...
  public static URL makeURL(String spec)
    throws IllegalArgumentException
  {
    // For applets/webstart, we should use this thread's ClassLoader,
which
    //   will default to the system classloader if it hasn't been
overridden
    URL url =
Thread.currentThread().getContextClassLoader().getResource(spec);

    // Call back to the SystemResouce if we can't find it
    if (null == url)
      url = ClassLoader.getSystemResource(spec);

    // Try parsing it as a pre-formed URL
    if (null == url)
    {
      try
      {
        url = new URL(spec);
      }
      catch (MalformedURLException e)
      {
        url = null;
      }
    }

    // If we couldn't find it from the classloader, try the local
filesystem
    if (url == null)
    {
      try
      {
        File file = new File(spec);
        if (file.isFile())
        {
          url = file.toURL();
        }
      }
      catch (MalformedURLException e)
      {
        //throw new IllegalArgumentException("Unable to open: " +
onedoc);
      }
    }

    if (url == null)
    {
      throw new IllegalArgumentException(
        "Unable to create URL from \"" + spec + "\"");
    }

    return url;
  }
}

Reply via email to