Debian Codegraph @

net/sf/saxon/query/QueryResult.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.query;
9
10 import net.sf.saxon.Configuration;
11 import net.sf.saxon.event.*;
12 import net.sf.saxon.expr.parser.ExplicitLocation;
13 import net.sf.saxon.lib.SerializerFactory;
14 import net.sf.saxon.om.CopyOptions;
15 import net.sf.saxon.om.DocumentInfo;
16 import net.sf.saxon.om.NodeInfo;
17 import net.sf.saxon.om.SequenceIterator;
18 import net.sf.saxon.serialize.SerializationProperties;
19 import net.sf.saxon.trans.XPathException;
20 import net.sf.saxon.tree.iter.SingletonIterator;
21 import net.sf.saxon.tree.tiny.TinyBuilder;
22 import net.sf.saxon.type.Type;
23
24 import javax.xml.transform.Result;
25 import javax.xml.transform.stream.StreamResult;
26 import java.io.*;
27 import java.net.URI;
28 import java.net.URISyntaxException;
29 import java.util.Properties;
30
31 /**
32 * This utility class takes the result sequence produced by a query, and wraps it as
33 * an XML document. The class is never instantiated.
34 */
35 public class QueryResult {
36
37 /*@NotNull*/ public static String RESULT_NS = "http://saxon.sf.net/xquery-results";
38
39 private QueryResult() {
40 }
41
42 /**
43 * Convenience method to serialize a node using default serialization options, placing
44 * the result in a string.
45 *
46 * @param nodeInfo the node to be serialized. This must not be an attribute or namespace node.
47 * @return the serialization of the node
48 * @throws net.sf.saxon.trans.XPathException
49 * if a serialization error occurs
50 * @since 9.0
51 */
52
53 public static String serialize(/*@NotNull*/ NodeInfo nodeInfo) throws XPathException {
54 StringWriter sw = new StringWriter();
55 Properties props = new Properties();
56 props.setProperty("method", "xml");
57 props.setProperty("indent", "yes");
58 props.setProperty("omit-xml-declaration", "yes");
59 serialize(nodeInfo, new StreamResult(sw), props);
60 return sw.toString();
61 }
62
63 /**
64 * Take the results of a query (or any other SequenceIterator) and create
65 * an XML document containing copies of all items in the sequence, each item wrapped in a containing
66 * element that identifies its type
67 *
68 * @param iterator The values to be wrapped
69 * @param config The Saxon configuration used to evaluate the query
70 * @return the document containing the wrapped results
71 * @throws XPathException if any failure occurs
72 * @since 8.8
73 */
74
75 /*@Nullable*/
76 public static DocumentInfo wrap(SequenceIterator iterator, /*@NotNull*/ Configuration config) throws XPathException {
77 PipelineConfiguration pipe = config.makePipelineConfiguration();
78 TinyBuilder builder = new TinyBuilder(pipe);
79 builder.setStatistics(config.getTreeStatistics().SOURCE_DOCUMENT_STATISTICS);
80 NamespaceReducer reducer = new NamespaceReducer(builder);
81 ComplexContentOutputter outputter = new ComplexContentOutputter(reducer);
82 sendWrappedSequence(iterator, outputter);
83 return new DocumentInfo(builder.getCurrentRoot());
84 }
85
86 /**
87 * Take a sequence supplied in the form of an iterator and generate a wrapped represention of the
88 * items in the sequence, the wrapped representation being a sequence of events sent to a supplied
89 * Receiver, in which each item is wrapped in a containing element that identifies its type
90 *
91 * @param iterator the input sequence
92 * @param destination the Receiver to accept the wrapped output
93 * @throws net.sf.saxon.trans.XPathException
94 * if a failure occurs processing the input iterator
95 * @since 8.8
96 */
97
98 public static void sendWrappedSequence(SequenceIterator iterator, Receiver destination) throws XPathException {
99 SerializerFactory sf = destination.getPipelineConfiguration().getConfiguration().getSerializerFactory();
100 SequenceCopier.copySequence(iterator, sf.newSequenceWrapper(destination));
101 }
102
103 /**
104 * Serialize a document containing wrapped query results (or any other document, in fact)
105 * as XML.
106 *
107 * @param node The document or element to be serialized
108 * @param destination The Result object to contain the serialized form
109 * @param outputProperties Serialization options as defined in JAXP. The requested properties are
110 * not validated.
111 * @throws XPathException If serialization fails
112 * @since 8.9
113 */
114
115 public static void serialize(/*@NotNull*/ NodeInfo node, /*@NotNull*/ Result destination, /*@NotNull*/ Properties outputProperties)
116 throws XPathException {
117 Configuration config = node.getConfiguration();
118 serializeSequence(SingletonIterator.makeIterator(node), config, destination, outputProperties);
119 }
120
121 /**
122 * Serialize a document or element node.
123 *
124 * @param node The document or element to be serialized
125 * @param destination The Result object to contain the serialized form
126 * @param properties Serialization options as defined in JAXP. The requested properties are
127 * not validated.
128 * @throws XPathException If serialization fails
129 * @since 9.9.1.3
130 */
131
132 public static void serialize(NodeInfo node, Result destination, SerializationProperties properties)
133 throws XPathException {
134 Configuration config = node.getConfiguration();
135 serializeSequence(SingletonIterator.makeIterator(node), config, destination, properties);
136 }
137
138 /**
139 * Serialize an arbitrary sequence, without any special wrapping.
140 *
141 * @param iterator the sequence to be serialized
142 * @param config the configuration (gives access to information such as the NamePool)
143 * @param destination the output stream to which the output is to be written
144 * @param outputProps a set of serialization properties as defined in JAXP. The requested properties are
145 * not validated.
146 * @throws XPathException if any failure occurs
147 * @since 8.9
148 */
149
150 public static void serializeSequence(
151 SequenceIterator<?> iterator, Configuration config, OutputStream destination, Properties outputProps)
152 throws XPathException {
153 serializeSequence(iterator, config, new StreamResult(destination), outputProps);
154 try {
155 destination.flush();
156 } catch (IOException err) {
157 throw new XPathException(err);
158 }
159 }
160
161 /**
162 * Serialize an arbitrary sequence, without any special wrapping.
163 *
164 * @param iterator the sequence to be serialized
165 * @param config the configuration (gives access to information such as the NamePool)
166 * @param writer the writer to which the output is to be written
167 * @param outputProps a set of serialization properties as defined in JAXP. The requested properties are
168 * not validated.
169 * @throws XPathException if any failure occurs
170 * @since 8.9
171 */
172
173 public static void serializeSequence(
174 SequenceIterator<?> iterator, Configuration config, Writer writer, Properties outputProps)
175 throws XPathException {
176 serializeSequence(iterator, config, new StreamResult(writer), outputProps);
177 try {
178 writer.flush();
179 } catch (IOException err) {
180 throw new XPathException(err);
181 }
182 }
183
184 /**
185 * Serialize a sequence to a given result
186 *
187 * @param iterator the sequence to be serialized
188 * @param config the Saxon Configuration
189 * @param result the destination to receive the output
190 * @param outputProperties the serialization properties to be used. The requested properties are
191 * not validated.
192 * @throws XPathException if any failure occurs
193 * @since 9.0
194 */
195
196 public static void serializeSequence(
197 /*@NotNull*/ SequenceIterator<?> iterator, Configuration config, Result result, Properties outputProperties)
198 throws XPathException {
199 SerializerFactory sf = config.getSerializerFactory();
200 Receiver tr = sf.getReceiver(result, new SerializationProperties(outputProperties));
201 SequenceCopier.copySequence(iterator, tr);
202 }
203
204 /**
205 * Serialize a sequence to a given result. This version of the method allows character maps to be supplied
206 *
207 * @param iterator the sequence to be serialized
208 * @param config the Saxon Configuration
209 * @param result the destination to receive the output
210 * @param properties the serialization properties to be used. The requested properties are
211 * not validated.
212 * @throws XPathException if any failure occurs
213 * @since 9.9.1.3
214 */
215
216 public static void serializeSequence(
217 SequenceIterator<?> iterator, Configuration config, Result result, SerializationProperties properties)
218 throws XPathException {
219 SerializerFactory sf = config.getSerializerFactory();
220 Receiver tr = sf.getReceiver(result, properties);
221 SequenceCopier.copySequence(iterator, tr);
222 }
223
224 /**
225 * Write an updated document back to disk, using the original URI from which it was read
226 *
227 * @param doc an updated document. Must be a document node, or a parentless element, or an
228 * element that has a document node as its parent. The document will be written to the URI
229 * found in the systemId property of this node.
230 * @param outputProperties serialization properties
231 * @param backup true if the old document at that location is to be copied to a backup file
232 * @param log destination for progress messages; if null, no progress messages are written
233 * @throws XPathException if the document has no known URI, if the URI is not a writable location,
234 * or if a serialization error occurs.
235 */
236
237 public static void rewriteToDisk(NodeInfo doc, Properties outputProperties, boolean backup, PrintStream log)
238 throws XPathException {
239 switch (doc.getNodeKind()) {
240 case Type.DOCUMENT:
241 // OK
242 break;
243 case Type.ELEMENT:
244 NodeInfo parent = doc.getParent();
245 if (parent != null && parent.getNodeKind() != Type.DOCUMENT) {
246 throw new XPathException("Cannot rewrite an element node unless it is top-level");
247 }
248 break;
249 default:
250 throw new XPathException("Node to be rewritten must be a document or element node");
251 }
252 String uri = doc.getSystemId();
253 if (uri == null || uri.isEmpty()) {
254 throw new XPathException("Cannot rewrite a document with no known URI");
255 }
256 URI u;
257 try {
258 u = new URI(uri);
259 } catch (URISyntaxException e) {
260 throw new XPathException("SystemId of updated document is not a valid URI: " + uri);
261 }
262 File existingFile = new File(u);
263 File dir = existingFile.getParentFile();
264 if (backup && existingFile.exists()) {
265 File backupFile = new File(dir, existingFile.getName() + ".bak");
266 if (log != null) {
267 log.println("Creating backup file " + backupFile);
268 }
269 boolean success = existingFile.renameTo(backupFile);
270 if (!success) {
271 throw new XPathException("Failed to create backup file of " + backupFile);
272 }
273 }
274 if (!existingFile.exists()) {
275 if (log != null) {
276 log.println("Creating file " + existingFile);
277 }
278 try {
279 //noinspection ResultOfMethodCallIgnored
280 existingFile.createNewFile();
281 } catch (IOException e) {
282 throw new XPathException("Failed to create new file " + existingFile);
283 }
284 } else {
285 if (log != null) {
286 log.println("Overwriting file " + existingFile);
287 }
288 }
289 Configuration config = doc.getConfiguration();
290 SerializerFactory factory = config.getSerializerFactory();
291 Receiver r = factory.getReceiver(new StreamResult(existingFile), new SerializationProperties(outputProperties));
292 doc.copy(r, CopyOptions.ALL_NAMESPACES, ExplicitLocation.UNKNOWN_LOCATION);
293 r.close();
294 }
295 }