Debian Codegraph @

net/sf/saxon/s9api/XdmValue.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.Receiver;
12 import net.sf.saxon.event.SequenceCopier;
13 import net.sf.saxon.expr.sort.DocumentOrderIterator;
14 import net.sf.saxon.expr.sort.GlobalOrderComparer;
15 import net.sf.saxon.ma.arrays.ArrayItem;
16 import net.sf.saxon.ma.map.MapItem;
17 import net.sf.saxon.om.*;
18 import net.sf.saxon.s9api.streams.Step;
19 import net.sf.saxon.s9api.streams.XdmStream;
20 import net.sf.saxon.serialize.SerializationProperties;
21 import net.sf.saxon.trans.XPathException;
22 import net.sf.saxon.value.AtomicValue;
23 import net.sf.saxon.value.ExternalObject;
24 import net.sf.saxon.value.SequenceExtent;
25
26 import javax.xml.transform.OutputKeys;
27 import javax.xml.transform.stream.StreamResult;
28 import java.io.StringWriter;
29 import java.util.ArrayList;
30 import java.util.Iterator;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.stream.Stream;
34 import java.util.stream.StreamSupport;
35
36 /**
37 * An value in the XDM data model. A value is a sequence of zero or more items,
38 * each item being either an atomic value or a node.
39 * <p>An XdmValue is immutable.</p>
40 * <p>A sequence consisting of a single item may be represented as an instance of {@link XdmItem},
41 * which is a subtype of XdmValue. However, there is no guarantee that a sequence of length one
42 * will always be an instance of XdmItem.</p>
43 * <p>Similarly, a zero-length sequence may be represented as an instance of {@link XdmEmptySequence},
44 * but there is no guarantee that every sequence of length zero will always be an instance of
45 * XdmEmptySequence.</p>
46 *
47 * @since 9.0
48 */
49
50 public class XdmValue implements Iterable<XdmItem> {
51
52 private GroundedValue<?> value;
53
54 protected XdmValue() {
55 // must be followed by setValue()
56 }
57
58 /**
59 * Create an XdmValue as a sequence of XdmItem objects
60 *
61 * @param items a sequence of XdmItem objects. Note that if this is supplied as a list or similar
62 * collection, subsequent changes to the list/collection will have no effect on the XdmValue.
63 * @since 9.0.0.4
64 */
65
66 public XdmValue(Iterable<? extends XdmItem> items) {
67 List<Item<?>> values = new ArrayList<>();
68 for (XdmItem item : items) {
69 values.add(item.getUnderlyingValue());
70 }
71 value = new SequenceExtent<>(values);
72 }
73
74 /**
75 * Create an XdmValue containing the items returned by an {@link Iterator}.
76 *
77 * @param iterator the iterator that supplies the values
78 * @throws SaxonApiException if an error occurs reading values from the supplied iterator
79 * @since 9.6. Extended in 9.9 to take any Iterator, not just an {@link XdmSequenceIterator}.
80 */
81
82 public XdmValue(Iterator<? extends XdmItem> iterator) throws SaxonApiException {
83 try {
84 List<Item<?>> values = new ArrayList<>();
85 while (iterator.hasNext()) {
86 values.add(iterator.next().getUnderlyingValue());
87 }
88 value = new SequenceExtent<>(values);
89 } catch (SaxonApiUncheckedException e) {
90 throw new SaxonApiException(e.getCause());
91 }
92 }
93
94 /**
95 * Create an XdmValue containing the results of reading a Stream
96 * @param stream the stream to be read
97 */
98
99 public XdmValue(Stream<? extends XdmItem> stream) throws SaxonApiException {
100 this(stream.iterator());
101 }
102
103 protected static XdmValue fromGroundedValue(GroundedValue<?> value) {
104 XdmValue xv = new XdmValue();
105 xv.setValue(value);
106 return xv;
107 }
108
109 protected void setValue(GroundedValue<?> value) {
110 this.value = value;
111 }
112
113 /**
114 * Create an XdmValue that wraps an existing Saxon Sequence
115 *
116 * @param value the supplied Sequence (which may be a singleton Item),
117 * @return an XdmValue corresponding to the supplied Sequence. If the
118 * supplied value is null, an empty sequence is returned. If the supplied
119 * value is an atomic value, the result will be an instance of XdmAtomicValue.
120 * <ul>
121 * <li>If the supplied value is a node, the result will be an instance of XdmNode.</li>
122 * <li>If the supplied value is a map, the result will be an instance of XdmMap.</li>
123 * <li>If the supplied value is an array, the result will be an instance of XdmArray.</li>
124 * <li>If the supplied value is a function item, the result will be an instance of
125 * XdmFunctionItem.</li>
126 * </ul>
127 * @throws SaxonApiUncheckedException if the supplied Sequence is not yet fully evaluated, and evaluation
128 * of the underlying expression fails with a dynamic error.
129 * @since 9.5 (previously a protected method)
130 */
131
132 public static XdmValue wrap(Sequence<?> value) {
133 if (value == null) {
134 return XdmEmptySequence.getInstance();
135 }
136 GroundedValue<?> gv;
137 try {
138 gv = value.materialize();
139 } catch (XPathException e) {
140 throw new SaxonApiUncheckedException(e);
141 }
142 if (gv.getLength() == 0) {
143 return XdmEmptySequence.getInstance();
144 } else if (gv.getLength() == 1) {
145 Item first = gv.head();
146 if (first instanceof NodeInfo) {
147 return new XdmNode((NodeInfo) first);
148 } else if (first instanceof AtomicValue) {
149 return new XdmAtomicValue((AtomicValue) first, true);
150 } else if (first instanceof MapItem) {
151 return new XdmMap((MapItem)first);
152 } else if (first instanceof ArrayItem) {
153 return new XdmArray((ArrayItem)first);
154 } else if (first instanceof Function) {
155 return new XdmFunctionItem((Function) first);
156 } else if (first instanceof ExternalObject) {
157 return new XdmExternalObject(first);
158 } else {
159 throw new IllegalArgumentException("Unknown item type " + first.getClass());
160 }
161 } else {
162 return fromGroundedValue(gv);
163 }
164 }
165
166 public static XdmValue wrap(AtomicSequence value) {
167 switch (value.getLength()) {
168 case 0:
169 return XdmEmptySequence.getInstance();
170 case 1:
171 return new XdmAtomicValue(value.head(), true);
172 default:
173 return fromGroundedValue(value);
174 }
175 }
176
177
178 /**
179 * Create a new XdmValue by concatenating the contents of this XdmValue and another
180 * XdmValue into a single sequence. The two input XdmValue objects are unaffected by this operation.
181 * <p>Note: creating a sequence of N values by successive calls on this method
182 * takes time proportional to N-squared.</p>
183 *
184 * @param otherValue the value to be appended
185 * @return a new XdmValue containing the concatenation of the two input XdmValue objects
186 * @since 9.2
187 */
188
189 public XdmValue append(XdmValue otherValue) {
190 List<Item<?>> values = new ArrayList<>();
191 for (XdmItem item : this) {
192 values.add(item.getUnderlyingValue());
193 }
194 for (XdmItem item : otherValue) {
195 values.add(item.getUnderlyingValue());
196 }
197 GroundedValue<Item<?>> gv = SequenceExtent.makeSequenceExtent(values);
198 return XdmValue.fromGroundedValue(gv);
199 }
200
201 /**
202 * Get the number of items in the sequence
203 *
204 * @return the number of items in the value, considered as a sequence. Note that for arrays
205 * and maps, the answer will be 1 (one) since arrays and maps are items.
206 * @throws SaxonApiUncheckedException if the value is lazily evaluated and the delayed
207 * evaluation fails with a dynamic error.
208 */
209
210 public int size() {
211 try {
212 return SequenceTool.getLength(value);
213 } catch (XPathException err) {
214 throw new SaxonApiUncheckedException(err);
215 }
216 }
217
218 /**
219 * Get the n'th item in the value, counting from zero.
220 *
221 * @param n the item that is required, counting the first item in the sequence as item zero
222 * @return the n'th item in the sequence making up the value, counting from zero
223 * @throws IndexOutOfBoundsException if n is less than zero or greater than or equal to the number
224 * of items in the value
225 * @throws SaxonApiUncheckedException if the value is lazily evaluated and the delayed
226 * evaluation fails with a dynamic error.
227 */
228
229 public XdmItem itemAt(int n) throws IndexOutOfBoundsException, SaxonApiUncheckedException {
230 if (n < 0 || n >= size()) {
231 throw new IndexOutOfBoundsException("" + n);
232 }
233 try {
234 Item<?> item = SequenceTool.itemAt(value, n);
235 return (XdmItem)XdmItem.wrap(item);
236 } catch (XPathException e) {
237 throw new SaxonApiUncheckedException(e);
238 }
239 }
240
241 /**
242 * Get an iterator over the items in this value.
243 *
244 * @return an Iterator over the items in this value.
245 * @throws SaxonApiUncheckedException if the value is lazily evaluated and the delayed
246 * evaluation fails with a dynamic error.
247 */
248 public Iterator<XdmItem> iterator() throws SaxonApiUncheckedException {
249 try {
250 Sequence<?> v = getUnderlyingValue();
251 return new XdmSequenceIterator<>(v.iterate());
252 } catch (XPathException e) {
253 throw new SaxonApiUncheckedException(e);
254 }
255 }
256
257
258
259 /**
260 * Get the underlying implementation object representing the value. This method allows
261 * access to lower-level Saxon functionality, including classes and methods that offer
262 * no guarantee of stability across releases.
263 *
264 * @return the underlying implementation object representing the value
265 */
266
267 public GroundedValue<?> getUnderlyingValue() {
268 return value;
269 }
270
271 /**
272 * Create a string representation of the value. The is the result of serializing
273 * the value using the adaptive serialization method.
274 * @return a string representation of the value
275 */
276
277 public String toString() {
278 try {
279 Configuration config = null;
280 SequenceIterator iter = value.iterate();
281 Item item;
282 while ((item = iter.next()) != null) {
283 if (item instanceof NodeInfo) {
284 config = ((NodeInfo)item).getConfiguration();
285 break;
286 }
287 }
288 if (config == null) {
289 config = Configuration.newConfiguration();
290 }
291 StringWriter writer = new StringWriter();
292 StreamResult result = new StreamResult(writer);
293 SerializationProperties properties = new SerializationProperties();
294 properties.setProperty(OutputKeys.METHOD, "adaptive");
295 properties.setProperty(OutputKeys.INDENT, "true");
296 properties.setProperty(OutputKeys.OMIT_XML_DECLARATION, "true");
297 Receiver r = config.getSerializerFactory().getReceiver(result, properties);
298 SequenceCopier.copySequence(value.iterate(), r);
299 return writer.toString();
300 } catch (XPathException e) {
301 return super.toString();
302 }
303
304 }
305
306 /**
307 * Make an XDM sequence from a Java {@link Iterable}. Each value delivered by the iterable
308 * is first converted to an XDM value using the {@link #makeValue(Object)} method;
309 * if the result is anything other than a single XDM item, it is then wrapped in an
310 * {@link XdmArray}.
311 * @return the result of the conversion if successful
312 * @throws IllegalArgumentException if conversion is not possible
313 */
314
315 public static XdmValue makeSequence(Iterable<?> list) throws IllegalArgumentException {
316 List<Item<?>> result = new ArrayList<>();
317 for (Object o : list) {
318 XdmValue v = XdmValue.makeValue(o);
319 if (v instanceof XdmItem) {
320 result.add((Item)v.getUnderlyingValue());
321 } else {
322 result.add(new XdmArray(v).getUnderlyingValue());
323 }
324 }
325 return XdmValue.wrap(SequenceExtent.makeSequenceExtent(result));
326 }
327
328 /**
329 * Make an XDM value from a Java object. The supplied object may be any of the following:
330 * <ul>
331 * <li>An instance of {@link XdmValue} (for example, an
332 * {@link XdmNode} or {@link XdmAtomicValue} or {@link XdmArray} or {@link XdmMap}),
333 * which is returned unchanged</li>
334 * <li>An instance of {@link net.sf.saxon.om.Sequence} (for example, a
335 * {@link net.sf.saxon.om.NodeInfo} or {@link net.sf.saxon.value.AtomicValue}),
336 * which is wrapped as an {@code XdmValue}</li>
337 * <li>An instance of {@link java.util.Map}, which is converted to an XDM Map using
338 * the {@link XdmMap#makeMap} method</li>
339 * <li>A Java array, of any type, which is converted to an XDM Array using the
340 * {@link XdmArray#makeArray} method</li>
341 * <li>A Java collection, more specifically {@link java.lang.Iterable}, which is converted to an XDM sequence
342 * using the {@link XdmValue#makeSequence(Iterable)} method</li>
343 * <li>Any object that is convertible to an XDM atomic value using the
344 * method {@link XdmAtomicValue#makeAtomicValue(Object)}</li>
345 * </ul>
346 *
347 * @return the result of the conversion if successful
348 * @throws IllegalArgumentException if conversion is not possible
349 */
350
351 public static XdmValue makeValue(Object o) throws IllegalArgumentException {
352 if (o instanceof Sequence) {
353 return XdmValue.wrap((Sequence<?>) o);
354 } else if (o instanceof XdmValue) {
355 return (XdmValue) o;
356 } else if (o instanceof Map) {
357 return XdmMap.makeMap((Map) o);
358 } else if (o instanceof Object[]) {
359 return XdmArray.makeArray((Object[]) o);
360 } else if (o instanceof Iterable) {
361 return XdmValue.makeSequence((Iterable) o);
362 } else {
363 return XdmAtomicValue.makeAtomicValue(o);
364 }
365 }
366
367 /**
368 * Return a new XdmValue containing the nodes present in this XdmValue,
369 * with duplicates eliminated, and sorted into document order
370 * @return the same nodes, sorted into document order, with duplicates eliminated
371 * @throws SaxonApiException if anything goes wrong (typically during delayed evaluation of the
372 * input sequence)
373 * @throws ClassCastException if the sequence contains items that are not nodes
374 * @since 9.9
375 */
376
377 public XdmValue documentOrder() throws SaxonApiException {
378 try {
379 SequenceIterator<?> iter = value.iterate();
380 SequenceIterator<NodeInfo> sorted = new DocumentOrderIterator(iter, GlobalOrderComparer.getInstance());
381 return XdmValue.fromGroundedValue(sorted.materialize());
382 } catch (XPathException e) {
383 throw new SaxonApiException(e);
384 }
385 }
386
387 /**
388 * Get a stream comprising the items in this value
389 *
390 * @return a Stream over the items in this value
391 * @since 9.9
392 */
393 public XdmStream<? extends XdmItem> stream() {
394 return new XdmStream<>(StreamSupport.stream(spliterator(), false));
395 }
396
397 /**
398 * Get a stream of items by applying a {@link Step} to the items in this value. This operation
399 * is analogous to the {@code Stream.flatMap} operation in Java, or to the "!" operator
400 * in XPath.
401 *
402 * @param step the Step to be applied to the items in this value
403 * @return a Stream of items obtained by replacing each item X in this value by the items obtained
404 * by applying the Step function to X.
405 * @since 9.9
406 */
407
408 public <T extends XdmItem> XdmStream<T> select(Step<T> step) {
409 return stream().flatMapToXdm(step);
410 }
411
412 }
413