-
Notifications
You must be signed in to change notification settings - Fork 6
/
ValueHolder.java
1587 lines (1437 loc) · 68.4 KB
/
ValueHolder.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
package com.credibledoc.iso8583packer;
import com.credibledoc.iso8583packer.bcd.BcdBodyPacker;
import com.credibledoc.iso8583packer.bcd.BcdService;
import com.credibledoc.iso8583packer.bitmap.BitmapPacker;
import com.credibledoc.iso8583packer.body.BodyPacker;
import com.credibledoc.iso8583packer.dump.DumpService;
import com.credibledoc.iso8583packer.dump.Visualizer;
import com.credibledoc.iso8583packer.exception.PackerRuntimeException;
import com.credibledoc.iso8583packer.length.LengthPacker;
import com.credibledoc.iso8583packer.message.MsgField;
import com.credibledoc.iso8583packer.message.MsgFieldType;
import com.credibledoc.iso8583packer.message.MsgPair;
import com.credibledoc.iso8583packer.message.MsgValue;
import com.credibledoc.iso8583packer.navigator.Navigator;
import com.credibledoc.iso8583packer.navigator.NavigatorService;
import com.credibledoc.iso8583packer.offset.Offset;
import com.credibledoc.iso8583packer.tag.TagPacker;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.BitSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* This builder helps to fill the existing {@link MsgField} definition with data. It contains
* two state objects, the {@link #msgValue} and {@link #msgField}.
* <p>
* The {@link MsgField} definition can be created by {@link FieldBuilder}.
*
* @author Kyrylo Semenko
*/
public class ValueHolder {
protected static final int INITIAL_SIZE_100_BYTES = 100;
protected static final String PARTIAL_DUMP = "\nPartial dump:\n";
protected static final String ROOT_MSG_FIELD = "\nRoot MsgField:\n";
protected static final String THE_MSG_FIELD = "The MsgField '";
protected static final String MSG_FIELD = "\nMsgField:\n";
/**
* The builder state. Contains an object created from the {@link #msgField} template. This field will be a part
* of object graph for packing and unpacking this graph from / to a byte array. You can show this graph by calling
* the {@link com.credibledoc.iso8583packer.dump.DumpService#dumpMsgValue(MsgField, MsgValue, boolean)} method.
*/
protected MsgValue msgValue;
/**
* The builder state. Contains an object created by the {@link FieldBuilder} builder. It contains a graph of
* {@link MsgField}s connected to each other. This graph defines rules of packing and unpacking of bytes from / to
* a {@link #msgValue} object graph. You can show this graph by calling
* the {@link com.credibledoc.iso8583packer.dump.DumpService#dumpMsgField(MsgField)} method.
*/
protected MsgField msgField;
/**
* The service helps to navigate through the {@link MsgField} and {@link MsgValue} object graphs.
*/
protected Navigator navigator;
/**
* The service helps to visualize the {@link MsgField} and {@link MsgValue} object graphs.
*/
protected Visualizer visualizer;
/**
* Please do not create instances of this builder. It uses for internal purposes only,
* please use one of the newInstance() methods.
*/
protected ValueHolder() {
// empty
}
/**
* Call the {@link #newInstance(MsgField, boolean)} method with the fromRoot=<b>false</b> value.
*
* @param definition see the {@link #newInstance(MsgField, boolean)} method description.
* @return See the {@link #newInstance(MsgField, boolean)} method description.
*/
public static ValueHolder newInstance(MsgField definition) {
return newInstance(definition, false);
}
/**
* Create a new instance of {@link MsgValue} from the {@link MsgField} definition for filling it with data.
* <p>
* Example of usage:
* <pre>
* ValueHolder valueHolder = ValueHolder.newInstance(isoMsgField);
* </pre>
* <p>
* How to fill the data to the {@link FieldBuilder}? See the following example:
* <pre>
* String mtiValue = "0200";
* valueHolder.jumpToChild(MTI_NAME).setValue(mtiValue);
* </pre>
*
* @param definition existing definition created with {@link FieldBuilder}.
* @param fromRoot if 'false', the current MsgField definition will be used as a current position in the
* MsgField graph.<p>
* If 'true', the root definition in the MsgField graph will be used as a current position.
* @return A new instance of the {@link ValueHolder} with {@link #msgValue} and {@link #msgField} in its context.
*/
public static ValueHolder newInstance(MsgField definition, boolean fromRoot) {
if (definition == null) {
throw new PackerRuntimeException("MsgField definition cannot be 'null'.");
}
ValueHolder valueHolder = new ValueHolder();
valueHolder.createDefaultServices();
return valueHolder.setValueAndField(definition, fromRoot);
}
/**
* Call the {@link #newInstance(FieldBuilder, boolean)} method with fromRoot=<b>false</b> value.
*
* @param fieldBuilder see the the {@link #newInstance(FieldBuilder, boolean)} method description.
* @return See the {@link #newInstance(FieldBuilder, boolean)} method description.
*/
public static ValueHolder newInstance(FieldBuilder fieldBuilder) {
return newInstance(fieldBuilder.getCurrentField());
}
/**
* Call the {@link #newInstance(MsgField, boolean)} method.
*
* @param fieldBuilder the current {@link FieldBuilder} with the {@link FieldBuilder#msgField} value.
* @param fromRoot see the {@link #newInstance(MsgField, boolean)} description.
* @return See the {@link #newInstance(MsgField, boolean)} description.
*/
public static ValueHolder newInstance(FieldBuilder fieldBuilder, boolean fromRoot) {
return newInstance(fieldBuilder.getCurrentField(), fromRoot);
}
/**
* Create instances of services used in the builder. The method may be overridden if needed.
*/
protected void createDefaultServices() {
navigator = NavigatorService.getInstance();
visualizer = DumpService.getInstance();
visualizer.setNavigator(navigator);
navigator.setVisualizer(visualizer);
}
/**
* Create a new {@link MsgValue} instance.
*
* @param definition an existing definition.
* @param fromRoot if 'true', the root {@link MsgField} will be used as a definition.
* @return A new instance of the {@link ValueHolder} with {@link #msgValue} and the {@link #msgField} in its context.
*/
protected ValueHolder setValueAndField(MsgField definition, boolean fromRoot) {
if (fromRoot) {
definition = navigator.findRoot(definition);
}
msgField = definition;
msgValue = navigator.newFromNameAndTag(definition);
msgValue.setRoot(msgValue); // root field references to itself
if (msgValue.getParent() != null) {
msgValue.getParent().getChildNamesMap().put(msgValue.getName(), msgValue);
}
return this;
}
/**
* Create a new instance of {@link ValueHolder}.
*
* @param msgValue will be set to the {@link ValueHolder#msgValue}.
* @param msgField will be set to the {@link ValueHolder#msgField}.
* @return The new created {@link ValueHolder} with the {@link #msgValue} and {@link #msgField} in its context.
*/
public static ValueHolder newInstance(MsgValue msgValue, MsgField msgField) {
if (msgValue == null) {
throw new PackerRuntimeException("MsgValue cannot be 'null'.");
}
if (msgField == null) {
throw new PackerRuntimeException("MsgField cannot be 'null'.");
}
ValueHolder valueHolder = new ValueHolder();
valueHolder.createDefaultServices();
return valueHolder.setValueAndField(msgValue, msgField);
}
/**
* Set the arguments to the current instance of the {@link ValueHolder}.
*
* @param msgValue will be set to the {@link ValueHolder#msgValue}.
* @param msgField will be set to the {@link ValueHolder#msgField}.
* @return The current instance of {@link ValueHolder} with the {@link #msgValue} and {@link #msgField} in its context.
*/
protected ValueHolder setValueAndField(MsgValue msgValue, MsgField msgField) {
try {
this.msgValue = msgValue;
this.msgField = msgField;
if (this.msgValue.getName() == null) {
this.msgValue.setName(msgField.getName());
}
if (this.msgValue.getRoot() == null) {
this.msgValue.setRoot(this.msgValue);
}
return this;
} catch (Exception e) {
MsgField rootMsgField = navigator.findRoot(msgField);
throw new PackerRuntimeException("Exception in method get(msgValue, msgField): " + e.getMessage() + "\n" +
"\nThe root MsgField:\n" + visualizer.dumpMsgField(rootMsgField) +
"\nMsgValue:\n" + visualizer.dumpMsgValue(msgField, msgValue, true) + "\n", e);
}
}
/**
* Unpack the bytes started from offset to a new {@link MsgField} using its definition from the third argument.
* @param bytes the source bytes.
* @param offset the index where the field starts in the bytes.
* @param msgField the definition of the {@link MsgField} structure.
* @return The unpacked {@link MsgValue}.
*/
public static MsgValue unpack(byte[] bytes, int offset, MsgField msgField) {
ValueHolder valueHolder = newInstance(msgField);
return valueHolder.unpackMsgField(bytes, offset);
}
/**
* Unpack the bytes started from offset to the {@link #msgField} in the context.
* @param bytes the source bytes.
* @param offset the index where the field starts in the bytes.
* @return The unpacked {@link MsgValue}.
*/
protected MsgValue unpackMsgField(byte[] bytes, int offset) {
MsgValue newMsgValue = msgValue;
try {
Offset offsetObject = new Offset();
offsetObject.setValue(offset);
MsgPair msgPair = new MsgPair(msgField, newMsgValue);
unpackFieldRecursively(bytes, offsetObject, msgPair);
msgValue = newMsgValue;
msgField = msgPair.getMsgField();
if (newMsgValue.getParent() != null) {
newMsgValue.getParent().getChildNamesMap().put(newMsgValue.getName(), newMsgValue);
}
return newMsgValue;
} catch (Exception e) {
String dump = PARTIAL_DUMP + visualizer.dumpMsgValue(msgField, newMsgValue, true) +
ROOT_MSG_FIELD + visualizer.dumpMsgField(navigator.findRoot(msgField));
throw new PackerRuntimeException("Cannot unpack field: " + navigator.generatePath(newMsgValue) + dump, e);
}
}
/**
* @param bytes the source bytes.
* @param offset the index where the field starts in the bytes.
* @param msgPair the definition of the {@link MsgField} structure and the field values.
*/
protected void unpackFieldRecursively(byte[] bytes, Offset offset, MsgPair msgPair) {
navigator.validateSameNamesAndTags(msgPair);
Integer rawDataLength;
MsgFieldType msgFieldType = msgPair.getMsgField().getType();
if (MsgFieldType.MSG == msgFieldType) {
if (isValType(msgPair.getMsgField().getChildren())) {
rawDataLength = sumChildrenLen(msgPair.getMsgField().getChildren());
} else {
rawDataLength = bytes.length - offset.getValue();
}
} else if (msgFieldType == MsgFieldType.BIT_SET) {
rawDataLength = unpackBitSet(bytes, offset, msgPair);
} else if (MsgFieldType.VAL == msgFieldType) {
rawDataLength = unpackFixedLengthType(bytes, offset, msgPair);
} else {
rawDataLength = unpackOtherTypes(bytes, offset, msgPair);
}
MsgValue parent = msgPair.getMsgValue().getParent();
if (parent != null) {
parent.getChildNamesMap().put(msgPair.getMsgValue().getName(), msgPair.getMsgValue());
}
if (msgPair.getMsgField().getChildren() == null) {
// set value, but for leaves (outer children) only.
setValueToLeaf(bytes, offset, msgPair, rawDataLength);
} else {
unpackChildren(bytes, offset, msgPair, rawDataLength);
return;
}
offset.add(rawDataLength);
}
protected int sumChildrenLen(List<MsgField> children) {
int result = 0;
for (MsgField child : children) {
result = result + child.getLen();
}
return result;
}
protected boolean isValType(List<MsgField> children) {
for (MsgField child : children) {
if (child.getType() != MsgFieldType.VAL) {
return false;
}
}
return true;
}
protected Integer unpackOtherTypes(byte[] bytes, Offset offset, MsgPair msgPair) {
Integer rawDataLength = null;
TagPacker tagPacker = navigator.getTagPacker(msgPair.getMsgField());
int tagPackedLength = tagPacker == null ? 0 : tagPacker.getPackedLength();
boolean lengthFirst = MsgFieldType.getLengthFirstTypes().contains(msgPair.getMsgField().getType());
Object tag = null;
if (lengthFirst && MsgFieldType.isLengthType(msgPair.getMsgField())) {
rawDataLength = unpackLength(bytes, offset, msgPair) - tagPackedLength;
}
if (MsgFieldType.getTaggedTypes().contains(msgPair.getMsgField().getType())) {
tag = unpackTag(bytes, offset, msgPair);
}
boolean tagUnpackedButIsDifferent = tag != null && !Objects.equals(tag, msgPair.getMsgField().getTag());
if (tagUnpackedButIsDifferent) {
replaceWithSibling(msgPair, tag);
}
if (MsgFieldType.getTaggedTypes().contains(msgPair.getMsgField().getType())) {
unpackTagBytes(bytes, offset, msgPair, tagPackedLength, tag);
}
if (!lengthFirst && MsgFieldType.isLengthType(msgPair.getMsgField())) {
rawDataLength = unpackLength(bytes, offset, msgPair);
}
if (msgPair.getMsgField().getParent() != null && msgPair.getMsgField().getParent().getChildrenBodyLen() != null) {
rawDataLength = msgPair.getMsgField().getParent().getChildrenBodyLen();
}
if (msgPair.getMsgField().getLen() != null) {
rawDataLength = msgPair.getMsgField().getLen();
}
if (rawDataLength == null) {
throw new PackerRuntimeException("Cannot find rawDataLength of the msgField with path '" + navigator.getPathRecursively(msgPair.getMsgField()) + "'");
}
// unpack field body
unpackBodyBytes(bytes, offset, msgPair, rawDataLength);
return rawDataLength;
}
protected Integer unpackFixedLengthType(byte[] bytes, Offset offset, MsgPair msgPair) {
Integer rawDataLength;
MsgField currentMsgField = msgPair.getMsgField();
rawDataLength = currentMsgField.getLen();
if (rawDataLength == null) {
MsgValue currentMsgValue = msgPair.getMsgValue();
MsgValue currentMsgValueParent = currentMsgValue.getParent();
if (currentMsgValueParent != null && currentMsgValueParent.getLengthBytes() != null) {
LengthPacker parentLengthPacker = currentMsgField.getParent().getLengthPacker();
if (parentLengthPacker == null) {
parentLengthPacker = currentMsgField.getParent().getParent().getChildrenLengthPacker();
}
int parentLength = parentLengthPacker.unpack(currentMsgValueParent.getLengthBytes(), 0);
int childrenLength = calculateLengthUpTo(currentMsgValueParent.getChildren(), currentMsgValue);
rawDataLength = parentLength - childrenLength;
} else {
rawDataLength = bytes.length - offset.getValue();
}
}
int remaining = bytes.length - offset.getValue();
if (rawDataLength > remaining) {
throw new PackerRuntimeException("Cannot unpack bytes because the remaining data length '" + remaining +
"' of the byte array is less than defined 'len' value '" + rawDataLength +
"' of the MsgField with path '" + navigator.getPathRecursively(currentMsgField) + "'.");
}
unpackBodyBytes(bytes, offset, msgPair, rawDataLength);
return rawDataLength;
}
private int calculateLengthUpTo(List<MsgValue> siblings, MsgValue currentSibling) {
int length = 0;
for (MsgValue sibling : siblings) {
if (sibling == currentSibling) {
return length;
}
length += sibling.getBodyBytes().length;
}
throw new PackerRuntimeException("It is expected, that the siblings' list contains the current sibling, " +
"but the current sibling cannot be found in the list.\n" +
"Siblings: '" + siblings + "'.\n" +
"Current sibling: '" + currentSibling + "'.");
}
protected LengthPacker getLengthPackerFromParentOrSelfOrThrowException(MsgField msgField) {
boolean parentContainsChildrenLengthPacker = msgField.getParent() != null &&
msgField.getParent().getChildrenLengthPacker() != null;
if (parentContainsChildrenLengthPacker) {
return msgField.getParent().getChildrenLengthPacker();
}
if (msgField.getLengthPacker() == null) {
throw new PackerRuntimeException("Property lengthPacker is not defined. Please define it by calling " +
"the .defineHeaderLengthPacker() method. " +
"Current MsgField: " + navigator.generatePath(msgField));
}
return msgField.getLengthPacker();
}
protected void unpackBodyBytes(byte[] bytes, Offset offset, MsgPair msgPair, Integer rawDataLength) {
try {
byte[] rawData = new byte[rawDataLength];
System.arraycopy(bytes, offset.getValue(), rawData, 0, rawData.length);
msgPair.getMsgValue().setBodyBytes(rawData);
} catch (Exception e) {
String path = navigator.getPathRecursively(msgPair.getMsgField());
throw new PackerRuntimeException("Current MsgField: '" + path + "', source bytes length: '" + bytes.length +
"', offset: '" + offset.getValue() + "', rawDataLength: '" + rawDataLength + "'", e);
}
}
protected void unpackChildren(byte[] bytes, Offset offset, MsgPair msgPair, Integer rawDataLength) {
int offsetWithChildren = offset.getValue() + rawDataLength;
if (rawDataLength > 0) {
msgPair.getMsgValue().setChildren(new ArrayList<>());
}
int childNum = 0;
while (offset.getValue() < offsetWithChildren) {
List<MsgField> children = msgPair.getMsgField().getChildren();
MsgField nextMsgFieldChild = children.get(childNum);
if (children.size() > childNum + 1) {
childNum++; // the number of real children may be higher than defined in MsgField
// for example for repeated values or undefined TLV and LTV values
}
MsgValue nextMsgValueChild = navigator.newFromNameAndTag(nextMsgFieldChild);
msgPair.getMsgValue().getChildren().add(nextMsgValueChild);
nextMsgValueChild.setParent(msgPair.getMsgValue());
nextMsgValueChild.setRoot(nextMsgValueChild.getParent().getRoot());
MsgPair msgPairChild = new MsgPair(nextMsgFieldChild, nextMsgValueChild);
unpackFieldRecursively(bytes, offset, msgPairChild);
}
if (offset.getValue() != offsetWithChildren) {
throw new PackerRuntimeException("Expected end of children is '" + offsetWithChildren +
"' but current offset is '" + offset.getValue() +
"'. These values should be equal.");
}
}
protected void unpackTagBytes(byte[] bytes, Offset offset, MsgPair msgPair, Integer fieldTagLength,
Object tag) {
byte[] tagBytes = new byte[fieldTagLength];
System.arraycopy(bytes, offset.getValue(), tagBytes, 0, tagBytes.length);
offset.add(fieldTagLength);
msgPair.getMsgValue().setTagBytes(tagBytes);
msgPair.getMsgValue().setTag(tag);
}
protected Object unpackTag(byte[] bytes, Offset offset, MsgPair msgPair) {
Object tag;
TagPacker tagPacker = navigator.getTagPacker(msgPair.getMsgField());
if (tagPacker == null) {
tag = msgPair.getMsgField().getTag();
} else {
tag = tagPacker.unpack(bytes, offset.getValue());
}
return tag;
}
protected int unpackBitSet(byte[] bytes, Offset offset, MsgPair msgPair) {
List<Integer> fieldNums = getFieldNumsFromBitSet(bytes, offset, msgPair);
for (int nextFieldNum : fieldNums) {
MsgField msgFieldChild = findChildByFieldNumUnsafe(msgPair.getMsgField(), nextFieldNum);
// Bits 1 and 65 in a bitmap may be used as flags of a secondary and tertiary bitmaps, as well as flags of used msgFields
if (msgFieldChild == null && (nextFieldNum == 1 || nextFieldNum == 65)) {
continue;
}
if (msgFieldChild == null) {
throw new PackerRuntimeException("Cannot find child with fieldNum '" + nextFieldNum +
"' in the msgField " + navigator.getPathRecursively(msgField));
}
MsgValue msgValueChild = navigator.newFromNameAndTag(msgFieldChild);
List<MsgValue> children = msgPair.getMsgValue().getChildren();
if (children == null) {
children = new ArrayList<>();
msgPair.getMsgValue().setChildren(children);
}
children.add(msgValueChild);
msgValueChild.setParent(msgPair.getMsgValue());
msgValueChild.setRoot(msgPair.getMsgValue().getRoot());
msgPair.getMsgValue().getChildNamesMap().put(msgValueChild.getName(), msgValueChild);
MsgPair msgPairChild = new MsgPair(msgFieldChild, msgValueChild);
unpackFieldRecursively(bytes, offset, msgPairChild);
}
return 0;
}
protected int unpackLength(byte[] bytes, Offset offset, MsgPair msgPair) {
LengthPacker lengthPacker = getLengthPackerFromParentOrSelfOrThrowException(msgPair.getMsgField());
int lenLength = lengthPacker.calculateLenLength(bytes, offset.getValue());
byte[] lengthBytes = new byte[lenLength];
System.arraycopy(bytes, offset.getValue(), lengthBytes, 0, lengthBytes.length);
msgPair.getMsgValue().setLengthBytes(lengthBytes);
int rawDataLength = lengthPacker.unpack(bytes, offset.getValue());
offset.add(lenLength);
return rawDataLength;
}
protected void setValueToLeaf(byte[] bytes, Offset offset, MsgPair msgPair, int bodyBytesLength) {
BodyPacker bodyPacker = null;
if (msgPair.getMsgField().getBodyPacker() != null) {
bodyPacker = msgPair.getMsgField().getBodyPacker();
} else if (msgPair.getMsgField().getParent() != null) {
bodyPacker = msgPair.getMsgField().getParent().getChildrenBodyPacker();
}
if (bodyPacker == null) {
String path = navigator.getPathRecursively(msgPair.getMsgField());
throw new PackerRuntimeException("BodyPacker not found for MsgField with path '" + path + "'. " +
"Please call the defineBodyPacker(...) method " +
"of the FieldBuilder class, for example " +
"MsgField subfield35 = FieldBuilder.builder(...).defineBodyPacker(...).");
}
Object bodyValue = bodyPacker.unpack(bytes, offset.getValue(), bodyBytesLength);
msgPair.getMsgValue().setBodyValue(bodyValue);
}
protected void replaceWithSibling(MsgPair msgPair, Object tag) {
MsgPair result = new MsgPair();
MsgField msgFieldSibling = findSiblingByTag(tag, msgPair.getMsgField());
boolean isUndefined = false;
if (msgFieldSibling == null) {
isUndefined = true;
MsgField parent = msgPair.getMsgField().getParent();
if (parent != null && parent.getChildrenTagPacker() != null) {
MsgField undefinedMsgField = new MsgField();
String originalName = msgPair.getMsgField().getName();
Map<String, MsgValue> undefinedSiblings = msgPair.getMsgValue().getParent().getUndefinedChildrenMap();
String cloneName = getCloneName(originalName, undefinedSiblings);
undefinedMsgField.setName(cloneName);
undefinedMsgField.setParent(parent);
undefinedMsgField.setDepth(msgPair.getMsgField().getDepth());
resolveBodyPacker(msgPair, parent, undefinedMsgField);
resolveLengthPacker(msgPair, parent, undefinedMsgField);
resolveTagPacker(msgPair, parent, undefinedMsgField);
resolveLen(msgPair, parent, undefinedMsgField);
MsgFieldType newType = msgPair.getMsgField().getType();
undefinedMsgField.setType(newType);
undefinedMsgField.setTag(tag);
msgFieldSibling = undefinedMsgField;
} else {
throwSiblingNotFound(msgPair, tag);
}
}
MsgValue oldMsgValue = msgPair.getMsgValue();
MsgValue parentMsgValue = oldMsgValue.getParent();
result.setMsgField(msgFieldSibling);
assert msgFieldSibling != null;
MsgValue newMsgValue = navigator.newFromNameAndTag(msgFieldSibling);
if (parentMsgValue != null) {
parentMsgValue.getChildren().remove(oldMsgValue);
parentMsgValue.getChildren().add(newMsgValue);
newMsgValue.setParent(parentMsgValue);
newMsgValue.setRoot(parentMsgValue.getRoot());
parentMsgValue.getChildNamesMap().put(newMsgValue.getName(), newMsgValue);
}
result.setMsgValue(newMsgValue);
newMsgValue.setBitSet(oldMsgValue.getBitSet());
newMsgValue.setTagBytes(oldMsgValue.getTagBytes());
newMsgValue.setLengthBytes(oldMsgValue.getLengthBytes());
if (isUndefined) {
Map<String, MsgValue> undefinedChildrenMap = newMsgValue.getParent().getUndefinedChildrenMap();
undefinedChildrenMap.put(newMsgValue.getName(), newMsgValue);
}
msgPair.setMsgField(result.getMsgField());
msgPair.setMsgValue(result.getMsgValue());
}
protected void resolveLen(MsgPair msgPair, MsgField parent, MsgField undefinedMsgField) {
Integer len;
if (msgPair.getMsgField().getLen() != null) {
len = msgPair.getMsgField().getLen();
} else {
len = parent.getChildrenBodyLen();
}
undefinedMsgField.setLen(len);
}
protected void resolveTagPacker(MsgPair msgPair, MsgField parent, MsgField undefinedMsgField) {
TagPacker newTagPacker;
if (msgPair.getMsgField().getTagPacker() != null) {
newTagPacker = msgPair.getMsgField().getTagPacker();
} else {
newTagPacker = parent.getChildrenTagPacker();
}
undefinedMsgField.setTagPacker(newTagPacker);
}
protected void resolveLengthPacker(MsgPair msgPair, MsgField parent, MsgField undefinedMsgField) {
LengthPacker newLengthPacker;
if (msgPair.getMsgField().getLengthPacker() != null) {
newLengthPacker = msgPair.getMsgField().getLengthPacker();
} else {
newLengthPacker = parent.getChildrenLengthPacker();
}
undefinedMsgField.setLengthPacker(newLengthPacker);
}
protected void resolveBodyPacker(MsgPair msgPair, MsgField parent, MsgField undefinedMsgField) {
BodyPacker newBodyPacker;
if (msgPair.getMsgField().getBodyPacker() != null) {
newBodyPacker = msgPair.getMsgField().getBodyPacker();
} else {
newBodyPacker = parent.getChildrenBodyPacker();
}
undefinedMsgField.setBodyPacker(newBodyPacker);
}
protected String getCloneName(String originalName, Map<String, MsgValue> undefinedChildrenMap) {
return originalName + "-clone-" + (undefinedChildrenMap.size() + 1);
}
protected List<Integer> getFieldNumsFromBitSet(byte[] bytes, Offset offset, MsgPair msgPair) {
// unpack
BitmapPacker bitmapPacker = msgPair.getMsgField().getBitMapPacker();
if (bitmapPacker == null) {
throw new PackerRuntimeException("Please call the defineHeaderBitmapPacker(...) " +
"method for this field " + navigator.getPathRecursively(msgPair.getMsgValue()));
}
int consumed = bitmapPacker.unpack(msgPair.getMsgValue(), bytes, offset.getValue());
byte[] bitMapBytes = new byte[consumed];
System.arraycopy(bytes, offset.getValue(), bitMapBytes, 0, consumed);
offset.add(consumed);
msgPair.getMsgValue().setBodyBytes(bitMapBytes);
return getFieldNumsAndValidateBitSet(msgPair);
}
protected MsgField findChildByFieldNumUnsafe(MsgField msgField, int nextFieldNum) {
for (MsgField child : msgField.getChildren()) {
if (nextFieldNum == child.getFieldNum()) {
return child;
}
}
return null;
}
protected List<Integer> getFieldNumsAndValidateBitSet(MsgPair msgPair) {
BitSet unpackedBitSet = msgPair.getMsgValue().getBitSet();
List<Integer> fieldNums = new ArrayList<>();
int maxFieldNum = getMaxFieldNum(msgPair.getMsgField().getChildren(), msgPair.getMsgField());
boolean secondaryBitmapMarked = false;
boolean tertiaryBitmapMarked = false;
for (int nextFieldNum = 1; nextFieldNum <= maxFieldNum; nextFieldNum++) {
MsgField childMsgField = navigator.findByFieldNum(msgPair.getMsgField().getChildren(), nextFieldNum);
boolean bitMarked = unpackedBitSet.get(nextFieldNum);
// Bits 1 and 65 in a bitmap may be used as flags of a secondary and tertiary bitmaps, as well as flags of used msgFields
if (!bitMarked || (childMsgField == null && (nextFieldNum == 65 || nextFieldNum == 1))) {
continue;
}
if (childMsgField == null) {
String path = navigator.getPathRecursively(msgPair.getMsgField());
throw new PackerRuntimeException("Unpacked bitSet contains fieldNum '" + nextFieldNum + "', " +
"but the MsgField with path '" + path + "' has no child with such fieldNum. " +
"Please set the defineFieldNum(" + nextFieldNum + ") value " +
"to one of the field '" + path + "' children.");
}
secondaryBitmapMarked = markSecondaryBitmap(fieldNums, secondaryBitmapMarked, nextFieldNum);
tertiaryBitmapMarked = markTertiaryBitmap(fieldNums, tertiaryBitmapMarked, nextFieldNum);
fieldNums.add(nextFieldNum);
}
return fieldNums;
}
protected boolean markTertiaryBitmap(List<Integer> fieldNums, boolean tertiaryBitmapMarked, int nextFieldNum) {
if (nextFieldNum > 129 && !tertiaryBitmapMarked) {
int tertiaryFlagIndex = findTertiaryFlagIndex(fieldNums);
fieldNums.add(tertiaryFlagIndex, 65);
tertiaryBitmapMarked = true;
}
return tertiaryBitmapMarked;
}
protected boolean markSecondaryBitmap(List<Integer> fieldNums, boolean secondaryBitmapMarked, int nextFieldNum) {
if (nextFieldNum > 65 && nextFieldNum < 130 && !secondaryBitmapMarked) {
fieldNums.add(0, 1);
secondaryBitmapMarked = true;
}
return secondaryBitmapMarked;
}
protected int findTertiaryFlagIndex(List<Integer> fieldNums) {
int index = 0;
for (int num : fieldNums) {
if (num > 64) {
return index;
}
index++;
}
return fieldNums.size();
}
protected void throwSiblingNotFound(MsgPair paramMsgPair, Object tag) {
MsgField paramMsgField = paramMsgPair.getMsgField();
MsgValue paramMsgValue = paramMsgPair.getMsgValue();
String previousFieldCause = "";
MsgField parentMsgField = paramMsgField.getParent();
if (parentMsgField != null && parentMsgField.getLengthPacker() != null) {
previousFieldCause = " \nNext cause is incorrect implementation of the " +
parentMsgField.getLengthPacker().getClass().getSimpleName() +
" class of the previous '" +
navigator.getPathRecursively(parentMsgField) + "' field.";
}
String tagPackerClass = "null";
TagPacker tagPacker = navigator.getTagPacker(paramMsgField);
if (tagPacker != null) {
tagPackerClass = tagPacker.getClass().getSimpleName();
}
throw new PackerRuntimeException("Cannot find a sibling with tag '" + tag +
"' for the '" + navigator.getPathRecursively(paramMsgValue) +
"' field. Its parent '" + navigator.getPathRecursively(parentMsgField) +
"' has no child with such tag." +
"\nThere are few possible causes of this error. " +
"\nFirst cause is an incorrect implementation of " + tagPackerClass +
".unpack() method used for unpacking a tag from bytes. " +
"\nSecond cause is an undefined (unknown) child with tag '" + tag +
"' and parent '" + navigator.getPathRecursively(parentMsgField) +
"' in the MsgField definition. Unknown TLV and LTV tags should have tag, length and body packers in the parent."
+ previousFieldCause + " " +
"\nNext cause may be an incorrect order of tag and length subfields." +
"\nNext cause is wrong place of actual context inside the rootMsgField, actual place is " +
navigator.getPathRecursively(paramMsgField) + ".");
}
protected int getMaxFieldNum(List<MsgField> children, MsgField parent) {
int result = 0;
for (MsgField nextMsgField : children) {
Integer fieldNum = nextMsgField.getFieldNum();
if (fieldNum == null) {
String path = navigator.getPathRecursively(nextMsgField);
throw new PackerRuntimeException("The MsgField with path '" + path + "' " +
"has no 'fieldNum' property defined. " +
"Please call the defineFieldNum(...) value to the MsgField. " +
"The value is mandatory because its parent has the '" + MsgFieldType.class.getSimpleName() +
"." + parent.getType() + "' type.");
}
if (fieldNum > result) {
result = fieldNum;
}
}
return result;
}
protected MsgField findSiblingByTag(Object tag, MsgField msgField) {
MsgField parent = msgField.getParent();
for (MsgField child : parent.getChildren()) {
if (Objects.equals(child.getTag(), tag)) {
return child;
}
}
return null;
}
/**
* Create a new instance of {@link ValueHolder} and set msgPair values to its
* {@link #msgField} and {@link #msgValue} context objects.
* @param msgPair contains {@link MsgField} and {@link MsgValue}.
* @return The created instance.
*/
public static ValueHolder newInstance(MsgPair msgPair) {
ValueHolder valueHolder = new ValueHolder();
valueHolder.createDefaultServices();
valueHolder.msgField = msgPair.getMsgField();
if (valueHolder.msgField == null) {
throw new PackerRuntimeException("MsgField cannot be 'null'.");
}
valueHolder.msgValue = msgPair.getMsgValue();
if (valueHolder.msgValue == null) {
throw new PackerRuntimeException("MsgValue cannot be 'null'.");
}
return valueHolder;
}
/**
* Change the current {@link #msgField} and {@link #msgValue} to the new location in the {@link #msgField} graph.
* <p>
* The new location will be the child with given name from {@link #msgField}
* and the <b>first</b> child of the {@link #msgValue} with the name.
* <p>
* If the current {@link #msgValue} doesn't have the child, it will be created. Else the found child will be set
* tho the {@link #msgValue} field.
*
* @param childName the {@link #msgField}'s child.
* @return The current instance of {@link ValueHolder}.
*/
public ValueHolder jumpToChild(String childName) {
try {
MsgField msgFieldChild = navigator.getChildOrThrowException(childName, msgField);
MsgValue msgValueChild = msgValue.getChildNamesMap().get(childName);
if (msgValueChild == null) {
msgValueChild = createChildren(childName);
}
this.msgValue = msgValueChild;
this.msgField = msgFieldChild;
return this;
} catch (Exception e) {
MsgField rootMsgField = navigator.findRoot(msgField);
if (e instanceof PackerRuntimeException) {
throw new PackerRuntimeException("Message: " + e.getMessage(), e);
} else {
String dump = "\nCannot find a child." + ROOT_MSG_FIELD + visualizer.dumpMsgField(rootMsgField);
throw new PackerRuntimeException("Exception message: " + e.getMessage() + dump, e);
}
}
}
protected MsgValue createChildren(String childName) {
List<MsgField> msgFieldChildren = msgField.getChildren();
if (msgValue.getChildren() == null) {
msgValue.setChildren(new ArrayList<>());
}
List<MsgValue> msgValueChildren = msgValue.getChildren();
Map<String, MsgValue> childNamesMap = msgValue.getChildNamesMap();
MsgValue msgValueChild = null;
for (int i = 0; i < msgFieldChildren.size(); i++) {
MsgField nextMsgField = msgFieldChildren.get(i);
MsgValue newMsgValue;
if (msgValueChildren.size() < i + 1) {
newMsgValue = createMsgValue(nextMsgField);
msgValueChildren.add(newMsgValue);
} else if (!nextMsgField.getName().equals(msgValueChildren.get(i).getName())) {
newMsgValue = createMsgValue(nextMsgField);
msgValueChildren.add(i, newMsgValue);
} else {
newMsgValue = msgValueChildren.get(i);
if (!childNamesMap.containsKey(newMsgValue.getName())) {
childNamesMap.put(newMsgValue.getName(), newMsgValue);
}
}
if (newMsgValue.getName().equals(childName)) {
msgValueChild = newMsgValue;
}
}
if (msgValueChild == null) {
throw new PackerRuntimeException("Cannot create MsgValue with name " + childName);
}
return msgValueChild;
}
protected MsgValue createMsgValue(MsgField nextMsgField) {
MsgValue newMsgValue = navigator.newFromNameAndTag(nextMsgField);
newMsgValue.setParent(msgValue);
newMsgValue.setRoot(msgValue.getRoot());
msgValue.getChildNamesMap().put(newMsgValue.getName(), newMsgValue);
return newMsgValue;
}
/**
* Change actual {@link #msgField} and {@link #msgValue} to their parents.
* @return The current instance of {@link ValueHolder}.
*/
public ValueHolder jumpToParent() {
if (msgField.getParent() == null) {
throw new PackerRuntimeException("MsgField '" + navigator.getPathRecursively(msgField) + "' has no parent.");
}
if (msgValue.getParent() == null) {
throw new PackerRuntimeException("MsgValue '" + navigator.getPathRecursively(msgValue) + "' has no parent.");
}
msgField = msgField.getParent();
msgValue = msgValue.getParent();
return this;
}
/**
* Set the {@link MsgValue#setBodyValue(Object)} from the argument to the {@link #msgValue}.
* <p>
* Example of usage:
* <pre>
* ValueHolder.newInstance(msgPair)
* .jumpToChild("child_name")
* .setValue("some_value");
* </pre>
*
* <p>
* Set the {@link MsgValue#setBodyBytes(byte[])} from the bodyValue to the field, see the
* {@link #setBytes(Object)} method description.
* <p>
* Length and tag are not mandatory.
*
* @param bodyValue can be 'null' for deletion the current msgField. In the case current positions of the
* {@link #msgField} and {@link #msgValue} object graphs will be changed to theirs parents.
* @return The current {@link ValueHolder} with the same {@link #msgValue} and {@link #msgField} in its context.
*/
public ValueHolder setValue(Object bodyValue) {
if (msgField.getChildren() != null && !msgField.getChildren().isEmpty()) {
throw new PackerRuntimeException("Cannot set bodyValue to fields with children. Values can only be set to " +
"leaf fields. Field: " + navigator.getPathRecursively(msgField) + ", bodyValue: " + bodyValue);
}
if (bodyValue == null) {
msgValue.setBodyBytes(null);
msgValue.setLengthBytes(null);
msgValue.setBodyValue(null);
return this;
}
try {
msgValue.setBodyValue(bodyValue);
byte[] valueBytes = setBytes(bodyValue);
setTagAndLenBytes(valueBytes, msgValue, msgField);
return this;
} catch (Exception e) {
MsgValue rootMsgValue = navigator.findRoot(msgValue);
MsgField rootMsgField = navigator.findRoot(msgField);
MsgField appropriateMsgField = navigator.findByNameAndTagOrThrowException(rootMsgField, rootMsgValue);
throw new PackerRuntimeException("Exception message: " + e.getMessage() + "\nCannot set bodyValue" +
" to field '" + navigator.getPathRecursively(msgField) + "'" +
"\nRoot MsgValue:\n" + visualizer.dumpMsgValue(appropriateMsgField, rootMsgValue, true) +
"\nThe MsgField:\n" + visualizer.dumpMsgField(msgField) +
ROOT_MSG_FIELD + visualizer.dumpMsgField(rootMsgField), e);
}
}
/**
* Call the {@link #setValue(Object)} method. Current positions in the {@link #msgField} and {@link #msgValue}
* object graphs remain unchanged.
*
* @param bodyValue see the {@link #setValue(Object)} method description
* @param absolutePath the {@link MsgValue#getName()}s from the root field
* @return See the {@link #setValue(Object)} method description
*/
public ValueHolder setValue(Object bodyValue, String... absolutePath) {
MsgField currentMsgField = msgField;
MsgValue currentMsgValue = msgValue;
jumpAbsolute(absolutePath);
setValue(bodyValue);
this.msgField = currentMsgField;
this.msgValue = currentMsgValue;
return this;
}
/**
* Call the {@link #setValue(Object, String...)} method.
*
* @param bodyValue see the {@link #setValue(Object, String...)} method description
* @param absolutePath the field names from the root field
* @return See the {@link #setValue(Object, String...)} method description
*/
public ValueHolder setValue(Object bodyValue, List<String> absolutePath) {
return setValue(bodyValue, absolutePath.toArray(new String[0]));
}
protected byte[] setBytes(Object bodyValue) {
BodyPacker bodyPacker = msgField.getBodyPacker();
if (bodyPacker == null && msgField.getParent() != null) {
bodyPacker = msgField.getParent().getChildrenBodyPacker();
}
if (bodyPacker == null) {
throw new PackerRuntimeException("BodyPacker not found. Please call setBodyPacker(...) " +
"method\n" +
"MsgField: " + navigator.getPathRecursively(msgField));
}
byte[] bodyBytes;
int bodyLength = bodyPacker.getPackedLength(bodyValue);
Integer exactlyLength = msgField.getExactlyLength();
if (exactlyLength != null && bodyLength != exactlyLength) {
throw new PackerRuntimeException(THE_MSG_FIELD + navigator.getPathRecursively(msgField) +
"' contains the 'exactlyLength' definition with value '" + exactlyLength +
"', but the bodyValue length '" + bodyLength + "' is not the same.");
}
Integer maxLen = msgField.getMaxLen();
if (maxLen != null && maxLen < bodyLength) {
throw new PackerRuntimeException(THE_MSG_FIELD + navigator.getPathRecursively(msgField) +
"' contains the 'maxLen' definition with value '" + maxLen +
"', but its bodyValue length '" + bodyLength + "' is greater.");
}
Integer len = msgField.getLen();
if (len != null && bodyLength != len) {