-
Notifications
You must be signed in to change notification settings - Fork 868
/
ODocument.java
executable file
·3415 lines (3002 loc) · 120 KB
/
ODocument.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 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.record.impl;
import com.orientechnologies.common.collection.OMultiValue;
import com.orientechnologies.common.exception.OException;
import com.orientechnologies.common.io.OIOUtils;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.common.util.OCommonConst;
import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.db.ODatabase;
import com.orientechnologies.orient.core.db.ODatabaseDocumentInternal;
import com.orientechnologies.orient.core.db.ODatabaseRecordThreadLocal;
import com.orientechnologies.orient.core.db.document.ODatabaseDocument;
import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.db.record.*;
import com.orientechnologies.orient.core.db.record.ridbag.ORidBag;
import com.orientechnologies.orient.core.exception.*;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.iterator.OEmptyMapEntryIterator;
import com.orientechnologies.orient.core.metadata.OMetadataInternal;
import com.orientechnologies.orient.core.metadata.schema.*;
import com.orientechnologies.orient.core.metadata.security.OIdentity;
import com.orientechnologies.orient.core.metadata.security.OSecurityShared;
import com.orientechnologies.orient.core.record.*;
import com.orientechnologies.orient.core.serialization.ODocumentSerializable;
import com.orientechnologies.orient.core.serialization.serializer.OStringSerializerHelper;
import com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializer;
import com.orientechnologies.orient.core.serialization.serializer.record.ORecordSerializerFactory;
import com.orientechnologies.orient.core.serialization.serializer.record.binary.ORecordSerializerNetwork;
import com.orientechnologies.orient.core.sql.OSQLHelper;
import com.orientechnologies.orient.core.sql.filter.OSQLPredicate;
import com.orientechnologies.orient.core.storage.OBasicTransaction;
import com.orientechnologies.orient.core.storage.OStorage;
import java.io.*;
import java.lang.ref.WeakReference;
import java.util.*;
import java.util.Map.Entry;
import java.util.stream.Collectors;
/**
* Document representation to handle values dynamically. Can be used in schema-less, schema-mixed and schema-full modes. Fields can
* be added at run-time. Instances can be reused across calls by using the reset() before to re-use.
*/
@SuppressWarnings({ "unchecked" })
public class ODocument extends ORecordAbstract
implements Iterable<Entry<String, Object>>, ORecordSchemaAware, ODetachable, Externalizable, OElement {
public static final byte RECORD_TYPE = 'd';
protected static final String[] EMPTY_STRINGS = new String[] {};
private static final long serialVersionUID = 1L;
protected int _fieldSize;
protected Map<String, ODocumentEntry> _fields;
protected boolean _trackingChanges = true;
protected boolean _ordered = true;
protected boolean _lazyLoad = true;
protected boolean _allowChainedAccess = true;
protected transient List<WeakReference<ORecordElement>> _owners = null;
protected OImmutableSchema _schema;
private String _className;
private OImmutableClass _immutableClazz;
private int _immutableSchemaVersion = 1;
/**
* Internal constructor used on unmarshalling.
*/
public ODocument() {
setup();
}
/**
* Creates a new instance by the raw stream usually read from the database. New instances are not persistent until {@link #save()}
* is called.
*
* @param iSource Raw stream
*/
@Deprecated
public ODocument(final byte[] iSource) {
_source = iSource;
setup();
}
/**
* Creates a new instance by the raw stream usually read from the database. New instances are not persistent until {@link #save()}
* is called.
*
* @param iSource Raw stream as InputStream
*/
public ODocument(final InputStream iSource) throws IOException {
final ByteArrayOutputStream out = new ByteArrayOutputStream();
OIOUtils.copyStream(iSource, out, -1);
_source = out.toByteArray();
setup();
}
/**
* Creates a new instance in memory linked by the Record Id to the persistent one. New instances are not persistent until {@link
* #save()} is called.
*
* @param iRID Record Id
*/
public ODocument(final ORID iRID) {
setup();
_recordId = (ORecordId) iRID;
_status = STATUS.NOT_LOADED;
_dirty = false;
_contentChanged = false;
}
/**
* Creates a new instance in memory of the specified class, linked by the Record Id to the persistent one. New instances are not
* persistent until {@link #save()} is called.
*
* @param iClassName Class name
* @param iRID Record Id
*/
public ODocument(final String iClassName, final ORID iRID) {
this(iClassName);
_recordId = (ORecordId) iRID;
final ODatabaseDocumentInternal database = getDatabaseInternal();
if (_recordId.getClusterId() > -1) {
final OSchema schema = database.getMetadata().getImmutableSchemaSnapshot();
final OClass cls = schema.getClassByClusterId(_recordId.getClusterId());
if (cls != null && !cls.getName().equals(iClassName))
throw new IllegalArgumentException(
"Cluster id does not correspond class name should be " + iClassName + " but found " + cls.getName());
}
_dirty = false;
_contentChanged = false;
_status = STATUS.NOT_LOADED;
}
/**
* Creates a new instance in memory of the specified class. New instances are not persistent until {@link #save()} is called.
*
* @param iClassName Class name
*/
public ODocument(final String iClassName) {
setup();
setClassName(iClassName);
}
/**
* Creates a new instance in memory of the specified schema class. New instances are not persistent until {@link #save()} is
* called. The database reference is taken from the thread local.
*
* @param iClass OClass instance
*/
public ODocument(final OClass iClass) {
this(iClass != null ? iClass.getName() : null);
}
/**
* Fills a document passing the field array in form of pairs of field name and value.
*
* @param iFields Array of field pairs
*/
public ODocument(final Object[] iFields) {
setup();
if (iFields != null && iFields.length > 0)
for (int i = 0; i < iFields.length; i += 2) {
field(iFields[i].toString(), iFields[i + 1]);
}
}
/**
* Fills a document passing a map of key/values where the key is the field name and the value the field's value.
*
* @param iFieldMap Map of Object/Object
*/
public ODocument(final Map<?, Object> iFieldMap) {
setup();
if (iFieldMap != null && !iFieldMap.isEmpty())
for (Entry<?, Object> entry : iFieldMap.entrySet()) {
field(entry.getKey().toString(), entry.getValue());
}
}
/**
* Fills a document passing the field names/values pair, where the first pair is mandatory.
*/
public ODocument(final String iFieldName, final Object iFieldValue, final Object... iFields) {
this(iFields);
field(iFieldName, iFieldValue);
}
@Override
public Optional<OVertex> asVertex() {
if (this instanceof OVertex)
return Optional.of((OVertex) this);
OClass type = this.getSchemaClass();
if (type == null) {
return Optional.empty();
}
if (type.isVertexType()) {
return Optional.of(new OVertexDelegate(this));
}
return Optional.empty();
}
@Override
public Optional<OEdge> asEdge() {
if (this instanceof OEdge)
return Optional.of((OEdge) this);
OClass type = this.getSchemaClass();
if (type == null) {
return Optional.empty();
}
if (type.isEdgeType()) {
return Optional.of(new OEdgeDelegate(this));
}
return Optional.empty();
}
@Override
public boolean isVertex() {
if (this instanceof OVertex)
return true;
OClass type = this.getSchemaClass();
if (type == null) {
return false;
}
return type.isVertexType();
}
@Override
public boolean isEdge() {
if (this instanceof OEdge)
return true;
OClass type = this.getSchemaClass();
if (type == null) {
return false;
}
return type.isEdgeType();
}
@Override
public Optional<OClass> getSchemaType() {
return Optional.ofNullable(getSchemaClass());
}
@Override
public Set<String> getPropertyNames() {
checkForLoading();
if (_status == ORecordElement.STATUS.LOADED && _source != null && ODatabaseRecordThreadLocal.instance().isDefined()
&& !ODatabaseRecordThreadLocal.instance().get().isClosed()) {
// DESERIALIZE FIELD NAMES ONLY (SUPPORTED ONLY BY BINARY SERIALIZER)
final String[] fieldNames = _recordFormat.getFieldNamesRoot(this, _source);
if (fieldNames != null) {
Set<String> result = new HashSet<>();
Collections.addAll(result, fieldNames);
return result;
}
}
checkForFields();
if (_fields == null || _fields.size() == 0)
return Collections.EMPTY_SET;
return _fields.entrySet().stream().filter(s -> s.getValue().exist()).map(Entry::getKey).collect(Collectors.toSet());
}
/**
* retrieves a property value from the current document
*
* @param iFieldName The field name, it can contain any character (it's not evaluated as an expression, as in #eval()
* @param <RET>
*
* @return the field value. Null if the field does not exist.
*/
public <RET> RET getProperty(final String iFieldName) {
if (iFieldName == null)
return null;
checkForLoading();
RET value = (RET) ODocumentHelper.getIdentifiableValue(this, iFieldName);
if (!iFieldName.startsWith("@") && _lazyLoad && value instanceof ORID && (((ORID) value).isPersistent() || ((ORID) value)
.isNew()) && ODatabaseRecordThreadLocal.instance().isDefined()) {
// CREATE THE DOCUMENT OBJECT IN LAZY WAY
RET newValue = getDatabase().load((ORID) value);
if (newValue != null) {
unTrack((ORID) value);
track((OIdentifiable) newValue);
value = newValue;
if (isTrackingChanges()) {
ORecordInternal.setDirtyManager((ORecord) value, this.getDirtyManager());
}
ODocumentEntry entry = _fields.get(iFieldName);
removeCollectionChangeListener(entry, entry.value);
entry.value = value;
addCollectionChangeListener(entry);
}
}
if (value instanceof OElement) {
if (((OElement) value).isVertex()) {
value = (RET) ((OElement) value).asVertex().get();
} else if (((OElement) value).isEdge()) {
value = (RET) ((OElement) value).asEdge().get();
}
}
return value;
}
/**
* retrieves a property value from the current document, without evaluating it (eg. no conversion from RID to document)
*
* @param iFieldName The field name, it can contain any character (it's not evaluated as an expression, as in #eval()
* @param <RET>
*
* @return the field value. Null if the field does not exist.
*/
protected <RET> RET getRawProperty(final String iFieldName) {
if (iFieldName == null)
return null;
checkForLoading();
return (RET) ODocumentHelper.getIdentifiableValue(this, iFieldName);
}
/**
* sets a property value on current document
*
* @param iFieldName The property name
* @param iPropertyValue The property value
*/
public void setProperty(final String iFieldName, Object iPropertyValue) {
setProperty(iFieldName, iPropertyValue, OCommonConst.EMPTY_TYPES_ARRAY);
}
/**
* Sets
*
* @param iPropetyName The property name
* @param iPropertyValue The property value
* @param iFieldType Forced type (not auto-determined)
*/
public void setProperty(String iPropetyName, Object iPropertyValue, OType... iFieldType) {
if (iPropetyName == null)
throw new IllegalArgumentException("Field is null");
if (iPropetyName.isEmpty())
throw new IllegalArgumentException("Field name is empty");
if (ODocumentHelper.ATTRIBUTE_CLASS.equals(iPropetyName)) {
setClassName(iPropertyValue.toString());
return;
} else if (ODocumentHelper.ATTRIBUTE_RID.equals(iPropetyName)) {
_recordId.fromString(iPropertyValue.toString());
return;
} else if (ODocumentHelper.ATTRIBUTE_VERSION.equals(iPropetyName)) {
if (iPropertyValue != null) {
int v;
if (iPropertyValue instanceof Number)
v = ((Number) iPropertyValue).intValue();
else
v = Integer.parseInt(iPropertyValue.toString());
_recordVersion = v;
}
return;
}
checkForLoading();
checkForFields();
ODocumentEntry entry = _fields.get(iPropetyName);
final boolean knownProperty;
final Object oldValue;
final OType oldType;
if (entry == null) {
entry = new ODocumentEntry();
_fieldSize++;
_fields.put(iPropetyName, entry);
entry.setCreated(true);
knownProperty = false;
oldValue = null;
oldType = null;
} else {
knownProperty = entry.exist();
oldValue = entry.value;
oldType = entry.type;
}
OType fieldType = deriveFieldType(iPropetyName, entry, iFieldType);
if (iPropertyValue != null && fieldType != null) {
iPropertyValue = ODocumentHelper.convertField(this, iPropetyName, fieldType, null, iPropertyValue);
} else if (iPropertyValue instanceof Enum)
iPropertyValue = iPropertyValue.toString();
if (knownProperty)
// CHECK IF IS REALLY CHANGED
if (iPropertyValue == null) {
if (oldValue == null)
// BOTH NULL: UNCHANGED
return;
} else {
try {
if (iPropertyValue.equals(oldValue)) {
if (fieldType == oldType) {
if (!(iPropertyValue instanceof ORecordElement))
// SAME BUT NOT TRACKABLE: SET THE RECORD AS DIRTY TO BE SURE IT'S SAVED
setDirty();
// SAVE VALUE: UNCHANGED
return;
}
}
} catch (Exception e) {
OLogManager.instance()
.warn(this, "Error on checking the value of property %s against the record %s", e, iPropetyName, getIdentity());
}
}
if (oldValue instanceof ORidBag) {
final ORidBag ridBag = (ORidBag) oldValue;
ridBag.setOwner(null);
} else if (oldValue instanceof ODocument) {
((ODocument) oldValue).removeOwner(this);
}
if (oldValue instanceof OIdentifiable) {
unTrack((OIdentifiable) oldValue);
}
if (iPropertyValue != null) {
if (iPropertyValue instanceof ODocument) {
if (OType.EMBEDDED.equals(fieldType)) {
final ODocument embeddedDocument = (ODocument) iPropertyValue;
ODocumentInternal.addOwner(embeddedDocument, this);
}
}
if (iPropertyValue instanceof OIdentifiable) {
track((OIdentifiable) iPropertyValue);
}
if (iPropertyValue instanceof ORidBag) {
final ORidBag ridBag = (ORidBag) iPropertyValue;
ridBag.setOwner(null); // in order to avoid IllegalStateException when ridBag changes the owner (ODocument.merge)
ridBag.setOwner(this);
}
}
if (oldType != fieldType && oldType != null) {
// can be made in a better way, but "keeping type" issue should be solved before
if (iPropertyValue == null || fieldType != null || oldType != OType.getTypeByValue(iPropertyValue))
entry.type = fieldType;
}
removeCollectionChangeListener(entry, oldValue);
entry.value = iPropertyValue;
if (!entry.exist()) {
entry.setExist(true);
_fieldSize++;
}
addCollectionChangeListener(entry);
if (_status != STATUS.UNMARSHALLING) {
setDirty();
if (!entry.isChanged()) {
entry.original = oldValue;
entry.setChanged(true);
}
}
}
public <RET> RET removeProperty(final String iFieldName) {
checkForLoading();
checkForFields();
if (ODocumentHelper.ATTRIBUTE_CLASS.equalsIgnoreCase(iFieldName)) {
setClassName(null);
} else if (ODocumentHelper.ATTRIBUTE_RID.equalsIgnoreCase(iFieldName)) {
_recordId = new ORecordId();
}
final ODocumentEntry entry = _fields.get(iFieldName);
if (entry == null)
return null;
Object oldValue = entry.value;
if (entry.exist() && _trackingChanges) {
// SAVE THE OLD VALUE IN A SEPARATE MAP
if (entry.original == null)
entry.original = entry.value;
entry.value = null;
entry.setExist(false);
entry.setChanged(true);
} else {
_fields.remove(iFieldName);
}
_fieldSize--;
removeCollectionChangeListener(entry, oldValue);
if (oldValue instanceof OIdentifiable)
unTrack((OIdentifiable) oldValue);
if (oldValue instanceof ORidBag)
((ORidBag) oldValue).setOwner(null);
setDirty();
return (RET) oldValue;
}
protected static void validateField(ODocument iRecord, OImmutableProperty p) throws OValidationException {
final Object fieldValue;
ODocumentEntry entry = iRecord._fields.get(p.getName());
if (entry != null && entry.exist()) {
// AVOID CONVERSIONS: FASTER!
fieldValue = entry.value;
if (p.isNotNull() && fieldValue == null)
// NULLITY
throw new OValidationException("The field '" + p.getFullName() + "' cannot be null, record: " + iRecord);
if (fieldValue != null && p.getRegexp() != null && p.getType().equals(OType.STRING)) {
// REGEXP
if (!((String) fieldValue).matches(p.getRegexp()))
throw new OValidationException(
"The field '" + p.getFullName() + "' does not match the regular expression '" + p.getRegexp() + "'. Field value is: "
+ fieldValue + ", record: " + iRecord);
}
} else {
if (p.isMandatory()) {
throw new OValidationException("The field '" + p.getFullName() + "' is mandatory, but not found on record: " + iRecord);
}
fieldValue = null;
}
final OType type = p.getType();
if (fieldValue != null && type != null) {
// CHECK TYPE
switch (type) {
case LINK:
validateLink(p, fieldValue, false);
break;
case LINKLIST:
if (!(fieldValue instanceof List))
throw new OValidationException(
"The field '" + p.getFullName() + "' has been declared as LINKLIST but an incompatible type is used. Value: "
+ fieldValue);
validateLinkCollection(p, (Collection<Object>) fieldValue, entry);
break;
case LINKSET:
if (!(fieldValue instanceof Set))
throw new OValidationException(
"The field '" + p.getFullName() + "' has been declared as LINKSET but an incompatible type is used. Value: "
+ fieldValue);
validateLinkCollection(p, (Collection<Object>) fieldValue, entry);
break;
case LINKMAP:
if (!(fieldValue instanceof Map))
throw new OValidationException(
"The field '" + p.getFullName() + "' has been declared as LINKMAP but an incompatible type is used. Value: "
+ fieldValue);
validateLinkCollection(p, ((Map<?, Object>) fieldValue).values(), entry);
break;
case LINKBAG:
if (!(fieldValue instanceof ORidBag))
throw new OValidationException(
"The field '" + p.getFullName() + "' has been declared as LINKBAG but an incompatible type is used. Value: "
+ fieldValue);
validateLinkCollection(p, (Iterable<Object>) fieldValue, entry);
break;
case EMBEDDED:
validateEmbedded(p, fieldValue);
break;
case EMBEDDEDLIST:
if (!(fieldValue instanceof List))
throw new OValidationException(
"The field '" + p.getFullName() + "' has been declared as EMBEDDEDLIST but an incompatible type is used. Value: "
+ fieldValue);
if (p.getLinkedClass() != null) {
for (Object item : ((List<?>) fieldValue))
validateEmbedded(p, item);
} else if (p.getLinkedType() != null) {
for (Object item : ((List<?>) fieldValue))
validateType(p, item);
}
break;
case EMBEDDEDSET:
if (!(fieldValue instanceof Set))
throw new OValidationException(
"The field '" + p.getFullName() + "' has been declared as EMBEDDEDSET but an incompatible type is used. Value: "
+ fieldValue);
if (p.getLinkedClass() != null) {
for (Object item : ((Set<?>) fieldValue))
validateEmbedded(p, item);
} else if (p.getLinkedType() != null) {
for (Object item : ((Set<?>) fieldValue))
validateType(p, item);
}
break;
case EMBEDDEDMAP:
if (!(fieldValue instanceof Map))
throw new OValidationException(
"The field '" + p.getFullName() + "' has been declared as EMBEDDEDMAP but an incompatible type is used. Value: "
+ fieldValue);
if (p.getLinkedClass() != null) {
for (Entry<?, ?> colleEntry : ((Map<?, ?>) fieldValue).entrySet())
validateEmbedded(p, colleEntry.getValue());
} else if (p.getLinkedType() != null) {
for (Entry<?, ?> collEntry : ((Map<?, ?>) fieldValue).entrySet())
validateType(p, collEntry.getValue());
}
break;
}
}
if (p.getMin() != null && fieldValue != null) {
// MIN
final String min = p.getMin();
if (p.getMinComparable().compareTo(fieldValue) > 0) {
switch (p.getType()) {
case STRING:
throw new OValidationException(
"The field '" + p.getFullName() + "' contains fewer characters than " + min + " requested");
case DATE:
case DATETIME:
throw new OValidationException(
"The field '" + p.getFullName() + "' contains the date " + fieldValue + " which precedes the first acceptable date ("
+ min + ")");
case BINARY:
throw new OValidationException("The field '" + p.getFullName() + "' contains fewer bytes than " + min + " requested");
case EMBEDDEDLIST:
case EMBEDDEDSET:
case LINKLIST:
case LINKSET:
case EMBEDDEDMAP:
case LINKMAP:
throw new OValidationException("The field '" + p.getFullName() + "' contains fewer items than " + min + " requested");
default:
throw new OValidationException("The field '" + p.getFullName() + "' is less than " + min);
}
}
}
if (p.getMaxComparable() != null && fieldValue != null) {
final String max = p.getMax();
if (p.getMaxComparable().compareTo(fieldValue) < 0) {
switch (p.getType()) {
case STRING:
throw new OValidationException("The field '" + p.getFullName() + "' contains more characters than " + max + " requested");
case DATE:
case DATETIME:
throw new OValidationException(
"The field '" + p.getFullName() + "' contains the date " + fieldValue + " which is after the last acceptable date ("
+ max + ")");
case BINARY:
throw new OValidationException("The field '" + p.getFullName() + "' contains more bytes than " + max + " requested");
case EMBEDDEDLIST:
case EMBEDDEDSET:
case LINKLIST:
case LINKSET:
case EMBEDDEDMAP:
case LINKMAP:
throw new OValidationException("The field '" + p.getFullName() + "' contains more items than " + max + " requested");
default:
throw new OValidationException("The field '" + p.getFullName() + "' is greater than " + max);
}
}
}
if (p.isReadonly() && !ORecordVersionHelper.isTombstone(iRecord.getVersion())) {
if (entry != null && (entry.changed || entry.timeLine != null) && !entry.created) {
// check if the field is actually changed by equal.
// this is due to a limitation in the merge algorithm used server side marking all non simple fields as dirty
Object orgVal = entry.original;
boolean simple = fieldValue != null ? OType.isSimpleType(fieldValue) : OType.isSimpleType(orgVal);
if ((simple) || (fieldValue != null && orgVal == null) || (fieldValue == null && orgVal != null) || (fieldValue != null
&& !fieldValue.equals(orgVal)))
throw new OValidationException(
"The field '" + p.getFullName() + "' is immutable and cannot be altered. Field value is: " + entry.value);
}
}
}
protected static void validateLinkCollection(final OProperty property, Iterable<Object> values, ODocumentEntry value) {
if (property.getLinkedClass() != null) {
if (value.timeLine != null) {
List<OMultiValueChangeEvent<Object, Object>> event = value.timeLine.getMultiValueChangeEvents();
for (OMultiValueChangeEvent object : event) {
if (object.getChangeType() == OMultiValueChangeEvent.OChangeType.ADD
|| object.getChangeType() == OMultiValueChangeEvent.OChangeType.UPDATE && object.getValue() != null)
validateLink(property, object.getValue(), OSecurityShared.ALLOW_FIELDS.contains(property.getName()));
}
} else {
boolean autoconvert = false;
if (values instanceof ORecordLazyMultiValue) {
autoconvert = ((ORecordLazyMultiValue) values).isAutoConvertToRecord();
((ORecordLazyMultiValue) values).setAutoConvertToRecord(false);
}
for (Object object : values) {
validateLink(property, object, OSecurityShared.ALLOW_FIELDS.contains(property.getName()));
}
if (values instanceof ORecordLazyMultiValue)
((ORecordLazyMultiValue) values).setAutoConvertToRecord(autoconvert);
}
}
}
protected static void validateType(final OProperty p, final Object value) {
if (value != null)
if (OType.convert(value, p.getLinkedType().getDefaultJavaType()) == null)
throw new OValidationException(
"The field '" + p.getFullName() + "' has been declared as " + p.getType() + " of type '" + p.getLinkedType()
+ "' but the value is " + value);
}
protected static void validateLink(final OProperty p, final Object fieldValue, boolean allowNull) {
if (fieldValue == null) {
if (allowNull)
return;
else
throw new OValidationException("The field '" + p.getFullName() + "' has been declared as " + p.getType()
+ " but contains a null record (probably a deleted record?)");
}
final ORecord linkedRecord;
if (!(fieldValue instanceof OIdentifiable))
throw new OValidationException("The field '" + p.getFullName() + "' has been declared as " + p.getType()
+ " but the value is not a record or a record-id");
final OClass schemaClass = p.getLinkedClass();
if (schemaClass != null && !schemaClass.isSubClassOf(OIdentity.CLASS_NAME)) {
// DON'T VALIDATE OUSER AND OROLE FOR SECURITY RESTRICTIONS
final ORID rid = ((OIdentifiable) fieldValue).getIdentity();
if (!schemaClass.hasPolymorphicClusterId(rid.getClusterId())) {
linkedRecord = ((OIdentifiable) fieldValue).getRecord();
if (linkedRecord != null) {
if (!(linkedRecord instanceof ODocument))
throw new OValidationException(
"The field '" + p.getFullName() + "' has been declared as " + p.getType() + " of type '" + schemaClass
+ "' but the value is the record " + linkedRecord.getIdentity() + " that is not a document");
final ODocument doc = (ODocument) linkedRecord;
// AT THIS POINT CHECK THE CLASS ONLY IF != NULL BECAUSE IN CASE OF GRAPHS THE RECORD COULD BE PARTIAL
if (doc.getImmutableSchemaClass() != null && !schemaClass.isSuperClassOf(doc.getImmutableSchemaClass()))
throw new OValidationException(
"The field '" + p.getFullName() + "' has been declared as " + p.getType() + " of type '" + schemaClass.getName()
+ "' but the value is the document " + linkedRecord.getIdentity() + " of class '" + doc
.getImmutableSchemaClass() + "'");
}
}
}
}
protected static void validateEmbedded(final OProperty p, final Object fieldValue) {
if (fieldValue == null)
return;
if (fieldValue instanceof ORecordId)
throw new OValidationException(
"The field '" + p.getFullName() + "' has been declared as " + p.getType() + " but the value is the RecordID "
+ fieldValue);
else if (fieldValue instanceof OIdentifiable) {
final OIdentifiable embedded = (OIdentifiable) fieldValue;
if (embedded.getIdentity().isValid())
throw new OValidationException("The field '" + p.getFullName() + "' has been declared as " + p.getType()
+ " but the value is a document with the valid RecordID " + fieldValue);
final OClass embeddedClass = p.getLinkedClass();
if (embeddedClass != null) {
final ORecord embeddedRecord = embedded.getRecord();
if (!(embeddedRecord instanceof ODocument))
throw new OValidationException(
"The field '" + p.getFullName() + "' has been declared as " + p.getType() + " with linked class '" + embeddedClass
+ "' but the record was not a document");
final ODocument doc = (ODocument) embeddedRecord;
if (doc.getImmutableSchemaClass() == null)
throw new OValidationException(
"The field '" + p.getFullName() + "' has been declared as " + p.getType() + " with linked class '" + embeddedClass
+ "' but the record has no class");
if (!(doc.getImmutableSchemaClass().isSubClassOf(embeddedClass)))
throw new OValidationException(
"The field '" + p.getFullName() + "' has been declared as " + p.getType() + " with linked class '" + embeddedClass
+ "' but the record is of class '" + doc.getImmutableSchemaClass().getName()
+ "' that is not a subclass of that");
doc.validate();
}
} else
throw new OValidationException(
"The field '" + p.getFullName() + "' has been declared as " + p.getType() + " but an incompatible type is used. Value: "
+ fieldValue);
}
/**
* Copies the current instance to a new one. Hasn't been choose the clone() to let ODocument return type. Once copied the new
* instance has the same identity and values but all the internal structure are totally independent by the source.
*/
public ODocument copy() {
return (ODocument) copyTo(new ODocument());
}
/**
* Copies all the fields into iDestination document.
*/
@Override
public ORecordAbstract copyTo(final ORecordAbstract iDestination) {
// TODO: REMOVE THIS
checkForFields();
ODocument destination = (ODocument) iDestination;
super.copyTo(iDestination);
destination._ordered = _ordered;
destination._className = _className;
destination._immutableSchemaVersion = -1;
destination._immutableClazz = null;
destination._trackingChanges = _trackingChanges;
if (_owners != null)
destination._owners = new ArrayList<>(_owners);
else
destination._owners = null;
if (_fields != null) {
destination._fields = _fields instanceof LinkedHashMap ? new LinkedHashMap<>() : new HashMap<>();
for (Entry<String, ODocumentEntry> entry : _fields.entrySet()) {
ODocumentEntry docEntry = entry.getValue().clone();
destination._fields.put(entry.getKey(), docEntry);
docEntry.value = ODocumentHelper.cloneValue(destination, entry.getValue().value);
}
} else
destination._fields = null;
destination._fieldSize = _fieldSize;
destination.addAllMultiValueChangeListeners();
destination._dirty = _dirty; // LEAVE IT AS LAST TO AVOID SOMETHING SET THE FLAG TO TRUE
destination._contentChanged = _contentChanged;
return destination;
}
/**
* Returns an empty record as place-holder of the current. Used when a record is requested, but only the identity is needed.
*
* @return placeholder of this document
*/
public ORecord placeholder() {
final ODocument cloned = new ODocument();
cloned._source = null;
cloned._recordId = _recordId;
cloned._status = STATUS.NOT_LOADED;
cloned._dirty = false;
cloned._contentChanged = false;
return cloned;
}
/**
* Detaches all the connected records. If new records are linked to the document the detaching cannot be completed and false will
* be returned. RidBag types cannot be fully detached when the database is connected using "remote" protocol.
*
* @return true if the record has been detached, otherwise false
*/
public boolean detach() {
deserializeFields();
boolean fullyDetached = true;
if (_fields != null) {
Object fieldValue;
for (Map.Entry<String, ODocumentEntry> entry : _fields.entrySet()) {
fieldValue = entry.getValue().value;
if (fieldValue instanceof ORecord)
if (((ORecord) fieldValue).getIdentity().isNew())
fullyDetached = false;
else
entry.getValue().value = ((ORecord) fieldValue).getIdentity();
if (fieldValue instanceof ODetachable) {
if (!((ODetachable) fieldValue).detach())
fullyDetached = false;
}
}
}
return fullyDetached;
}
/**
* Loads the record using a fetch plan. Example: <p> <code>doc.load( "*:3" ); // LOAD THE DOCUMENT BY EARLY FETCHING UP TO 3rd
* LEVEL OF CONNECTIONS</code> </p>
*
* @param iFetchPlan Fetch plan to use
*/
public ODocument load(final String iFetchPlan) {
return load(iFetchPlan, false);
}
/**
* Loads the record using a fetch plan. Example: <p> <code>doc.load( "*:3", true ); // LOAD THE DOCUMENT BY EARLY FETCHING UP TO
* 3rd LEVEL OF CONNECTIONS IGNORING THE CACHE</code> </p>
*
* @param iIgnoreCache Ignore the cache or use it
*/
public ODocument load(final String iFetchPlan, boolean iIgnoreCache) {
Object result;
try {
result = getDatabase().load(this, iFetchPlan, iIgnoreCache);
} catch (Exception e) {
throw OException.wrapException(new ORecordNotFoundException(getIdentity()), e);
}
if (result == null)
throw new ORecordNotFoundException(getIdentity());
return (ODocument) result;
}
@Deprecated
public ODocument load(final String iFetchPlan, boolean iIgnoreCache, boolean loadTombstone) {
Object result;
try {
result = getDatabase().load(this, iFetchPlan, iIgnoreCache, loadTombstone, OStorage.LOCKING_STRATEGY.DEFAULT);
} catch (Exception e) {
throw OException.wrapException(new ORecordNotFoundException(getIdentity()), e);
}
if (result == null)
throw new ORecordNotFoundException(getIdentity());
return (ODocument) result;
}
@Override
public ODocument reload(final String fetchPlan, final boolean ignoreCache) {
super.reload(fetchPlan, ignoreCache);
if (!_lazyLoad) {
checkForLoading();
checkForFields();
}
return this;
}
public boolean hasSameContentOf(final ODocument iOther) {
final ODatabaseDocumentInternal currentDb = ODatabaseRecordThreadLocal.instance().getIfDefined();
return ODocumentHelper.hasSameContentOf(this, currentDb, iOther, currentDb, null);
}
@Override
public byte[] toStream() {
if (_recordFormat == null)
setup();
return toStream(false);
}
/**
* Returns the document as Map String,Object . If the document has identity, then the @rid entry is valued. If the document has a
* class, then the @class entry is valued.
*
* @since 2.0
*/
public Map<String, Object> toMap() {
final Map<String, Object> map = new HashMap<>();
for (String field : fieldNames())
map.put(field, field(field));
final ORID id = getIdentity();
if (id.isValid())
map.put(ODocumentHelper.ATTRIBUTE_RID, id);
final String className = getClassName();
if (className != null)
map.put(ODocumentHelper.ATTRIBUTE_CLASS, className);