/
JsonEncoder.java
356 lines (314 loc) · 10.7 KB
/
JsonEncoder.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
/*
* Copyright 2013, 2014 Deutsche Nationalbibliothek
*
* Licensed under the Apache License, Version 2.0 the "License";
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.metafacture.json;
import org.metafacture.framework.FluxCommand;
import org.metafacture.framework.MetafactureException;
import org.metafacture.framework.ObjectReceiver;
import org.metafacture.framework.StreamReceiver;
import org.metafacture.framework.annotations.Description;
import org.metafacture.framework.annotations.In;
import org.metafacture.framework.annotations.Out;
import org.metafacture.framework.helpers.DefaultStreamPipe;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonStreamContext;
import com.fasterxml.jackson.core.SerializableString;
import com.fasterxml.jackson.core.io.CharacterEscapes;
import com.fasterxml.jackson.core.io.SerializedString;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import java.io.IOException;
import java.io.StringWriter;
/**
* Serialises an object as JSON. Records and entities are represented
* as objects unless their name ends with []. If the name ends with [],
* an array is created.
*
* @author Christoph Böhme
* @author Michael Büchner
*
*/
@Description("Serialises an object as JSON")
@In(StreamReceiver.class)
@Out(String.class)
@FluxCommand("encode-json")
public final class JsonEncoder extends DefaultStreamPipe<ObjectReceiver<String>> {
public static final String ARRAY_MARKER = "[]";
public static final String BOOLEAN_MARKER = null;
public static final String NUMBER_MARKER = null;
private static final char ESCAPE_CHAR_LOW = 0x20;
private static final char ESCAPE_CHAR_HIGH = 0x7f;
private final JsonGenerator jsonGenerator;
private final StringWriter writer = new StringWriter();
private String arrayMarker = ARRAY_MARKER;
private String booleanMarker = BOOLEAN_MARKER;
private String numberMarker = NUMBER_MARKER;
/**
* Constructs a JsonEncoder if no IOException occurs. The root value
* separator of the JsonGenerator is set to null.
*/
public JsonEncoder() {
try {
jsonGenerator = new JsonFactory().createGenerator(writer);
jsonGenerator.setRootValueSeparator(null);
}
catch (final IOException e) {
throw new MetafactureException(e);
}
}
/**
* Sets the array marker.
*
* @param arrayMarker the array marker
*/
public void setArrayMarker(final String arrayMarker) {
this.arrayMarker = arrayMarker;
}
/**
* Gets the array marker.
*
* @return the array marker
*/
public String getArrayMarker() {
return arrayMarker;
}
/**
* Sets the boolean marker.
*
* @param booleanMarker the boolean marker
*/
public void setBooleanMarker(final String booleanMarker) {
this.booleanMarker = booleanMarker;
}
/**
* Gets the boolean marker.
*
* @return the boolean marker
*/
public String getBooleanMarker() {
return booleanMarker;
}
/**
* Sets the number marker.
*
* @param numberMarker the number marker
*/
public void setNumberMarker(final String numberMarker) {
this.numberMarker = numberMarker;
}
/**
* Gets the number marker.
*
* @return the number marker
*/
public String getNumberMarker() {
return numberMarker;
}
/**
* Flags whether to use pretty printing.
*
* @param prettyPrinting true if pretty printing should be used
*/
public void setPrettyPrinting(final boolean prettyPrinting) {
jsonGenerator.setPrettyPrinter(prettyPrinting ? new DefaultPrettyPrinter((SerializableString) null) : null);
}
/**
* Checks if the {@link JsonGenerator} has a pretty printer.
*
* @return true if {@link JsonGenerator} has a pretty printer.
*/
public boolean getPrettyPrinting() {
return jsonGenerator.getPrettyPrinter() != null;
}
/**
* By default JSON output does only have escaping where it is strictly
* necessary. This is recommended in the most cases. Nevertheless it can
* be sometimes useful to have some more escaping.
*
* @param escapeCharacters an array which defines which characters should be
* escaped and how it will be done. See
* {@link CharacterEscapes}. In most cases this should
* be null. Use like this:
* <pre>{@code int[] esc = CharacterEscapes.standardAsciiEscapesForJSON();
* // and force escaping of a few others:
* esc['\''] = CharacterEscapes.ESCAPE_STANDARD;
* JsonEncoder.useEscapeJavaScript(esc);
* }</pre>
*/
public void setJavaScriptEscapeChars(final int[] escapeCharacters) {
final CharacterEscapes ce = new CharacterEscapes() {
private static final long serialVersionUID = 1L;
@Override
public int[] getEscapeCodesForAscii() {
if (escapeCharacters == null) {
return CharacterEscapes.standardAsciiEscapesForJSON();
}
return escapeCharacters;
}
@Override
public SerializableString getEscapeSequence(final int ch) {
final String jsEscaped = escapeChar((char) ch);
return new SerializedString(jsEscaped);
}
};
jsonGenerator.setCharacterEscapes(ce);
}
@Override
public void startRecord(final String id) {
final StringBuffer buffer = writer.getBuffer();
buffer.delete(0, buffer.length());
startGroup(id);
}
@Override
public void endRecord() {
endGroup();
try {
jsonGenerator.flush();
}
catch (final IOException e) {
throw new MetafactureException(e);
}
getReceiver().process(writer.toString());
}
@Override
public void startEntity(final String name) {
startGroup(name);
}
@Override
public void endEntity() {
endGroup();
}
@Override
public void literal(final String name, final String value) {
try {
final JsonStreamContext ctx = jsonGenerator.getOutputContext();
if (ctx.inObject()) {
jsonGenerator.writeFieldName(getUnmarkedName(name, booleanMarker, numberMarker));
}
if (value == null) {
jsonGenerator.writeNull();
}
else if (isMarkedName(name, booleanMarker)) {
jsonGenerator.writeBoolean(Boolean.parseBoolean(value));
}
else if (isMarkedName(name, numberMarker)) {
jsonGenerator.writeNumber(value);
}
else {
jsonGenerator.writeString(value);
}
}
catch (final JsonGenerationException e) {
throw new MetafactureException(e);
}
catch (final IOException e) {
throw new MetafactureException(e);
}
}
private void startGroup(final String name) {
try {
final JsonStreamContext ctx = jsonGenerator.getOutputContext();
if (isMarkedName(name, arrayMarker)) {
if (ctx.inObject()) {
jsonGenerator.writeFieldName(getUnmarkedName(name, arrayMarker));
}
jsonGenerator.writeStartArray();
}
else {
if (ctx.inObject()) {
jsonGenerator.writeFieldName(name);
}
jsonGenerator.writeStartObject();
}
}
catch (final JsonGenerationException e) {
throw new MetafactureException(e);
}
catch (final IOException e) {
throw new MetafactureException(e);
}
}
private void endGroup() {
try {
final JsonStreamContext ctx = jsonGenerator.getOutputContext();
if (ctx.inObject()) {
jsonGenerator.writeEndObject();
}
else if (ctx.inArray()) {
jsonGenerator.writeEndArray();
}
}
catch (final JsonGenerationException e) {
throw new MetafactureException(e);
}
catch (final IOException e) {
throw new MetafactureException(e);
}
}
private boolean isMarkedName(final String name, final String marker) {
return marker != null && name.endsWith(marker);
}
private String getUnmarkedName(final String name, final String... markers) {
for (final String marker : markers) {
if (isMarkedName(name, marker)) {
return name.substring(0, name.length() - marker.length());
}
}
return name;
}
private String escapeChar(final char ch) {
final String namedEscape = namedEscape(ch);
return namedEscape != null ? namedEscape : (ch < ESCAPE_CHAR_LOW || ESCAPE_CHAR_HIGH < ch) ? unicodeEscape(ch) : Character.toString(ch);
}
private String namedEscape(final char ch) {
final String result;
switch (ch) {
case '\b':
result = "\\b";
break;
case '\n':
result = "\\n";
break;
case '\t':
result = "\\t";
break;
case '\f':
result = "\\f";
break;
case '\r':
result = "\\r";
break;
case '\'':
result = "\\'";
break;
case '\\':
result = "\\\\";
break;
case '"':
result = "\\\"";
break;
case '/':
result = "\\/";
break;
default:
result = null;
}
return result;
}
private String unicodeEscape(final char ch) {
return String.format("\\u%4H", ch).replace(' ', '0');
}
}