Jez Higgins

Freelance software grandad
software created
extended or repaired


Follow me on Twitter
My code on GitHub
Talks & Presentations

Hire me
Contact

Older posts are available in the archive or through tags.

Feed

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


Tagged xml, xslt, and code


Jez Higgins

Freelance software grandad
software created
extended or repaired

Follow me on Twitter
My code on GitHub
Talks & Presentations

Hire me
Contact

Older posts are available in the archive or through tags.

Feed