Debian Codegraph @

net/sf/saxon/functions/DocumentFn.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.functions;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.Controller;
12 import net.sf.saxon.event.Builder;
13 import net.sf.saxon.event.PipelineConfiguration;
14 import net.sf.saxon.event.Receiver;
15 import net.sf.saxon.event.Sender;
16 import net.sf.saxon.expr.*;
17 import net.sf.saxon.expr.parser.Location;
18 import net.sf.saxon.expr.parser.PathMap;
19 import net.sf.saxon.expr.sort.DocumentOrderIterator;
20 import net.sf.saxon.expr.sort.GlobalOrderComparer;
21 import net.sf.saxon.lib.Feature;
22 import net.sf.saxon.lib.ParseOptions;
23 import net.sf.saxon.lib.RelativeURIResolver;
24 import net.sf.saxon.lib.StandardErrorHandler;
25 import net.sf.saxon.om.*;
26 import net.sf.saxon.style.StylesheetPackage;
27 import net.sf.saxon.trans.Err;
28 import net.sf.saxon.trans.NonDelegatingURIResolver;
29 import net.sf.saxon.trans.XPathException;
30 import net.sf.saxon.trans.XsltController;
31 import net.sf.saxon.tree.tiny.TinyBuilder;
32 import net.sf.saxon.value.Cardinality;
33
34 import javax.xml.transform.Source;
35 import javax.xml.transform.SourceLocator;
36 import javax.xml.transform.TransformerException;
37 import javax.xml.transform.URIResolver;
38 import javax.xml.transform.dom.DOMSource;
39 import javax.xml.transform.stream.StreamSource;
40 import java.net.URI;
41 import java.net.URISyntaxException;
42
43
44 /**
45 * Implements the XSLT document() function
46 */
47
48 public class DocumentFn extends SystemFunction implements Callable {
49
50 private Location location;
51
52 /**
53 * Determine the static cardinality
54 */
55
56 public int getCardinality(Expression[] arguments) {
57 Expression expression = arguments[0];
58 if (Cardinality.allowsMany(expression.getCardinality())) {
59 return StaticProperty.ALLOWS_ZERO_OR_MORE;
60 } else {
61 return StaticProperty.ALLOWS_ZERO_OR_ONE;
62 }
63 // may have to revise this if the argument can be a list-valued element or attribute
64 }
65
66 /**
67 * Get the static properties of this expression (other than its type). The result is
68 * bit-signficant. These properties are used for optimizations. In general, if
69 * property bit is set, it is true, but if it is unset, the value is unknown.
70 * @param arguments the expressions supplied as arguments to the function call
71 */
72
73 public int getSpecialProperties(Expression[] arguments) {
74 return StaticProperty.ORDERED_NODESET |
75 StaticProperty.PEER_NODESET |
76 StaticProperty.NO_NODES_NEWLY_CREATED;
77 // Declaring it as a peer node-set expression avoids sorting of expressions such as
78 // document(XXX)/a/b/c
79 // The document() function might appear to be creative: but it isn't, because multiple calls
80 // with the same arguments will produce identical results.
81 }
82
83 @Override
84 public Expression makeFunctionCall(Expression... arguments) {
85 location = arguments[0].getLocation();
86 Expression expr = Doc.maybePreEvaluate(this, arguments);
87 return expr == null ? super.makeFunctionCall(arguments) : expr;
88 }
89
90 /**
91 * Evaluate the expression
92 *
93 * @param context the dynamic evaluation context
94 * @param arguments the values of the arguments, supplied as SequenceIterators
95 * @return the result of the evaluation, in the form of a SequenceIterator
96 * @throws net.sf.saxon.trans.XPathException
97 * if a dynamic error occurs during the evaluation of the expression
98 */
99 public Sequence<?> call(XPathContext context, Sequence[] arguments) throws XPathException {
100 int numArgs = getArity();
101
102 SequenceIterator hrefSequence = arguments[0].iterate();
103 String baseURI = null;
104 if (numArgs == 2) {
105 // we can trust the type checking: it must be a node
106 NodeInfo base = (NodeInfo) arguments[1].head();
107 baseURI = base.getBaseURI();
108 if (baseURI == null) {
109 throw new XPathException("The second argument to document() is a node with no base URI", "XTDE1162");
110 }
111 }
112
113 DocumentMappingFunction map = new DocumentMappingFunction(context);
114 map.baseURI = baseURI;
115 map.stylesheetURI = getStaticBaseUriString();
116 map.packageData = getRetainedStaticContext().getPackageData();
117 map.locator = location;
118
119 ItemMappingIterator iter = new ItemMappingIterator(hrefSequence, map);
120
121 //if (Cardinality.allowsMany(expression.getCardinality())) {
122 return SequenceTool.toLazySequence(new DocumentOrderIterator(iter, GlobalOrderComparer.getInstance()));
123 // this is to make sure we eliminate duplicates: two href's might be the same
124 // } else {
125 // return SequenceTool.toLazySequence(iter);
126 // }
127 }
128
129 private static class DocumentMappingFunction implements ItemMappingFunction {
130
131 public String baseURI;
132 public String stylesheetURI;
133 public Location locator;
134 public PackageData packageData;
135 public XPathContext context;
136
137 public DocumentMappingFunction(XPathContext context) {
138 this.context = context;
139 }
140
141 public Item mapItem(Item item) throws XPathException {
142 String b = baseURI;
143 if (b == null) {
144 if (item instanceof NodeInfo) {
145 b = ((NodeInfo) item).getBaseURI();
146 } else {
147 b = stylesheetURI;
148 }
149 }
150 try {
151 return makeDoc(item.getStringValue(), b, packageData, null, context, locator, false);
152 } catch (XPathException xerr) {
153 switch (xerr.getErrorCodeLocalPart()) {
154 case "XTRE1160":
155 // Invalid fragment identifier: error code changes in XSLT 3.0
156 xerr.setErrorCode("XTDE1160");
157 // Report a "recoverable error"
158 try {
159 context.getController().recoverableError(xerr);
160 } catch (XPathException err2) {
161 throw xerr;
162 }
163 // If recovering, the recovery action is to ignore the fragment identifier
164 String href = item.getStringValue();
165 int hash = href.indexOf('#');
166 href = href.substring(0, hash);
167 return makeDoc(href, b, packageData, null, context, locator, false);
168 case "XTDE1162":
169 // non-recoverable error
170 throw xerr;
171 default:
172 // Other errors
173 if (!xerr.hasBeenReported()) {
174 xerr.maybeSetLocation(locator);
175 String code = (xerr.getException() instanceof URISyntaxException) ? "FODC0005" : "FODC0002";
176 xerr.maybeSetErrorCode(code);
177 try {
178 context.getController().recoverableError(xerr);
179 } catch (XPathException err2) {
180 throw xerr;
181 }
182 } else {
183 throw xerr;
184 }
185 break;
186 }
187 return null;
188 }
189 }
190 }
191
192 /**
193 * Supporting routine to load one external document given a URI (href) and a baseURI. This is used
194 * in the normal case when a document is loaded at run-time (that is, when a Controller is available)
195 *
196 *
197 * @param href the relative URI
198 * @param baseURI the base URI
199 * @param packageData the stylesheet (or other) package in which the call appears
200 * @param options parse options to be used. May be null.
201 * @param c the dynamic XPath context
202 * @param locator used to identify the location of the instruction in event of error
203 * @param silent if true, errors should not be notified to the ErrorListener @return the root of the constructed document, or the selected element within the document
204 * if a fragment identifier was supplied
205 * @throws XPathException if reading or parsing the document fails
206 */
207
208 public static NodeInfo makeDoc(String href, String baseURI, PackageData packageData, ParseOptions options, XPathContext c, Location locator, boolean silent)
209 throws XPathException {
210
211 Configuration config = c.getConfiguration();
212
213 // If the href contains a fragment identifier, strip it out now
214 //System.err.println("Entering makeDoc " + href);
215 int hash = href.indexOf('#');
216
217 String fragmentId = null;
218 if (hash >= 0) {
219 if (hash == href.length() - 1) {
220 // # sign at end - just ignore it
221 href = href.substring(0, hash);
222 } else {
223 fragmentId = href.substring(hash + 1);
224 href = href.substring(0, hash);
225 if (!NameChecker.isValidNCName(fragmentId)) {
226 XPathException de = new XPathException("The fragment identifier " + Err.wrap(fragmentId) + " is not a valid NCName");
227 de.setErrorCode("XTRE1160");
228 de.setXPathContext(c);
229 de.setLocator(locator);
230 throw de;
231 }
232 }
233 }
234
235 Controller controller = c.getController();
236 if (controller == null) {
237 throw new XPathException("doc() function is not available in this environment");
238 }
239
240 // Resolve relative URI
241 DocumentURI documentKey = computeDocumentKey(href, baseURI, packageData, c);
242
243 // see if the document is already loaded
244
245 TreeInfo doc = config.getGlobalDocumentPool().find(documentKey);
246 if (doc != null) {
247 return doc.getRootNode();
248 }
249
250 DocumentPool pool = controller.getDocumentPool();
251
252 //noinspection SynchronizationOnLocalVariableOrMethodParameter
253 synchronized (controller) {
254 doc = pool.find(documentKey);
255 if (doc != null) {
256 return getFragment(doc, fragmentId, c, locator);
257 }
258
259 // check that the document was not written by this transformation
260
261 if (controller instanceof XsltController &&
262 !((XsltController)controller).checkUniqueOutputDestination(documentKey)) {
263 pool.markUnavailable(documentKey);
264 XPathException err = new XPathException(
265 "Cannot read a document that was written during the same transformation: " + documentKey);
266 err.setXPathContext(c);
267 err.setErrorCode("XTRE1500");
268 err.setLocator(locator);
269 throw err;
270 }
271
272 if (pool.isMarkedUnavailable(documentKey)) {
273 XPathException err = new XPathException(
274 "Document has been marked not available: " + documentKey);
275 err.setXPathContext(c);
276 err.setErrorCode("FODC0002");
277 err.setLocator(locator);
278 throw err;
279 }
280 }
281
282 try {
283
284 // Get a Source from the URIResolver
285
286 Source source = resolveURI(href, baseURI, documentKey.toString(), c);
287
288
289 //System.err.println("URI resolver returned " + source.getClass() + " " + source.getSystemId());
290 source = config.getSourceResolver().resolveSource(source, config);
291 //System.err.println("Resolved source " + source.getClass() + " " + source.getSystemId());
292
293 TreeInfo newdoc;
294 if (source instanceof NodeInfo || source instanceof DOMSource) {
295 NodeInfo startNode = controller.prepareInputTree(source);
296 newdoc = startNode.getTreeInfo();
297 } else {
298 Builder b = controller.makeBuilder();
299 b.setUseEventLocation(true);
300 if (b instanceof TinyBuilder) {
301 ((TinyBuilder) b).setStatistics(config.getTreeStatistics().SOURCE_DOCUMENT_STATISTICS);
302 }
303
304 Receiver s = b;
305 if (options == null) {
306 options = new ParseOptions(b.getPipelineConfiguration().getParseOptions());
307 if (packageData instanceof StylesheetPackage) {
308 SpaceStrippingRule rule = ((StylesheetPackage)packageData).getSpaceStrippingRule();
309 if (rule != NoElementsSpaceStrippingRule.getInstance()) {
310 options.setSpaceStrippingRule(rule);
311 }
312 }
313 options.setSchemaValidationMode(controller.getSchemaValidationMode());
314 }
315 b.getPipelineConfiguration().setParseOptions(options);
316 if (options.isLineNumbering()) {
317 b.setLineNumbering(true);
318 }
319
320 if (silent) {
321 StandardErrorHandler eh = new StandardErrorHandler(controller.getErrorListener());
322 eh.setSilent(true);
323 options.setErrorHandler(eh);
324 }
325 if (packageData instanceof StylesheetPackage && ((StylesheetPackage)packageData).isStripsTypeAnnotations()) {
326 s = config.getAnnotationStripper(s);
327 }
328
329 PathMap map = controller.getPathMapForDocumentProjection();
330 if (map != null) {
331 PathMap.PathMapRoot pathRoot = map.getRootForDocument(documentKey.toString());
332 if (pathRoot != null && !pathRoot.isReturnable() && !pathRoot.hasUnknownDependencies()) {
333 options.addFilter(config.makeDocumentProjector(pathRoot));
334 }
335 }
336 s.setPipelineConfiguration(b.getPipelineConfiguration());
337 try {
338 Sender.send(source, s, options);
339 newdoc = b.getCurrentRoot().getTreeInfo();
340 b.reset();
341 } catch (XPathException err) {
342 if (err.getErrorCodeLocalPart() == null || err.getErrorCodeLocalPart().equals("SXXP0003")) {
343 err.setErrorCode("FODC0002");
344 }
345 throw err;
346 } finally {
347 if (options.isPleaseCloseAfterUse()) {
348 ParseOptions.close(source);
349 }
350 }
351 }
352
353 // At this point, we have built the document. But it's possible that another thread
354 // has built the same document and put it in the document pool. So we do another
355 // check on the document pool, and if this has happened, we discard the document
356 // we have just built and use the one from the pool instead.
357 //noinspection SynchronizationOnLocalVariableOrMethodParameter
358 synchronized (controller) {
359 doc = pool.find(documentKey);
360 if (doc != null) {
361 return getFragment(doc, fragmentId, c, locator);
362 }
363 controller.registerDocument(newdoc, documentKey);
364 if (controller instanceof XsltController) {
365 ((XsltController) controller).addUnavailableOutputDestination(documentKey);
366 }
367 }
368 return getFragment(newdoc, fragmentId, c, locator);
369
370 } catch (TransformerException err) {
371 pool.markUnavailable(documentKey);
372 XPathException xerr = XPathException.makeXPathException(err);
373 xerr.maybeSetLocation(locator);
374 String code = (err.getException() instanceof URISyntaxException) ? "FODC0005" : "FODC0002";
375 xerr.maybeSetErrorCode(code);
376 throw xerr;
377 }
378 }
379
380 /**
381 * Call the URIResolver to resolve a URI
382 *
383 * @param href the supplied relative URI, stripped of any fragment identifier
384 * @param baseURI the base URI
385 * @param documentKey the absolute URI if already available, or null otherwise
386 * @param context the dynamic context
387 * @return a Source representing the document to be read
388 * @throws XPathException if the relative URI cannot be resolved
389 */
390
391 public static Source resolveURI(String href, String baseURI, String documentKey, XPathContext context)
392 throws XPathException {
393 URIResolver resolver = context.getURIResolver();
394 Source source;
395
396 if (baseURI == null) {
397 try {
398 URI uri = new URI(href);
399 if (!uri.isAbsolute()) {
400 throw new XPathException("Relative URI passed to document() function (" + href +
401 "); but no base URI is available", "XTDE1162");
402 }
403 } catch (URISyntaxException e) {
404 throw new XPathException("Invalid URI passed to document() function: " + href, "FODC0005");
405 }
406 }
407
408 try {
409 if (resolver instanceof RelativeURIResolver && documentKey != null) {
410 source = ((RelativeURIResolver) resolver).dereference(documentKey);
411 } else {
412 source = resolver.resolve(href, baseURI);
413 }
414 } catch (Exception ex) {
415 //ex.printStackTrace();
416 XPathException de = new XPathException("Exception thrown by URIResolver", ex);
417 if (context.getConfiguration().getBooleanProperty(Feature.TRACE_EXTERNAL_FUNCTIONS)) {
418 ex.printStackTrace();
419 }
420 throw de;
421 }
422
423 if(source instanceof StreamSource && ((StreamSource)source).getInputStream() == null && ((StreamSource)source).getReader() == null) {
424 String uri = source.getSystemId();
425 resolver = context.getController().getStandardURIResolver();
426 try {
427 source = resolver.resolve(uri, "");
428 } catch (TransformerException ex) {
429 throw XPathException.makeXPathException(ex);
430 }
431 }
432 // if a user URI resolver returns null, try the standard one
433 // (Note, the standard URI resolver never returns null)
434 if (source == null && !(resolver instanceof NonDelegatingURIResolver) ) {
435 resolver = context.getController().getStandardURIResolver();
436 try {
437 if (resolver instanceof RelativeURIResolver && documentKey != null) {
438 source = ((RelativeURIResolver) resolver).dereference(documentKey);
439 } else {
440 source = resolver.resolve(href, baseURI);
441 }
442 } catch (TransformerException ex) {
443 throw XPathException.makeXPathException(ex);
444 }
445 }
446 return source;
447
448 }
449
450 /**
451 * Compute a document key
452 */
453
454 protected static DocumentURI computeDocumentKey(String href, String baseURI, PackageData packageData, XPathContext c) throws XPathException {
455 // Resolve relative URI
456 Controller controller = c.getController();
457
458 URIResolver resolver = controller.getURIResolver();
459 if (resolver == null) {
460 resolver = controller.getStandardURIResolver();
461 }
462 return computeDocumentKey(href, baseURI, packageData, resolver, true);
463 }
464
465 /**
466 * Compute a document key (an absolute URI that can be used to see if a document is already loaded)
467 * @param href the relative URI
468 * @param baseURI the base URI
469 * @param packageData the package in which the call to doc() or document() appears (affects options
470 * such as strip-space)
471 * @param resolver the URIResolver
472 * @param strip true if the document is subject to whitespace stripping (typically a source document), false
473 * otherwise (typically a stylesheet module)
474 */
475
476 public static DocumentURI computeDocumentKey(
477 String href, String baseURI, PackageData packageData, URIResolver resolver, boolean strip) {
478 String documentKey;
479 if (resolver instanceof RelativeURIResolver) {
480 // If this is the case, the URIResolver is responsible for absolutization as well as dereferencing
481 try {
482 documentKey = ((RelativeURIResolver) resolver).makeAbsolute(href, baseURI);
483 } catch (TransformerException e) {
484 documentKey = '/' + href;
485 }
486 } else {
487 // Saxon takes charge of absolutization, leaving the user URIResolver to handle dereferencing only
488 href = ResolveURI.escapeSpaces(href);
489 if (baseURI == null) { // no base URI available
490 try {
491 // the href might be an absolute URL
492 documentKey = new URI(href).toString();
493 } catch (URISyntaxException err) {
494 // it isn't; but the URI resolver might know how to cope
495 documentKey = '/' + href;
496 }
497 } else if (href.isEmpty()) {
498 // common case in XSLT, which java.net.URI#resolve() does not handle correctly
499 documentKey = baseURI;
500 } else {
501 try {
502 URI uri = new URI(baseURI).resolve(href);
503 documentKey = uri.toString();
504 } catch (URISyntaxException | IllegalArgumentException err) {
505 documentKey = baseURI + "/../" + href;
506 }
507 }
508 }
509 if (strip && packageData instanceof StylesheetPackage &&
510 ((StylesheetPackage) packageData).getSpaceStrippingRule() != NoElementsSpaceStrippingRule.getInstance()) {
511 String name = ((StylesheetPackage) packageData).getPackageName();
512 if (name != null) {
513 documentKey = name + " " + ((StylesheetPackage) packageData).getPackageVersion() + " " + documentKey;
514 }
515 }
516 return new DocumentURI(documentKey);
517 }
518
519 /**
520 * Supporting routine to load one external document given a URI (href) and a baseURI. This is used
521 * when the document is pre-loaded at compile time.
522 *
523 * @param href the relative URI. This must not contain a fragment identifier
524 * @param baseURI the base URI
525 * @param config the Saxon configuration
526 * @param locator used to identify the location of the instruction in event of error. May be null.
527 * @return the root of the constructed document, or the selected element within the document
528 * if a fragment identifier was supplied
529 */
530
531 public static NodeInfo preLoadDoc(String href, String baseURI, Configuration config, SourceLocator locator)
532 throws XPathException {
533
534 int hash = href.indexOf('#');
535 if (hash >= 0) {
536 throw new XPathException("Fragment identifier not supported for preloaded documents");
537 }
538
539 // Resolve relative URI
540 String documentKey;
541 URIResolver resolver = config.getURIResolver();
542 if (resolver instanceof RelativeURIResolver) {
543 try {
544 documentKey = ((RelativeURIResolver) resolver).makeAbsolute(href, baseURI);
545 } catch (TransformerException e) {
546 documentKey = '/' + href;
547 baseURI = "";
548 }
549 } else {
550 if (baseURI == null) { // no base URI available
551 try {
552 // the href might be an absolute URL
553 documentKey = new URI(href).toString();
554 } catch (URISyntaxException err) {
555 // it isn't; but the URI resolver might know how to cope
556 documentKey = '/' + href;
557 baseURI = "";
558 }
559 } else if (href.isEmpty()) {
560 // common case in XSLT, which java.net.URI#resolve() does not handle correctly
561 documentKey = baseURI;
562 } else {
563 try {
564 URI uri = new URI(baseURI).resolve(href);
565 documentKey = uri.toString();
566 } catch (URISyntaxException err) {
567 documentKey = baseURI + "/../" + href;
568 } catch (IllegalArgumentException err) {
569 documentKey = baseURI + "/../" + href;
570 }
571 }
572 }
573
574 // see if the document is already loaded
575
576 TreeInfo doc = config.getGlobalDocumentPool().find(documentKey);
577 if (doc != null) {
578 return doc.getRootNode();
579 }
580
581 try {
582 // Get a Source from the URIResolver
583
584 URIResolver r = resolver;
585 Source source = null;
586 if (r != null) {
587 try {
588 source = r.resolve(href, baseURI);
589 } catch (Exception ex) {
590 XPathException de = new XPathException("Exception thrown by URIResolver", ex);
591 if (config.getBooleanProperty(Feature.TRACE_EXTERNAL_FUNCTIONS)) {
592 ex.printStackTrace();
593 }
594 de.setLocator(locator);
595 throw de;
596 }
597 }
598
599 // if a user URI resolver returns null, try the standard one
600 // (Note, the standard URI resolver never returns null)
601 if (source == null && !(r instanceof NonDelegatingURIResolver)) {
602 r = config.getSystemURIResolver();
603 source = r.resolve(href, baseURI);
604 }
605 //System.err.println("URI resolver returned " + source.getClass() + " " + source.getSystemId());
606 source = config.getSourceResolver().resolveSource(source, config);
607 //System.err.println("Resolved source " + source.getClass() + " " + source.getSystemId());
608
609 TreeInfo newdoc = config.buildDocumentTree(source);
610 config.getGlobalDocumentPool().add(newdoc, documentKey);
611 return newdoc.getRootNode();
612
613 } catch (TransformerException err) {
614 XPathException xerr = XPathException.makeXPathException(err);
615 xerr.setLocator(locator);
616 xerr.setErrorCode("FODC0002");
617 throw new XPathException(err);
618 }
619 }
620
621
622
623 /**
624 * Supporting routine to push one external document given a URI (href) and a baseURI to a given Receiver.
625 * This method cannot handle fragment identifiers
626 *
627 * @param href the relative URI
628 * @param baseURL the base URI
629 * @param c the XPath dynamic context
630 * @param locator used to identify the lcoation of the instruction in case of error
631 * @param out the destination where the document is to be sent
632 */
633
634 public static void sendDoc(String href, String baseURL, XPathContext c,
635 Location locator, Receiver out,
636 ParseOptions parseOptions) throws XPathException {
637
638 PipelineConfiguration pipe = out.getPipelineConfiguration();
639 if (pipe == null) {
640 pipe = c.getController().makePipelineConfiguration();
641 pipe.setXPathContext(c);
642 out.setPipelineConfiguration(pipe);
643 }
644
645 // Resolve relative URI
646
647 String documentKey;
648 if (baseURL == null) { // no base URI available
649 try {
650 // the href might be an absolute URL
651 documentKey = new URI(href).toString();
652 } catch (URISyntaxException err) {
653 // it isn't; but the URI resolver might know how to cope
654 documentKey = '/' + href;
655 baseURL = "";
656 }
657 } else if (href.isEmpty()) {
658 // common case in XSLT, which java.net.URI#resolve() does not handle correctly
659 documentKey = baseURL;
660 } else {
661 try {
662 URI url = new URI(baseURL).resolve(href);
663 documentKey = url.toString();
664 } catch (URISyntaxException err) {
665 documentKey = baseURL + "/../" + href;
666 } catch (IllegalArgumentException err) {
667 documentKey = baseURL + "/../" + href;
668 }
669 }
670
671 Controller controller = c.getController();
672
673 // see if the document is already loaded
674
675 TreeInfo doc = controller.getDocumentPool().find(documentKey);
676 Source source = null;
677 if (doc != null) {
678 source = doc.getRootNode();
679 } else {
680
681 try {
682 // Get a Source from the URIResolver
683
684 URIResolver r = controller.getURIResolver();
685 if (r != null) {
686 source = r.resolve(href, baseURL);
687 }
688
689 // if a user URI resolver returns null, try the standard one
690 // (Note, the standard URI resolver never returns null)
691 if (source == null) {
692 r = controller.getStandardURIResolver();
693 source = r.resolve(href, baseURL);
694 }
695 if (source instanceof NodeInfo || source instanceof DOMSource) {
696 NodeInfo startNode = controller.prepareInputTree(source);
697 source = startNode.getRoot();
698 }
699 } catch (TransformerException err) {
700 XPathException xerr = XPathException.makeXPathException(err);
701 xerr.setLocator(locator);
702 xerr.maybeSetErrorCode("FODC0005");
703 throw xerr;
704 }
705 }
706
707 if (controller.getConfiguration().isTiming()) {
708 controller.getConfiguration().getLogger().info("Streaming input document " + source.getSystemId());
709 }
710 out.setPipelineConfiguration(pipe);
711 try {
712 Sender.send(source, out, parseOptions);
713 } catch (XPathException e) {
714 e.maybeSetLocation(locator);
715 e.maybeSetErrorCode("FODC0002");
716 throw e;
717 }
718 }
719
720
721 /**
722 * Resolve the fragment identifier within a URI Reference.
723 * Only "bare names" XPointers are recognized, that is, a fragment identifier
724 * that matches an ID attribute value within the target document.
725 *
726 * @param doc the document node
727 * @param fragmentId the fragment identifier (an ID value within the document)
728 * @param context the XPath dynamic context
729 * @return the element within the supplied document that matches the
730 * given id value; or null if no such element is found.
731 */
732
733 private static NodeInfo getFragment(TreeInfo doc, String fragmentId, XPathContext context, SourceLocator locator)
734 throws XPathException {
735 // TODO: we only support one kind of fragment identifier. The rules say
736 // that the interpretation of the fragment identifier depends on media type,
737 // but we aren't getting the media type from the URIResolver.
738 if (fragmentId == null) {
739 return doc.getRootNode();
740 }
741 if (!NameChecker.isValidNCName(fragmentId)) {
742 XPathException err = new XPathException("Invalid fragment identifier in URI");
743 err.setXPathContext(context);
744 err.setErrorCode("XTRE1160");
745 err.setLocator(locator);
746 try {
747 context.getController().recoverableError(err);
748 } catch (XPathException dynamicError) {
749 throw err;
750 }
751 return doc.getRootNode();
752 }
753 return doc.selectID(fragmentId, false);
754 }
755
756 }
757