Debian Codegraph @

net/sf/saxon/s9api/DocumentBuilder.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.s9api;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.event.*;
12 import net.sf.saxon.expr.EarlyEvaluationContext;
13 import net.sf.saxon.expr.JPConverter;
14 import net.sf.saxon.lib.ParseOptions;
15 import net.sf.saxon.lib.Validation;
16 import net.sf.saxon.om.*;
17 import net.sf.saxon.query.XQueryExpression;
18 import net.sf.saxon.trans.XPathException;
19 import net.sf.saxon.value.Whitespace;
20
21 import javax.xml.transform.Source;
22 import javax.xml.transform.stream.StreamSource;
23 import java.io.File;
24 import java.net.URI;
25
26 /**
27 * A document builder holds properties controlling how a Saxon document tree should be built, and
28 * provides methods to invoke the tree construction.
29 * <p>This class has no public constructor. Users should construct a DocumentBuilder
30 * by calling the factory method {@link net.sf.saxon.s9api.Processor#newDocumentBuilder()}.</p>
31 * <p>All documents used in a single Saxon query, transformation, or validation episode must
32 * be built with the same {@link net.sf.saxon.Configuration}. However, there is no requirement that they
33 * should use the same <code>DocumentBuilder</code>.</p>
34 * <p>Sharing of a <code>DocumentBuilder</code> across multiple threads is not recommended. However,
35 * in the current implementation sharing a <code>DocumentBuilder</code> (once initialized) will only
36 * cause problems if a <code>SchemaValidator</code> is used.</p>
37 *
38 * @since 9.0
39 */
40
41 public class DocumentBuilder {
42
43 private Configuration config;
44 private SchemaValidator schemaValidator;
45 private boolean dtdValidation;
46 private boolean lineNumbering;
47 private TreeModel treeModel = TreeModel.TINY_TREE;
48 private WhitespaceStrippingPolicy whitespacePolicy = WhitespaceStrippingPolicy.UNSPECIFIED;
49 private URI baseURI;
50 private XQueryExecutable projectionQuery;
51
52 /**
53 * Create a DocumentBuilder. This is a protected constructor. Users should construct a DocumentBuilder
54 * by calling the factory method {@link net.sf.saxon.s9api.Processor#newDocumentBuilder()}.
55 *
56 * @param config the Saxon configuration
57 */
58
59 protected DocumentBuilder(Configuration config) {
60 this.config = config;
61 }
62
63 /**
64 * Set the tree model to be used for documents constructed using this DocumentBuilder.
65 * By default, the TinyTree is used (irrespective of the TreeModel set in the underlying
66 * Configuration).
67 *
68 * @param model typically one of the constants {@link net.sf.saxon.om.TreeModel#TINY_TREE},
69 * {@link TreeModel#TINY_TREE_CONDENSED}, or {@link TreeModel#LINKED_TREE}. It can also be
70 * an external object model such as {@link net.sf.saxon.option.xom.XOMObjectModel}
71 * @since 9.2
72 */
73
74 public void setTreeModel(TreeModel model) {
75 this.treeModel = model;
76 }
77
78 /**
79 * Get the tree model to be used for documents constructed using this DocumentBuilder.
80 * By default, the TinyTree is used (irrespective of the TreeModel set in the underlying
81 * Configuration).
82 *
83 * @return the tree model in use: typically one of the constants {@link net.sf.saxon.om.TreeModel#TINY_TREE},
84 * {@link net.sf.saxon.om.TreeModel#TINY_TREE_CONDENSED}, or {@link TreeModel#LINKED_TREE}. However, in principle
85 * a user-defined tree model can be used.
86 * @since 9.2
87 */
88
89 public TreeModel getTreeModel() {
90 return treeModel;
91 }
92
93 /**
94 * Say whether line and column numbering and is to be enabled for documents constructed using this DocumentBuilder.
95 * This has the effect that the line and column number in the original source document is maintained in the constructed
96 * tree, for each element node (and only for elements). The line and column number in question are generally the position
97 * at which the closing "&gt;" of the element start tag appears.
98 * <p>By default, line and column numbers are not maintained.</p>
99 * <p>Errors relating to document parsing and validation will generally contain line numbers whether or not
100 * this option is set, because such errors are detected during document construction.</p>
101 * <p>Line numbering is not available for all kinds of source: for example,
102 * it is not available when loading from an existing DOM Document.</p>
103 * <p>The resulting line and column numbers are accessible to applications using the
104 * XPath extension functions saxon:line-number() and saxon:column-number() applied to a node, or using the
105 * Java methods {@link net.sf.saxon.om.NodeInfo#getLineNumber()} and
106 * {@link net.sf.saxon.om.NodeInfo#getColumnNumber()}</p>
107 * <p>Line and column numbers are maintained only for element nodes; the line number
108 * returned for any other node will be that of the most recent element. For an element node, the
109 * line and column number are generally that of the closing angle bracket at the end of the start tag
110 * (this is what a SAX parser notifies)</p>
111 *
112 * @param option true if line numbers are to be maintained, false otherwise.
113 */
114
115 public void setLineNumbering(boolean option) {
116 lineNumbering = option;
117 }
118
119 /**
120 * Ask whether line and column numbering is enabled for documents loaded using this
121 * <code>DocumentBuilder</code>.
122 * <p>By default, line and column numbering is disabled.</p>
123 * <p>Line numbering is not available for all kinds of source: in particular,
124 * it is not available when loading from an existing DOM Document.</p>
125 * <p>The resulting line and column numbers are accessible to applications using the
126 * extension functions saxon:line-number() and saxon:column-number applied to a node, or using the
127 * Java methods {@link net.sf.saxon.om.NodeInfo#getLineNumber()} and
128 * {@link net.sf.saxon.om.NodeInfo#getColumnNumber()}</p>
129 * <p>Line and column numbers are maintained only for element nodes; the line number
130 * returned for any other node will be that of the most recent element. For an element node, the
131 * line number is generally that of the closing angle bracket at the end of the start tag
132 * (this is what a SAX parser notifies)</p>
133 *
134 * @return true if line numbering is enabled
135 */
136
137 public boolean isLineNumbering() {
138 return lineNumbering;
139 }
140
141 /**
142 * Set the schemaValidator to be used. This determines whether schema validation is applied to an input
143 * document and whether type annotations in a supplied document are retained. If no schemaValidator
144 * is supplied, then schema validation does not take place.
145 * <p>This option requires the schema-aware version of the Saxon product (Saxon-EE).</p>
146 * <p>Since a <code>SchemaValidator</code> is serially reusable but not thread-safe, using this
147 * method is not appropriate when the <code>DocumentBuilder</code> is shared between threads.</p>
148 *
149 * @param validator the SchemaValidator to be used
150 */
151
152 public void setSchemaValidator(SchemaValidator validator) {
153 schemaValidator = validator;
154 }
155
156 /**
157 * Get the SchemaValidator used to validate documents loaded using this
158 * <code>DocumentBuilder</code>.
159 *
160 * @return the SchemaValidator if one has been set; otherwise null.
161 */
162 public SchemaValidator getSchemaValidator() {
163 return schemaValidator;
164 }
165
166 /**
167 * Set whether DTD validation should be applied to documents loaded using this
168 * <code>DocumentBuilder</code>.
169 * <p>By default, no DTD validation takes place.</p>
170 *
171 * @param option true if DTD validation is to be applied to the document
172 */
173
174 public void setDTDValidation(boolean option) {
175 dtdValidation = option;
176 }
177
178 /**
179 * Ask whether DTD validation is to be applied to documents loaded using this <code>DocumentBuilder</code>
180 *
181 * @return true if DTD validation is to be applied
182 */
183
184 public boolean isDTDValidation() {
185 return dtdValidation;
186 }
187
188 /**
189 * Set the whitespace stripping policy applied when loading a document
190 * using this <code>DocumentBuilder</code>.
191 *
192 * <p>(New rule in 9.8:) If DTD or schema validation is applied, the only permitted setting
193 * is {@link WhitespaceStrippingPolicy#IGNORABLE}. Any other value results
194 * in an exception from the {@link #build(File)} method</p>
195 *
196 * @param policy the policy for stripping whitespace-only text nodes from
197 * source documents
198 */
199
200 public void setWhitespaceStrippingPolicy(WhitespaceStrippingPolicy policy) {
201 whitespacePolicy = policy;
202 }
203
204 /**
205 * Get the white whitespace stripping policy applied when loading a document
206 * using this <code>DocumentBuilder</code>.
207 *
208 * @return the policy for stripping whitespace-only text nodes
209 */
210
211 public WhitespaceStrippingPolicy getWhitespaceStrippingPolicy() {
212 return whitespacePolicy;
213 }
214
215 /**
216 * Set the base URI of a document loaded using this <code>DocumentBuilder</code>.
217 * <p>This is used for resolving any relative URIs appearing
218 * within the document, for example in references to DTDs and external entities.</p>
219 * <p>This information is required when the document is loaded from a source that does not
220 * provide an intrinsic URI, notably when loading from a Stream or a DOMSource. The value is
221 * ignored when loading from a source that does have an intrinsic base URI.</p>
222 *
223 * @param uri the base URI of documents loaded using this <code>DocumentBuilder</code>. This
224 * must be an absolute URI.
225 * @throws IllegalArgumentException if the baseURI supplied is not an absolute URI
226 */
227
228 public void setBaseURI(URI uri) {
229 if (!uri.isAbsolute()) {
230 throw new IllegalArgumentException("Supplied base URI must be absolute");
231 }
232 baseURI = uri;
233 }
234
235 /**
236 * Get the base URI of documents loaded using this DocumentBuilder when no other URI is available.
237 *
238 * @return the base URI to be used, or null if no value has been set.
239 */
240
241 public URI getBaseURI() {
242 return baseURI;
243 }
244
245 /**
246 * Set a compiled query to be used for implementing document projection. The effect of using
247 * this option is that the tree constructed by the DocumentBuilder contains only those parts
248 * of the source document that are needed to answer this query. Running this query against
249 * the projected document should give the same results as against the raw document, but the
250 * projected document typically occupies significantly less memory. It is permissible to run
251 * other queries against the projected document, but unless they are carefully chosen, they
252 * will give the wrong answer, because the document being used is different from the original.
253 * <p>The query should be written to use the projected document as its initial context item.
254 * For example, if the query is <code>//ITEM[COLOR='blue')</code>, then only <code>ITEM</code>
255 * elements and their <code>COLOR</code> children will be retained in the projected document.</p>
256 * <p>This facility is only available in Saxon-EE; if the facility is not available,
257 * calling this method has no effect.</p>
258 *
259 * @param query the compiled query used to control document projection
260 * @since 9.3
261 */
262
263 public void setDocumentProjectionQuery(XQueryExecutable query) {
264 this.projectionQuery = query;
265 }
266
267 /**
268 * Get the compiled query to be used for implementing document projection.
269 *
270 * @return the query set using {@link #setDocumentProjectionQuery} if this
271 * has been called, or null otherwise
272 * @since 9.3. In 9.4 the unused and undocumented first argument is removed.
273 */
274
275 public XQueryExecutable getDocumentProjectionQuery() {
276 return this.projectionQuery;
277 }
278
279 /**
280 * Load an XML document, to create a tree representation of the document in memory.
281 *
282 * @param source A JAXP Source object identifying the source of the document. This can always be
283 * a {@link javax.xml.transform.stream.StreamSource} or a {@link javax.xml.transform.sax.SAXSource}.
284 * Some kinds of Source are consumed by this method, and should only be used once.
285 * <p>If a SAXSource is supplied, the XMLReader held within the SAXSource may be modified (by setting
286 * features and properties) to reflect the options selected on this DocumentBuilder.</p>
287 * <p>If the source is an instance of {@link net.sf.saxon.om.NodeInfo} then the subtree rooted at this node
288 * will be copied (applying schema validation if requested) to create a new tree.</p>
289 * <p>Saxon also accepts an instance of {@link javax.xml.transform.stax.StAXSource} or
290 * {@link net.sf.saxon.pull.PullSource}, which can be used to supply a document that is to be parsed
291 * using a StAX parser.</p>
292 * <p>(9.8.0.5) This method now (once again) accepts an instance of {@link net.sf.saxon.lib.AugmentedSource}.
293 * If an {@code AugmentedSource} is supplied, the properties of the {@code AugmentedSource} take
294 * precedence over any properties set on this {@code DocumentBuilder}, which in turn take precedence
295 * over properties set at the {@link Processor} or {@link Configuration} level. The concept of
296 * "taking precedence" is explained more fully at {@link ParseOptions#merge(ParseOptions)}</p>
297 *
298 * @return An <code>XdmNode</code>. This will be
299 * the document node at the root of the tree of the resulting in-memory document.
300 * @throws NullPointerException if the source argument is null
301 * @throws IllegalArgumentException if the kind of source is not recognized
302 * @throws SaxonApiException if any other failure occurs building the document, for example
303 * a parsing error
304 */
305
306 public XdmNode build(Source source) throws SaxonApiException {
307 if (source == null) {
308 throw new NullPointerException("source");
309 }
310 if (!(whitespacePolicy == WhitespaceStrippingPolicy.UNSPECIFIED
311 || whitespacePolicy == WhitespaceStrippingPolicy.IGNORABLE
312 || whitespacePolicy.ordinal() == Whitespace.XSLT)) {
313 if (dtdValidation) {
314 throw new SaxonApiException("When DTD validation is used, the whitespace stripping policy must be IGNORABLE");
315 }
316 if (schemaValidator != null) {
317 throw new SaxonApiException("When schema validation is used, the whitespace stripping policy must be IGNORABLE");
318 }
319 }
320 ParseOptions options = new ParseOptions(config.getParseOptions());
321 options.setDTDValidationMode(dtdValidation ? Validation.STRICT : Validation.STRIP);
322 if (schemaValidator != null) {
323 options.setSchemaValidationMode(schemaValidator.isLax() ? Validation.LAX : Validation.STRICT);
324 if (schemaValidator.getDocumentElementName() != null) {
325 QName qn = schemaValidator.getDocumentElementName();
326 options.setTopLevelElement(new StructuredQName(
327 qn.getPrefix(), qn.getNamespaceURI(), qn.getLocalName()));
328 }
329 if (schemaValidator.getDocumentElementType() != null) {
330 options.setTopLevelType(schemaValidator.getDocumentElementType());
331 }
332 }
333 if (treeModel != null) {
334 options.setModel(treeModel);
335 }
336 if (whitespacePolicy != null && whitespacePolicy != WhitespaceStrippingPolicy.UNSPECIFIED) {
337 int option = whitespacePolicy.ordinal();
338 if (option == Whitespace.XSLT) {
339 options.setSpaceStrippingRule(NoElementsSpaceStrippingRule.getInstance());
340 options.addFilter(whitespacePolicy.makeStripper());
341 } else {
342 options.setSpaceStrippingRule(whitespacePolicy.getSpaceStrippingRule());
343 }
344 }
345 options.setLineNumbering(lineNumbering);
346 if (source.getSystemId() == null && baseURI != null) {
347 source.setSystemId(baseURI.toString());
348 }
349 if (projectionQuery != null) {
350 XQueryExpression exp = projectionQuery.getUnderlyingCompiledQuery();
351 FilterFactory ff = config.makeDocumentProjector(exp);
352 if (ff != null) {
353 options.addFilter(ff);
354 }
355 }
356 try {
357 TreeInfo doc = config.buildDocumentTree(source, options);
358 return new XdmNode(doc.getRootNode());
359 } catch (XPathException e) {
360 throw new SaxonApiException(e);
361 }
362 }
363
364 /**
365 * Build a document from a supplied XML file
366 *
367 * @param file the supplied file
368 * @return the XdmNode representing the root of the document tree
369 * @throws SaxonApiException if any failure occurs retrieving or parsing the document
370 */
371
372 public XdmNode build(File file) throws SaxonApiException {
373 return build(new StreamSource(file));
374 }
375
376 /**
377 * Get an {@link org.xml.sax.ContentHandler} that may be used to build the document programmatically.
378 *
379 * @return a newly constructed {@link BuildingContentHandler}, which implements the <code>ContentHandler</code>
380 * interface. If schema validation has been requested for this <code>DocumentBuilder</code>, then the document constructed
381 * using the <code>ContentHandler</code> will be validated as it is written.
382 * <p>Note that the returned <code>ContentHandler</code> expects namespace scopes to be indicated
383 * explicitly by calls to {@link org.xml.sax.ContentHandler#startPrefixMapping} and
384 * {@link org.xml.sax.ContentHandler#endPrefixMapping}.</p>
385 * <p>If the stream of events supplied to the <code>ContentHandler</code> does not constitute
386 * a well formed (and namespace-well-formed) document, the effect is undefined; Saxon may fail
387 * to detect the error, and construct an unusable tree. </p>
388 * @throws SaxonApiException if any failure occurs
389 * @since 9.3
390 */
391
392 public BuildingContentHandler newBuildingContentHandler() throws SaxonApiException {
393 PipelineConfiguration pipe = config.makePipelineConfiguration();
394 Builder builder = treeModel.makeBuilder(pipe);
395 if (baseURI != null) {
396 builder.setSystemId(baseURI.toASCIIString());
397 }
398 builder.setLineNumbering(lineNumbering);
399 Receiver r = builder;
400 r = new NamespaceReducer(r);
401 r = injectValidator(r, builder);
402 return new BuildingContentHandlerImpl(r, builder);
403 }
404
405 private Receiver injectValidator(Receiver r, Builder builder) throws SaxonApiException {
406 if (schemaValidator != null) {
407 PipelineConfiguration pipe = builder.getPipelineConfiguration();
408 Receiver val = schemaValidator.getReceiver(pipe, config.obtainDefaultSerializationProperties());
409 val.setPipelineConfiguration(pipe);
410 if (val instanceof ProxyReceiver) {
411 ((ProxyReceiver) val).setUnderlyingReceiver(r);
412 }
413 return val;
414 }
415 return r;
416 }
417
418 /**
419 * Private implementation of BuildingContentHandler
420 */
421
422 private static class BuildingContentHandlerImpl extends ReceivingContentHandler
423 implements BuildingContentHandler {
424
425 private Builder builder;
426
427 public BuildingContentHandlerImpl(Receiver r, Builder b) {
428 setReceiver(r);
429 setPipelineConfiguration(r.getPipelineConfiguration());
430 this.builder = b;
431 }
432
433 public XdmNode getDocumentNode() {
434 return new XdmNode(builder.getCurrentRoot());
435 }
436 }
437
438 /**
439 * Get an {@link javax.xml.stream.XMLStreamWriter} that may be used to build the document programmatically.
440 *
441 * @return a newly constructed {@link BuildingStreamWriter}, which implements the <code>XMLStreamWriter</code>
442 * interface. If schema validation has been requested for this <code>DocumentBuilder</code>, then the document constructed
443 * using the <code>XMLStreamWriter</code> will be validated as it is written.
444 * <p>If the stream of events supplied to the <code>XMLStreamWriter</code> does not constitute
445 * a well formed (and namespace-well-formed) document, the effect is undefined; Saxon may fail
446 * to detect the error, and construct an unusable tree. </p>
447 * @throws SaxonApiException if any failure occurs
448 * @since 9.3
449 */
450
451 public BuildingStreamWriterImpl newBuildingStreamWriter() throws SaxonApiException {
452 PipelineConfiguration pipe = config.makePipelineConfiguration();
453 Builder builder = treeModel.makeBuilder(pipe);
454 builder.setLineNumbering(lineNumbering);
455 Receiver r = builder;
456 r = new NamespaceReducer(r);
457 r = injectValidator(r, builder);
458 return new BuildingStreamWriterImpl(r, builder);
459 }
460
461 /**
462 * Create a node by wrapping a recognized external node from a supported object model.
463 * <p>If the supplied object implements the {@link net.sf.saxon.om.NodeInfo} interface then it
464 * will be wrapped as an <code>XdmNode</code> without copying and without change. The <code>NodeInfo</code>
465 * must have been created using a {@link net.sf.saxon.Configuration} compatible
466 * with the one used by this <code>Processor</code> (specifically, one that uses the same
467 * {@link net.sf.saxon.om.NamePool})</p>
468 * <p>To wrap nodes from other object models, such as DOM, the support module for the external object
469 * model must be on the class path and registered with the Saxon configuration. The support modules
470 * for DOM, JDOM, DOM4J and XOM are registered automatically if they can be found on the classpath.</p>
471 * <p>It is best to avoid calling this method repeatedly to wrap different nodes in the same document.
472 * Each such wrapper conceptually creates a new XDM tree instance with its own identity. Although the
473 * memory is shared, operations that rely on node identity might not have the expected result. It is
474 * best to create a single wrapper for the document node, and then to navigate to the other nodes in the
475 * tree using S9API interfaces.</p>
476 *
477 * @param node the node in the external tree representation. Either an instance of
478 * {@link net.sf.saxon.om.NodeInfo}, or an instances of a node in an external object model.
479 * Nodes in other object models (such as DOM, JDOM, etc) are recognized only if
480 * the support module for the external object model is known to the Configuration.
481 * @return the supplied node wrapped as an XdmNode
482 * @throws IllegalArgumentException if the type of object supplied is not recognized. This may be because
483 * node was created using a different Saxon Processor, or because the required code for the external
484 * object model is not on the class path
485 */
486
487 public XdmNode wrap(Object node) throws IllegalArgumentException {
488 if (node instanceof NodeInfo) {
489 NodeInfo nodeInfo = (NodeInfo) node;
490 if (nodeInfo.getConfiguration().isCompatible(config)) {
491 return new XdmNode(nodeInfo);
492 } else {
493 throw new IllegalArgumentException("Supplied NodeInfo was created using a different Configuration");
494 }
495 } else {
496 try {
497 JPConverter converter = JPConverter.allocate(node.getClass(), null, config);
498 NodeInfo nodeInfo = (NodeInfo) converter.convert(node, new EarlyEvaluationContext(config));
499 return XdmItem.wrapItem(nodeInfo);
500 } catch (XPathException e) {
501 throw new IllegalArgumentException(e.getMessage());
502 }
503 }
504 }
505
506
507 }
508