Debian Codegraph @

net/sf/saxon/lib/StandardURIResolver.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2018 Saxonica Limited.
3 // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
4 // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0.
6 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
7
8 package net.sf.saxon.lib;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.Platform;
12 import net.sf.saxon.Version;
13 import net.sf.saxon.event.FilterFactory;
14 import net.sf.saxon.event.IDFilter;
15 import net.sf.saxon.event.ProxyReceiver;
16 import net.sf.saxon.event.Receiver;
17 import net.sf.saxon.functions.EncodeForUri;
18 import net.sf.saxon.functions.ResolveURI;
19 import net.sf.saxon.functions.URIQueryParameters;
20 import net.sf.saxon.om.SpaceStrippingRule;
21 import net.sf.saxon.resource.BinaryResource;
22 import net.sf.saxon.resource.DataURIScheme;
23 import net.sf.saxon.resource.UnparsedTextResource;
24 import net.sf.saxon.trans.Err;
25 import net.sf.saxon.trans.Maker;
26 import net.sf.saxon.trans.NonDelegatingURIResolver;
27 import net.sf.saxon.trans.XPathException;
28 import org.xml.sax.InputSource;
29 import org.xml.sax.XMLReader;
30
31 import javax.xml.transform.Source;
32 import javax.xml.transform.sax.SAXSource;
33 import java.io.ByteArrayInputStream;
34 import java.io.InputStream;
35 import java.net.URI;
36 import java.net.URISyntaxException;
37
38
39 /**
40 * This class provides the service of converting a URI into an {@link Source}.
41 * It is used to get stylesheet modules referenced by xsl:import and xsl:include,
42 * and source documents referenced by the document() function. The standard version
43 * handles anything that the java URL class will handle, plus the <code>classpath</code>
44 * URI scheme defined in the Spring framework, and the <code>data</code> URI scheme defined in
45 * RFC 2397.
46 * <p>You can write a subclass to handle other kinds of URI, for example references to data in
47 * a database, or to handle standard URIs in non-standard ways, for example by supplying
48 * authentication credentials.</p>
49 *
50 * @author Michael H. Kay
51 */
52
53 public class StandardURIResolver implements NonDelegatingURIResolver {
54
55 /*@Nullable*/ private Configuration config = null;
56 protected boolean recognizeQueryParameters = false;
57
58 /**
59 * Create a StandardURIResolver, with no reference to a Configuration.
60 * Note: it is preferable but not essential to supply a Configuration, either in the constructor
61 * or in a subsequent call of <code>setConfiguration()</code>
62 */
63
64 public StandardURIResolver() {
65 this(null);
66 }
67
68 /**
69 * Create a StandardURIResolver, with a reference to a Configuration
70 *
71 * @param config The Configuration object. May be null.
72 * This is used (if available) to get a reusable SAX Parser for a source XML document
73 */
74
75 public StandardURIResolver(/*@Nullable*/ Configuration config) {
76 this.config = config;
77 }
78
79 /**
80 * Indicate that query parameters (such as validation=strict) are to be recognized
81 *
82 * @param recognize Set to true if query parameters in the URI are to be recognized and acted upon.
83 * The default (for compatibility and interoperability reasons) is false.
84 */
85
86 public void setRecognizeQueryParameters(boolean recognize) {
87 recognizeQueryParameters = recognize;
88 }
89
90 /**
91 * Determine whether query parameters (such as validation=strict) are to be recognized
92 *
93 * @return true if query parameters are recognized and interpreted by Saxon.
94 */
95
96 public boolean queryParametersAreRecognized() {
97 return recognizeQueryParameters;
98 }
99
100 /**
101 * Get the relevant platform
102 *
103 * @return the platform
104 */
105
106 protected Platform getPlatform() {
107 return Version.platform;
108 }
109
110 /**
111 * Set the configuration
112 *
113 * @param config the configuration
114 */
115
116 public void setConfiguration(Configuration config) {
117 this.config = config;
118 }
119
120 /**
121 * Get the configuration if available
122 *
123 * @return the configuration
124 */
125
126 public Configuration getConfiguration() {
127 return config;
128 }
129
130 /**
131 * Resolve a URI
132 *
133 * @param href The relative or absolute URI. May be an empty string. May contain
134 * a fragment identifier starting with "#", which must be the value of an ID attribute
135 * in the referenced XML document.
136 * @param base The base URI that should be used. May be null if uri is absolute.
137 * @return a Source object representing an XML document
138 */
139
140 public Source resolve(String href, String base)
141 throws XPathException {
142
143 if (config != null && config.isTiming()) {
144 assert config != null;
145 config.getStandardErrorOutput().println("URIResolver.resolve href=\"" + href + "\" base=\"" + base + "\"");
146 }
147 // System.err.println("StandardURIResolver, href=" + href + ", base=" + base);
148
149 String relativeURI = href;
150 String id = null;
151
152 // Extract any fragment identifier. Note, this code is no longer used to
153 // resolve fragment identifiers in URI references passed to the document()
154 // function: the code of the document() function handles these itself.
155
156 int hash = href.indexOf('#');
157 if (hash >= 0) {
158 relativeURI = href.substring(0, hash);
159 id = href.substring(hash + 1);
160 // System.err.println("StandardURIResolver, href=" + href + ", id=" + id);
161 }
162
163 URIQueryParameters params = null;
164 URI uri;
165 URI relative;
166 try {
167 relativeURI = ResolveURI.escapeSpaces(relativeURI);
168 relative = new URI(relativeURI);
169 } catch (URISyntaxException err) {
170 throw new XPathException("Invalid relative URI " + Err.wrap(relativeURI), err);
171 }
172
173 String query = relative.getQuery();
174 if (query != null && recognizeQueryParameters) {
175 params = new URIQueryParameters(query, config);
176 int q = relativeURI.indexOf('?');
177 relativeURI = relativeURI.substring(0, q);
178 }
179
180 Source source = null;
181 if (recognizeQueryParameters && relativeURI.endsWith(".ptree")) {
182 source = getPTreeSource(relativeURI, base);
183 }
184
185 if (source == null) {
186 try {
187 uri = ResolveURI.makeAbsolute(relativeURI, base);
188 } catch (URISyntaxException err) {
189 // System.err.println("Recovering from " + err);
190 // last resort: if the base URI is null, or is itself a relative URI, we
191 // try to expand it relative to the current working directory
192 String expandedBase = ResolveURI.tryToExpand(base);
193 if (!expandedBase.equals(base)) { // prevent infinite recursion
194 return resolve(href, expandedBase);
195 }
196 //err.printStackTrace();
197 throw new XPathException("Invalid URI " + Err.wrap(relativeURI) + " - base " + Err.wrap(base), err);
198 }
199
200 // Check that any "%" sign in the URI is part of a well-formed percent-encoded UTF-8 character.
201 // Without this check, dereferencing the resulting URL can fail with arbitrary unchecked exceptions
202
203 final String uriString = uri.toString();
204 EncodeForUri.checkPercentEncoding(uriString);
205
206 // Handle a URI using the data: URI scheme
207 if ("data".equals(uri.getScheme())) {
208 Resource resource;
209 try {
210 resource = DataURIScheme.decode(uri);
211 } catch (IllegalArgumentException e) {
212 throw new XPathException("Invalid URI using 'data' scheme: " + e.getMessage());
213 }
214 if (resource instanceof BinaryResource) {
215 byte[] contents = ((BinaryResource)resource).getData();
216 InputSource is = new InputSource(new ByteArrayInputStream(contents));
217 source = new SAXSource(is);
218 source.setSystemId(uriString);
219 } else {
220 assert resource instanceof UnparsedTextResource;
221 InputStream is = ((UnparsedTextResource)resource).getInputStream();
222 source = new SAXSource(new InputSource(is));
223 source.setSystemId(uriString);
224 }
225 } else {
226 source = new SAXSource();
227 setSAXInputSource((SAXSource) source, uriString);
228 }
229
230 if (params != null) {
231 Maker<XMLReader> parser = params.getXMLReaderMaker();
232 if (parser != null) {
233 ((SAXSource) source).setXMLReader(parser.make());
234 }
235 }
236
237 if (((SAXSource) source).getXMLReader() == null) {
238 if (config == null) {
239 try {
240 ((SAXSource) source).setXMLReader(Version.platform.loadParser());
241 } catch (Exception err) {
242 throw new XPathException(err);
243 }
244 } else {
245 //((SAXSource)source).setXMLReader(config.getSourceParser());
246 // Leave the Sender to allocate an XMLReader, so that it can be returned to the pool after use
247 }
248 }
249 }
250
251 if (params != null) {
252 SpaceStrippingRule stripSpace = params.getSpaceStrippingRule();
253 source = AugmentedSource.makeAugmentedSource(source);
254 ((AugmentedSource) source).getParseOptions().setSpaceStrippingRule(stripSpace);
255 }
256
257 if (id != null) {
258 final String idFinal = id;
259 FilterFactory factory = new FilterFactory() {
260 public ProxyReceiver makeFilter(Receiver next) {
261 return new IDFilter(next, idFinal);
262 }
263 };
264 source = AugmentedSource.makeAugmentedSource(source);
265 ((AugmentedSource) source).addFilter(factory);
266 }
267
268 if (params != null) {
269 Integer validation = params.getValidationMode();
270 if (validation != null) {
271 source = AugmentedSource.makeAugmentedSource(source);
272 ((AugmentedSource) source).setSchemaValidationMode(validation);
273 }
274 }
275
276 if (params != null) {
277 Boolean xinclude = params.getXInclude();
278 if (xinclude != null) {
279 source = AugmentedSource.makeAugmentedSource(source);
280 ((AugmentedSource) source).setXIncludeAware(xinclude.booleanValue());
281 }
282 }
283
284 return source;
285 }
286
287 /**
288 * Handle a PTree source file (Saxon-EE only)
289 *
290 * @param href the relative URI
291 * @param base the base URI
292 * @return the new Source object
293 */
294
295 protected Source getPTreeSource(String href, String base) throws XPathException {
296 throw new XPathException("PTree files can only be read using a Saxon-EE configuration");
297 }
298
299 /**
300 * Set the InputSource part of the returned SAXSource. This is done in a separate
301 * method to allow subclassing. The default implementation checks for the (Spring-defined)
302 * "classpath" URI scheme, and if this is in use, it attempts to locate the resource on the
303 * classpath and set the supplied SAXSource to use the corresponding input stream.
304 * In other cases it simply places the URI in the
305 * InputSource, allowing the XML parser to take responsibility for the dereferencing.
306 * A subclass may choose to dereference the URI at this point and place an InputStream
307 * in the SAXSource.
308 *
309 * @param source the SAXSource being initialized
310 * @param uriString the absolute (resolved) URI to be used
311 */
312
313 protected void setSAXInputSource(SAXSource source, String uriString) {
314 if (uriString.startsWith("classpath:") && uriString.length() > 10) {
315 InputStream is = getConfiguration().getDynamicLoader().getResourceAsStream(uriString.substring(10));
316 if (is != null) {
317 source.setInputSource(new InputSource(is));
318 source.setSystemId(uriString);
319 return;
320 }
321 }
322 source.setInputSource(new InputSource(uriString));
323 source.setSystemId(uriString);
324 }
325
326 }
327