Simple URIReslover

I don’t mind admitting that despite it being pretty straight forward, I have been caught out by this more than once. So, in an attempt to prevent that Doh! moment again in the future…

The scenario revolves around an XSL Stylesheet that references another resource, be it an XML file for lookups, another stylesheet or whatever. Everything works a treat when processed locally, but blows up when invoked in its Java context. “Can not load requested doc:” or something similar.

This is where brain failure kicks in and I can’t think where the resource should be and waste time moving files around, changing references and trawling the web. In fact the reason the document cannot be found is simply because I haven’t told the transformer where, or more accurately how, to look for it!

The following is a simple resolver that looks on the class path for the missing file.

public class ResourceResolver implements URIResolver { 
  private static final String RESOURCE_PREFIX = "resource://"; 
  public Source resolve(String href, String base) throws TransformerException { 
    if (!href.startsWith(RESOURCE_PREFIX)) return null; 
    try { 
      if (log.isDebugEnabled()) { 
        log.debug("Resolving stylesheet resource: " + href); 
      String resource = href.substring(RESOURCE_PREFIX.length()); 
      ClassLoader loader = getClass().getClassLoader(); 
      InputStream is = loader.getResourceAsStream(resource); 
      return new StreamSource(is, resource); } 
    catch (Exception ex) { 
      throw new TransformerException(ex); 
comments powered by Disqus