Debian Codegraph @

net/sf/saxon/ma/json/JsonHandlerXML.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.Configuration;
11 import net.sf.saxon.event.Builder;
12 import net.sf.saxon.event.NamespaceReducer;
13 import net.sf.saxon.event.Receiver;
14 import net.sf.saxon.expr.XPathContext;
15 import net.sf.saxon.expr.parser.ExplicitLocation;
16 import net.sf.saxon.lib.NamespaceConstant;
17 import net.sf.saxon.lib.StandardEntityResolver;
18 import net.sf.saxon.om.*;
19 import net.sf.saxon.trans.XPathException;
20 import net.sf.saxon.type.*;
21 import org.xml.sax.InputSource;
22 import org.xml.sax.SAXException;
23
24 import javax.xml.transform.sax.SAXSource;
25 import java.io.IOException;
26 import java.util.HashMap;
27 import java.util.HashSet;
28 import java.util.Stack;
29
30 /**
31 * Handler to generate an XML representation of JSON from a series of events
32 */
33 public class JsonHandlerXML extends JsonHandler {
34
35 private Receiver out;
36 private Builder builder;
37
38 private Stack<String> keys;
39 private Stack<Boolean> inMap = new Stack<Boolean>();
40
41 public boolean allowAnyTopLevel;
42 public boolean liberal;
43 public boolean validate;
44 public boolean checkForDuplicates;
45
46 public static final String SCHEMA_URI = "http://www.w3.org/2005/xpath-functions.xsd";
47 public static final String JSON_NS = NamespaceConstant.FN;
48 public static final String PREFIX = "";
49
50 private NamePool namePool;
51 private FingerprintedQName mapQN;
52 private FingerprintedQName arrayQN;
53 private FingerprintedQName stringQN;
54 private FingerprintedQName numberQN;
55 private FingerprintedQName booleanQN;
56 private FingerprintedQName nullQN;
57 private FingerprintedQName keyQN;
58 private FingerprintedQName escapedQN;
59 private FingerprintedQName escapedKeyQN;
60
61 private static final Untyped UNTYPED = Untyped.getInstance();
62 private static final AnySimpleType SIMPLE_TYPE = AnySimpleType.getInstance();
63 private static final BuiltInAtomicType BOOLEAN_TYPE = BuiltInAtomicType.BOOLEAN;
64 private static final BuiltInAtomicType STRING_TYPE = BuiltInAtomicType.STRING;
65
66 public HashMap<String, SchemaType> types;
67 private Stack<HashSet<String>> mapKeys = new Stack<HashSet<String>>();
68
69
70 /**
71 * Create a QName in null namespace
72 *
73 * @param s the local name
74 * @return the QName
75 */
76 private FingerprintedQName qname(String s) {
77 FingerprintedQName fp = new FingerprintedQName("", "", s);
78 fp.obtainFingerprint(namePool);
79 return fp;
80 }
81
82 /**
83 * Create a QName in the JSON namespace
84 *
85 * @param s the local name
86 * @return the QName
87 */
88 private FingerprintedQName qnameNS(String s) {
89 FingerprintedQName fp = new FingerprintedQName(PREFIX, JSON_NS, s);
90 fp.obtainFingerprint(namePool);
91 return fp;
92 }
93
94 /**
95 * Make the handler to construct the XML tree representation for JSON
96 *
97 * @param context the context in which the result tree is to be built
98 * @param staticBaseUri the static base URI, used for the base URI of the constructed tree
99 * @param flags flags indicating the chosen options
100 * @throws XPathException if initialization fails, for example because of problems loading the schema
101 */
102 public JsonHandlerXML(XPathContext context, String staticBaseUri, int flags) throws XPathException {
103 init(context, flags);
104 builder = context.getController().makeBuilder();
105 builder.setSystemId(staticBaseUri);
106 builder.setTiming(false);
107 out = new NamespaceReducer(builder);
108 out.open();
109 out.startDocument(0);
110 }
111
112 /**
113 * Initialise the tree builder.
114 * <p>This also ensures the appropriate schema is loaded when type validation is required</p>
115 *
116 * @param context the context in which the result tree is to be built
117 * @param flags flags indicating the chosen options
118 * @throws XPathException if anything goes wrong (for example, with getting schema information)
119 */
120 private void init(XPathContext context, int flags) throws XPathException {
121 keys = new Stack<String>();
122 /* This may not need to be a stack as there should only be at most one pre-selected key
123 * However, the stack neatly indicates its empty state
124 * */
125 setContext(context);
126 charChecker = context.getConfiguration().getValidCharacterChecker();
127 escape = (flags & JsonParser.ESCAPE) != 0;
128 allowAnyTopLevel = (flags & JsonParser.ALLOW_ANY_TOP_LEVEL) != 0;
129 validate = (flags & JsonParser.VALIDATE) != 0;
130 checkForDuplicates = validate || (flags & JsonParser.DUPLICATES_RETAINED) == 0;
131 types = new HashMap<String, SchemaType>();
132
133 namePool = context.getConfiguration().getNamePool();
134 mapQN = qnameNS("map");
135 arrayQN = qnameNS("array");
136 stringQN = qnameNS("string");
137 numberQN = qnameNS("number");
138 booleanQN = qnameNS("boolean");
139 nullQN = qnameNS("null");
140 keyQN = qname("key");
141 escapedQN = qname("escaped");
142 escapedKeyQN = qname("escaped-key");
143
144 if (validate) {
145 // Note, we do not actually perform schema validation, because we assume the XML we are generating
146 // is valid. Instead, we just set type annotations "on trust", as if we were validating.
147 // Currently this means we aren't detecting duplicate keys, which would cause validation to fail.
148 // The spec needs clarification in this area.
149 try {
150 Configuration config = context.getConfiguration();
151 //noinspection SynchronizationOnLocalVariableOrMethodParameter
152 synchronized (config) {
153 config.checkLicensedFeature(Configuration.LicenseFeature.SCHEMA_VALIDATION, "validation", -1);
154 if (!config.isSchemaAvailable(JSON_NS)) {
155 InputSource is = StandardEntityResolver.getInstance().resolveEntity(null, SCHEMA_URI);
156 if (config.isTiming()) {
157 config.getLogger().info("Loading a schema from resources for: " + JSON_NS);
158 }
159 config.addSchemaSource(new SAXSource(is));
160 }
161 }
162 String typeNames[] = {"mapType", "arrayType", "stringType", "numberType", "booleanType", "nullType",
163 "mapWithinMapType", "arrayWithinMapType", "stringWithinMapType",
164 "numberWithinMapType", "booleanWithinMapType", "nullWithinMapType"};
165 for (String t : typeNames) {
166 setType(t, config.getSchemaType(new StructuredQName(PREFIX, JSON_NS, t)));
167 }
168 } catch (SchemaException e) {
169 throw new XPathException(e);
170 } catch (SAXException e) {
171 throw new XPathException(e);
172 } catch (IOException e) {
173 throw new XPathException(e);
174 }
175 }
176 }
177
178 /**
179 * Record a SchemaType for a particular name
180 *
181 * @param name the name to be used for the type, e.g. "arrayType"
182 * @param st the schema type to be used for typing such entities
183 */
184 public void setType(String name, SchemaType st) {
185 types.put(name, st);
186 }
187
188 /**
189 * Set the key to be written for the next entry in an object/map
190 *
191 * @param unEscaped the key for the entry (null implies no key) in unescaped form (backslashes,
192 * if present, do not signal an escape sequence)
193 * @param reEscaped the key for the entry (null implies no key) in reescaped form. In this form
194 * special characters are represented as backslash-escaped sequences if the escape
195 * option is yes; if escape=no, the reEscaped form is the same as the unEscaped form.
196 * @return true if the key is already present in the map, false if it is not
197 */
198 public boolean setKey(String unEscaped, String reEscaped) {
199 this.keys.push(unEscaped);
200 return checkForDuplicates && !mapKeys.peek().add(reEscaped);
201 }
202
203 /**
204 * Return the complete parsed result
205 *
206 * @return the XML document for this JSON
207 * @throws XPathException
208 */
209 public Item getResult() throws XPathException {
210 out.endDocument();
211 out.close();
212 return builder.getCurrentRoot();
213 }
214
215 /**
216 * Check whether a string contains an escape sequence
217 *
218 * @param literal the string to be checked
219 * @return true if the string contains a backslash
220 */
221 protected boolean containsEscape(String literal) {
222 return literal.indexOf('\\') >= 0;
223 }
224
225 private boolean isInMap() {
226 return !inMap.isEmpty() && inMap.peek();
227 }
228
229 /**
230 * Start an element in the result tree
231 *
232 * @param qn the QName of the element
233 * @param typeName the string name of the type to use
234 * @throws XPathException if a dynamic error occurs
235 */
236 private void startElement(FingerprintedQName qn, String typeName) throws XPathException {
237 startElement(qn, types.get(typeName));
238 }
239
240 /**
241 * Start an element in the result tree, which will have a key attribute if a key has been pre-selected
242 *
243 * @param qn the QName of the element
244 * @param st the schema type to use when validating - null implies untyped.
245 * @throws XPathException if a dynamic error occurs
246 */
247 private void startElement(FingerprintedQName qn, SchemaType st) throws XPathException {
248 out.startElement(qn, validate && st != null ? st : UNTYPED, ExplicitLocation.UNKNOWN_LOCATION, 0);
249 if (isInMap()) {
250 String k = keys.pop();
251 k = reEscape(k);
252 if (escape) {
253 markAsEscaped(k, true);
254 }
255 out.attribute(keyQN, validate ? STRING_TYPE : SIMPLE_TYPE, k, ExplicitLocation.UNKNOWN_LOCATION, 0);
256 }
257 }
258
259 /**
260 * Write characters as a text node in the tree
261 *
262 * @param s the string to be added
263 * @throws XPathException if a dynamic error occurs
264 */
265 private void characters(String s) throws XPathException {
266 out.characters(s, ExplicitLocation.UNKNOWN_LOCATION, 0);
267 }
268
269 /**
270 * End the current element in the treel
271 *
272 * @throws XPathException if a dynamic error occurs
273 */
274 private void endElement() throws XPathException {
275 out.endElement();
276 }
277
278
279 /**
280 * Open a new array
281 *
282 * @throws XPathException if a dynamic error occurs
283 */
284
285 public void startArray() throws XPathException {
286 startElement(arrayQN, isInMap() ? "arrayWithinMapType" : "arrayType");
287 inMap.push(false);
288 }
289
290 /**
291 * Close the current array
292 *
293 * @throws XPathException if a dynamic error occurs
294 */
295
296 public void endArray() throws XPathException {
297 inMap.pop();
298 endElement();
299 }
300
301 /**
302 * Start a new object/map
303 *
304 * @throws XPathException if a dynamic error occurs
305 */
306 public void startMap() throws XPathException {
307 startElement(mapQN, isInMap() ? "mapWithinMapType": "mapType");
308 if (checkForDuplicates) {
309 mapKeys.push(new HashSet<String>());
310 }
311 inMap.push(true);
312 }
313
314 /**
315 * Close the current object/map
316 *
317 * @throws XPathException if a dynamic error occurs
318 */
319 public void endMap() throws XPathException {
320 inMap.pop();
321 if (checkForDuplicates) {
322 mapKeys.pop();
323 }
324 endElement();
325 }
326
327 /**
328 * Write a numeric value
329 *
330 * @param asString the string representation of the value
331 * @param asDouble the double representation of the value
332 * @throws XPathException if a dynamic error occurs
333 */
334 public void writeNumeric(String asString, double asDouble) throws XPathException {
335 startElement(numberQN, isInMap() ? "numberWithinMapType" : "numberType");
336 characters(asString);
337 endElement();
338 }
339
340 /**
341 * Write a string value
342 *
343 * @param val the string to be written. This will be in unescaped form if unescaping was requested
344 * in the flags, otherwise it may contain JSON escape sequences
345 * @throws XPathException if a dynamic error occurs
346 */
347 public void writeString(String val) throws XPathException {
348 startElement(stringQN, isInMap() ? "stringWithinMapType" : "stringType");
349 CharSequence escaped = reEscape(val);
350 if (escape) {
351 markAsEscaped(escaped, false);
352 }
353 characters(escaped.toString());
354 endElement();
355 }
356
357 @Override
358 protected void markAsEscaped(CharSequence escaped, boolean isKey) throws XPathException {
359 if (containsEscape(escaped.toString()) && escape) {
360 NodeName name = isKey ? escapedKeyQN : escapedQN;
361 out.attribute(name, validate ? BOOLEAN_TYPE : SIMPLE_TYPE, "true", ExplicitLocation.UNKNOWN_LOCATION, 0);
362 }
363 }
364
365 /**
366 * Write a boolean value
367 *
368 * @param value the boolean value to be written
369 * @throws XPathException if a dynamic error occurs
370 */
371 public void writeBoolean(boolean value) throws XPathException {
372 startElement(booleanQN, isInMap() ? "booleanWithinMapType" : "booleanType");
373 characters(Boolean.toString(value));
374 endElement();
375 }
376
377 /**
378 * Write a null value
379 *
380 * @throws XPathException if a dynamic error occurs
381 */
382 public void writeNull() throws XPathException {
383 startElement(nullQN, isInMap() ? "nullWithinMapType" : "nullType");
384 endElement();
385 }
386 }
387
388 // Copyright (c) 2014-2015 Saxonica Limited.