-
Notifications
You must be signed in to change notification settings - Fork 1
/
ESBulkEncoder.java
370 lines (336 loc) · 12.7 KB
/
ESBulkEncoder.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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
package org.swissbib.linked.mf.pipe;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
/**
* Serialises an object as JSON-LD.
*
* @author Sebastian Schüpbach, project swissbib, Basel
*/
@Description("Serialises an object as JSON-LD")
@In(StreamReceiver.class)
@Out(String.class)
public final class ESBulkEncoder extends DefaultStreamPipe<ObjectReceiver<String>> {
private static final char COMMA = ','; // Comma transition (e.g. between value and parent)
private static final String NONE = ""; // No transition
private static final byte BNODE = 0; // Node without key
private static final byte OBJECT = 1;
private static final byte ARRAY = 2;
private static final byte KEY = 3; // Equals literal ""<Name>""
private static final byte VALUE = 4; // Equals literal ""<Name>""
private final static Logger LOG = LoggerFactory.getLogger(ESBulkEncoder.class);
private Multimap<JsonToken, JsonToken> ctxRegistry; // Registers root parent of every parent
private boolean makeChildNode; // Set next key as child node of current node
private JsonToken node; // Current node
private JsonToken rootNode; // Current root node
private String outputString = "";
private boolean header = true; // Should bulk-header be printed?
private boolean escapeChars = true; // Should prohibited characters in JSON string be escaped?
private String type; // Type of record
private String index; // Index of record
private boolean avoidMergers = false;
/**
* Should header be created?
*
* @param header true, false
*/
public void setHeader(String header) {
this.header = Boolean.parseBoolean(header);
LOG.debug("Settings - Write header: {}", header);
}
/**
* Escape prohibited characters in JSON strings
*
* @param escapeChars true, false
*/
public void setEscapeChars(String escapeChars) {
this.escapeChars = Boolean.parseBoolean(escapeChars);
LOG.debug("Settings - Escape problematic characters: {}", escapeChars);
}
/**
* Sets index of record
*
* @param index Index of record
*/
public void setIndex(String index) {
this.index = index;
LOG.debug("Settings - Set index name: {}", index);
}
/**
* Sets type of record
*
* @param type Type of record
*/
public void setType(String type) {
this.type = type;
LOG.debug("Settings - Set type: {}", type);
}
public void setAvoidMergers(String avoidMergers) {
this.avoidMergers = Boolean.parseBoolean(avoidMergers);
}
@Override
public void startRecord(String id) {
LOG.debug("Parsing record {}", id);
ctxRegistry = HashMultimap.create();
node = new JsonToken(BNODE, null, null);
rootNode = node;
makeChildNode = true;
outputString = (header) ? "{\"index\":{\"_type\":\"" + type + "\",\"_index\":\"" +
index + "\",\"_id\":\"" + id + "\"}}\n" :
"";
}
@Override
public void endRecord() {
if (rootNode != null) {
LOG.debug("Serializing record to JSON-LD");
outputString += "{" + buildJsonString((byte) -1, rootNode) + "}\n";
LOG.trace("Sending record to {}", getReceiver().getClass());
getReceiver().process(outputString);
}
}
@Override
public void startEntity(String name) {
buildKey(name);
makeChildNode = true;
if (name.endsWith("{}") || avoidMergers) node = new JsonToken(BNODE, null, getParentNode());
}
@Override
public void endEntity() {
if (node.getChildren().size() == 0) {
new JsonToken(VALUE, "", node);
LOG.debug("Entity {} does not have a child node. Creating one with empty name (preventing key with no value.",
node.getName());
}
node = node.getParent();
if (node.getType() == BNODE) node = node.getParent();
}
@Override
public void literal(String name, String value) {
buildKey(name);
new JsonToken(VALUE, value, node);
}
/**
* Creates a new parent token
*
* @param name Name of parent
*/
private void buildKey(String name) {
JsonToken sameNode = checkKeyExists(getParentNode(), name);
node = (sameNode == null) ?
new JsonToken(KEY, name, getParentNode()) :
sameNode;
ctxRegistry.put(node.getParent(), node);
makeChildNode = false;
}
/**
* Checks if a parent with same name and same root parent (context) exists
*
* @param rootKey Reference to root parent
* @param name Name of parent
* @return JsonToken Root parent, if a parent has been found, otherwise null
*/
private JsonToken checkKeyExists(JsonToken rootKey, String name) {
if (name.endsWith("{}")) name = name.substring(0, name.length() - 2);
JsonToken foundKey = null;
if (ctxRegistry.containsKey(rootKey)) {
for (JsonToken jt : ctxRegistry.get(rootKey)) {
if (jt.getName().equals(name)) {
LOG.trace("Merging key {}", name);
foundKey = jt;
}
}
}
return foundKey;
}
/**
* Gets parent node
*
* @return Parent node
*/
private JsonToken getParentNode() {
return makeChildNode ? node : node.getParent();
}
/**
* Builds JSON string
*
* @return JSON string
*/
private String buildJsonString(byte lastTokenType, JsonToken jt) {
StringBuilder stringBuilder = new StringBuilder();
for (JsonToken child : jt.getChildren()) {
// Set prefixes if required
if (lastTokenType == OBJECT || lastTokenType == ARRAY) {
stringBuilder.append((child.getType() == KEY || child.getType() == BNODE) ? COMMA : NONE);
} else if (lastTokenType == VALUE) {
stringBuilder.append((child.getType() == KEY || child.getType() == VALUE) ? COMMA : NONE);
}
// Set name of key / value
stringBuilder.append(child.toString());
// Descend to child nodes if present
if (child.getType() == KEY || child.getType() == BNODE) {
switch (child.getParentheses()) {
case 0:
stringBuilder.append(":");
stringBuilder.append(buildJsonString((byte) 0, child));
lastTokenType = VALUE;
break;
case OBJECT:
if (child.getType() != BNODE) stringBuilder.append(":");
stringBuilder.append("{");
stringBuilder.append(buildJsonString((byte) 0, child));
stringBuilder.append("}");
lastTokenType = OBJECT;
break;
case ARRAY:
stringBuilder.append(":[");
stringBuilder.append(buildJsonString((byte) 0, child));
stringBuilder.append("]");
lastTokenType = ARRAY;
break;
}
} else {
lastTokenType = VALUE;
}
}
return stringBuilder.toString();
}
/**
* Contains information on a Json token (e.g. parent) and methods to query, modify and serialize it.
*/
private class JsonToken {
final byte type; // Type of the token
final String name; // Name (only if type == parent / value, else null)
final List<JsonToken> children = new ArrayList<>(); // Last element belonging to the parent (parent only, else null)
final JsonToken parent; // Key which token belongs to (for parent: root parent)
byte parentheses = -1; // Parentheses which surrounds descendants (none, brackets or braces)
/**
* Constructor for class JsonToken
*
* @param type Type of token (one of ROOT_NODE, OBJECT, ARRAY, END_OBJECT, END_ARRAY, KEY, VALUE)
* @param name Name of token (only if type == KEY or VALUE, else null)
* @param parent Refers to parent id of which a token belongs to (parent refer to their root parent)
*/
JsonToken(byte type, String name, JsonToken parent) {
this.type = type;
if (name == null) name = "";
if (name.endsWith("{}")) name = name.substring(0, name.length() - 2);
this.name = (escapeChars && !(name.equals(""))) ? escChars(name) : name;
this.parent = parent;
if (parent != null) parent.setChildren(this);
if (type == BNODE) this.parentheses = OBJECT;
}
/**
* Prints respective literal
*
* @return Literal
*/
@Override
public String toString() {
switch (this.getType()) {
case BNODE:
return NONE;
case KEY:
return "\"" + this.getName() + "\"";
case VALUE:
return "\"" + this.getName() + "\"";
default:
return NONE;
}
}
/**
* Gets name of this JSON token
*/
String getName() {
return name;
}
/**
* Gets descendants of node
*
* @return Last element
*/
List<JsonToken> getChildren() {
return children;
}
/**
* Adds a new descendant to node and probably sets new value for variable parentheses
*
* @param jt Respective JSON token
*/
void setChildren(JsonToken jt) {
if (jt.getType() == KEY) parentheses = OBJECT;
if ((parentheses == 0 && (jt.getType() == VALUE) | jt.getType() == BNODE)) parentheses = ARRAY;
if (parentheses == -1 && (jt.getType() == VALUE | jt.getType() == BNODE)) parentheses = 0;
children.add(jt);
}
/**
* Gets parent node
*
* @return Parent node
*/
JsonToken getParent() {
return parent;
}
/**
* Gets type of JSON token (ROOT_NODE, KEY, VALUE)
*
* @return Type of JSON token
*/
byte getType() {
return type;
}
/**
* Gets parentheses category (none, brackets or braces)
*
* @return Parantheses type (in byte)
*/
byte getParentheses() {
return parentheses;
}
String escChars(String value) {
StringBuilder stringBuilder = new StringBuilder();
String t;
for (char c : value.toCharArray()) {
switch (c) {
case '\\':
case '"':
stringBuilder.append('\\');
stringBuilder.append(c);
break;
case '\b':
stringBuilder.append("\\b");
break;
case '\t':
stringBuilder.append("\\t");
break;
case '\n':
stringBuilder.append("\\n");
break;
case '\f':
stringBuilder.append("\\f");
break;
case '\r':
stringBuilder.append("\\r");
break;
default:
if (c < ' ') {
t = "000" + Integer.toHexString(c);
stringBuilder.append("\\u");
stringBuilder.append(t.substring(t.length() - 4));
} else {
stringBuilder.append(c);
}
}
}
return stringBuilder.toString();
}
}
}