-
Notifications
You must be signed in to change notification settings - Fork 868
/
ORecordSerializerNetworkV37.java
executable file
·942 lines (850 loc) · 32.7 KB
/
ORecordSerializerNetworkV37.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
/*
*
* * Copyright 2010-2016 OrientDB LTD (http://orientdb.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.
* *
* * For more information: http://orientdb.com
*
*/
package com.orientechnologies.orient.core.serialization.serializer.record.binary;
import com.orientechnologies.common.collection.OMultiValue;
import com.orientechnologies.common.exception.OException;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.common.serialization.types.ODecimalSerializer;
import com.orientechnologies.common.serialization.types.OIntegerSerializer;
import com.orientechnologies.common.serialization.types.OLongSerializer;
import com.orientechnologies.common.serialization.types.OUUIDSerializer;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal;
import com.orientechnologies.orient.core.db.record.*;
import com.orientechnologies.orient.core.db.record.ridbag.ORidBag;
import com.orientechnologies.orient.core.exception.OSerializationException;
import com.orientechnologies.orient.core.exception.OValidationException;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OProperty;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.ORecord;
import com.orientechnologies.orient.core.record.ORecordInternal;
import com.orientechnologies.orient.core.record.impl.*;
import com.orientechnologies.orient.core.serialization.ODocumentSerializable;
import com.orientechnologies.orient.core.serialization.OSerializableStream;
import com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializer;
import com.orientechnologies.orient.core.storage.index.sbtreebonsai.local.OBonsaiBucketPointer;
import com.orientechnologies.orient.core.storage.ridbag.sbtree.Change;
import com.orientechnologies.orient.core.storage.ridbag.sbtree.ChangeSerializationHelper;
import com.orientechnologies.orient.core.storage.ridbag.sbtree.OBonsaiCollectionPointer;
import com.orientechnologies.orient.core.storage.ridbag.sbtree.OSBTreeCollectionManager;
import com.orientechnologies.orient.core.util.ODateHelper;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.*;
import java.util.Map.Entry;
public class ORecordSerializerNetworkV37 implements ORecordSerializer {
public static final String NAME = "onet_ser_v37";
private static final String CHARSET_UTF_8 = "UTF-8";
private static final ORecordId NULL_RECORD_ID = new ORecordId(-2, ORID.CLUSTER_POS_INVALID);
private static final long MILLISEC_PER_DAY = 86400000;
public static final ORecordSerializerNetworkV37 INSTANCE = new ORecordSerializerNetworkV37();
public ORecordSerializerNetworkV37() {
}
public void deserializePartial(final ODocument document, final BytesContainer bytes, final String[] iFields) {
final String className = readString(bytes);
if (className.length() != 0)
ODocumentInternal.fillClassNameIfNeeded(document, className);
String fieldName;
OType type;
int size = OVarIntSerializer.readAsInteger(bytes);
int matched = 0;
while ((size--) > 0) {
fieldName = readString(bytes);
type = readOType(bytes);
Object value;
if (type == null) {
value = null;
} else {
value = deserializeValue(bytes, type, document);
}
if (ODocumentInternal.rawContainsField(document, fieldName)) {
continue;
}
ODocumentInternal.rawField(document, fieldName, value, type);
for (String field : iFields) {
if (field.equals(fieldName)) {
matched++;
}
}
if (matched == iFields.length) {
break;
}
}
}
public void deserialize(final ODocument document, final BytesContainer bytes) {
final String className = readString(bytes);
if (className.length() != 0)
ODocumentInternal.fillClassNameIfNeeded(document, className);
String fieldName;
OType type;
Object value;
int size = OVarIntSerializer.readAsInteger(bytes);
while ((size--) > 0) {
// PARSE FIELD NAME
fieldName = readString(bytes);
type = readOType(bytes);
if (type == null) {
value = null;
} else {
value = deserializeValue(bytes, type, document);
}
if (ODocumentInternal.rawContainsField(document, fieldName)) {
continue;
}
ODocumentInternal.rawField(document, fieldName, value, type);
}
ORecordInternal.clearSource(document);
}
@SuppressWarnings("unchecked")
public void serialize(final ODocument document, final BytesContainer bytes, final boolean iClassOnly) {
serializeClass(document, bytes);
if (iClassOnly) {
writeEmptyString(bytes);
return;
}
final Set<Entry<String, ODocumentEntry>> fields = ODocumentInternal.rawEntries(document);
OVarIntSerializer.write(bytes, document.fields());
for (Entry<String, ODocumentEntry> entry : fields) {
ODocumentEntry docEntry = entry.getValue();
if (!docEntry.exist())
continue;
writeString(bytes, entry.getKey());
final Object value = entry.getValue().value;
if (value != null) {
final OType type = getFieldType(entry.getValue());
if (type == null) {
throw new OSerializationException(
"Impossible serialize value of type " + value.getClass() + " with the Result binary serializer");
}
writeOType(bytes, bytes.alloc(1), type);
serializeValue(bytes, value, type, getLinkedType(document, type, entry.getKey()));
} else {
writeOType(bytes, bytes.alloc(1), null);
}
}
}
public String[] getFieldNames(ODocument reference, final BytesContainer bytes) {
// SKIP CLASS NAME
final int classNameLen = OVarIntSerializer.readAsInteger(bytes);
bytes.skip(classNameLen);
final List<String> result = new ArrayList<String>();
int size = OVarIntSerializer.readAsInteger(bytes);
String fieldName;
OType type;
while ((size--) > 0) {
fieldName = readString(bytes);
type = readOType(bytes);
if (type != null) {
deserializeValue(bytes, type, new ODocument());
}
result.add(fieldName);
}
return result.toArray(new String[result.size()]);
}
protected OClass serializeClass(final ODocument document, final BytesContainer bytes) {
final OClass clazz = ODocumentInternal.getImmutableSchemaClass(document);
String name = null;
if (clazz != null)
name = clazz.getName();
if (name == null)
name = document.getClassName();
if (name != null)
writeString(bytes, name);
else
writeEmptyString(bytes);
return clazz;
}
protected OType readOType(final BytesContainer bytes) {
return OType.getById(readByte(bytes));
}
private void writeOType(BytesContainer bytes, int pos, OType type) {
if (type == null) {
bytes.bytes[pos] = (byte) -1;
} else {
bytes.bytes[pos] = (byte) type.getId();
}
}
public byte[] serializeValue(Object value, OType type) {
BytesContainer bytes = new BytesContainer();
serializeValue(bytes, value, type, null);
return bytes.fitBytes();
}
public Object deserializeValue(byte[] val, OType type) {
BytesContainer bytes = new BytesContainer(val);
return deserializeValue(bytes, type, null);
}
public Object deserializeValue(BytesContainer bytes, OType type, ODocument document) {
Object value = null;
switch (type) {
case INTEGER:
value = OVarIntSerializer.readAsInteger(bytes);
break;
case LONG:
value = OVarIntSerializer.readAsLong(bytes);
break;
case SHORT:
value = OVarIntSerializer.readAsShort(bytes);
break;
case STRING:
value = readString(bytes);
break;
case DOUBLE:
value = Double.longBitsToDouble(readLong(bytes));
break;
case FLOAT:
value = Float.intBitsToFloat(readInteger(bytes));
break;
case BYTE:
value = readByte(bytes);
break;
case BOOLEAN:
value = readByte(bytes) == 1;
break;
case DATETIME:
value = new Date(OVarIntSerializer.readAsLong(bytes));
break;
case DATE:
long savedTime = OVarIntSerializer.readAsLong(bytes) * MILLISEC_PER_DAY;
savedTime = convertDayToTimezone(TimeZone.getTimeZone("GMT"), ODateHelper.getDatabaseTimeZone(), savedTime);
value = new Date(savedTime);
break;
case EMBEDDED:
value = new ODocument();
deserialize((ODocument) value, bytes);
if (((ODocument) value).containsField(ODocumentSerializable.CLASS_NAME)) {
String className = ((ODocument) value).field(ODocumentSerializable.CLASS_NAME);
try {
Class<?> clazz = Class.forName(className);
ODocumentSerializable newValue = (ODocumentSerializable) clazz.newInstance();
newValue.fromDocument((ODocument) value);
value = newValue;
} catch (Exception e) {
throw new RuntimeException(e);
}
} else
ODocumentInternal.addOwner((ODocument) value, document);
break;
case EMBEDDEDSET:
value = readEmbeddedCollection(bytes, new OTrackedSet<Object>(document), document);
break;
case EMBEDDEDLIST:
value = readEmbeddedCollection(bytes, new OTrackedList<Object>(document), document);
break;
case LINKSET:
value = readLinkCollection(bytes, new ORecordLazySet(document));
break;
case LINKLIST:
value = readLinkCollection(bytes, new ORecordLazyList(document));
break;
case BINARY:
value = readBinary(bytes);
break;
case LINK:
value = readOptimizedLink(bytes);
break;
case LINKMAP:
value = readLinkMap(bytes, document);
break;
case EMBEDDEDMAP:
value = readEmbeddedMap(bytes, document);
break;
case DECIMAL:
value = ODecimalSerializer.INSTANCE.deserialize(bytes.bytes, bytes.offset);
bytes.skip(ODecimalSerializer.INSTANCE.getObjectSize(bytes.bytes, bytes.offset));
break;
case LINKBAG:
ORidBag bag = readRidBag(bytes);
bag.setOwner(document);
value = bag;
break;
case TRANSIENT:
break;
case CUSTOM:
try {
String className = readString(bytes);
Class<?> clazz = Class.forName(className);
OSerializableStream stream = (OSerializableStream) clazz.newInstance();
stream.fromStream(readBinary(bytes));
if (stream instanceof OSerializableWrapper)
value = ((OSerializableWrapper) stream).getSerializable();
else
value = stream;
} catch (Exception e) {
throw new RuntimeException(e);
}
break;
case ANY:
break;
}
return value;
}
private void writeRidBag(BytesContainer bytes, ORidBag bag) {
final OSBTreeCollectionManager sbTreeCollectionManager = ODatabaseRecordThreadLocal.instance().get()
.getSbTreeCollectionManager();
UUID uuid = null;
if (sbTreeCollectionManager != null)
uuid = sbTreeCollectionManager.listenForChanges(bag);
if (uuid == null)
uuid = new UUID(-1, -1);
int uuidPos = bytes.alloc(OUUIDSerializer.UUID_SIZE);
OUUIDSerializer.INSTANCE.serialize(uuid, bytes.bytes, uuidPos);
if (bag.isEmbedded() || OGlobalConfiguration.RID_BAG_SBTREEBONSAI_TO_EMBEDDED_THRESHOLD.getValueAsInteger() >= bag.size()) {
int pos = bytes.alloc(1);
bytes.bytes[pos] = 1;
OVarIntSerializer.write(bytes, bag.size());
Iterator<OIdentifiable> iterator = bag.rawIterator();
while (iterator.hasNext()) {
OIdentifiable itemValue = iterator.next();
if (itemValue == null)
writeNullLink(bytes);
else
writeOptimizedLink(bytes, itemValue);
}
} else {
int pos = bytes.alloc(1);
bytes.bytes[pos] = 2;
OBonsaiCollectionPointer pointer = bag.getPointer();
if (pointer == null)
pointer = OBonsaiCollectionPointer.INVALID;
OVarIntSerializer.write(bytes, pointer.getFileId());
OVarIntSerializer.write(bytes, pointer.getRootPointer().getPageIndex());
OVarIntSerializer.write(bytes, pointer.getRootPointer().getPageOffset());
OVarIntSerializer.write(bytes, bag.size());
NavigableMap<OIdentifiable, Change> changes = bag.getChanges();
if (changes != null) {
OVarIntSerializer.write(bytes, changes.size());
for (Map.Entry<OIdentifiable, Change> change : changes.entrySet()) {
writeOptimizedLink(bytes, change.getKey());
int posAll = bytes.alloc(1);
bytes.bytes[posAll] = change.getValue().getType();
OVarIntSerializer.write(bytes, change.getValue().getValue());
}
} else {
OVarIntSerializer.write(bytes, 0);
}
}
}
private ORidBag readRidBag(BytesContainer bytes) {
UUID uuid = OUUIDSerializer.INSTANCE.deserialize(bytes.bytes, bytes.offset);
bytes.skip(OUUIDSerializer.UUID_SIZE);
if (uuid.getMostSignificantBits() == -1 && uuid.getLeastSignificantBits() == -1)
uuid = null;
byte b = bytes.bytes[bytes.offset];
bytes.skip(1);
if (b == 1) {
ORidBag bag = new ORidBag(uuid);
int size = OVarIntSerializer.readAsInteger(bytes);
for (int i = 0; i < size; i++) {
OIdentifiable id = readOptimizedLink(bytes);
if (id.equals(NULL_RECORD_ID))
bag.add(null);
else
bag.add(id);
}
return bag;
} else {
long fileId = OVarIntSerializer.readAsLong(bytes);
long pageIndex = OVarIntSerializer.readAsLong(bytes);
int pageOffset = OVarIntSerializer.readAsInteger(bytes);
int bagSize = OVarIntSerializer.readAsInteger(bytes);
Map<OIdentifiable, Change> changes = new HashMap<>();
int size = OVarIntSerializer.readAsInteger(bytes);
while (size-- > 0) {
OIdentifiable link = readOptimizedLink(bytes);
byte type = bytes.bytes[bytes.offset];
bytes.skip(1);
int change = OVarIntSerializer.readAsInteger(bytes);
changes.put(link, ChangeSerializationHelper.createChangeInstance(type, change));
}
OBonsaiCollectionPointer pointer = null;
if (fileId != -1)
pointer = new OBonsaiCollectionPointer(fileId, new OBonsaiBucketPointer(pageIndex, pageOffset));
return new ORidBag(pointer, changes, uuid);
}
}
private byte[] readBinary(BytesContainer bytes) {
int n = OVarIntSerializer.readAsInteger(bytes);
byte[] newValue = new byte[n];
System.arraycopy(bytes.bytes, bytes.offset, newValue, 0, newValue.length);
bytes.skip(n);
return newValue;
}
private Map<Object, OIdentifiable> readLinkMap(final BytesContainer bytes, final ODocument document) {
int size = OVarIntSerializer.readAsInteger(bytes);
Map<Object, OIdentifiable> result = new ORecordLazyMap(document);
while ((size--) > 0) {
OType keyType = readOType(bytes);
Object key = deserializeValue(bytes, keyType, document);
OIdentifiable value = readOptimizedLink(bytes);
if (value.equals(NULL_RECORD_ID))
result.put(key, null);
else
result.put(key, value);
}
return result;
}
private Object readEmbeddedMap(final BytesContainer bytes, final ODocument document) {
int size = OVarIntSerializer.readAsInteger(bytes);
final Map<Object, Object> result = new OTrackedMap<Object>(document);
while ((size--) > 0) {
String key = readString(bytes);
OType valType = readOType(bytes);
Object value = null;
if (valType != null) {
value = deserializeValue(bytes, valType, document);
}
result.put(key, value);
}
return result;
}
private Collection<OIdentifiable> readLinkCollection(BytesContainer bytes, Collection<OIdentifiable> found) {
final int items = OVarIntSerializer.readAsInteger(bytes);
for (int i = 0; i < items; i++) {
OIdentifiable id = readOptimizedLink(bytes);
if (id.equals(NULL_RECORD_ID))
found.add(null);
else
found.add(id);
}
return found;
}
private OIdentifiable readOptimizedLink(final BytesContainer bytes) {
ORecordId id = new ORecordId(OVarIntSerializer.readAsInteger(bytes), OVarIntSerializer.readAsLong(bytes));
if (id.isTemporary()) {
OIdentifiable persRef = id.getRecord();
if (persRef != null)
return persRef;
}
return id;
}
private Collection<?> readEmbeddedCollection(final BytesContainer bytes, final Collection<Object> found,
final ODocument document) {
final int items = OVarIntSerializer.readAsInteger(bytes);
for (int i = 0; i < items; i++) {
OType itemType = readOType(bytes);
if (itemType == null)
found.add(null);
else
found.add(deserializeValue(bytes, itemType, document));
}
return found;
}
private OType getLinkedType(ODocument document, OType type, String key) {
if (type != OType.EMBEDDEDLIST && type != OType.EMBEDDEDSET && type != OType.EMBEDDEDMAP)
return null;
OClass immutableClass = ODocumentInternal.getImmutableSchemaClass(document);
if (immutableClass != null) {
OProperty prop = immutableClass.getProperty(key);
if (prop != null) {
return prop.getLinkedType();
}
}
return null;
}
@SuppressWarnings("unchecked")
public void serializeValue(final BytesContainer bytes, Object value, final OType type, final OType linkedType) {
int pointer = 0;
switch (type) {
case INTEGER:
case LONG:
case SHORT:
OVarIntSerializer.write(bytes, ((Number) value).longValue());
break;
case STRING:
writeString(bytes, value.toString());
break;
case DOUBLE:
long dg = Double.doubleToLongBits((Double) value);
pointer = bytes.alloc(OLongSerializer.LONG_SIZE);
OLongSerializer.INSTANCE.serializeLiteral(dg, bytes.bytes, pointer);
break;
case FLOAT:
int fg = Float.floatToIntBits((Float) value);
pointer = bytes.alloc(OIntegerSerializer.INT_SIZE);
OIntegerSerializer.INSTANCE.serializeLiteral(fg, bytes.bytes, pointer);
break;
case BYTE:
pointer = bytes.alloc(1);
bytes.bytes[pointer] = (Byte) value;
break;
case BOOLEAN:
pointer = bytes.alloc(1);
bytes.bytes[pointer] = ((Boolean) value) ? (byte) 1 : (byte) 0;
break;
case DATETIME:
if (value instanceof Long) {
OVarIntSerializer.write(bytes, (Long) value);
} else
OVarIntSerializer.write(bytes, ((Date) value).getTime());
break;
case DATE:
long dateValue;
if (value instanceof Long) {
dateValue = (Long) value;
} else
dateValue = ((Date) value).getTime();
dateValue = convertDayToTimezone(ODateHelper.getDatabaseTimeZone(), TimeZone.getTimeZone("GMT"), dateValue);
OVarIntSerializer.write(bytes, dateValue / MILLISEC_PER_DAY);
break;
case EMBEDDED:
if (value instanceof ODocumentSerializable) {
ODocument cur = ((ODocumentSerializable) value).toDocument();
cur.field(ODocumentSerializable.CLASS_NAME, value.getClass().getName());
serialize(cur, bytes, false);
} else {
serialize((ODocument) value, bytes, false);
}
break;
case EMBEDDEDSET:
case EMBEDDEDLIST:
if (value.getClass().isArray())
writeEmbeddedCollection(bytes, Arrays.asList(OMultiValue.array(value)), linkedType);
else
writeEmbeddedCollection(bytes, (Collection<?>) value, linkedType);
break;
case DECIMAL:
BigDecimal decimalValue = (BigDecimal) value;
pointer = bytes.alloc(ODecimalSerializer.INSTANCE.getObjectSize(decimalValue));
ODecimalSerializer.INSTANCE.serialize(decimalValue, bytes.bytes, pointer);
break;
case BINARY:
pointer = writeBinary(bytes, (byte[]) (value));
break;
case LINKSET:
case LINKLIST:
Collection<OIdentifiable> ridCollection = (Collection<OIdentifiable>) value;
writeLinkCollection(bytes, ridCollection);
break;
case LINK:
if (!(value instanceof OIdentifiable))
throw new OValidationException("Value '" + value + "' is not a OIdentifiable");
writeOptimizedLink(bytes, (OIdentifiable) value);
break;
case LINKMAP:
writeLinkMap(bytes, (Map<Object, OIdentifiable>) value);
break;
case EMBEDDEDMAP:
writeEmbeddedMap(bytes, (Map<Object, Object>) value);
break;
case LINKBAG:
writeRidBag(bytes, (ORidBag) value);
break;
case CUSTOM:
if (!(value instanceof OSerializableStream))
value = new OSerializableWrapper((Serializable) value);
writeString(bytes, value.getClass().getName());
writeBinary(bytes, ((OSerializableStream) value).toStream());
break;
case TRANSIENT:
break;
case ANY:
break;
}
}
private int writeBinary(final BytesContainer bytes, final byte[] valueBytes) {
final int pointer = OVarIntSerializer.write(bytes, valueBytes.length);
final int start = bytes.alloc(valueBytes.length);
System.arraycopy(valueBytes, 0, bytes.bytes, start, valueBytes.length);
return pointer;
}
private int writeLinkMap(final BytesContainer bytes, final Map<Object, OIdentifiable> map) {
final boolean disabledAutoConversion =
map instanceof ORecordLazyMultiValue && ((ORecordLazyMultiValue) map).isAutoConvertToRecord();
if (disabledAutoConversion)
// AVOID TO FETCH RECORD
((ORecordLazyMultiValue) map).setAutoConvertToRecord(false);
try {
final int fullPos = OVarIntSerializer.write(bytes, map.size());
for (Entry<Object, OIdentifiable> entry : map.entrySet()) {
// TODO:check skip of complex types
// FIXME: changed to support only string key on map
final OType type = OType.STRING;
writeOType(bytes, bytes.alloc(1), type);
writeString(bytes, entry.getKey().toString());
if (entry.getValue() == null)
writeNullLink(bytes);
else
writeOptimizedLink(bytes, entry.getValue());
}
return fullPos;
} finally {
if (disabledAutoConversion)
((ORecordLazyMultiValue) map).setAutoConvertToRecord(true);
}
}
@SuppressWarnings("unchecked")
private int writeEmbeddedMap(BytesContainer bytes, Map<Object, Object> map) {
final int fullPos = OVarIntSerializer.write(bytes, map.size());
for (Entry<Object, Object> entry : map.entrySet()) {
writeString(bytes, entry.getKey().toString());
final Object value = entry.getValue();
if (value != null) {
final OType type = getTypeFromValueEmbedded(value);
if (type == null) {
throw new OSerializationException(
"Impossible serialize value of type " + value.getClass() + " with the Result binary serializer");
}
writeOType(bytes, bytes.alloc(1), type);
serializeValue(bytes, value, type, null);
} else {
writeOType(bytes, bytes.alloc(1), null);
}
}
return fullPos;
}
private int writeNullLink(final BytesContainer bytes) {
final int pos = OVarIntSerializer.write(bytes, NULL_RECORD_ID.getIdentity().getClusterId());
OVarIntSerializer.write(bytes, NULL_RECORD_ID.getIdentity().getClusterPosition());
return pos;
}
private int writeOptimizedLink(final BytesContainer bytes, OIdentifiable link) {
if (!link.getIdentity().isPersistent()) {
final ORecord real = link.getRecord();
if (real != null)
link = real;
}
final int pos = OVarIntSerializer.write(bytes, link.getIdentity().getClusterId());
OVarIntSerializer.write(bytes, link.getIdentity().getClusterPosition());
return pos;
}
private int writeLinkCollection(final BytesContainer bytes, final Collection<OIdentifiable> value) {
final int pos = OVarIntSerializer.write(bytes, value.size());
final boolean disabledAutoConversion =
value instanceof ORecordLazyMultiValue && ((ORecordLazyMultiValue) value).isAutoConvertToRecord();
if (disabledAutoConversion)
// AVOID TO FETCH RECORD
((ORecordLazyMultiValue) value).setAutoConvertToRecord(false);
try {
for (OIdentifiable itemValue : value) {
// TODO: handle the null links
if (itemValue == null)
writeNullLink(bytes);
else
writeOptimizedLink(bytes, itemValue);
}
} finally {
if (disabledAutoConversion)
((ORecordLazyMultiValue) value).setAutoConvertToRecord(true);
}
return pos;
}
private int writeEmbeddedCollection(final BytesContainer bytes, final Collection<?> value, final OType linkedType) {
final int pos = OVarIntSerializer.write(bytes, value.size());
// TODO manage embedded type from schema and auto-determined.
for (Object itemValue : value) {
// TODO:manage in a better way null entry
if (itemValue == null) {
writeOType(bytes, bytes.alloc(1), null);
continue;
}
OType type;
if (linkedType == null)
type = getTypeFromValueEmbedded(itemValue);
else
type = linkedType;
if (type != null) {
writeOType(bytes, bytes.alloc(1), type);
serializeValue(bytes, itemValue, type, null);
} else {
throw new OSerializationException(
"Impossible serialize value of type " + value.getClass() + " with the ODocument binary serializer");
}
}
return pos;
}
private OType getFieldType(final ODocumentEntry entry) {
OType type = entry.type;
if (type == null) {
final OProperty prop = entry.property;
if (prop != null)
type = prop.getType();
}
if (type == null || OType.ANY == type)
type = OType.getTypeByValue(entry.value);
return type;
}
private OType getTypeFromValueEmbedded(final Object fieldValue) {
OType type = OType.getTypeByValue(fieldValue);
if (type == OType.LINK && fieldValue instanceof ODocument && !((ODocument) fieldValue).getIdentity().isValid())
type = OType.EMBEDDED;
return type;
}
protected String readString(final BytesContainer bytes) {
final int len = OVarIntSerializer.readAsInteger(bytes);
final String res = stringFromBytes(bytes.bytes, bytes.offset, len);
bytes.skip(len);
return res;
}
protected int readInteger(final BytesContainer container) {
final int value = OIntegerSerializer.INSTANCE.deserializeLiteral(container.bytes, container.offset);
container.offset += OIntegerSerializer.INT_SIZE;
return value;
}
private byte readByte(final BytesContainer container) {
return container.bytes[container.offset++];
}
private long readLong(final BytesContainer container) {
final long value = OLongSerializer.INSTANCE.deserializeLiteral(container.bytes, container.offset);
container.offset += OLongSerializer.LONG_SIZE;
return value;
}
private int writeEmptyString(final BytesContainer bytes) {
return OVarIntSerializer.write(bytes, 0);
}
private int writeString(final BytesContainer bytes, final String toWrite) {
final byte[] nameBytes = bytesFromString(toWrite);
final int pointer = OVarIntSerializer.write(bytes, nameBytes.length);
final int start = bytes.alloc(nameBytes.length);
System.arraycopy(nameBytes, 0, bytes.bytes, start, nameBytes.length);
return pointer;
}
private byte[] bytesFromString(final String toWrite) {
try {
return toWrite.getBytes(CHARSET_UTF_8);
} catch (UnsupportedEncodingException e) {
throw OException.wrapException(new OSerializationException("Error on string encoding"), e);
}
}
protected String stringFromBytes(final byte[] bytes, final int offset, final int len) {
try {
return new String(bytes, offset, len, CHARSET_UTF_8);
} catch (UnsupportedEncodingException e) {
throw OException.wrapException(new OSerializationException("Error on string decoding"), e);
}
}
public OBinaryField deserializeField(final BytesContainer bytes, final OClass iClass, final String iFieldName) {
// TODO: check if integrate the binary disc binary comparator here
throw new UnsupportedOperationException("network serializer doesn't support comparators");
}
private long convertDayToTimezone(TimeZone from, TimeZone to, long time) {
Calendar fromCalendar = Calendar.getInstance(from);
fromCalendar.setTimeInMillis(time);
Calendar toCalendar = Calendar.getInstance(to);
toCalendar.setTimeInMillis(0);
toCalendar.set(Calendar.ERA, fromCalendar.get(Calendar.ERA));
toCalendar.set(Calendar.YEAR, fromCalendar.get(Calendar.YEAR));
toCalendar.set(Calendar.MONTH, fromCalendar.get(Calendar.MONTH));
toCalendar.set(Calendar.DAY_OF_MONTH, fromCalendar.get(Calendar.DAY_OF_MONTH));
toCalendar.set(Calendar.HOUR_OF_DAY, 0);
toCalendar.set(Calendar.MINUTE, 0);
toCalendar.set(Calendar.SECOND, 0);
toCalendar.set(Calendar.MILLISECOND, 0);
return toCalendar.getTimeInMillis();
}
@Override
public ORecord fromStream(byte[] iSource, ORecord iRecord, String[] iFields) {
if (iSource == null || iSource.length == 0)
return iRecord;
if (iRecord == null) {
iRecord = new ODocument();
} else if (iRecord instanceof OBlob) {
iRecord.fromStream(iSource);
return iRecord;
} else if (iRecord instanceof ORecordFlat) {
iRecord.fromStream(iSource);
return iRecord;
}
ORecordInternal.setRecordSerializer(iRecord, this);
BytesContainer container = new BytesContainer(iSource);
try {
if (iFields != null && iFields.length > 0)
deserializePartial((ODocument) iRecord, container, iFields);
else
deserialize((ODocument) iRecord, container);
} catch (RuntimeException e) {
OLogManager.instance()
.warn(this, "Error deserializing record with id %s send this data for debugging: %s ", iRecord.getIdentity().toString(),
Base64.getEncoder().encodeToString(iSource));
throw e;
}
return iRecord;
}
@Override
public byte[] toStream(ORecord iSource, boolean iOnlyDelta) {
if (iSource instanceof OBlob) {
return iSource.toStream();
} else if (iSource instanceof ORecordFlat) {
return iSource.toStream();
} else {
final BytesContainer container = new BytesContainer();
ODocument doc = (ODocument) iSource;
// SERIALIZE RECORD
if (!iOnlyDelta){
serialize(doc, container, false);
}
else{
ODocument deltaDoc = doc.getDeltaFromOriginal();
serialize(deltaDoc, container, false);
}
return container.fitBytes();
}
}
@Override
public byte[] writeClassOnly(ORecord iSource) {
final BytesContainer container = new BytesContainer();
serialize((ODocument) iSource, container, true);
return container.fitBytes();
}
@Override
public int getCurrentVersion() {
return 0;
}
@Override
public int getMinSupportedVersion() {
return 0;
}
@Override
public boolean getSupportBinaryEvaluate() {
return false;
}
@Override
public String getName() {
return NAME;
}
@Override
public <RET> RET deserializeFieldFromRoot(byte[] record, String iFieldName) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public <RET> RET deserializeFieldFromEmbedded(byte[] record, int offset, String iFieldName, int serializerVersion) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
@Override
public String[] getFieldNamesRoot(ODocument reference, byte[] iSource) {
if (iSource == null || iSource.length == 0)
return new String[0];
final BytesContainer container = new BytesContainer(iSource);
try {
return getFieldNames(reference, container);
} catch (RuntimeException e) {
OLogManager.instance().warn(this, "Error deserializing record to get field-names, send this data for debugging: %s ",
Base64.getEncoder().encodeToString(iSource));
throw e;
}
}
@Override
public String[] getFieldNamesEmbedded(ODocument reference, byte[] iSource, int offset, int serializerVersion) {
return getFieldNamesRoot(reference, iSource);
}
}