Debian Codegraph @

net/sf/saxon/serialize/JSONEmitter.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.lib.SaxonOutputKeys;
12 import net.sf.saxon.ma.json.JsonReceiver;
13 import net.sf.saxon.serialize.charcode.CharacterSet;
14 import net.sf.saxon.serialize.codenorm.Normalizer;
15 import net.sf.saxon.trans.XPathException;
16 import net.sf.saxon.tree.util.FastStringBuffer;
17 import net.sf.saxon.value.AtomicValue;
18 import net.sf.saxon.value.BooleanValue;
19 import net.sf.saxon.value.IntegerValue;
20 import net.sf.saxon.value.NumericValue;
21
22 import javax.xml.transform.OutputKeys;
23 import javax.xml.transform.stream.StreamResult;
24 import java.io.IOException;
25 import java.io.Writer;
26 import java.util.Properties;
27 import java.util.Stack;
28
29 /**
30 * This class implements the back-end text generation of the JSON serialization method. It takes
31 * as input a sequence of event-based calls such as startArray, endArray, startMap, endMap,
32 * and generates the lexical JSON output.
33 *
34 * @author Michael H. Kay
35 */
36
37 public class JSONEmitter {
38
39 private ExpandedStreamResult result;
40
41 private Writer writer;
42 private Normalizer normalizer;
43 private CharacterMap characterMap;
44 private Properties outputProperties;
45 private CharacterSet characterSet;
46 private boolean isIndenting;
47 private int indentSpaces = 2;
48 private int maxLineLength;
49 private boolean first = true;
50 private boolean afterKey = false;
51 private int level;
52 private Stack<Boolean> oneLinerStack = new Stack<>();
53
54 private boolean unfailing = false;
55
56 public JSONEmitter(PipelineConfiguration pipe, StreamResult result, Properties outputProperties) throws XPathException {
57 setOutputProperties(outputProperties);
58 this.result = new ExpandedStreamResult(pipe.getConfiguration(), result, outputProperties);
59 }
60
61 /**
62 * Set output properties
63 *
64 * @param details the output serialization properties
65 */
66
67 public void setOutputProperties(Properties details) {
68 this.outputProperties = details;
69 if ("yes".equals(details.getProperty(OutputKeys.INDENT))) {
70 isIndenting = true;
71 }
72 if ("yes".equals(details.getProperty(SaxonOutputKeys.UNFAILING))) {
73 unfailing = true;
74 }
75 String max = details.getProperty(SaxonOutputKeys.LINE_LENGTH);
76 if (max != null) {
77 try {
78 maxLineLength = Integer.parseInt(max);
79 } catch (NumberFormatException err) {
80 // ignore the error.
81 }
82 }
83 String spaces = details.getProperty(SaxonOutputKeys.INDENT_SPACES);
84 if (spaces != null) {
85 try {
86 indentSpaces = Integer.parseInt(spaces);
87 } catch (NumberFormatException err) {
88 // ignore the error.
89 }
90 }
91 }
92
93 /**
94 * Get the output properties
95 *
96 * @return the properties that were set using setOutputProperties
97 */
98
99 public Properties getOutputProperties() {
100 return outputProperties;
101 }
102
103 /**
104 * Set the Unicode normalizer to be used for normalizing strings.
105 *
106 * @param normalizer the normalizer to be used
107 */
108
109 public void setNormalizer(Normalizer normalizer) {
110 this.normalizer = normalizer;
111 }
112
113 /**
114 * Set the CharacterMap to be used, if any
115 *
116 * @param map the character map
117 */
118
119 public void setCharacterMap(CharacterMap map) {
120 this.characterMap = map;
121 }
122
123 /**
124 * Output the key for an entry in a map. The corresponding value must be supplied
125 * in the following call.
126 * @param key the value of the key, without any escaping of special characters
127 * @throws XPathException if any error occurs
128 */
129
130 public void writeKey(String key) throws XPathException {
131 conditionalComma(false);
132 emit('"');
133 emit(escape(key));
134 emit("\":");
135 if (isIndenting) {
136 emit(" ");
137 }
138 afterKey = true;
139 }
140
141 /**
142 * Append a singleton value (number, string, or boolean) to the output
143 *
144 * @param item the atomic value to be appended, or null to append "null"
145 * @throws XPathException if the operation fails
146 */
147
148 public void writeAtomicValue(AtomicValue item) throws XPathException {
149 conditionalComma(false);
150 if (item == null) {
151 emit("null");
152 } else if (item instanceof NumericValue) {
153 NumericValue num = (NumericValue)item;
154 if (num.isNaN()) {
155 if (unfailing) {
156 emit("NaN");
157 } else {
158 throw new XPathException("JSON has no way of representing NaN", "SERE0020");
159 }
160 } else if (Double.isInfinite(num.getDoubleValue())) {
161 if (unfailing) {
162 emit(num.getDoubleValue() < 0 ? "-INF" : "INF");
163 } else {
164 throw new XPathException("JSON has no way of representing Infinity", "SERE0020");
165 }
166 } else if (item instanceof IntegerValue) {
167 // " Implementations MAY serialize the numeric value using any
168 // lexical representation of a JSON number defined in [RFC 7159]. "
169 // This avoids exponential notation for integers such as 1123456.
170 emit(num.longValue() + "");
171 } else if (num.isWholeNumber() && !num.isNegativeZero() && num.abs().compareTo(1_000_000_000_000_000_000L) < 0) {
172 emit(num.longValue() + "");
173 } else {
174 emit(num.getStringValue());
175 }
176 } else if (item instanceof BooleanValue) {
177 emit(item.getStringValue());
178 } else {
179 emit('"');
180 emit(escape(item.getStringValue()));
181 emit('"');
182 }
183 }
184
185 /**
186 * Output the start of an array. This call must be followed by the members of the
187 * array, followed by a call on {@link #endArray()}.
188 * @param oneLiner True if the caller thinks the value should be output without extra newlines
189 * after the open bracket or before the close bracket,
190 * even when indenting is on.
191 * @throws XPathException if any failure occurs
192 */
193
194 public void startArray(boolean oneLiner) throws XPathException {
195 emitOpen('[', oneLiner);
196 level++;
197 }
198
199 /**
200 * Output the end of an array
201 * @throws XPathException if any failure occurs
202 */
203
204 public void endArray() throws XPathException {
205 emitClose(']', level--);
206 }
207
208 /**
209 * Output the start of an map. This call must be followed by the entries in the
210 * map (each starting with a call on {@link #writeKey(String)}, followed by a call on
211 * {@link #endMap()}.
212 *
213 * @param oneLiner True if the caller thinks the value should be output without extra newlines
214 * after the open bracket or before the close bracket,
215 * even when indenting is on.
216 * @throws XPathException if any failure occurs
217 */
218
219 public void startMap(boolean oneLiner) throws XPathException {
220 emitOpen('{', oneLiner);
221 level++;
222 }
223
224 public void endMap() throws XPathException {
225 emitClose('}', level--);
226 }
227
228 private void emitOpen(char bracket, boolean oneLiner) throws XPathException {
229 conditionalComma(true);
230 oneLinerStack.push(oneLiner);
231 // if (isIndenting) {
232 // emit(' ');
233 // }
234 emit(bracket);
235 first = true;
236 if (isIndenting) {
237 if (oneLiner) {
238 emit(' ');
239 } else {
240 //indent(level + 1);
241 }
242 }
243
244 }
245
246 private void emitClose(char bracket, int level) throws XPathException {
247 boolean oneLiner = oneLinerStack.pop();
248 if (isIndenting) {
249 if (oneLiner) {
250 emit(' ');
251 } else {
252 indent(level);
253 }
254 }
255 emit(bracket);
256 first = false;
257
258 }
259
260 private void conditionalComma(boolean opening) throws XPathException {
261 boolean wasFirst = first;
262 if (first) {
263 first = false;
264 } else if (!afterKey) {
265 emit(',');
266 }
267 if (wasFirst && afterKey) {
268 emit(' ');
269 } else if (isIndenting && !afterKey && level != 0) {
270 emit('\n');
271 for (int i = 0; i < indentSpaces * (level + 1); i++) {
272 emit(' ');
273 }
274 }
275 afterKey = false;
276 }
277
278 private void indent(int level) throws XPathException {
279 emit('\n');
280 for (int i = 0; i < indentSpaces * level; i++) {
281 emit(' ');
282 }
283 }
284
285 private CharSequence escape(CharSequence cs) throws XPathException {
286 if (characterMap != null) {
287 FastStringBuffer out = new FastStringBuffer(cs.length());
288 cs = characterMap.map(cs, true);
289 String s = cs.toString();
290 int prev = 0;
291 while (true) {
292 int start = s.indexOf(0, prev);
293 if (start >= 0) {
294 out.append(simpleEscape(s.substring(prev, start)));
295 int end = s.indexOf(0, start + 1);
296 out.append(s.substring(start + 1, end));
297 prev = end + 1;
298 } else {
299 out.append(simpleEscape(s.substring(prev)));
300 return out;
301 }
302 }
303 } else {
304 return simpleEscape(cs);
305 }
306 }
307
308 private CharSequence simpleEscape(CharSequence cs) throws XPathException {
309 if (normalizer != null) {
310 cs = normalizer.normalize(cs);
311 }
312 return JsonReceiver.escape(cs, false,
313 c -> c < 31 || (c >= 127 && c <= 159) || !characterSet.inCharset(c));
314 }
315
316 private void emit(CharSequence s) throws XPathException {
317 if (writer == null) {
318 writer = result.obtainWriter();
319 characterSet = result.getCharacterSet();
320 }
321 try {
322 writer.append(s);
323 } catch (IOException e) {
324 throw new XPathException(e);
325 }
326 }
327
328 private void emit(char c) throws XPathException {
329 emit(c + "");
330 }
331
332
333 /**
334 * End of the document.
335 */
336
337 public void close() throws XPathException {
338 if (first) {
339 emit("null");
340 }
341 if (writer != null) {
342 try {
343 writer.close();
344 } catch (IOException e) {
345 // no action
346 }
347 }
348 }
349 }
350