View Javadoc

1   package org.lcsim.util.xml;
2   
3   import java.io.IOException;
4   import java.io.InputStream;
5   import java.net.URL;
6   
7   import org.xml.sax.EntityResolver;
8   import org.xml.sax.InputSource;
9   import org.xml.sax.SAXException;
10  
11  /**
12   * Resolves URIs to class resources.
13   * 
14   * For instance, the URI <code>http://www.lcsim.org/example/example.txt</code> would 
15   * be resolved to <code>org/lcsim/example/example.txt</code>.
16   *
17   * @author Jeremy McCormick
18   * @version $Id: ClasspathEntityResolver.java,v 1.5 2010/04/14 17:12:08 jeremy Exp $
19   */
20  public class ClasspathEntityResolver
21  implements EntityResolver
22  {    	
23      public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {                        
24  
25          //System.out.println("ClasspathEntityResolver.resolveEntity");
26          //System.out.println("  publicId: " + publicId);
27          //System.out.println("  systemId: " + systemId);
28  	
29      	URL url = new URL(systemId);
30      	String[] hostTokens = url.getHost().split("\\.");
31      	String org = "";
32      	for (int i = hostTokens.length - 1; i >= 0; i--) {
33      		if (!hostTokens[i].equals("www"))
34      			org += "/" + hostTokens[i];
35      	}
36      	org = org.substring(1);
37      	String fullpath = org + (new URL(systemId)).getPath();     
38      		
39      	InputStream in = this.getClass().getClassLoader().getResourceAsStream(fullpath);
40          
41          InputSource src = new InputSource(in);
42          src.setSystemId(systemId);
43          src.setPublicId(publicId);
44          
45          return src;
46      }
47  }