View Javadoc

1   package org.tinyjee.maven.dim.utils;
2   
3   import org.xml.sax.EntityResolver;
4   import org.xml.sax.InputSource;
5   import org.xml.sax.SAXException;
6   
7   import javax.xml.transform.Source;
8   import javax.xml.transform.TransformerException;
9   import javax.xml.transform.URIResolver;
10  import java.io.IOException;
11  import java.net.URL;
12  
13  /**
14   * This is a simple DTD resolver that attempts to load DTDs from the classpath first
15   * before delegating to a web query.
16   * <p/>
17   * It is doing so by translating any HTTP systemIds to local classpath URLs using the
18   * common translation rule between HTTP-url and CP url.
19   *
20   * @author Juergen_Kellerer, 2011-09-28
21   */
22  public class XhtmlEntityResolver implements EntityResolver {
23  	public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
24  		if (systemId.startsWith("http")) {
25  			URL systemIdUrl = new URL(systemId);
26  
27  			StringBuilder newPath = new StringBuilder(systemId.length());
28  			String[] domainParts = systemIdUrl.getHost().split("\\.");
29  			for (int i = domainParts.length - 1; i > 0; i--) newPath.append('/').append(domainParts[i]);
30  			newPath.append(systemIdUrl.getPath());
31  
32  			URL resource = getClass().getResource(newPath.toString());
33  			if (resource != null) {
34  				InputSource inputSource = new InputSource(resource.toExternalForm());
35  				inputSource.setPublicId(publicId);
36  				return inputSource;
37  			}
38  		}
39  
40  		return null;
41  	}
42  }