<< PreviousMarch 2005Next >>

Wednesday 02 March, 2005
#A simple javax.xml.transform.URIResolver for hooking stuff out of the class path.

Got a groovy application that uses loads of XSLT stylesheets? Want to stash those stylesheets in your Jar file? Well, go right ahead, because this simple URIResolver will take care of hooking them out when you need them.

package uk.co.jezuk.xcrete;

import javax.xml.transform.URIResolver;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.stream.StreamSource;
import java.io.InputStream;

public class ResourceResolver implements URIResolver
{
  public Source resolve(String href, String base) 
                              throws TransformerException
  {
    if(!href.startsWith("resource://"))
      return null; // will make Oracle XSLT processor explode, 
                   // even though it's correct 
    try    {
      String resource = href.substring(11); // chop off the resource://
      ClassLoader loader = getClass().getClassLoader();
      InputStream is = loader.getResourceAsStream(resource);
      return new StreamSource(is, resource);
    } // try
    catch(Exception ex)
    {
      throw new TransformerException(ex);
    } // catch
  } // resolve
} // ResourceResolver

Use it something like this -

  TransformerFactory transformerFactory_;
  transformerFactory_ = TransformerFactory.newInstance();
  transformerFactory_.setURIResolver(new ResourceResolver());
Your TransformerFactory (and any Transformers you create with it) will now be able to resolve URIs in the form resource://my/package/name/stylesheet.xsl, whether you are loading, importing or including them.

And yes, the Oracle XSLT processor will explode if you give it a null. If you are saddled with it though, don't return null, do something like this instead

  try {
    URL thing = new URL(new URL(base), href);
    return new StreamSource(thing.toString());
  } // try
  catch(MalformedURLException ex) {
    throw new TransformerException(ex);
  } // catch

anonymous said Very helpfull thanks. [added 1st Dec 2006]
anonymous said This is what I was exactly looking for [added 2nd Apr 2009]
Satya said Thanks ... this saved me a lot of time ... [added 12th Jan 2010]
anonymous said Very good!, maybe your solution help me alot! Thx! [added 24th Feb 2010]

[Add a comment]