Debian Codegraph @

net/sf/saxon/ma/json/JsonHandler.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.expr.XPathContext;
11 import net.sf.saxon.functions.SystemFunction;
12 import net.sf.saxon.om.Function;
13 import net.sf.saxon.om.Item;
14 import net.sf.saxon.om.Sequence;
15 import net.sf.saxon.serialize.charcode.UTF16CharacterSet;
16 import net.sf.saxon.trans.XPathException;
17 import net.sf.saxon.tree.util.FastStringBuffer;
18 import net.sf.saxon.type.SpecificFunctionType;
19 import net.sf.saxon.value.SequenceType;
20 import net.sf.saxon.value.StringValue;
21
22 import java.util.function.IntPredicate;
23
24 import java.util.Map;
25
26 /**
27 * Default handler class for accepting the result from parsing JSON strings
28 */
29 public class JsonHandler {
30
31 public boolean escape;
32 protected IntPredicate charChecker;
33 private XPathContext context;
34
35 private Function fallbackFunction = null;
36 private static final String REPLACEMENT = "\ufffd";
37
38 public void setContext(XPathContext context) {
39 this.context = context;
40 }
41
42 public XPathContext getContext() {
43 return context;
44 }
45
46 public Sequence<?> getResult() throws XPathException {
47 return null;
48 }
49
50 /**
51 * Set the key to be written for the next entry in an object/map
52 *
53 * @param unEscaped the key for the entry (null implies no key) in unescaped form (backslashes,
54 * if present, do not signal an escape sequence)
55 * @param reEscaped the key for the entry (null implies no key) in reescaped form. In this form
56 * special characters are represented as backslash-escaped sequences if the escape
57 * option is yes; if escape=no, the reEscaped form is the same as the unEscaped form.
58 * @return true if the key is already present in the map, false if it is not
59 */
60 public boolean setKey(String unEscaped, String reEscaped) {
61 return false;
62 }
63
64 /**
65 * Open a new array
66 *
67 * @throws XPathException if any error occurs
68 */
69 public void startArray() throws XPathException {}
70
71 /**
72 * Close the current array
73 *
74 * @throws XPathException if any error occurs
75 */
76 public void endArray() throws XPathException {}
77
78 /**
79 * Start a new object/map
80 *
81 * @throws XPathException if any error occurs
82 */
83 public void startMap() throws XPathException {}
84
85 /**
86 * Close the current object/map
87 *
88 * @throws XPathException if any error occurs
89 */
90 public void endMap() throws XPathException {}
91
92 /**
93 * Write a numeric value
94 *
95 * @param asString the string representation of the value
96 * @param asDouble the double representation of the value
97 * @throws XPathException if any error occurs
98 */
99 public void writeNumeric(String asString, double asDouble) throws XPathException {}
100
101 /**
102 * Write a string value
103 *
104 * @param val The string to be written (which may or may not contain JSON escape sequences, according to the
105 * options that were set)
106 * @throws XPathException if any error occurs
107 */
108 public void writeString(String val) throws XPathException {}
109
110 /**
111 * Optionally apply escaping or unescaping to a value.
112 * @param val the string to be escaped or unEscaped
113 * @return the escaped or unescaped string
114 * @throws XPathException
115 */
116
117 public String reEscape(String val) throws XPathException {
118 CharSequence escaped;
119 if (escape) {
120 escaped = JsonReceiver.escape(val, true, new IntPredicate() {
121 public boolean test(int value) {
122 return (value >= 0 && value <= 0x1F) ||
123 (value >= 0x7F && value <= 0x9F) ||
124 !charChecker.test(value) ||
125 (value == 0x5C);
126 }
127 });
128 } else {
129 FastStringBuffer buffer = new FastStringBuffer(val);
130 handleInvalidCharacters(buffer);
131 escaped = buffer;
132 }
133 return escaped.toString();
134 }
135
136 /**
137 * Write a boolean value
138 * @param value the boolean value to be written
139 * @throws XPathException if any error occurs
140 */
141 public void writeBoolean(boolean value) throws XPathException {}
142
143 /**
144 * Write a null value
145 *
146 * @throws XPathException if any error occurs
147 */
148 public void writeNull() throws XPathException {}
149
150 /**
151 * Deal with invalid characters in the JSON string
152 * @param buffer the JSON string
153 * @throws XPathException if any error occurs
154 */
155 protected void handleInvalidCharacters(FastStringBuffer buffer) throws XPathException {
156 //if (checkSurrogates && !liberal) {
157 IntPredicate charChecker = context.getConfiguration().getValidCharacterChecker();
158 for (int i = 0; i < buffer.length(); i++) {
159 char ch = buffer.charAt(i);
160 if (UTF16CharacterSet.isHighSurrogate(ch)) {
161 if (i + 1 >= buffer.length() || !UTF16CharacterSet.isLowSurrogate(buffer.charAt(i + 1))) {
162 substitute(buffer, i, 1, context);
163 }
164 } else if (UTF16CharacterSet.isLowSurrogate(ch)) {
165 if (i == 0 || !UTF16CharacterSet.isHighSurrogate(buffer.charAt(i - 1))) {
166 substitute(buffer, i, 1, context);
167 } else {
168 int pair = UTF16CharacterSet.combinePair(buffer.charAt(i - 1), ch);
169 if (!charChecker.test(pair)) {
170 substitute(buffer, i - 1, 2, context);
171 }
172 }
173 } else {
174 if (!charChecker.test(ch)) {
175 substitute(buffer, i, 1, context);
176 }
177 }
178 }
179 //}
180 }
181
182 protected void markAsEscaped(CharSequence escaped, boolean isKey) throws XPathException {
183 // do nothing in this class
184 }
185
186 /**
187 * Replace an character or two characters within a string buffer, either by executing the replacement function,
188 * or using the default Unicode replacement character
189 *
190 * @param buffer the string buffer, which is modified by this call
191 * @param offset the position of the characters to be replaced
192 * @param count the number of characters to be replaced
193 * @param context the XPath context
194 * @throws XPathException if the callback function throws an exception
195 */
196 private void substitute(FastStringBuffer buffer, int offset, int count, XPathContext context) throws XPathException {
197 FastStringBuffer escaped = new FastStringBuffer(count*6);
198 for (int j=0; j<count; j++) {
199 escaped.append("\\u");
200 String hex = Integer.toHexString(buffer.charAt(offset + j));
201 while (hex.length() < 4) {
202 hex = "0" + hex;
203 }
204 hex = hex.toUpperCase(); // cheat to get through test json-to-xml-039
205 escaped.append(hex);
206 }
207 String replacement = replace(escaped.toString(), context);
208 if (replacement.length() == count) {
209 for (int j = 0; j < count; j++) {
210 buffer.setCharAt(offset + j, replacement.charAt(j));
211 }
212 } else {
213 for (int j = 0; j < count; j++) {
214 buffer.removeCharAt(offset + j);
215 }
216 for (int j=0; j < replacement.length(); j++) {
217 buffer.insert(offset + j, replacement.charAt(j));
218 }
219 }
220 }
221
222 /**
223 * Replace an illegal XML character, either by executing the replacement function,
224 * or using the default Unicode replacement character
225 *
226 * @param s the string representation of the illegal character
227 * @param context the XPath context
228 * @return the replacement string
229 * @throws XPathException if the callback function throws an exception
230 */
231 private String replace(String s, XPathContext context) throws XPathException {
232 if (fallbackFunction != null) {
233 Sequence<?>[] args = new Sequence[1];
234 args[0] = new StringValue(s);
235 Sequence<?> result = SystemFunction.dynamicCall(fallbackFunction, context, args).head();
236 Item first = result.head();
237 return first == null ? "" : first.getStringValue();
238 } else {
239 return REPLACEMENT;
240 }
241 }
242
243 public void setFallbackFunction(Map<String, Sequence<?>> options, XPathContext context) throws XPathException {
244 Sequence<?> val = options.get("fallback");
245 if (val != null) {
246 Item fn = val.head();
247 if (fn instanceof Function) {
248 fallbackFunction = (Function) fn;
249 if (fallbackFunction.getArity() != 1) {
250 throw new XPathException("Fallback function must have arity=1", "FOJS0005");
251 }
252 SpecificFunctionType required = new SpecificFunctionType(
253 new SequenceType[]{SequenceType.SINGLE_STRING}, SequenceType.ANY_SEQUENCE);
254 if (!required.matches(fallbackFunction, context.getConfiguration().getTypeHierarchy())) {
255 throw new XPathException("Fallback function does not match the required type", "FOJS0005");
256 }
257 } else {
258 throw new XPathException("Value of option 'fallback' is not a function", "FOJS0005");
259 }
260 }
261 }
262 }
263
264 // Copyright (c) 2018 Saxonica Limited.