Debian Codegraph @

net/sf/saxon/event/Sender.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.event;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.Controller;
12 import net.sf.saxon.Version;
13 import net.sf.saxon.expr.number.Numberer_en;
14 import net.sf.saxon.expr.parser.ExplicitLocation;
15 import net.sf.saxon.expr.parser.Location;
16 import net.sf.saxon.lib.*;
17 import net.sf.saxon.om.*;
18 import net.sf.saxon.pull.PullProvider;
19 import net.sf.saxon.pull.PullPushCopier;
20 import net.sf.saxon.pull.PullSource;
21 import net.sf.saxon.pull.StaxBridge;
22 import net.sf.saxon.trans.SaxonErrorCode;
23 import net.sf.saxon.trans.XPathException;
24 import net.sf.saxon.type.Type;
25 import org.xml.sax.*;
26
27 import javax.xml.stream.XMLStreamReader;
28 import javax.xml.transform.Source;
29 import javax.xml.transform.sax.SAXSource;
30 import javax.xml.transform.stax.StAXSource;
31 import javax.xml.transform.stream.StreamSource;
32 import java.util.List;
33 import java.util.Map;
34
35 /**
36 * Sender is a helper class that sends events to a Receiver from any kind of Source object
37 */
38
39 public abstract class Sender {
40
41 // Converted to an abstract static class in Saxon 9.3
42
43 private static Class[] EMPTY_CLASS_ARRAY = new Class[0];
44
45 private Sender() {
46 }
47
48 /**
49 * Send the contents of a Source to a Receiver.
50 *
51 * @param source the source to be copied. Note that if the Source contains an InputStream
52 * or Reader then it will be left open, unless it is an AugmentedSource with the pleaseCloseAfterUse
53 * flag set. On the other hand, if it contains a URI that needs to be dereferenced to obtain
54 * an InputStream, then the InputStream will be closed after use.
55 * @param receiver the destination to which it is to be copied. The pipelineConfiguration
56 * of this receiver must have been initialized. The implementation sends a sequence
57 * of events to the {@code Receiver}, starting with an {@link Receiver#open()} call
58 * and ending with {@link Receiver#close()}; this will be a <b>regular event sequence</b>
59 * as defined by {@link RegularSequenceChecker}.
60 * @param options Parsing options. If source is an {@link AugmentedSource}, any options set in the
61 * {@code AugmentedSource} are used in preference to those set in options. If neither specifies
62 * a particular option, the defaults from the Configuration are used. If null is supplied,
63 * the parse options from the PipelineConfiguration of the receiver are used.
64 * @throws net.sf.saxon.trans.XPathException
65 * if any error occurs
66 */
67
68 public static void send(Source source, Receiver receiver, ParseOptions options)
69 throws XPathException {
70 PipelineConfiguration pipe = receiver.getPipelineConfiguration();
71 if (options == null) {
72 options = new ParseOptions(pipe.getParseOptions());
73 } else {
74 options = new ParseOptions(options);
75 }
76 String systemId = source.getSystemId();
77 if (source instanceof AugmentedSource) {
78 options.merge(((AugmentedSource) source).getParseOptions());
79 systemId = source.getSystemId();
80 source = ((AugmentedSource) source).getContainedSource();
81 }
82 Configuration config = pipe.getConfiguration();
83 options.applyDefaults(config);
84
85 receiver.setSystemId(systemId);
86 Receiver next = receiver;
87
88 int schemaValidation = options.getSchemaValidationMode();
89
90 List<FilterFactory> filters = options.getFilters();
91 if (filters != null) {
92 for (int i = filters.size() - 1; i >= 0; i--) {
93 Receiver filter = filters.get(i).makeFilter(next);
94 filter.setSystemId(source.getSystemId());
95 next = filter;
96 }
97 }
98
99 SpaceStrippingRule strippingRule = options.getSpaceStrippingRule();
100 if (strippingRule != null && !(strippingRule instanceof NoElementsSpaceStrippingRule)) {
101 next = strippingRule.makeStripper(next);
102 }
103 // else if (options.getStripSpace() == Whitespace.ALL) {
104 // next = new Stripper(AllElementsSpaceStrippingRule.getInstance(), next);
105 // } else if (options.getStripSpace() == Whitespace.XSLT) {
106 // Controller controller = pipe.getController();
107 // if (controller != null) {
108 // next = controller.makeStripper(next);
109 // }
110 // }
111
112 if (source instanceof TreeInfo) {
113 source = ((TreeInfo)source).getRootNode();
114 }
115
116 if (source instanceof NodeInfo) {
117 NodeInfo ns = (NodeInfo) source;
118 String baseURI = ns.getBaseURI();
119 if (schemaValidation != Validation.PRESERVE) {
120 next = config.getDocumentValidator(next, baseURI, options, null);
121 }
122
123 int kind = ns.getNodeKind();
124 if (kind != Type.DOCUMENT && kind != Type.ELEMENT) {
125 throw new IllegalArgumentException("Sender can only handle document or element nodes");
126 }
127 next.setSystemId(baseURI);
128 ExplicitLocation loc = new ExplicitLocation(systemId, -1, -1);
129 sendDocumentInfo(ns, next, loc);
130 return;
131
132 } else if (source instanceof PullSource) {
133 sendPullSource((PullSource) source, next, options);
134 return;
135
136 } else if (source instanceof EventSource) {
137 ((EventSource) source).send(next);
138 return;
139
140 } else if (source instanceof SAXSource) {
141 sendSAXSource((SAXSource) source, next, options);
142 return;
143
144 } else if (source instanceof StreamSource) {
145 StreamSource ss = (StreamSource) source;
146 // Following code allows the .NET platform to use a Pull parser
147 boolean dtdValidation = options.getDTDValidationMode() == Validation.STRICT;
148 Source ps = Version.platform.getParserSource(
149 pipe, ss, schemaValidation, dtdValidation, options.getStripSpace());
150 if (ps == ss) {
151 String url = source.getSystemId();
152 InputSource is = new InputSource(url);
153 is.setCharacterStream(ss.getReader());
154 is.setByteStream(ss.getInputStream());
155 boolean reuseParser = false;
156 XMLReader parser = options.obtainXMLReader();
157 if (parser == null) {
158 parser = config.getSourceParser();
159 if (options.getEntityResolver() != null && parser.getEntityResolver() == null) {
160 parser.setEntityResolver(options.getEntityResolver());
161 }
162 reuseParser = true;
163 }
164 //System.err.println("Using parser: " + parser.getClass().getName());
165 SAXSource sax = new SAXSource(parser, is);
166 sax.setSystemId(source.getSystemId());
167 sendSAXSource(sax, next, options);
168 if (reuseParser) {
169 config.reuseSourceParser(parser);
170 }
171
172 } else {
173 // the Platform substituted a different kind of source
174 // On .NET with a default URIResolver we can expect an AugnmentedSource wrapping a PullSource
175 send(ps, next, options);
176 }
177 return;
178 } else if (source instanceof StAXSource) {
179 XMLStreamReader reader = ((StAXSource)source).getXMLStreamReader();
180 if (reader == null) {
181 throw new XPathException("Saxon can only handle a StAXSource that wraps an XMLStreamReader");
182 }
183 StaxBridge bridge = new StaxBridge();
184 bridge.setXMLStreamReader(reader);
185 sendPullSource(new PullSource(bridge), next, options);
186 return;
187 } else {
188 next = makeValidator(next, source.getSystemId(), options);
189
190 // See if there is a registered SourceResolver than can handle it
191 Source newSource = config.getSourceResolver().resolveSource(source, config);
192 if (newSource instanceof StreamSource ||
193 newSource instanceof SAXSource ||
194 newSource instanceof NodeInfo ||
195 newSource instanceof PullSource ||
196 newSource instanceof AugmentedSource ||
197 newSource instanceof EventSource) {
198 send(newSource, next, options);
199 return;
200 }
201
202 // See if there is a registered external object model that knows about this kind of source
203 // (Note, this should pick up the platform-specific DOM model)
204
205 List externalObjectModels = config.getExternalObjectModels();
206 for (Object externalObjectModel : externalObjectModels) {
207 ExternalObjectModel model = (ExternalObjectModel) externalObjectModel;
208 boolean done = model.sendSource(source, next);
209 if (done) {
210 return;
211 }
212 }
213
214 }
215
216 throw new XPathException("A source of type " + source.getClass().getName() +
217 " is not supported in this environment");
218 }
219
220 /**
221 * Send a copy of a Saxon NodeInfo representing a document or element node to a receiver
222 *
223 * @param top the root of the subtree to be send. Despite the method name, this can be a document
224 * node or an element node
225 * @param receiver the destination to receive the events
226 * @throws XPathException if any error occurs
227 * @throws IllegalArgumentException if the node is not a document or element node
228 */
229
230
231 private static void sendDocumentInfo(NodeInfo top, Receiver receiver, Location location)
232 throws XPathException {
233 PipelineConfiguration pipe = receiver.getPipelineConfiguration();
234 NamePool targetNamePool = pipe.getConfiguration().getNamePool();
235 if (top.getConfiguration().getNamePool() != targetNamePool) {
236 // This code allows a document in one Configuration to be copied to another, changing
237 // namecodes as necessary
238 receiver = new NamePoolConverter(receiver, top.getConfiguration().getNamePool(), targetNamePool);
239 }
240 LocationCopier copier = new LocationCopier(top.getNodeKind() == Type.DOCUMENT);
241 pipe.setComponent(CopyInformee.class.getName(), copier);
242
243 // start event stream
244 receiver.open();
245
246 // copy the contents of the document
247 switch (top.getNodeKind()) {
248 case Type.DOCUMENT:
249 top.copy(receiver, CopyOptions.ALL_NAMESPACES | CopyOptions.TYPE_ANNOTATIONS, location);
250 break;
251 case Type.ELEMENT:
252 receiver.startDocument(0);
253 top.copy(receiver, CopyOptions.ALL_NAMESPACES | CopyOptions.TYPE_ANNOTATIONS, location);
254 receiver.endDocument();
255 break;
256 default:
257 throw new IllegalArgumentException("Expected document or element node");
258
259 }
260
261 // end event stream
262 receiver.close();
263 }
264
265 /**
266 * Send the contents of a SAXSource to a given Receiver
267 *
268 * @param source the SAXSource
269 * @param receiver the destination Receiver
270 * @param options options for parsing the SAXSource
271 * @throws XPathException if any failure occurs processing the Source object
272 */
273
274 private static void sendSAXSource(SAXSource source, Receiver receiver, ParseOptions options)
275 throws XPathException {
276 PipelineConfiguration pipe = receiver.getPipelineConfiguration();
277 XMLReader parser = source.getXMLReader();
278 boolean reuseParser = false;
279 final Configuration config = pipe.getConfiguration();
280 UnfailingErrorListener listener = options.getErrorListener();
281 if (listener == null) {
282 listener = pipe.getErrorListener();
283 }
284 ErrorHandler errorHandler = options.getErrorHandler();
285 if (errorHandler == null) {
286 errorHandler = new StandardErrorHandler(listener);
287 }
288 if (parser == null) {
289 parser = options.obtainXMLReader();
290 }
291 if (parser == null) {
292 SAXSource ss = new SAXSource();
293 ss.setInputSource(source.getInputSource());
294 ss.setSystemId(source.getSystemId());
295 parser = config.getSourceParser();
296 parser.setErrorHandler(errorHandler);
297 if (options.getEntityResolver() != null && parser.getEntityResolver() == null) {
298 parser.setEntityResolver(options.getEntityResolver());
299 }
300 ss.setXMLReader(parser);
301 source = ss;
302 reuseParser = true;
303 } else {
304 // user-supplied parser: ensure that it meets the namespace requirements
305 configureParser(parser);
306 if (parser.getErrorHandler() == null) {
307 parser.setErrorHandler(errorHandler);
308 }
309 }
310
311 if (!pipe.getParseOptions().isExpandAttributeDefaults()) {
312 try {
313 parser.setFeature("http://xml.org/sax/features/use-attributes2", true);
314 } catch (SAXNotRecognizedException | SAXNotSupportedException err) {
315 // ignore the failure, we did our best (Xerces gives us an Attribute2 even though it
316 // doesn't recognize this request!)
317 }
318 }
319
320 boolean dtdRecover = options.getDTDValidationMode() == Validation.LAX;
321
322 Map<String, Boolean> parserFeatures = options.getParserFeatures();
323 Map<String, Object> parserProperties = options.getParserProperties();
324
325 if (parserFeatures != null) {
326 for (Map.Entry<String, Boolean> entry : parserFeatures.entrySet()) {
327 try {
328 String name = entry.getKey();
329 boolean value = entry.getValue();
330 if (name.equals("http://apache.org/xml/features/xinclude")) {
331 boolean tryAgain = false;
332 try {
333 // This feature name is supported in Xerces 2.9.0
334 parser.setFeature(name, value);
335 } catch (SAXNotRecognizedException | SAXNotSupportedException err) {
336 tryAgain = true;
337 }
338 if (tryAgain) {
339 try {
340 // This feature name is supported in the version of Xerces bundled with JDK 1.5
341 parser.setFeature(name + "-aware", value);
342 } catch (SAXNotRecognizedException err) {
343 throw new XPathException(namedParser(parser) +
344 " does not recognize request for XInclude processing", err);
345 } catch (SAXNotSupportedException err) {
346 throw new XPathException(namedParser(parser) +
347 " does not support XInclude processing", err);
348 }
349 }
350 } else {
351 parser.setFeature(entry.getKey(), entry.getValue());
352 }
353 } catch (SAXNotRecognizedException err) {
354 // No warning if switching a feature off doesn't work: bugs 2540 and 2551
355 if (entry.getValue()) {
356 config.getLogger().warning(namedParser(parser) + " does not recognize the feature " + entry.getKey());
357 }
358 } catch (SAXNotSupportedException err) {
359 if (entry.getValue()) {
360 config.getLogger().warning(namedParser(parser) + " does not support the feature " + entry.getKey());
361 }
362 }
363 }
364 }
365
366 if (parserProperties != null) {
367 for (Map.Entry<String, Object> entry : parserProperties.entrySet()) {
368 try {
369 parser.setProperty(entry.getKey(), entry.getValue());
370 } catch (SAXNotRecognizedException err) {
371 config.getLogger().warning(namedParser(parser) + " does not recognize the property " + entry.getKey());
372 } catch (SAXNotSupportedException err) {
373 config.getLogger().warning(namedParser(parser) + " does not support the property " + entry.getKey());
374 }
375
376 }
377 }
378
379 boolean xInclude = options.isXIncludeAware();
380 if (xInclude) {
381 boolean tryAgain = false;
382 try {
383 // This feature name is supported in the version of Xerces bundled with JDK 1.5
384 parser.setFeature("http://apache.org/xml/features/xinclude-aware", true);
385 } catch (SAXNotRecognizedException | SAXNotSupportedException err) {
386 tryAgain = true;
387 }
388 if (tryAgain) {
389 try {
390 // This feature name is supported in Xerces 2.9.0
391 parser.setFeature("http://apache.org/xml/features/xinclude", true);
392 } catch (SAXNotRecognizedException err) {
393 throw new XPathException(namedParser(parser) +
394 " does not recognize request for XInclude processing", err);
395 } catch (SAXNotSupportedException err) {
396 throw new XPathException(namedParser(parser) +
397 " does not support XInclude processing", err);
398 }
399 }
400 }
401 // if (config.isTiming()) {
402 // System.err.println("Using SAX parser " + parser);
403 // }
404
405
406 receiver = makeValidator(receiver, source.getSystemId(), options);
407
408 // Reuse the previous ReceivingContentHandler if possible (it contains a useful cache of names)
409
410 ReceivingContentHandler ce;
411 final ContentHandler ch = parser.getContentHandler();
412 if (ch instanceof ReceivingContentHandler && config.isCompatible(((ReceivingContentHandler) ch).getConfiguration())) {
413 ce = (ReceivingContentHandler) ch;
414 ce.reset();
415 } else {
416 ce = new ReceivingContentHandler();
417 parser.setContentHandler(ce);
418 parser.setDTDHandler(ce);
419 try {
420 parser.setProperty("http://xml.org/sax/properties/lexical-handler", ce);
421 } catch (SAXNotSupportedException | SAXNotRecognizedException err) {
422 // this just means we won't see the comments
423 // ignore the error
424 }
425 }
426 // TracingFilter tf = new TracingFilter();
427 // tf.setUnderlyingReceiver(receiver);
428 // tf.setPipelineConfiguration(pipe);
429 // receiver = tf;
430
431 ce.setReceiver(receiver);
432 ce.setPipelineConfiguration(pipe);
433
434 try {
435 parser.parse(source.getInputSource());
436 } catch (SAXException err) {
437 Exception nested = err.getException();
438 if (nested instanceof XPathException) {
439 throw (XPathException) nested;
440 } else if (nested instanceof RuntimeException) {
441 throw (RuntimeException) nested;
442 } else {
443 // Check for a couple of conditions where the error reporting needs to be improved.
444 // (a) The built-in parser for JDK 1.6 has a nasty habit of not notifying errors to the ErrorHandler
445 // (b) Sometimes (e.g. when given an empty file), the SAXException has no location information
446 if ((errorHandler instanceof StandardErrorHandler && ((StandardErrorHandler) errorHandler).getFatalErrorCount() == 0) ||
447 (err instanceof SAXParseException && ((SAXParseException) err).getSystemId() == null && source.getSystemId() != null)) {
448 //
449 XPathException de = new XPathException("Error reported by XML parser processing " +
450 source.getSystemId() + ": " + err.getMessage(), err);
451 listener.fatalError(de);
452 de.setHasBeenReported(true);
453 throw de;
454 } else {
455 XPathException de = new XPathException(err);
456 de.setErrorCode(SaxonErrorCode.SXXP0003);
457 de.setHasBeenReported(true);
458 throw de;
459 }
460 }
461 } catch (java.io.IOException err) {
462 throw new XPathException("I/O error reported by XML parser processing " +
463 source.getSystemId() + ": " + err.getMessage(), err);
464 }
465 if (errorHandler instanceof StandardErrorHandler) {
466 int errs = ((StandardErrorHandler) errorHandler).getFatalErrorCount();
467 if (errs > 0) {
468 throw new XPathException("The XML parser reported " + errs + (errs == 1 ? " error" : " errors"));
469 }
470 errs = ((StandardErrorHandler) errorHandler).getErrorCount();
471 if (errs > 0) {
472 String message = "The XML parser reported " + new Numberer_en().toWords(errs).toLowerCase() +
473 " validation error" + (errs == 1 ? "" : "s");
474 if (dtdRecover) {
475 message += ". Processing continues, because recovery from validation errors was requested";
476 listener.warning(new XPathException(message));
477 } else {
478 throw new XPathException(message);
479 }
480 }
481 }
482 if (reuseParser) {
483 config.reuseSourceParser(parser);
484 }
485 }
486
487 private static String namedParser(XMLReader parser) {
488 return "Selected XML parser " + parser.getClass().getName();
489 }
490
491 private static Receiver makeValidator(Receiver receiver, String systemId, ParseOptions options) throws XPathException {
492 PipelineConfiguration pipe = receiver.getPipelineConfiguration();
493 Configuration config = pipe.getConfiguration();
494 int sv = options.getSchemaValidationMode();
495 if (sv != Validation.PRESERVE && sv != Validation.DEFAULT) {
496 Controller controller = pipe.getController();
497 if (controller != null && !controller.getExecutable().isSchemaAware() && sv != Validation.STRIP) {
498 throw new XPathException("Cannot use schema-validated input documents when the query/stylesheet is not schema-aware");
499 }
500 //#if EE==true
501 // Add a document validator to the pipeline
502 if (!(receiver instanceof DocumentValidator)) {
503 receiver = config.getDocumentValidator(receiver, systemId, options, null);
504 }
505 //#endif
506 }
507 return receiver;
508 }
509
510 /**
511 * Copy data from a pull source to a push destination
512 *
513 * @param source the pull source
514 * @param receiver the push destination
515 * @param options provides options for schema validation
516 * @throws XPathException if any error occurs
517 */
518
519 private static void sendPullSource(PullSource source, Receiver receiver, ParseOptions options)
520 throws XPathException {
521 PipelineConfiguration pipe = receiver.getPipelineConfiguration();
522 boolean xInclude = options.isXIncludeAware();
523 if (xInclude) {
524 throw new XPathException("XInclude processing is not supported with a pull parser");
525 }
526 receiver = makeValidator(receiver, source.getSystemId(), options);
527
528 PullProvider provider = source.getPullProvider();
529
530 provider.setPipelineConfiguration(pipe);
531 receiver.setPipelineConfiguration(pipe);
532 PullPushCopier copier = new PullPushCopier(provider, receiver);
533 try {
534 copier.copy();
535 } finally {
536 if (options.isPleaseCloseAfterUse()) {
537 provider.close();
538 }
539 }
540 }
541
542 /**
543 * Configure a SAX parser to ensure it has the correct namesapce properties set
544 *
545 * @param parser the parser to be configured
546 * @throws net.sf.saxon.trans.XPathException
547 * if the parser cannot be configured to the
548 * required settings (namespaces=true, namespace-prefixes=false). Note that the SAX
549 * specification requires every XMLReader to support these settings, so this error implies
550 * that the XMLReader is non-conformant; this is not uncommon in cases where the XMLReader
551 * is user-written.
552 */
553
554 public static void configureParser(XMLReader parser) throws XPathException {
555 try {
556 parser.setFeature("http://xml.org/sax/features/namespaces", true);
557 } catch (SAXNotSupportedException err) { // SAX2 parsers MUST support this feature!
558 throw new XPathException(
559 "The SAX2 parser " + parser.getClass().getName() +
560 " does not recognize the 'namespaces' feature", err);
561 } catch (SAXNotRecognizedException err) {
562 throw new XPathException(
563 "The SAX2 parser " + parser.getClass().getName() +
564 " does not support setting the 'namespaces' feature to true", err);
565 }
566
567 try {
568 parser.setFeature("http://xml.org/sax/features/namespace-prefixes", false);
569 } catch (SAXNotSupportedException err) { // SAX2 parsers MUST support this feature!
570 throw new XPathException(
571 "The SAX2 parser " + parser.getClass().getName() +
572 " does not recognize the 'namespace-prefixes' feature", err);
573 } catch (SAXNotRecognizedException err) {
574 throw new XPathException(
575 "The SAX2 parser " + parser.getClass().getName() +
576 " does not support setting the 'namespace-prefixes' feature to false", err);
577 }
578
579 }
580
581 // public static void main(String[] args) throws Exception {
582 // SAXParserFactory factory = new SAXParserFactoryImpl();
583 // SAXParserFactory factory = SAXParserFactory.newInstance(
584 // "com.fasterxml.aalto.sax.SAXParserFactoryImpl", new String().getClass().getClassLoader());
585 // SAXParser parser = factory.newSAXParser();
586 // XMLReader reader = parser.getXMLReader();
587 // System.err.println(reader.getClass());
588 // }
589
590 }
591