Debian Codegraph @

net/sf/saxon/ma/json/JsonReceiver.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.ma.json;
9
10 import net.sf.saxon.event.PipelineConfiguration;
11 import net.sf.saxon.event.Receiver;
12 import net.sf.saxon.event.StartTagBuffer;
13 import net.sf.saxon.expr.parser.Location;
14 import net.sf.saxon.lib.NamespaceConstant;
15 import net.sf.saxon.om.NamespaceBindingSet;
16 import net.sf.saxon.om.NodeName;
17 import net.sf.saxon.trans.Err;
18 import net.sf.saxon.trans.XPathException;
19 import net.sf.saxon.tree.util.FastStringBuffer;
20 import net.sf.saxon.type.SchemaType;
21 import net.sf.saxon.type.SimpleType;
22 import net.sf.saxon.type.StringConverter;
23 import net.sf.saxon.value.DoubleValue;
24 import net.sf.saxon.value.StringToDouble11;
25 import net.sf.saxon.value.Whitespace;
26
27 import java.util.function.IntPredicate;
28
29 import java.util.HashSet;
30 import java.util.Set;
31 import java.util.Stack;
32
33 /**
34 * A Receiver which receives a stream of XML events using the vocabulary defined for the XML representation
35 * of JSON in XSLT 3.0, and which generates the corresponding JSON text as a string
36 */
37
38
39 public class JsonReceiver implements Receiver {
40
41 private PipelineConfiguration pipe;
42 private FastStringBuffer output;
43 private FastStringBuffer textBuffer = new FastStringBuffer(128);
44 private Stack<NodeName> stack = new Stack<NodeName>();
45 private boolean atStart = true;
46 private StartTagBuffer startTagBuffer;
47 private boolean indenting = false;
48 private boolean escaped = false;
49 private Stack<Set<String>> keyChecker = new Stack<Set<String>>();
50
51 private static final String ERR_INPUT = "FOJS0006";
52
53 public JsonReceiver(PipelineConfiguration pipe) {
54 setPipelineConfiguration(pipe);
55 }
56
57 public void setPipelineConfiguration(PipelineConfiguration pipe) {
58 this.pipe = pipe;
59 startTagBuffer = (StartTagBuffer) pipe.getComponent(StartTagBuffer.class.getName());
60 }
61
62 public PipelineConfiguration getPipelineConfiguration() {
63 return pipe;
64 }
65
66 public void setSystemId(String systemId) {
67 // no action
68 }
69
70 public void setIndenting(boolean indenting) {
71 this.indenting = indenting;
72 }
73
74 public boolean isIndenting() {
75 return indenting;
76 }
77
78 public void open() throws XPathException {
79 output = new FastStringBuffer(2048);
80 }
81
82 public void startDocument(int properties) throws XPathException {
83 if (output == null) {
84 output = new FastStringBuffer(2048);
85 }
86 }
87
88 public void endDocument() throws XPathException {
89 // no action
90 }
91
92 public void setUnparsedEntity(String name, String systemID, String publicID) throws XPathException {
93 // no action
94 }
95
96 public void startElement(NodeName elemName, SchemaType typeCode, Location location, int properties) throws XPathException {
97 String parent = stack.empty() ? null : stack.peek().getLocalPart();
98 boolean inMap = "map".equals(parent);
99 stack.push(elemName);
100 //started.push(false);
101 if (!elemName.hasURI(NamespaceConstant.FN)) {
102 throw new XPathException("xml-to-json: element found in wrong namespace: " +
103 elemName.getStructuredQName().getEQName(), ERR_INPUT);
104 }
105 if (!atStart) {
106 output.append(',');
107 if (indenting) {
108 indent(stack.size());
109 }
110 }
111 if (inMap) {
112 if (startTagBuffer == null) {
113 startTagBuffer = (StartTagBuffer) pipe.getComponent(StartTagBuffer.class.getName());
114 }
115 if (startTagBuffer == null) {
116 throw new IllegalStateException();
117 }
118 String key = startTagBuffer.getAttribute("", "key");
119 if (key == null) {
120 throw new XPathException("xml-to-json: Child elements of <map> must have a key attribute", ERR_INPUT);
121 }
122 String keyEscaped = startTagBuffer.getAttribute("", "escaped-key");
123 boolean alreadyEscaped = false;
124 if (keyEscaped != null) {
125 try {
126 alreadyEscaped = StringConverter.StringToBoolean.INSTANCE.convertString(keyEscaped).asAtomic().effectiveBooleanValue();
127 } catch (XPathException e) {
128 throw new XPathException("xml-to-json: Value of escaped-key attribute '" + Err.wrap(keyEscaped) +
129 "' is not a valid xs:boolean", ERR_INPUT);
130 }
131 }
132 key = (alreadyEscaped ? handleEscapedString(key) : escape(key, false, new ControlChar())).toString();
133
134 String normalizedKey = alreadyEscaped ? unescape(key) : key;
135 boolean added = keyChecker.peek().add(normalizedKey);
136 if (!added) {
137 throw new XPathException("xml-to-json: duplicate key value " + Err.wrap(key), ERR_INPUT);
138 }
139
140 output.append('"');
141 output.append(key);
142 output.append('"');
143 output.append(indenting ? " : " : ":");
144 }
145 String local = elemName.getLocalPart();
146 escaped = false;
147 if (local.equals("array")) {
148 if (indenting) {
149 indent(stack.size());
150 output.append("[ ");
151 } else {
152 output.append('[');
153 }
154 atStart = true;
155 } else if (local.equals("map")) {
156 if (indenting) {
157 indent(stack.size());
158 output.append("{ ");
159 } else {
160 output.append('{');
161 }
162 atStart = true;
163 keyChecker.push(new HashSet<String>());
164 } else if (local.equals("null")) {
165 checkParent(local, parent);
166 output.append("null");
167 atStart = false;
168 } else if (local.equals("string")) {
169 if (startTagBuffer == null) {
170 startTagBuffer = (StartTagBuffer) pipe.getComponent(StartTagBuffer.class.getName());
171 }
172 String escapeAtt = startTagBuffer.getAttribute("", "escaped");
173 if (escapeAtt != null) {
174 try {
175 escaped = StringConverter.StringToBoolean.INSTANCE.convertString(escapeAtt).asAtomic().effectiveBooleanValue();
176 } catch (XPathException e) {
177 throw new XPathException("xml-to-json: value of escaped attribute (" +
178 escapeAtt + ") is not a valid xs:boolean", ERR_INPUT);
179 }
180 }
181 checkParent(local, parent);
182 atStart = false;
183 } else if (local.equals("boolean") || local.equals("number")) {
184 checkParent(local, parent);
185 atStart = false;
186 } else {
187 throw new XPathException("xml-to-json: unknown element <" + local + ">", ERR_INPUT);
188 }
189 textBuffer.setLength(0);
190 }
191
192 private void checkParent(String child, String parent) throws XPathException {
193 if ("null".equals(parent) || "string".equals(parent) || "number".equals(parent) || "boolean".equals(parent)) {
194 throw new XPathException("xml-to-json: A " + Err.wrap(child, Err.ELEMENT) +
195 " element cannot appear as a child of " + Err.wrap(parent, Err.ELEMENT), ERR_INPUT);
196 }
197 }
198
199 public void namespace(NamespaceBindingSet namespaceBindings, int properties) throws XPathException {
200 // no action
201 }
202
203 public void attribute(NodeName attName, SimpleType typeCode, CharSequence value, Location locationId, int properties) throws XPathException {
204 if (attName.hasURI("") && (attName.getLocalPart().equals("key") || attName.getLocalPart().equals("escaped-key"))) {
205 boolean inMap = stack.size() == 1 || stack.get(stack.size() - 2).getLocalPart().equals("map");
206 if (!inMap) {
207 throw new XPathException(
208 "xml-to-json: The " + attName.getLocalPart() +
209 " attribute is allowed only on elements within a map", ERR_INPUT);
210 }
211 } else if (attName.hasURI("") && attName.getLocalPart().equals("escaped")) {
212 boolean allowed = stack.size() == 1 ||
213 (stack.size() > 1 && stack.peek().getLocalPart().equals("string"));
214 // See bugs 29917 and 30077: at the top level, the escaped attribute is ignored
215 // whatever element it appears on
216 if (!allowed) {
217 throw new XPathException(
218 "xml-to-json: The escaped attribute is allowed only on the <string> element",
219 ERR_INPUT);
220 }
221 } else if (attName.hasURI("") || attName.hasURI(NamespaceConstant.FN)) {
222 throw new XPathException("xml-to-json: Disallowed attribute in input: " + attName.getDisplayName(), ERR_INPUT);
223 }
224 // Attributes in other namespaces are ignored
225 }
226
227 public void startContent() throws XPathException {
228 // no action
229 }
230
231 public void endElement() throws XPathException {
232 NodeName name = stack.pop();
233 String local = name.getLocalPart();
234 if (local.equals("boolean")) {
235 try {
236 boolean b = StringConverter.StringToBoolean.INSTANCE.convertString(textBuffer).asAtomic().effectiveBooleanValue();
237 output.append(b ? "true" : "false");
238 } catch (XPathException e) {
239 throw new XPathException("xml-to-json: Value of <boolean> element is not a valid xs:boolean", ERR_INPUT);
240 }
241 } else if (local.equals("number")) {
242 try {
243 double d = StringToDouble11.getInstance().stringToNumber(textBuffer);
244 if (Double.isNaN(d) || Double.isInfinite(d)) {
245 throw new XPathException("xml-to-json: Infinity and NaN are not allowed", ERR_INPUT);
246 }
247 output.append(new DoubleValue(d).getStringValueCS());
248 } catch (NumberFormatException e) {
249 throw new XPathException("xml-to-json: Invalid number: " + textBuffer, ERR_INPUT);
250 }
251 } else if (local.equals("string")) {
252 output.append('"');
253 String str = textBuffer.toString();
254 if (escaped) {
255 output.append(handleEscapedString(str));
256 } else {
257 output.append(escape(str, false, new ControlChar()));
258 }
259 output.append('"');
260 } else if (!Whitespace.isWhite(textBuffer)) {
261 throw new XPathException("xml-to-json: Element " + name.getDisplayName() + " must have no text content", ERR_INPUT);
262 }
263 textBuffer.setLength(0);
264 escaped = false;
265 if (local.equals("array")) {
266 output.append(indenting ? " ]" : "]");
267 } else if (local.equals("map")) {
268 keyChecker.pop();
269 output.append(indenting ? " }" : "}");
270 }
271 atStart = false;
272 }
273
274 /**
275 * Handle a string that is already escaped, and that should remain escaped, while normalizing
276 * escape sequences to standard format
277 *
278 * @param str the input string
279 * @return the result string
280 * @throws XPathException if the input contains invalid escape sequences
281 */
282
283 private static CharSequence handleEscapedString(String str) throws XPathException {
284 // check that escape sequences are valid
285 unescape(str);
286 FastStringBuffer out = new FastStringBuffer(str.length() * 2);
287 boolean afterEscapeChar = false;
288 for (int i = 0; i < str.length(); i++) {
289 char c = str.charAt(i);
290 if (c == '"' && !afterEscapeChar) {
291 out.append("\\\"");
292 } else if (c < 32 || (c >= 127 && c < 160)) {
293 if (c == '\b') {
294 out.append("\\b");
295 } else if (c == '\f') {
296 out.append("\\f");
297 } else if (c == '\n') {
298 out.append("\\n");
299 } else if (c == '\r') {
300 out.append("\\r");
301 } else if (c == '\t') {
302 out.append("\\t");
303 } else {
304 out.append("\\u");
305 String hex = Integer.toHexString(c).toUpperCase();
306 while (hex.length() < 4) {
307 hex = "0" + hex;
308 }
309 out.append(hex);
310 }
311 } else if (c == '/' && !afterEscapeChar) {
312 out.append("\\/");
313 } else {
314 out.append(c);
315 }
316 afterEscapeChar = c == '\\' && !afterEscapeChar;
317 }
318 return out;
319 }
320
321
322 /**
323 * Escape a string using backslash escape sequences as defined in JSON
324 *
325 * @param in the input string
326 * @param forXml true if the output is for the json-to-xml functino
327 * @param hexEscapes a predicate identifying characters that should be output as hex escapes using \ u XXXX notation.
328 * @return the escaped string
329 */
330
331 public static CharSequence escape(CharSequence in, boolean forXml, IntPredicate hexEscapes) throws XPathException {
332 FastStringBuffer out = new FastStringBuffer(in.length());
333 for (int i = 0; i < in.length(); i++) {
334 char c = in.charAt(i);
335 switch (c) {
336 case '"':
337 out.append(forXml ? "\"" : "\\\"");
338 break;
339 case '\b':
340 out.append("\\b");
341 break;
342 case '\f':
343 out.append("\\f");
344 break;
345 case '\n':
346 out.append("\\n");
347 break;
348 case '\r':
349 out.append("\\r");
350 break;
351 case '\t':
352 out.append("\\t");
353 break;
354 case '/':
355 out.append(forXml ? "/" : "\\/"); // spec bug 29665, saxon bug 2849
356 break;
357 case '\\':
358 out.append("\\\\");
359 break;
360 default:
361 if (hexEscapes.test(c)) {
362 out.append("\\u");
363 String hex = Integer.toHexString(c).toUpperCase();
364 while (hex.length() < 4) {
365 hex = "0" + hex;
366 }
367 out.append(hex);
368 } else {
369 out.append(c);
370 }
371 }
372 }
373 return out;
374 }
375
376 private static class ControlChar implements IntPredicate {
377 public boolean test(int c) {
378 return c < 31 || (c >= 127 && c <= 159);
379 }
380 }
381
382 public void characters(CharSequence chars, Location locationId, int properties) throws XPathException {
383 textBuffer.append(chars);
384 }
385
386 public void processingInstruction(String name, CharSequence data, Location locationId, int properties) throws XPathException {
387 // no action
388 }
389
390 public void comment(CharSequence content, Location locationId, int properties) throws XPathException {
391 // no action
392 }
393
394 public void close() throws XPathException {
395 // no action
396 }
397
398 public boolean usesTypeAnnotations() {
399 return false;
400 }
401
402 public String getSystemId() {
403 return null;
404 }
405
406 /**
407 * On completion, get the assembled JSON string
408 *
409 * @return the JSON string representing the supplied XML content.
410 */
411
412 public String getJsonString() {
413 return output.toString();
414 }
415
416 /**
417 * Add indentation whitespace to the buffer
418 *
419 * @param depth the level of indentation
420 */
421
422 private void indent(int depth) {
423 output.append('\n');
424 for (int i = 0; i < depth; i++) {
425 output.append(" ");
426 }
427 }
428
429 /**
430 * Unescape a JSON string literal,
431 *
432 * @param literal the string literal to be processed
433 * @return the result of expanding escape sequences
434 * @throws net.sf.saxon.trans.XPathException if the input contains invalid escape sequences
435 */
436
437 private static String unescape(String literal) throws XPathException {
438 if (literal.indexOf('\\') < 0) {
439 return literal;
440 }
441 FastStringBuffer buffer = new FastStringBuffer(literal.length());
442 for (int i = 0; i < literal.length(); i++) {
443 char c = literal.charAt(i);
444 if (c == '\\') {
445 if (i++ == literal.length() - 1) {
446 throw new XPathException("String '" + Err.wrap(literal) + "' ends in backslash ", "FOJS0007");
447 }
448 switch (literal.charAt(i)) {
449 case '"':
450 buffer.append('"');
451 break;
452 case '\\':
453 buffer.append('\\');
454 break;
455 case '/':
456 buffer.append('/');
457 break;
458 case 'b':
459 buffer.append('\b');
460 break;
461 case 'f':
462 buffer.append('\f');
463 break;
464 case 'n':
465 buffer.append('\n');
466 break;
467 case 'r':
468 buffer.append('\r');
469 break;
470 case 't':
471 buffer.append('\t');
472 break;
473 case 'u':
474 try {
475 String hex = literal.substring(i + 1, i + 5);
476 int code = Integer.parseInt(hex, 16);
477 buffer.append((char) code);
478 i += 4;
479 } catch (Exception e) {
480 throw new XPathException("Invalid hex escape sequence in string '" + Err.wrap(literal) + "'", "FOJS0007");
481 }
482 break;
483 default:
484 char next = literal.charAt(i);
485 String xx = next < 256 ? next + "" : "x" + Integer.toHexString(next);
486 throw new XPathException("Unknown escape sequence \\" + xx, "FOJS0007");
487 }
488 } else {
489 buffer.append(c);
490 }
491 }
492 return buffer.toString();
493 }
494 }
495
496 // Copyright (c) 2018 Saxonica Limited. All rights reserved