-
Notifications
You must be signed in to change notification settings - Fork 9
/
JsonDocument.java
1359 lines (1255 loc) · 46.3 KB
/
JsonDocument.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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright 2015 Jan Lolling jan.lolling@gmail.com
*
* 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 de.jlo.talendcomp.json;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.MissingNode;
import com.fasterxml.jackson.databind.node.NullNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.ValueNode;
import com.github.fge.jsonschema.core.exceptions.ProcessingException;
import com.github.fge.jsonschema.core.report.ProcessingMessage;
import com.github.fge.jsonschema.core.report.ProcessingReport;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
import com.github.fge.jsonschema.main.JsonValidator;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.ParseContext;
import com.jayway.jsonpath.PathNotFoundException;
import com.jayway.jsonpath.spi.json.JacksonJsonNodeJsonProvider;
import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider;
/**
* Convenient class to work with the Jackson-API for JSON
*/
public class JsonDocument {
public static final String NULL_STRING = "null";
public static final Integer NULL_INTEGER = Integer.MAX_VALUE;
public static final Long NULL_LONG = Long.MAX_VALUE;
public static final Double NULL_DOUBLE = Double.MAX_VALUE;
public static final Float NULL_FLOAT = Float.MAX_VALUE;
public static final Short NULL_SHORT = Short.MAX_VALUE;
public static final BigDecimal NULL_BIGDECIMAL = new BigDecimal(Long.MAX_VALUE);
public static final BigInteger NULL_BIGINTEGER = new BigInteger(String.valueOf(Long.MAX_VALUE));
public static final Date NULL_DATE = new Date(Long.MAX_VALUE);
private JsonNode rootNode = null;
private final static ObjectMapper objectMapper = new ObjectMapper();
private static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd'T'HH:mm:ss.SSS";
private final Map<String, SimpleDateFormat> dateFormatMap = new HashMap<String, SimpleDateFormat>();
private DocumentContext rootContext = null;
private static final Configuration JACKSON_JSON_NODE_CONFIGURATION = Configuration
.builder()
.mappingProvider(new JacksonMappingProvider())
.jsonProvider(new JacksonJsonNodeJsonProvider())
.build();
private final ParseContext parseContext = JsonPath.using(JACKSON_JSON_NODE_CONFIGURATION);
private static final ParseContext staticParseContext = JsonPath.using(JACKSON_JSON_NODE_CONFIGURATION);
private final Map<String, JsonPath> compiledPathMap = new HashMap<String, JsonPath>();
private String currentPath = "";
private Locale defaultLocale = Locale.getDefault();
private static final Map<String, JsonNode> schemaMap = new HashMap<String, JsonNode>();
private static final JsonSchemaFactory schemaFactory = JsonSchemaFactory.byDefault();
public JsonDocument(boolean isArray) {
if (isArray) {
rootContext = parseContext.parse("[]");
} else {
rootContext = parseContext.parse("{}");
}
rootNode = rootContext.read("$");
JsonNode testNode = rootContext.read("$");
if (rootNode != testNode) {
throw new IllegalStateException("Cloned objects detected! Use the latest Jayway library 2.2.1+");
}
}
public JsonDocument(String jsonContent) {
if (jsonContent != null && jsonContent.trim().isEmpty() == false) {
rootContext = parseContext.parse(jsonContent);
} else {
throw new IllegalArgumentException("Json input content cannot be empty or null");
}
rootNode = rootContext.read("$");
JsonNode testNode = rootContext.read("$");
if (rootNode != testNode) {
throw new IllegalStateException("Cloned objects detected! Use the latest Jayway library 2.2.1+");
}
}
public JsonDocument(File jsonFile) throws Exception {
if (jsonFile != null) {
if (jsonFile.exists() == false) {
throw new Exception("JSON input file: " + jsonFile.getAbsolutePath() + " does not exists or is not readable!");
}
InputStream in = new FileInputStream(jsonFile);
rootContext = parseContext.parse(in);
// parseContext closes this stream
} else {
throw new IllegalArgumentException("Json input input file cannot be null!");
}
rootNode = rootContext.read("$");
JsonNode testNode = rootContext.read("$");
if (rootNode != testNode) {
throw new IllegalStateException("Clones objects detected! Use the latest Jayway library 2.2.1+");
}
}
public JsonDocument(JsonNode jsonNode) throws Exception {
if (jsonNode == null || jsonNode.isNull()) {
throw new IllegalArgumentException("jsonNode cannor be null or a NullNode");
}
ParseContext parseContext = JsonPath.using(JACKSON_JSON_NODE_CONFIGURATION);
rootContext = parseContext.parse(jsonNode);
rootNode = jsonNode;
JsonNode testNode = rootContext.read("$");
if (rootNode != testNode) {
throw new IllegalStateException("Clones objects detected! Use the latest Jayway library 2.2.1+");
}
}
public DocumentContext getDocumentContext() {
return rootContext;
}
public boolean isArray() {
return rootNode.isArray();
}
public int getCountRootObjects() {
return getCountObjects(rootNode);
}
public boolean isEmpty() {
if (rootNode instanceof ArrayNode || rootNode instanceof ObjectNode) {
return rootNode.size() == 0;
} else if (rootNode != null) {
if (rootNode.isNull()) {
return true;
} else {
return false;
}
} else {
return false;
}
}
public int getCountObjects(JsonNode node) {
if (node instanceof ArrayNode) {
return node.size();
} else if (node instanceof ObjectNode) {
return 1;
} else {
return 0;
}
}
public ObjectNode createEmptyNode() {
return objectMapper.createObjectNode();
}
public ObjectNode createObjectNode(String name) {
ObjectNode child = ((ObjectNode) rootNode).objectNode();
if (isArray()) {
throw new IllegalStateException("Root is an array, use addObjectNode instead!");
}
((ObjectNode) rootNode).set(name, child);
return child;
}
public ObjectNode addObjectNode(String name) {
ObjectNode child = ((ArrayNode) rootNode).objectNode();
if (isArray() == false) {
throw new IllegalStateException("Root is an array, use addObjectNode instead!");
}
((ArrayNode) rootNode).add(child);
return child;
}
public ObjectNode addObjectNode(JsonNode parent, String name) {
if (parent instanceof ArrayNode) {
ObjectNode child = ((ArrayNode) parent).objectNode();
((ArrayNode) parent).add(child);
return child;
} else {
throw new IllegalArgumentException("parent must be an ArrayNode!");
}
}
public ArrayNode addArrayNode(JsonNode parent, String name) {
if (parent instanceof ArrayNode) {
ArrayNode child = ((ArrayNode) parent).arrayNode();
((ArrayNode) parent).add(child);
return child;
} else {
throw new IllegalArgumentException("parent must be an ArrayNode!");
}
}
public ArrayNode createArrayNode(String name) {
if (isArray()) {
ArrayNode child = ((ArrayNode) rootNode).arrayNode();
((ArrayNode) rootNode).add(child);
return child;
} else {
ArrayNode child = ((ObjectNode) rootNode).arrayNode();
((ObjectNode) rootNode).set(name, child);
return child;
}
}
@Override
public String toString() {
return rootNode.toString();
}
public JsonPath getCompiledJsonPath(String jsonPathStr) {
JsonPath compiledPath = compiledPathMap.get(jsonPathStr);
if (compiledPath == null) {
compiledPath = JsonPath.compile(jsonPathStr);
compiledPathMap.put(jsonPathStr, compiledPath);
}
return compiledPath;
}
/**
* returns the node start from the root
* @param jsonPath
* @return node or null if nothing found or a MissingNode was found
*/
public JsonNode getNode(String jsonPath) {
try {
JsonPath compiledPath = getCompiledJsonPath(jsonPath);
JsonNode node = rootContext.read(compiledPath);
if (node.isMissingNode() || node.isNull()) {
return null;
} else {
return node;
}
} catch (PathNotFoundException e) {
return null;
}
}
/**
* returns the node start from the root
* @param jsonPath
* @return node or null if nothing found or a MissingNode was found
*/
public JsonNode getNodeIncludeMissing(String jsonPath) {
try {
JsonPath compiledPath = getCompiledJsonPath(jsonPath);
JsonNode node = rootContext.read(compiledPath);
if (node.isNull()) {
return null;
} else {
return node;
}
} catch (PathNotFoundException e) {
return MissingNode.getInstance();
}
}
/**
* Retrieve a node by direct-path jsonPath
* @param jsonPath must be a path with query parts and starts with root
* @param create if true, missing nodes will be created
* @return node
* @throws Exception
*/
public JsonNode getNode(String jsonPath, boolean create) throws Exception {
return getNode(rootNode, jsonPath, create);
}
/**
* Retrieves with real JSONPath the nodes starting from the given node
* @param parentNode
* @param jsonPath
* @return an ArrayNode with the search result
*/
public JsonNode getNode(JsonNode parentNode, String jsonPath) {
if (jsonPath == null || jsonPath.trim().isEmpty()) {
throw new IllegalArgumentException("jsonPath cannot be null or empty");
}
if (parentNode == null) {
throw new IllegalArgumentException("parentNode cannot be null");
}
if (parentNode == rootNode && jsonPath.startsWith("$")) {
return getNode(jsonPath);
}
if (jsonPath.equals(".")) {
return parentNode;
}
ParseContext parseContext = JsonPath.using(JACKSON_JSON_NODE_CONFIGURATION);
DocumentContext context = parseContext.parse(parentNode);
// fake a root path but use a arbitrary node as fake root
JsonPath compiledPath = getCompiledJsonPath(jsonPath);
JsonNode node = null;
try {
node = context.read(compiledPath);
if (node.isMissingNode() || node.isNull()) {
return null;
} else {
return node;
}
} catch (PathNotFoundException e) {
return null;
}
}
/**
* Retrieves with real JSONPath the nodes starting from the given node
* @param parentNode
* @param jsonPath
* @return an ArrayNode with the search result
*/
public JsonNode getNodeIncludeMissing(JsonNode parentNode, String jsonPath) {
if (jsonPath == null || jsonPath.trim().isEmpty()) {
throw new IllegalArgumentException("jsonPath cannot be null or empty");
}
if (parentNode == null) {
throw new IllegalArgumentException("parentNode cannot be null");
}
if (parentNode == rootNode || jsonPath.startsWith("$")) {
return getNodeIncludeMissing(jsonPath);
}
if (jsonPath.equals(".")) {
return parentNode;
}
ParseContext parseContext = JsonPath.using(JACKSON_JSON_NODE_CONFIGURATION);
DocumentContext context = parseContext.parse(parentNode);
// fake a root path but use a arbitrary node as fake root
JsonPath compiledPath = getCompiledJsonPath(jsonPath);
JsonNode node = null;
try {
node = context.read(compiledPath);
if (node.isNull()) {
return null;
} else {
return node;
}
} catch (PathNotFoundException e) {
return MissingNode.getInstance();
}
}
/**
* Retrieve a node by direct-path jsonPath
* @param parentNode node to start
* @param jsonPath must be a path with query parts and starts with the given parent node
* @param create if true, missing nodes will be created otherwise it returns null
* @return node
*/
public JsonNode getNode(JsonNode parentNode, String jsonPath, boolean create) throws Exception {
if (jsonPath == null || jsonPath.trim().isEmpty()) {
throw new IllegalArgumentException("jsonPath cannot be null or empty");
}
if (parentNode == null) {
throw new IllegalArgumentException("parentNode cannot be null");
}
if (jsonPath.equals("$")) {
return rootNode;
}
if (jsonPath.equals(".")) {
return parentNode;
}
if (create == false) {
if (parentNode == rootNode || jsonPath.startsWith("$")) {
return getNode(jsonPath);
} else {
return getNode(parentNode, jsonPath);
}
} else {
JsonNode childNode = null;
if (jsonPath == null || jsonPath.trim().isEmpty() || jsonPath.trim().equals(".")) {
return parentNode;
}
// starting from the given parentNode we search the childNode
// $.bo.person[1].address[2][3].street[4]
List<PathToken> listTokens = PathToken.parse(jsonPath);
for (PathToken t : listTokens) {
childNode = null;
if (parentNode instanceof ObjectNode) {
if (t instanceof AttributeToken) {
String name = ((AttributeToken) t).getName();
// check if there is a NullNode -> withArray does not work in this case
childNode = ((ObjectNode) parentNode).get(name);
if (childNode instanceof NullNode) {
((ObjectNode) parentNode).remove(name);
childNode = null;
}
if (childNode == null) {
if (t.isNextTokenArray()) {
// setup an array
childNode = ((ObjectNode) parentNode).withArray(name);
} else {
// setup an object
childNode = ((ObjectNode) parentNode).with(name);
}
}
} else if (t instanceof ArrayToken) {
// we have a ObjectNode and expect to get an node from an array
// we are wrong here
throw new Exception("The jsonpath expects an array node but found an object node at: "+ t.getPath() + " parentNode: " + parentNode);
}
} else if (parentNode instanceof ArrayNode) {
if (t instanceof ArrayToken) {
childNode = ((ArrayNode) parentNode).get(((ArrayToken) t).getIndex());
if (childNode == null || childNode.isNull()) {
if (t.hasNext()) {
if (t.isNextTokenArray()) {
childNode = ((ArrayNode) parentNode).addArray();
} else {
childNode = ((ArrayNode) parentNode).addObject();
}
} else {
childNode = parentNode;
}
}
} else if (t instanceof AttributeToken) {
// we have a ObjectNode and expect to get an node from an array
// we are wrong here
throw new Exception("The jsonpath expects an object node but found an array node at: "+ t.getPath() + " parentNode: " + parentNode);
}
} else if (parentNode instanceof ValueNode) {
if (parentNode.isNull() == false) {
throw new Exception("The jsonpath expects an object or array node but found an value node at: "+ t.getPath() + " parentNode: " + parentNode);
}
}
if (childNode != null) {
parentNode = childNode;
} else {
break;
}
}
return childNode;
}
}
public DocumentContext getRootContext() {
return rootContext;
}
public JsonNode getRootNode() {
return rootNode;
}
public String formatDate(Date value, String pattern) {
if (value == null) {
return null;
}
if (pattern == null || pattern.trim().isEmpty()) {
pattern = DEFAULT_DATE_PATTERN;
}
SimpleDateFormat sdf = dateFormatMap.get(pattern);
if (sdf == null) {
sdf = new SimpleDateFormat(pattern);
dateFormatMap.put(pattern, sdf);
}
return sdf.format(value);
}
public Date parseDate(String value, String pattern) throws ParseException {
if (value == null) {
return null;
}
return GenericDateUtil.parseDate(value, defaultLocale, pattern);
}
public JsonNode setJsonObject(ObjectNode node, String fieldName, String json) throws Exception {
return setJsonObject(node, fieldName, json, false);
}
public JsonNode setJsonObject(ObjectNode node, String fieldName, String json, boolean omitAttrIfNullValue) throws Exception {
if (omitAttrIfNullValue && json == null) {
return node;
}
JsonNode newnode = buildNode(json);
node.set(fieldName, newnode);
return node;
}
public JsonNode setJsonObject(ObjectNode node, String fieldName, JsonNode json) throws Exception {
return setJsonObject(node, fieldName, json, false);
}
public JsonNode setJsonObject(ObjectNode node, String fieldName, JsonNode json, boolean omitAttrIfNullValue) throws Exception {
if (omitAttrIfNullValue && json == null) {
return node;
}
node.set(fieldName, json);
return node;
}
public ObjectNode setValue(ObjectNode node, String fieldName, String value) {
return setValue(node, fieldName, value, false);
}
public ObjectNode setValue(ObjectNode node, String fieldName, String value, boolean omitAttrIfNullValue) {
if (omitAttrIfNullValue && value == null) {
return node;
}
node.put(fieldName, value);
return node;
}
public ObjectNode setValue(ObjectNode node, String fieldName, Boolean value) {
return setValue(node, fieldName, value, false);
}
public ObjectNode setValue(ObjectNode node, String fieldName, Boolean value, boolean omitAttrIfNullValue) {
if (omitAttrIfNullValue && value == null) {
return node;
}
node.put(fieldName, value);
return node;
}
public ObjectNode setValue(ObjectNode node, String fieldName, Integer value) {
return setValue(node, fieldName, value, false);
}
public ObjectNode setValue(ObjectNode node, String fieldName, Integer value, boolean omitAttrIfNullValue) {
if (omitAttrIfNullValue && value == null) {
return node;
}
node.put(fieldName, value);
return node;
}
public ObjectNode setValue(ObjectNode node, String fieldName, Long value) {
return setValue(node, fieldName, value, false);
}
public ObjectNode setValue(ObjectNode node, String fieldName, Long value, boolean omitAttrIfNullValue) {
if (omitAttrIfNullValue && value == null) {
return node;
}
node.put(fieldName, value);
return node;
}
public ObjectNode setValue(ObjectNode node, String fieldName, BigDecimal value) {
return setValue(node, fieldName, value, false);
}
public ObjectNode setValue(ObjectNode node, String fieldName, BigDecimal value, boolean omitAttrIfNullValue) {
if (omitAttrIfNullValue && value == null) {
return node;
}
node.put(fieldName, value);
return node;
}
public ObjectNode setValue(ObjectNode node, String fieldName, BigInteger value) {
return setValue(node, fieldName, value, false);
}
public ObjectNode setValue(ObjectNode node, String fieldName, BigInteger value, boolean omitAttrIfNullValue) {
if (omitAttrIfNullValue && value == null) {
return node;
}
node.put(fieldName, value);
return node;
}
public ObjectNode setValue(ObjectNode node, String fieldName, Double value) {
return setValue(node, fieldName, value, false);
}
public ObjectNode setValue(ObjectNode node, String fieldName, Double value, boolean omitAttrIfNullValue) {
if (omitAttrIfNullValue && value == null) {
return node;
}
node.put(fieldName, value);
return node;
}
public ObjectNode setValue(ObjectNode node, String fieldName, Float value) {
return setValue(node, fieldName, value, false);
}
public ObjectNode setValue(ObjectNode node, String fieldName, Float value, boolean omitAttrIfNullValue) {
if (omitAttrIfNullValue && value == null) {
return node;
}
node.put(fieldName, value);
return node;
}
public ObjectNode setValue(ObjectNode node, String fieldName, Short value) {
return setValue(node, fieldName, value, false);
}
public ObjectNode setValue(ObjectNode node, String fieldName, Short value, boolean omitAttrIfNullValue) {
if (omitAttrIfNullValue && value == null) {
return node;
}
node.put(fieldName, value);
return node;
}
public ObjectNode setValue(ObjectNode node, String fieldName, Date value, String pattern) {
return setValue(node, fieldName, value, pattern, false);
}
public ObjectNode setValue(ObjectNode node, String fieldName, Date value, String pattern, boolean omitAttrIfNullValue) {
if (omitAttrIfNullValue && value == null) {
return node;
}
node.put(fieldName, formatDate(value, pattern));
return node;
}
public JsonNode buildNode(Object value) throws Exception {
if (value instanceof String) {
String jsonString = (String) value;
if (jsonString == null || jsonString.trim().isEmpty()) {
return null;
} else {
return objectMapper.readTree(jsonString);
}
} else if (value instanceof JsonNode) {
return (JsonNode) value;
} else {
return null;
}
}
public String getJsonString(boolean prettyPrint, boolean suppressEmpty) throws JsonProcessingException {
if (suppressEmpty) {
objectMapper.setSerializationInclusion(Include.NON_EMPTY);
} else {
objectMapper.setSerializationInclusion(Include.ALWAYS);
}
if (prettyPrint) {
return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootNode);
} else {
return objectMapper.writeValueAsString(rootNode);
}
}
public String getJsonString(JsonNode node, boolean prettyPrint, boolean suppressEmpty) throws JsonProcessingException {
if (suppressEmpty) {
objectMapper.setSerializationInclusion(Include.NON_EMPTY);
} else {
objectMapper.setSerializationInclusion(Include.ALWAYS);
}
if (node != null) {
if (prettyPrint) {
return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(node);
} else {
return objectMapper.writeValueAsString(node);
}
} else {
return "{}";
}
}
public void writeToFile(String filePath, boolean prettyPrint, boolean suppressEmpty) throws Exception {
writeToFile(rootNode, filePath, prettyPrint, suppressEmpty);
}
public void writeToFile(JsonNode node, String filePath, boolean prettyPrint, boolean suppressEmpty) throws Exception {
if (filePath == null || filePath.trim().isEmpty()) {
throw new IllegalArgumentException("Output file path cannot be null or empty!");
}
File file = new File(filePath);
File dir = file.getParentFile();
if (dir.exists() == false) {
dir.mkdirs();
}
if (dir.exists() == false) {
throw new Exception("Cannot create output dir: " + dir.getAbsolutePath());
}
BufferedWriter br = null;
try {
br = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
br.write(getJsonString(node, prettyPrint, suppressEmpty));
br.flush();
} finally {
if (br != null) {
br.close();
}
}
}
/**
* Returns the value of the addressed field
* @param node node containing the field
* @param fieldName attribute name
* @param isNullable
* @param dummy only to become compatible with the other methods
* @return if node is an ObjectNode: the value of the attribute, if node is a value node: the node itself, if the fieldName == ".": the node itself
* @throws Exception if iNullable == false and the attribute does not exists or is null or the node is null.
*/
public JsonNode getValueAsObject(JsonNode node, String fieldName, boolean isNullable, boolean allowMissing, Object dummy) throws Exception {
if (node != null) {
JsonNode valueNode = null;
if (fieldName == null || ".".equals(fieldName) || node.isValueNode()) {
valueNode = node;
} else {
if (fieldName.contains(".") || fieldName.contains("[") || fieldName.contains("$")) {
valueNode = getNodeIncludeMissing(node, fieldName);
} else {
valueNode = node.path(fieldName);
}
if (isNullable == false && valueNode != null && valueNode.isNull()) {
throw new Exception(currentPath + ": Attribute: " + fieldName + ": value is null but configured as not-nullable!");
}
if (allowMissing == false && valueNode != null && valueNode.isMissingNode()) {
throw new Exception(currentPath + ": Attribute: " + fieldName + " is missing but mandatory!");
}
}
return valueNode;
} else if (isNullable == false) {
throw new Exception(currentPath + ": Parent node does not exists.");
}
return null;
}
/**
* Returns the value of the addressed field
* @param node node containing the field
* @param fieldName attribute name
* @param isNullable
* @param dummy only to become compatible with the other methods
* @return if node is an ObjectNode: the value of the attribute, if node is a value node: the node itself, if the fieldName == ".": the node itself
* @throws Exception if iNullable == false and the attribute does not exists or is null or the node is null.
*/
private JsonNode getValueNode(JsonNode node, String fieldName, boolean isNullable, boolean allowMissing) throws Exception {
if (node != null) {
JsonNode valueNode = null;
if (fieldName == null || ".".equals(fieldName) || node.isValueNode()) {
valueNode = node;
if (valueNode != null && valueNode.isNull()) {
if (isNullable == false) {
throw new Exception(currentPath + ": Value of the given node is null but configured as not-nullable!");
} else {
valueNode = null;
}
}
} else {
if (fieldName.contains(".") || fieldName.contains("[") || fieldName.contains("$")) {
valueNode = getNodeIncludeMissing(node, fieldName);
} else {
valueNode = node.path(fieldName);
}
if (valueNode != null && valueNode.isNull()) {
if (isNullable == false) {
throw new Exception(currentPath + ": Attribute: " + fieldName + ": value is null but configured as not-nullable!");
} else {
valueNode = null;
}
}
if (allowMissing == false && valueNode != null && valueNode.isMissingNode()) {
throw new Exception(currentPath + ": Attribute: " + fieldName + " is missing but mandatory! Node: " + node);
}
}
return valueNode;
} else if (isNullable == false) {
throw new Exception(currentPath + ": Parent node does not exists.");
} else {
return null;
}
}
public String getArrayValuesAsChain(ArrayNode arrayNode) {
StringBuilder sb = new StringBuilder();
if (arrayNode != null) {
boolean firstLoop = true;
for (JsonNode valueNode : arrayNode) {
if (valueNode.isValueNode()) {
String value = valueNode.asText();
if (value != null && value.isEmpty() == false) {
if (firstLoop) {
firstLoop = false;
} else {
sb.append(",");
}
sb.append(value);
}
}
}
}
return sb.toString();
}
private void collectNodes(JsonNode node, List<JsonNode> result, boolean unique) {
if (node instanceof ArrayNode) {
ArrayNode arrayNode = (ArrayNode) node;
// because the search returns an array within an array
// if we have more than one array (with a search over more than one elements) within the loop
// we must uncover an additional array
// check if we have an array made of arrays
for (JsonNode childNode : arrayNode) {
if (childNode instanceof ArrayNode) {
collectNodes(childNode, result, unique);
} else {
if (unique == false || result.contains(childNode) == false) {
result.add(childNode);
}
}
}
} else if (node instanceof ObjectNode) {
if (unique == false || result.contains(node) == false) {
result.add(node);
}
} else if (node instanceof ValueNode) {
if (unique == false || result.contains(node) == false) {
result.add(node);
}
}
}
public List<JsonNode> getArrayValuesAsList(JsonNode node, boolean unique, boolean deep) {
if (deep) {
return getArrayValuesAsList(node, unique);
}
List<JsonNode> result = new ArrayList<JsonNode>();
if (node instanceof ArrayNode) {
ArrayNode arrayNode = (ArrayNode) node;
// because the search returns an array within an array
// if we have more than one array (with a search over more than one elements) within the loop
// we must uncover an additional array
// check if we have an array made of arrays
for (JsonNode childNode : arrayNode) {
if (unique == false || result.contains(childNode) == false) {
result.add(childNode);
}
}
} else if (node instanceof ObjectNode) {
if (unique == false || result.contains(node) == false) {
result.add(node);
}
} else if (node instanceof ValueNode) {
if (unique == false || result.contains(node) == false) {
result.add(node);
}
}
return result;
}
public List<JsonNode> getArrayValuesAsList(JsonNode node) {
return getArrayValuesAsList(node, false);
}
public List<JsonNode> getArrayValuesAsList(JsonNode node, boolean unique) {
List<JsonNode> result = new ArrayList<JsonNode>();
collectNodes(node, result, unique);
return result;
}
private JsonNode getNodeFromArray(JsonNode node, int arrayIndex, boolean allowMissing) throws Exception {
if (node instanceof ArrayNode) {
ArrayNode arrayNode = (ArrayNode) node;
if (arrayIndex < arrayNode.size()) {
return arrayNode.get(arrayIndex);
} else if (allowMissing) {
return null;
} else {
throw new Exception("Node: " + node + " has less elements than expected array index: " + arrayIndex);
}
}
return node;
}
public String getValueAsString(JsonNode node, int arrayIndex, boolean isNullable, boolean allowMissing, String missingNodeValue) throws Exception {
JsonNode oneNode = getNodeFromArray(node, arrayIndex, allowMissing);
return getValueAsString(oneNode, ".", isNullable, allowMissing, missingNodeValue);
}
public String getValueAsString(JsonNode node, String fieldName, boolean isNullable, boolean allowMissing, String missingNodeValue) throws Exception {
JsonNode valueNode = getValueNode(node, fieldName, isNullable, allowMissing);
if (valueNode != null) {
if (valueNode.isMissingNode()) {
if (isNullable == false && missingNodeValue == null) {
throw new Exception(currentPath + ": Attribute: " + fieldName + " is missing and configured as not-nullable but the replacement value is also null!");
} else {
return missingNodeValue;
}
}
if (valueNode.isValueNode()) {
return valueNode.asText();
} else {
return valueNode.toString();
}
} else {
return null;
}
}
public Boolean getValueAsBoolean(JsonNode node, int arrayIndex, boolean isNullable, boolean allowMissing, Boolean missingNodeValue) throws Exception {
JsonNode oneNode = getNodeFromArray(node, arrayIndex, allowMissing);
return getValueAsBoolean(oneNode, ".", isNullable, allowMissing, missingNodeValue);
}
public Boolean getValueAsBoolean(JsonNode node, String fieldName, boolean isNullable, boolean allowMissing, Boolean missingNodeValue) throws Exception {
JsonNode valueNode = getValueNode(node, fieldName, isNullable, allowMissing);
if (valueNode != null) {
if (valueNode.isMissingNode()) {
if (isNullable == false && missingNodeValue == null) {
throw new Exception(currentPath + ": Attribute: " + fieldName + " is missing and configured as not-nullable but the replacement value is also null!");
} else {
return missingNodeValue;
}
}
try {
return TypeUtil.convertToBoolean(valueNode);
} catch (Exception e) {
throw new Exception("Read attribute: " + fieldName + " failed.", e);
}
} else {
return null;
}
}
public Integer getValueAsInteger(JsonNode node, int arrayIndex, boolean isNullable, boolean allowMissing, Integer missingNodeValue) throws Exception {
JsonNode oneNode = getNodeFromArray(node, arrayIndex, allowMissing);
return getValueAsInteger(oneNode, ".", isNullable, allowMissing, missingNodeValue);
}
public Integer getValueAsInteger(JsonNode node, String fieldName, boolean isNullable, boolean allowMissing, Integer missingNodeValue) throws Exception {
JsonNode valueNode = getValueNode(node, fieldName, isNullable, allowMissing);
if (valueNode != null) {
if (valueNode.isMissingNode()) {
if (isNullable == false && missingNodeValue == null) {
throw new Exception(currentPath + ": Attribute: " + fieldName + " is missing and configured as not-nullable but the replacement value is also null!");
} else {
return missingNodeValue;
}
}
try {
return TypeUtil.convertToInteger(valueNode);
} catch (Exception e) {
throw new Exception("Read attribute: " + fieldName + " failed.", e);
}
} else {
return null;
}
}
public Long getValueAsLong(JsonNode node, int arrayIndex, boolean isNullable, boolean allowMissing, Long missingNodeValue) throws Exception {
JsonNode oneNode = getNodeFromArray(node, arrayIndex, allowMissing);
return getValueAsLong(oneNode, ".", isNullable, allowMissing, missingNodeValue);
}
public Long getValueAsLong(JsonNode node, String fieldName, boolean isNullable, boolean allowMissing, Long missingNodeValue) throws Exception {
JsonNode valueNode = getValueNode(node, fieldName, isNullable, allowMissing);
if (valueNode != null) {
if (valueNode.isMissingNode()) {
if (isNullable == false && missingNodeValue == null) {
throw new Exception(currentPath + ": Attribute: " + fieldName + " is missing and configured as not-nullable but the replacement value is also null!");
} else {
return missingNodeValue;
}
}
try {
return TypeUtil.convertToLong(valueNode);
} catch (Exception e) {
throw new Exception("Read attribute: " + fieldName + " failed.", e);
}
} else {
return null;
}
}
public Double getValueAsDouble(JsonNode node, int arrayIndex, boolean isNullable, boolean allowMissing, Double missingNodeValue) throws Exception {
JsonNode oneNode = getNodeFromArray(node, arrayIndex, allowMissing);
return getValueAsDouble(oneNode, ".", isNullable, allowMissing, missingNodeValue);
}
public Double getValueAsDouble(JsonNode node, String fieldName, boolean isNullable, boolean allowMissing, Double missingNodeValue) throws Exception {
JsonNode valueNode = getValueNode(node, fieldName, isNullable, allowMissing);