1 package com.icl.saxon; 2 import org.xml.sax.*; 3 import java.util.*; 4 import java.net.*; 5 import javax.xml.parsers.SAXParserFactory ; 6 import javax.xml.transform.*; 7 import javax.xml.transform.sax.SAXSource ; 8 9 10 19 20 public class StandardURIResolver implements URIResolver { 21 22 private TransformerFactoryImpl factory = null; 23 24 protected StandardURIResolver() { 25 this(null); 26 } 27 28 public StandardURIResolver(TransformerFactoryImpl factory) { 29 this.factory = factory; 30 } 31 32 40 41 public Source resolve(String href, String base) 42 throws TransformerException { 43 44 String relativeURI = href; 45 String id = null; 46 int hash = href.indexOf('#'); 47 if (hash>=0) { 48 relativeURI = href.substring(0, hash); 49 id = href.substring(hash+1); 50 } 52 53 URL url; 54 try { 55 if (base==null) { 56 url = new URL(relativeURI); 57 } else { 59 URL baseURL = new URL(base); 61 url = (relativeURI.length()==0 ? 62 baseURL : 63 new URL(baseURL, relativeURI) 64 ); 65 } 66 } catch (java.net.MalformedURLException err) { 67 String expandedBase = tryToExpand(base); 71 if (!expandedBase.equals(base)) { return resolve(href, expandedBase); 73 } 74 throw new TransformerException("Malformed URL [" + relativeURI + "] - base [" + base + "]", err); 76 } 77 78 79 SAXSource source = new SAXSource (); 80 source.setInputSource(new InputSource(url.toString())); 81 82 if (id!=null) { 83 IDFilter filter = new IDFilter(id); 84 XMLReader parser; 85 if (factory==null) { 86 try { 87 parser = SAXParserFactory.newInstance().newSAXParser().getXMLReader(); 88 } catch (Exception err) { 89 throw new TransformerException(err); 90 } 91 } else { 92 parser = factory.getSourceParser(); 93 } 94 filter.setParent(parser); 95 source.setXMLReader(filter); 96 } 97 return source; 98 } 99 100 101 106 107 private String tryToExpand(String systemId) { 108 if (systemId==null) { 109 systemId = ""; 110 } 111 try { 112 URL u = new URL(systemId); 113 return systemId; } catch (MalformedURLException err) { 115 String dir = System.getProperty("user.dir"); 116 if (dir.startsWith("/")) { 117 dir = "file://" + dir; 118 } else { 119 dir = "file:///" + dir; 120 } 121 if (!(dir.endsWith("/") || systemId.startsWith("/"))) { 122 dir = dir + "/"; 123 } 124 String file = dir + systemId; 125 try { 126 URL u2 = new URL(file); 127 return file; } catch (MalformedURLException err2) { 130 return systemId; 132 } 133 } 134 } 135 136 } 137 138 139 140 141 142 | Popular Tags |