Debian Codegraph @

net/sf/saxon/serialize/AdaptiveEmitter.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.serialize;
9
10 import net.sf.saxon.event.PipelineConfiguration;
11 import net.sf.saxon.event.ReceiverWithOutputProperties;
12 import net.sf.saxon.event.SequenceWriter;
13 import net.sf.saxon.functions.FormatNumber;
14 import net.sf.saxon.lib.NamespaceConstant;
15 import net.sf.saxon.lib.SaxonOutputKeys;
16 import net.sf.saxon.ma.arrays.ArrayItem;
17 import net.sf.saxon.ma.map.KeyValuePair;
18 import net.sf.saxon.ma.map.MapItem;
19 import net.sf.saxon.om.*;
20 import net.sf.saxon.query.QueryResult;
21 import net.sf.saxon.serialize.codenorm.Normalizer;
22 import net.sf.saxon.trans.XPathException;
23 import net.sf.saxon.type.Type;
24 import net.sf.saxon.value.AtomicValue;
25 import net.sf.saxon.value.DoubleValue;
26 import net.sf.saxon.value.QualifiedNameValue;
27
28 import javax.xml.transform.stream.StreamResult;
29 import java.io.IOException;
30 import java.io.StringWriter;
31 import java.io.Writer;
32 import java.util.Properties;
33
34 /**
35 * This class implements the Adaptive serialization method defined in XSLT+XQuery Serialization 3.1.
36 */
37
38 public class AdaptiveEmitter extends SequenceWriter implements ReceiverWithOutputProperties {
39
40 private Writer writer;
41 private Normalizer normalizer;
42 private CharacterMap characterMap;
43 private Properties outputProperties;
44 private String itemSeparator = "\n";
45 private boolean started = false;
46
47 public AdaptiveEmitter(PipelineConfiguration pipe, Writer writer) {
48 super(pipe);
49 this.writer = writer;
50 }
51
52 public void setOutputProperties(Properties props) {
53 outputProperties = props;
54 String sep = props.getProperty(SaxonOutputKeys.ITEM_SEPARATOR);
55 if (sep != null && !"#absent".equals(sep)) {
56 itemSeparator = sep;
57 }
58 }
59
60 public Properties getOutputProperties() {
61 return outputProperties;
62 }
63
64 /**
65 * Set the Unicode normalizer to be used for normalizing strings.
66 *
67 * @param normalizer the normalizer to be used
68 */
69
70 public void setNormalizer(Normalizer normalizer) {
71 this.normalizer = normalizer;
72 }
73
74 /**
75 * Set the CharacterMap to be used, if any
76 *
77 * @param map the character map
78 */
79
80 public void setCharacterMap(CharacterMap map) {
81 this.characterMap = map;
82 }
83
84
85 private void emit(CharSequence s) throws XPathException {
86 try {
87 writer.append(s);
88 } catch (IOException e) {
89 throw new XPathException(e);
90 }
91 }
92
93 /**
94 * Abstract method to be supplied by subclasses: output one item in the sequence.
95 *
96 * @param item the item to be written to the sequence
97 * @throws XPathException if any failure occurs while writing the item
98 */
99 @Override
100 public void write(Item item) throws XPathException {
101 if (started) {
102 emit(itemSeparator);
103 } else {
104 if (writer == null) {
105 // TODO: ????
106 }
107 started = true;
108 }
109 serializeItem(item);
110 }
111
112 private void serializeItem(Item item) throws XPathException {
113 if (item instanceof AtomicValue) {
114 emit(serializeAtomicValue((AtomicValue) item));
115 } else if (item instanceof NodeInfo) {
116 serializeNode((NodeInfo) item);
117 } else if (item instanceof MapItem) {
118 serializeMap((MapItem) item);
119 } else if (item instanceof ArrayItem) {
120 serializeArray((ArrayItem) item);
121 } else if (item instanceof Function) {
122 serializeFunction((Function) item);
123 }
124 }
125
126 private String serializeAtomicValue(AtomicValue value) throws XPathException {
127 switch(value.getPrimitiveType().getFingerprint()) {
128 case StandardNames.XS_STRING:
129 case StandardNames.XS_ANY_URI:
130 case StandardNames.XS_UNTYPED_ATOMIC: {
131 String s = value.getStringValue();
132 if (s.contains("\"")) {
133 s = s.replace("\"", "\"\"");
134 }
135 if (characterMap != null) {
136 s = characterMap.map(s,false).toString();
137 }
138 return "\"" + s + "\"";
139 }
140 case StandardNames.XS_BOOLEAN:
141 return value.effectiveBooleanValue() ? "true()" : "false()";
142
143 case StandardNames.XS_DECIMAL:
144 case StandardNames.XS_INTEGER:
145 return value.getStringValue();
146
147 case StandardNames.XS_DOUBLE:
148 return FormatNumber.formatExponential((DoubleValue)value);
149
150 case StandardNames.XS_FLOAT:
151 case StandardNames.XS_DURATION:
152 case StandardNames.XS_DATE_TIME:
153 case StandardNames.XS_DATE:
154 case StandardNames.XS_TIME:
155 case StandardNames.XS_G_YEAR_MONTH:
156 case StandardNames.XS_G_MONTH:
157 case StandardNames.XS_G_MONTH_DAY:
158 case StandardNames.XS_G_YEAR:
159 case StandardNames.XS_G_DAY:
160 case StandardNames.XS_HEX_BINARY:
161 case StandardNames.XS_BASE64_BINARY:
162 return value.getPrimitiveType().getDisplayName() + "(\"" + value.getStringValue() + "\")";
163
164 case StandardNames.XS_DAY_TIME_DURATION:
165 case StandardNames.XS_YEAR_MONTH_DURATION:
166 return "xs:duration(\"" + value.getStringValue() + "\")";
167
168 case StandardNames.XS_QNAME:
169 case StandardNames.XS_NOTATION:
170 return ((QualifiedNameValue)value).getStructuredQName().getEQName();
171 default:
172 return "***";
173 }
174 }
175
176 private void serializeFunction(Function fn) throws XPathException {
177 StructuredQName fname = fn.getFunctionName();
178 if (fname == null || fname.hasURI(NamespaceConstant.ANONYMOUS)) {
179 emit("(anonymous-function)");
180 } else if (fname.hasURI(NamespaceConstant.FN)) {
181 emit("fn:" + fname.getLocalPart());
182 } else if (fname.hasURI(NamespaceConstant.MATH)) {
183 emit("math:" + fname.getLocalPart());
184 } else if (fname.hasURI(NamespaceConstant.MAP_FUNCTIONS)) {
185 emit("map:" + fname.getLocalPart());
186 } else if (fname.hasURI(NamespaceConstant.ARRAY_FUNCTIONS)) {
187 emit("array:" + fname.getLocalPart());
188 } else if (fname.hasURI(NamespaceConstant.SCHEMA)) {
189 emit("xs:" + fname.getLocalPart());
190 } else {
191 emit(fname.getEQName());
192 }
193 emit("#" + fn.getArity());
194 }
195
196 private void serializeNode(NodeInfo node) throws XPathException {
197 switch (node.getNodeKind()) {
198 case Type.ATTRIBUTE:
199 emit(node.getDisplayName());
200 emit("=\"");
201 emit(node.getStringValueCS());
202 emit("\"");
203 break;
204 case Type.NAMESPACE:
205 emit(node.getLocalPart().isEmpty() ? "xmlns" : "xmlns:" + node.getLocalPart());
206 emit("=\"");
207 emit(node.getStringValueCS());
208 emit("\"");
209 break;
210 default:
211 StringWriter sw = new StringWriter();
212 Properties props = new Properties(outputProperties);
213 String nodeMethod = outputProperties.getProperty(SaxonOutputKeys.JSON_NODE_OUTPUT_METHOD);
214 if (nodeMethod == null) {
215 nodeMethod = "xml";
216 }
217 props.setProperty("method", nodeMethod);
218 props.setProperty("indent", "no");
219 props.setProperty("omit-xml-declaration", "yes");
220 props.setProperty(SaxonOutputKeys.UNFAILING, "yes");
221 CharacterMapIndex cmi = null;
222 if (characterMap != null) {
223 cmi = new CharacterMapIndex();
224 cmi.putCharacterMap(characterMap.getName(), characterMap);
225 }
226 SerializationProperties sProps = new SerializationProperties(props, cmi);
227 QueryResult.serialize(node, new StreamResult(sw), sProps);
228 emit(sw.toString().trim());
229 }
230 }
231
232 private void serializeArray(ArrayItem array) throws XPathException {
233 emit("[");
234 boolean first = true;
235 for (Sequence<?> seq: array.members()) {
236 if (first) {
237 first = false;
238 } else {
239 emit(",");
240 }
241 outputInternalSequence(seq);
242 }
243 emit("]");
244 }
245
246 private void serializeMap(MapItem map) throws XPathException {
247 emit("map{");
248 boolean first = true;
249 for (KeyValuePair pair : map.keyValuePairs()) {
250 if (first) {
251 first = false;
252 } else {
253 emit(",");
254 }
255 serializeItem(pair.key);
256 emit(":");
257 Sequence<?> value = pair.value;
258 outputInternalSequence(value);
259 }
260 emit("}");
261 }
262
263 private void outputInternalSequence(Sequence value) throws XPathException {
264 boolean first = true;
265 Item it;
266 SequenceIterator iter = value.iterate();
267 boolean omitParens = value instanceof GroundedValue && ((GroundedValue)value).getLength() == 1;
268 if (!omitParens) {
269 emit("(");
270 }
271 while ((it = iter.next()) != null) {
272 if (!first) {
273 emit(",");
274 }
275 first = false;
276 serializeItem(it);
277 }
278 if (!omitParens) {
279 emit(")");
280 }
281 }
282
283 @Override
284 public void close() throws XPathException {
285 super.close();
286 if (writer != null) {
287 try {
288 writer.close();
289 } catch (IOException e) {
290 throw new XPathException(e);
291 }
292 }
293 }
294 }
295