Debian Codegraph @

net/sf/saxon/lib/StandardCollectionURIResolver.java

raw symbols SCIP
1 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
2 // Copyright (c) 2014 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.Controller;
11 import net.sf.saxon.event.Builder;
12 import net.sf.saxon.event.PipelineConfiguration;
13 import net.sf.saxon.event.Receiver;
14 import net.sf.saxon.event.Sender;
15 import net.sf.saxon.expr.*;
16 import net.sf.saxon.functions.DocumentFn;
17 import net.sf.saxon.functions.ResolveURI;
18 import net.sf.saxon.functions.URIQueryParameters;
19 import net.sf.saxon.functions.UnparsedTextFunction;
20 import net.sf.saxon.om.*;
21 import net.sf.saxon.pattern.NodeKindTest;
22 import net.sf.saxon.resource.AbstractResourceCollection;
23 import net.sf.saxon.resource.StandardCollectionFinder;
24 import net.sf.saxon.trans.Err;
25 import net.sf.saxon.trans.Maker;
26 import net.sf.saxon.trans.XPathException;
27 import net.sf.saxon.tree.iter.ArrayIterator;
28 import net.sf.saxon.tree.iter.AxisIterator;
29 import net.sf.saxon.tree.iter.SingletonIterator;
30 import net.sf.saxon.tree.tiny.TinyBuilder;
31 import net.sf.saxon.value.AnyURIValue;
32 import net.sf.saxon.value.ExternalObject;
33 import net.sf.saxon.value.ObjectValue;
34 import net.sf.saxon.value.TextFragmentValue;
35 import org.xml.sax.XMLReader;
36
37 import javax.xml.transform.Source;
38 import javax.xml.transform.stream.StreamSource;
39 import java.io.*;
40 import java.net.URI;
41 import java.net.URISyntaxException;
42 import java.util.function.IntPredicate;
43
44 /**
45 * This class implements the default collection URI Resolver.
46 * <p>
47 * This supports two implementations of collections. If the URI supplied uses the "file:/" scheme, and the
48 * file that is referenced is a directory, then the collection is the set of files in that directory. Query parameters
49 * may be included in the URI:
50 * <ul>
51 * <li><p>recurse=yes|no controls whether the directory is scanned recursively; </p></li>
52 * <li><p>strip-space=yes|no determines whether whitespace text nodes are stripped from the selected documents; </p></li>
53 * <li><p>validation=strict|lax|preserve|strip determines whether schema validation is applied;</p></li>
54 * <li><p>select=pattern determines which files in the directory are selected.</p></li>
55 * <li><p>on-error=fail|warn|ignore determines the action taken if processing of a file fails</p></li>
56 * <li><p>parser=qualified.class.name selects the parser (XMLReader) to be used to read the files</p></li>
57 * </ul>
58 * <p>
59 * Otherwise, the resolver attempts to dereference the URI to obtain a catalog file. This is an XML file
60 * containing a list of documents, in the format: </p>
61 * <pre>
62 * &lt;collection&gt;
63 * &lt;doc href="doc1.xml"/&gt;
64 * &lt;doc href="doc2.xml"/&gt;
65 * &lt;/collection&gt;
66 * </pre>
67 */
68
69 public class StandardCollectionURIResolver implements CollectionURIResolver {
70
71 /**
72 * Resolve a URI.
73 *
74 * @param href The relative URI of the collection. This corresponds to the
75 * argument supplied to the collection() function. If the collection() function
76 * was called with no arguments (to get the "default collection") this argument
77 * will be null.
78 * @param base The base URI that should be used. This is the base URI of the
79 * static context in which the call to collection() was made, typically the URI
80 * of the stylesheet or query module
81 * @return an Iterator over the documents in the collection. The items returned
82 * by this iterator must be instances either of xs:anyURI, or of node() (specifically,
83 * {@link net.sf.saxon.om.NodeInfo}.). If xs:anyURI values are returned, the corresponding
84 * document will be retrieved as if by a call to the doc() function: this means that
85 * the system first checks to see if the document is already loaded, and if not, calls
86 * the registered URIResolver to dereference the URI. This is the recommended approach
87 * to ensure that the resulting collection is stable: however, it has the consequence
88 * that the documents will by default remain in memory for the duration of the query
89 * or transformation.
90 */
91
92 public SequenceIterator<?> resolve(
93 String href, String base, XPathContext context) throws XPathException {
94
95 StandardCollectionFinder.checkNotNull(href, context);
96
97 URIQueryParameters params = null;
98 URI relativeURI;
99 try {
100 relativeURI = new URI(ResolveURI.escapeSpaces(href));
101 String query = relativeURI.getQuery();
102 if (query != null) {
103 params = new URIQueryParameters(query, context.getConfiguration());
104 int q = href.indexOf('?');
105 href = ResolveURI.escapeSpaces(href.substring(0, q));
106 relativeURI = new URI(href);
107 }
108
109 } catch (URISyntaxException e) {
110 XPathException err = new XPathException("Invalid relative URI " + Err.wrap(href, Err.VALUE) + " passed to collection() function");
111 err.setErrorCode("FODC0004");
112 err.setXPathContext(context);
113 throw err;
114 }
115
116 URI resolvedURI = makeAbsoluteURI(href, base, context, relativeURI);
117
118 if ("file".equals(resolvedURI.getScheme())) {
119 File file = new File(resolvedURI);
120 checkFileExists(file, resolvedURI, context);
121 if (file.isDirectory()) {
122 return directoryContents(file, params, context);
123 }
124 }
125 return catalogContents(href, base, resolvedURI.toString(), context);
126
127 }
128
129 public static void checkFileExists(File file, URI resolvedURI, XPathContext context) throws XPathException {
130 if (!file.exists()) {
131 XPathException err = new XPathException("The file or directory " + resolvedURI + " does not exist");
132 err.setErrorCode("FODC0002");
133 err.setXPathContext(context);
134 throw err;
135 }
136 }
137
138 protected URI makeAbsoluteURI(String href, String base, XPathContext context, URI relativeURI) throws XPathException {
139 URI resolvedURI;
140 if (!relativeURI.isAbsolute()) {
141 if (base == null) {
142 base = ResolveURI.tryToExpand(base);
143 }
144 try {
145 resolvedURI = ResolveURI.makeAbsolute(href, base);
146 } catch (URISyntaxException e) {
147 XPathException err = new XPathException("Cannot resolve relative URI: " + e.getMessage());
148 err.setErrorCode("FODC0004");
149 err.setXPathContext(context);
150 throw err;
151 }
152 } else {
153 resolvedURI = relativeURI;
154 }
155 return resolvedURI;
156 }
157
158 /**
159 * Return the contents of a collection that maps to a directory in filestore
160 *
161 * @param directory the directory to be processed
162 * @param params parameters indicating whether to process recursively, what to do on
163 * errors, and which files to select
164 * @param context the dynamic XPath evaluation context
165 * @return an iterator over the documents in the collection
166 */
167
168 protected SequenceIterator<?> directoryContents(File directory, URIQueryParameters params, XPathContext context) {
169
170 FilenameFilter filter = null;
171
172 if (params != null) {
173 FilenameFilter f = params.getFilenameFilter();
174 if (f != null) {
175 filter = f;
176 }
177 }
178
179 File[] files;
180 if (filter == null) {
181 files = directory.listFiles();
182 } else {
183 files = directory.listFiles(filter);
184 }
185
186 ObjectValue<File>[] fileValues = new ObjectValue[files.length];
187 for (int f = 0; f < files.length; f++) {
188 fileValues[f] = new ObjectValue<>(files[f]);
189 }
190
191 // If the URI requested suppression of errors, or that errors should be treated
192 // as warnings, we set up a special ErrorListener to achieve this
193
194 int onError = URIQueryParameters.ON_ERROR_FAIL;
195 if (params != null && params.getOnError() != null) {
196 onError = params.getOnError();
197 }
198 final Controller controller = context.getController();
199 final PipelineConfiguration oldPipe = context.getConfiguration().makePipelineConfiguration();
200 oldPipe.setController(context.getController());
201 final PipelineConfiguration newPipe = new PipelineConfiguration(oldPipe);
202 final UnfailingErrorListener oldErrorListener =
203 controller == null ? new StandardErrorListener() : controller.getErrorListener();
204 AbstractResourceCollection.setupErrorHandlingForCollection(
205 newPipe.getParseOptions(), onError, oldErrorListener);
206
207 FileExpander expander = new FileExpander(params, newPipe);
208 SequenceIterator<?> base = new ArrayIterator<>(fileValues);
209 return new MappingIterator(base, expander);
210 }
211
212 /**
213 * Return a collection defined as a list of URIs in a catalog file
214 *
215 * @param href the relative URI as supplied
216 * @param baseURI the base URI
217 * @param absURI the absolute URI of the catalog file
218 * @param context the dynamic evaluation context
219 * @return an iterator over the documents in the collection
220 * @throws XPathException if any failures occur
221 */
222
223 protected SequenceIterator<?> catalogContents(String href, String baseURI, String absURI, final XPathContext context)
224 throws XPathException {
225
226 boolean stable = true;
227 Source source = DocumentFn.resolveURI(href, baseURI, null, context);
228 ParseOptions options = new ParseOptions();
229 options.setSchemaValidationMode(Validation.SKIP);
230 DocumentInfo catalog = context.getConfiguration().buildDocument(source, options);
231 if (catalog == null) {
232 // we failed to read the catalogue
233 XPathException err = new XPathException("Failed to load collection catalog " + absURI);
234 err.setErrorCode("FODC0004");
235 err.setXPathContext(context);
236 throw err;
237 }
238
239 // Now return an iterator over the documents that it refers to
240
241 AxisIterator iter =
242 catalog.iterateAxis(AxisInfo.CHILD, NodeKindTest.ELEMENT);
243 NodeInfo top = iter.next();
244 if (top == null || !("collection".equals(top.getLocalPart()) && top.getURI().isEmpty())) {
245 String message;
246 if (top == null) {
247 message = "No outermost element found in collection catalog";
248 } else if (!top.getURI().isEmpty()) {
249 message = "Collection catalog should not use a namespace";
250 } else {
251 message = "Collection catalog outermost element should be <catalog> (found " + top.getLocalPart() + ">)";
252 }
253 XPathException err = new XPathException(message);
254 err.setErrorCode("FODC0004");
255 err.setXPathContext(context);
256 throw err;
257 }
258 iter.close();
259
260 String stableAtt = top.getAttributeValue("", "stable");
261 if (stableAtt != null) {
262 if ("true".equals(stableAtt)) {
263 stable = true;
264 } else if ("false".equals(stableAtt)) {
265 stable = false;
266 } else {
267 XPathException err = new XPathException(
268 "The 'stable' attribute of element <collection> must be true or false");
269 err.setErrorCode("FODC0004");
270 err.setXPathContext(context);
271 throw err;
272 }
273 }
274
275 final boolean finalStable = stable;
276 AxisIterator documents =
277 top.iterateAxis(AxisInfo.CHILD, NodeKindTest.ELEMENT);
278
279 ItemMappingFunction<Item<?>, Item<?>> catalogueMapper = item -> {
280 NodeInfo node = (NodeInfo)item;
281 if (!("doc".equals(node.getLocalPart()) && node.getURI().isEmpty())) {
282 XPathException err = new XPathException("children of <collection> element must be <doc> elements");
283 err.setErrorCode("FODC0004");
284 err.setXPathContext(context);
285 throw err;
286 }
287 String href1 = node.getAttributeValue("", "href");
288 if (href1 == null) {
289 XPathException err = new XPathException("\"<doc> element in catalog has no @href attribute\"");
290 err.setErrorCode("FODC0004");
291 err.setXPathContext(context);
292 throw err;
293 }
294 String uri;
295 try {
296 uri = new URI(node.getBaseURI()).resolve(href1).toString();
297 } catch (URISyntaxException e) {
298 XPathException err = new XPathException("Invalid base URI or href URI in collection catalog: ("
299 + node.getBaseURI() + ", " + href1 + ")");
300 err.setErrorCode("FODC0004");
301 err.setXPathContext(context);
302 throw err;
303 }
304 if (finalStable) {
305 return new AnyURIValue(uri);
306 } else {
307 // stability not required, bypass the document pool and URI resolver
308 return context.getConfiguration().buildDocument(new StreamSource(uri));
309 }
310 };
311
312 return new ItemMappingIterator(documents, catalogueMapper);
313 }
314
315 /**
316 * Mapping function to process the files in a directory. This maps a sequence of external
317 * objects representing files to a sequence of DocumentInfo nodes representing the parsed
318 * contents of those files.
319 */
320
321
322 protected static class FileExpander implements MappingFunction<ExternalObject<File>, Item<?>> {
323
324 private URIQueryParameters params;
325 boolean recurse = false;
326 SpaceStrippingRule strippingRule = null;
327 int validation = Validation.STRIP;
328 Boolean xinclude = null;
329 boolean unparsed;
330 Maker<XMLReader> parserMaker = null;
331 int onError = URIQueryParameters.ON_ERROR_FAIL;
332 FilenameFilter filter = null;
333 PipelineConfiguration pipe;
334
335 public FileExpander(URIQueryParameters params, PipelineConfiguration pipe) {
336 this.params = params;
337 this.pipe = pipe;
338 if (params != null) {
339 FilenameFilter f = params.getFilenameFilter();
340 if (f != null) {
341 filter = f;
342 }
343 Boolean r = params.getRecurse();
344 if (r != null) {
345 recurse = r;
346 }
347 Integer v = params.getValidationMode();
348 if (v != null) {
349 validation = v;
350 }
351 xinclude = params.getXInclude();
352 strippingRule = params.getSpaceStrippingRule();
353 unparsed = params.isUnparsed();
354 Integer e = params.getOnError();
355 if (e != null) {
356 onError = e;
357 }
358 Maker<XMLReader> p = params.getXMLReaderMaker();
359 if (p != null) {
360 parserMaker = p;
361 }
362 }
363
364 }
365
366 /**
367 * Map one item to a sequence.
368 *
369 * @param item The item to be mapped.
370 * If context is supplied, this must be the same as context.currentItem().
371 * @return either (a) a SequenceIterator over the sequence of items that the supplied input
372 * item maps to, or (b) an Item if it maps to a single item, or (c) null if it maps to an empty
373 * sequence.
374 */
375
376 public SequenceIterator<?> map(ExternalObject<File> item) throws XPathException {
377 File file = item.getObject();
378 if (file.isDirectory()) {
379 if (recurse) {
380 File[] files;
381 if (filter == null) {
382 files = file.listFiles();
383 } else {
384 files = file.listFiles(filter);
385 }
386
387 ObjectValue<File>[] fileValues = new ObjectValue[files.length];
388 for (int f = 0; f < files.length; f++) {
389 fileValues[f] = new ObjectValue<>(files[f]);
390 }
391
392 FileExpander expander = new FileExpander(params, pipe);
393 return new MappingIterator<>(new ArrayIterator<>(fileValues), expander);
394 } else {
395 return null;
396 }
397 } else if (unparsed) {
398 try {
399 Reader reader = new FileReader(file);
400 IntPredicate checker = pipe.getConfiguration().getValidCharacterChecker();
401 CharSequence content = UnparsedTextFunction.readFile(checker, reader);
402 String uri = file.toURI().toString();
403 TextFragmentValue doc = new TextFragmentValue(pipe.getConfiguration(), content, uri);
404 doc.setSystemId(file.toURI().toString());
405 return SingletonIterator.makeIterator(doc);
406 } catch (IOException err) {
407 if (onError == URIQueryParameters.ON_ERROR_IGNORE) {
408 return null;
409 } else if (onError == URIQueryParameters.ON_ERROR_WARNING) {
410 XPathException warn = new XPathException("Failed to read " + file.getPath(), err);
411 pipe.getErrorListener().warning(warn);
412 XPathException supp = new XPathException("The document will be excluded from the collection");
413 pipe.getErrorListener().warning(supp);
414 return null;
415 } else {
416 throw new XPathException("Failed to read " + file.getPath(), err);
417 }
418 }
419 } else {
420 try {
421 String escaped = file.toURI().toASCIIString();
422 Source source = new StreamSource(escaped);
423 ParseOptions options = new ParseOptions(pipe.getParseOptions()); // bug 2273
424 if (validation != Validation.STRIP && validation != Validation.PRESERVE) {
425 options.setSchemaValidationMode(validation);
426 }
427 if (xinclude != null) {
428 options.setXIncludeAware(xinclude);
429 }
430 if (parserMaker != null) {
431 options.setXMLReaderMaker(parserMaker);
432 }
433
434 if (params != null) {
435 SpaceStrippingRule stripSpace = params.getSpaceStrippingRule();
436 if (stripSpace != null) {
437 options.setSpaceStrippingRule(stripSpace);
438 }
439 }
440 if (pipe.getController() != null) {
441 Builder b = pipe.getController().makeBuilder();
442 if (b instanceof TinyBuilder) {
443 ((TinyBuilder) b).setStatistics(pipe.getConfiguration().getTreeStatistics().SOURCE_DOCUMENT_STATISTICS);
444 }
445 Receiver s = b;
446 if (pipe.getController().isStylesheetStrippingTypeAnnotations()) {
447 s = pipe.getConfiguration().getAnnotationStripper(s);
448 }
449 s.setPipelineConfiguration(pipe);
450 Sender.send(source, s, options);
451 NodeInfo node = b.getCurrentRoot();
452 b.reset();
453 return SingletonIterator.makeIterator(node);
454 } else {
455 DocumentInfo doc = pipe.getConfiguration().buildDocument(source, options);
456 return SingletonIterator.makeIterator(doc);
457 }
458 } catch (XPathException err) {
459 if (onError == URIQueryParameters.ON_ERROR_IGNORE) {
460 return null;
461 } else if (onError == URIQueryParameters.ON_ERROR_WARNING) {
462 if (!err.hasBeenReported()) {
463 pipe.getErrorListener().warning(err);
464 XPathException supp = new XPathException("The document will be excluded from the collection");
465 supp.setLocator(err.getLocator());
466 pipe.getErrorListener().warning(supp);
467 }
468 return null;
469 } else {
470 throw err;
471 }
472 }
473 }
474 }
475 }
476
477
478 }
479