-
Notifications
You must be signed in to change notification settings - Fork 14
/
UnitOfWorkImpl.java
1068 lines (954 loc) · 38.4 KB
/
UnitOfWorkImpl.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 (C) 2016 Czech Technical University in Prague
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details. You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package cz.cvut.kbss.jopa.sessions;
import cz.cvut.kbss.jopa.adapters.IndirectCollection;
import cz.cvut.kbss.jopa.exceptions.OWLEntityExistsException;
import cz.cvut.kbss.jopa.exceptions.OWLPersistenceException;
import cz.cvut.kbss.jopa.model.AbstractEntityManager;
import cz.cvut.kbss.jopa.model.EntityManagerImpl.State;
import cz.cvut.kbss.jopa.model.descriptors.Descriptor;
import cz.cvut.kbss.jopa.model.metamodel.EntityType;
import cz.cvut.kbss.jopa.model.metamodel.FieldSpecification;
import cz.cvut.kbss.jopa.model.metamodel.Metamodel;
import cz.cvut.kbss.jopa.model.query.Query;
import cz.cvut.kbss.jopa.model.query.TypedQuery;
import cz.cvut.kbss.jopa.query.sparql.SparqlQueryFactory;
import cz.cvut.kbss.jopa.sessions.change.ChangeManagerImpl;
import cz.cvut.kbss.jopa.sessions.change.ChangeRecordImpl;
import cz.cvut.kbss.jopa.sessions.change.ChangeSetFactory;
import cz.cvut.kbss.jopa.sessions.validator.IntegrityConstraintsValidator;
import cz.cvut.kbss.jopa.utils.CollectionFactory;
import cz.cvut.kbss.jopa.utils.Configuration;
import cz.cvut.kbss.jopa.utils.EntityPropertiesUtils;
import cz.cvut.kbss.jopa.utils.ErrorUtils;
import java.lang.reflect.Field;
import java.net.URI;
import java.util.*;
import java.util.Map.Entry;
public class UnitOfWorkImpl extends AbstractSession implements UnitOfWork, QueryFactory, ConfigurationHolder {
private final Map<Object, Object> cloneMapping;
private final Map<Object, Object> cloneToOriginals;
private final Map<Object, Object> keysToClones;
private Map<Object, Object> deletedObjects;
private Map<Object, Object> newObjectsCloneToOriginal;
private Map<Object, Object> newObjectsOriginalToClone;
private Map<Object, Object> newObjectsKeyToClone;
private RepositoryMap repoMap;
private boolean hasChanges;
private boolean hasNew;
private boolean hasDeleted;
private boolean shouldReleaseAfterCommit;
private boolean shouldClearCacheAfterCommit;
private boolean useTransactionalOntology;
private boolean isActive;
private boolean inCommit;
private UnitOfWorkChangeSet uowChangeSet;
private AbstractSession parent;
private AbstractEntityManager entityManager;
private final ConnectionWrapper storage;
private final MergeManager mergeManager;
private final CloneBuilder cloneBuilder;
private final ChangeManager changeManager;
private final QueryFactory queryFactory;
private final CollectionFactory collectionFactory;
/**
* This is a shortcut for the second level cache.
*/
private final CacheManager cacheManager;
public UnitOfWorkImpl(AbstractSession parent) {
this.parent = Objects.requireNonNull(parent, ErrorUtils.constructNPXMessage("parent"));
this.cloneMapping = createMap();
this.cloneToOriginals = createMap();
this.keysToClones = new HashMap<>();
this.repoMap = new RepositoryMap();
repoMap.initDescriptors();
this.cloneBuilder = new CloneBuilderImpl(this);
this.collectionFactory = new CollectionFactory(this);
this.cacheManager = parent.getLiveObjectCache();
this.storage = acquireConnection();
this.queryFactory = new SparqlQueryFactory(this, storage);
this.mergeManager = new MergeManagerImpl(this);
this.changeManager = new ChangeManagerImpl(this);
this.inCommit = false;
this.useTransactionalOntology = true;
this.isActive = true;
}
/**
* This method returns null, since we don't support nested Units of Work yet.
*/
@Override
public UnitOfWork acquireUnitOfWork() {
return null;
}
@Override
protected ConnectionWrapper acquireConnection() {
final ConnectionWrapper conn = parent.acquireConnection();
conn.setUnitOfWork(this);
return conn;
}
@Override
public <T> T readObject(Class<T> cls, Object primaryKey, Descriptor descriptor) {
Objects.requireNonNull(cls, ErrorUtils.constructNPXMessage("cls"));
Objects.requireNonNull(primaryKey, ErrorUtils.constructNPXMessage("primaryKey"));
Objects.requireNonNull(descriptor, ErrorUtils.constructNPXMessage("descriptor"));
return readObjectInternal(cls, primaryKey, descriptor);
}
private <T> T readObjectInternal(Class<T> cls, Object primaryKey, Descriptor descriptor) {
assert cls != null;
assert primaryKey != null;
assert descriptor != null;
// First try to find the object among new uncommitted objects
Object result = getNewObjectsKeyToClone().get(primaryKey);
if (result != null && (isInRepository(descriptor, result))) {
// The result can be returned, since it is already registered in
// this UOW
return cls.cast(result);
}
// Object is already managed
result = keysToClones.get(primaryKey);
if (result != null && isInRepository(descriptor, result) && !getDeletedObjects().containsKey(result)) {
return cls.cast(result);
}
// Search the cache
result = getObjectFromCache(cls, primaryKey, descriptor.getContext());
if (result == null) {
// The object is not in the session cache, so search the ontology
final URI pkUri = EntityPropertiesUtils.getValueAsURI(primaryKey);
result = storage.find(new LoadingParameters<>(cls, pkUri, descriptor));
}
if (result == null) {
return null;
}
Object clone = registerExistingObject(result, descriptor);
checkForCollections(clone);
return cls.cast(clone);
}
/**
* This method calculates the changes that were to the registered entities and adds these changes into the given
* change set for future commit to the ontology.
*/
private void calculateChanges() {
final UnitOfWorkChangeSet changeSet = getUowChangeSet();
if (hasNew()) {
calculateNewObjects(changeSet);
}
if (hasDeleted()) {
calculateDeletedObjects(changeSet);
}
}
/**
* Create object change sets for the new objects and adds them into our UnitOfWorkChangeSet.
*
* @param changeSet UnitOfWorkChangeSet
*/
private void calculateNewObjects(UnitOfWorkChangeSet changeSet) {
for (Object clone : getNewObjectsCloneToOriginal().keySet()) {
final Descriptor c = getDescriptor(clone);
Object original = getNewObjectsCloneToOriginal().get(clone);
if (original == null) {
original = this.cloneBuilder.buildClone(clone, c);
}
if (original == null) {
throw new OWLPersistenceException(
"Error while calculating changes for new objects. Original not found.");
}
getNewObjectsCloneToOriginal().put(clone, original);
getNewObjectsOriginalToClone().put(original, clone);
changeSet.addNewObjectChangeSet(ChangeSetFactory.createObjectChangeSet(original, clone,
c));
}
}
private void calculateDeletedObjects(final UnitOfWorkChangeSet changeSet) {
for (Object clone : getDeletedObjects().keySet()) {
Object original = cloneToOriginals.get(clone);
if (original == null) {
throw new OWLPersistenceException("Cannot find an original for clone!");
}
Descriptor descriptor = getDescriptor(clone);
changeSet.addDeletedObjectChangeSet(ChangeSetFactory.createObjectChangeSet(original, clone,
descriptor));
}
}
public void clear() {
cloneMapping.clear();
cloneToOriginals.clear();
keysToClones.clear();
this.deletedObjects = null;
this.newObjectsCloneToOriginal = null;
this.newObjectsOriginalToClone = null;
this.newObjectsKeyToClone = null;
this.hasChanges = false;
this.hasDeleted = false;
this.hasNew = false;
}
public boolean contains(Object entity) {
Objects.requireNonNull(entity, ErrorUtils.constructNPXMessage("entity"));
return isObjectManaged(entity);
}
public void commit() {
LOG.trace("UnitOfWork commit started.");
if (!isActive()) {
throw new IllegalStateException("Cannot commit inactive Unit of Work!");
}
this.inCommit = true;
commitUnitOfWork();
LOG.trace("UnitOfWork commit finished.");
}
public void rollback() {
LOG.trace("UnitOfWork rollback started.");
if (!isActive()) {
throw new IllegalStateException("Cannot rollback inactive Unit of Work!");
}
storage.rollback();
clear();
}
/**
* Commit this Unit of Work.
*/
protected void commitUnitOfWork() {
commitToOntology();
mergeChangesIntoParent();
postCommit();
}
/**
* Clean up after the commit.
*/
private void postCommit() {
// Remove indirect collections from clones
cloneMapping.keySet().forEach(this::removeIndirectCollections);
getNewObjectsCloneToOriginal().clear();
getNewObjectsOriginalToClone().clear();
getNewObjectsKeyToClone().clear();
getDeletedObjects().clear();
cloneToOriginals.clear();
cloneMapping.clear();
keysToClones.clear();
this.hasChanges = false;
this.hasDeleted = false;
this.hasNew = false;
this.inCommit = false;
cloneBuilder.reset();
this.repoMap = new RepositoryMap();
repoMap.initDescriptors();
this.uowChangeSet = null;
if (shouldClearCacheAfterCommit) {
cacheManager.evictAll();
this.shouldReleaseAfterCommit = true;
}
}
/**
* If there are any changes, commit them to the ontology.
*/
protected void commitToOntology() {
boolean hasChanges = this.hasNew || this.hasChanges || this.hasDeleted;
if (hasChanges) {
calculateChanges();
}
validateIntegrityConstraints();
storageCommit();
}
private void validateIntegrityConstraints() {
if (uowChangeSet == null) {
return;
}
final IntegrityConstraintsValidator validator = IntegrityConstraintsValidator.getValidator();
for (ObjectChangeSet changeSet : uowChangeSet.getNewObjects()) {
validator.validate(changeSet.getCloneObject(),
getMetamodel().entity((Class<Object>) changeSet.getObjectClass()), false);
}
uowChangeSet.getExistingObjectsChanges().forEach(changeSet -> validator.validate(changeSet, getMetamodel()));
}
private Map<Object, Object> createMap() {
return new IdentityHashMap<>();
}
/**
* Gets current state of the specified entity. </p>
* <p>
* Note that since no repository is specified we can only determine if the entity is managed or removed. Therefore
* if the case is different this method returns State#NOT_MANAGED.
*
* @param entity The entity to check
* @return State of the entity
*/
public State getState(Object entity) {
Objects.requireNonNull(entity, ErrorUtils.constructNPXMessage("entity"));
if (getDeletedObjects().containsKey(entity)) {
return State.REMOVED;
} else if (getNewObjectsCloneToOriginal().containsKey(entity)) {
return State.MANAGED_NEW;
} else if (cloneMapping.containsKey(entity)) {
return State.MANAGED;
} else {
return State.NOT_MANAGED;
}
}
/**
* Checks the state of the specified entity with regards to the specified repository.
*
* @param entity Object
* @param descriptor Entity descriptor
* @return The state of the specified entity
*/
public State getState(Object entity, Descriptor descriptor) {
Objects.requireNonNull(entity, ErrorUtils.constructNPXMessage("entity"));
Objects.requireNonNull(descriptor, ErrorUtils.constructNPXMessage("descriptor"));
if (getDeletedObjects().containsKey(entity)) {
return State.REMOVED;
} else if (cloneMapping.containsKey(entity) && isInRepository(descriptor, entity)) {
if (getNewObjectsCloneToOriginal().containsKey(entity)) {
return State.MANAGED_NEW;
}
return State.MANAGED;
} else {
return State.NOT_MANAGED;
}
}
/**
* Tries to find the original object for the given clone. It searches the existing objects, new objects and deleted
* objects.
*
* @param clone Object
* @return The original object for the given clone
*/
public Object getOriginal(Object clone) {
if (clone == null) {
return null;
}
Object original = cloneToOriginals.get(clone);
if (original == null) {
original = getNewObjectsCloneToOriginal().get(clone);
}
return original;
}
/**
* Gets managed original with the specified identifier or {@code null} if there is none matching.
* <p>
* Descriptor is used to check repository context validity.
*
* @param cls Return type of the original
* @param identifier Instance identifier
* @param descriptor Repository descriptor
* @return Original object managed by this UoW or {@code null} if this UoW doesn't contain a matching instance
*/
public <T> T getManagedOriginal(Class<T> cls, Object identifier, Descriptor descriptor) {
if (!keysToClones.containsKey(identifier)) {
return null;
}
final Object clone = keysToClones.get(identifier);
if (!cls.isAssignableFrom(clone.getClass())) {
return null;
}
if (!isInRepository(descriptor, clone)) {
return null;
}
return cls.cast(cloneToOriginals.get(clone));
}
/**
* Check if this UnitOfWork contains this original entity. This method is used by the CloneBuilder so it does not
* have to clone already managed referenced objects.
*
* @param entity The original entity.
* @return True if the original is managed in this UnitOfWork.
*/
boolean containsOriginal(Object entity) {
return entity != null && cloneToOriginals.containsValue(entity);
}
/**
* Finds clone for the specified original. This method assumes that the original is managed in this persistence
* context (UnitOfWork). However, if not, this method just goes through all the managed objects and if it does not
* find match, returns null.
*
* @param original The original object whose clone we are looking for.
* @return The clone or null, if there is none.
*/
Object getCloneForOriginal(Object original) {
for (Entry<Object, Object> entry : cloneToOriginals.entrySet()) {
// We use IdentityMap, so we can use ==
if (entry.getValue() == original) {
return entry.getKey();
}
}
return null;
}
public boolean hasDeleted() {
return hasDeleted;
}
public boolean hasChanges() {
return hasChanges || hasDeleted || hasNew;
}
public boolean hasNew() {
return hasNew;
}
public void setHasChanges() {
this.hasChanges = true;
}
public Map<Object, Object> getDeletedObjects() {
if (deletedObjects == null) {
this.deletedObjects = createMap();
}
return deletedObjects;
}
public Map<Object, Object> getNewObjectsCloneToOriginal() {
if (newObjectsCloneToOriginal == null) {
this.newObjectsCloneToOriginal = createMap();
}
return newObjectsCloneToOriginal;
}
public Map<Object, Object> getNewObjectsOriginalToClone() {
if (newObjectsOriginalToClone == null) {
this.newObjectsOriginalToClone = createMap();
}
return newObjectsOriginalToClone;
}
public Map<Object, Object> getNewObjectsKeyToClone() {
if (newObjectsKeyToClone == null) {
// Cannot use identity map, since it compares the key references
// which may not be the same
this.newObjectsKeyToClone = new HashMap<>();
}
return newObjectsKeyToClone;
}
@Override
public CacheManager getLiveObjectCache() {
return parent.getLiveObjectCache();
}
public UnitOfWorkChangeSet getUowChangeSet() {
if (uowChangeSet == null) {
this.uowChangeSet = ChangeSetFactory.createUoWChangeSet();
}
return uowChangeSet;
}
public boolean isActive() {
return this.isActive;
}
/**
* Returns true if the given clone represents a newly created object. Otherwise returns false.
*
* @param clone Object
* @return boolean
*/
public boolean isObjectNew(Object clone) {
return clone != null && getNewObjectsCloneToOriginal().containsKey(clone);
}
/**
* Returns true if the given object is already managed.
*
* @param entity Object
* @return boolean
*/
public boolean isObjectManaged(Object entity) {
Objects.requireNonNull(entity, ErrorUtils.constructNPXMessage("entity"));
return (cloneMapping.containsKey(entity) && !getDeletedObjects().containsKey(entity));
}
private boolean doesEntityExist(Object entity, Object primaryKey, Descriptor descriptor) {
assert entity != null;
assert descriptor != null;
if (cloneMapping.containsKey(entity) && !getDeletedObjects().containsKey(entity)
&& isInRepository(descriptor, entity)) {
return true;
}
return primaryKey != null
&& cacheManager.contains(entity.getClass(), primaryKey, descriptor.getContext());
}
/**
* Persists changed value of the specified field.
*
* @param entity Entity with changes (the clone)
* @param f The field whose value has changed
* @throws IllegalStateException If this UoW is not in transaction
*/
public void attributeChanged(Object entity, Field f) {
if (!isInTransaction()) {
throw new IllegalStateException("This unit of work is not in a transaction.");
}
final Descriptor descriptor = getDescriptor(entity);
if (descriptor == null) {
throw new OWLPersistenceException("Unable to find repository for entity " + entity
+ ". Is it registered in this UoW?");
}
storage.merge(entity, f, descriptor);
createChangeRecord(entity, f, descriptor);
setHasChanges();
setIndirectCollectionIfPresent(entity, f);
}
private void createChangeRecord(Object clone, Field field, Descriptor descriptor) {
final Object orig = getOriginal(clone);
if (orig == null) {
return;
}
ObjectChangeSet chSet = getUowChangeSet().getExistingObjectChanges(orig);
if (chSet == null) {
chSet = ChangeSetFactory.createObjectChangeSet(orig, clone, descriptor);
getUowChangeSet().addObjectChangeSet(chSet);
}
chSet.addChangeRecord(new ChangeRecordImpl(field.getName(), EntityPropertiesUtils.getFieldValue(field, clone)));
}
/**
* Merge the changes from this Unit of Work's change set into the server session.
*/
public void mergeChangesIntoParent() {
if (hasChanges()) {
mergeManager.mergeChangesFromChangeSet(getUowChangeSet());
}
}
@Override
public <T> T mergeDetached(T entity, Descriptor descriptor) {
Objects.requireNonNull(entity, ErrorUtils.constructNPXMessage("entity"));
Objects.requireNonNull(descriptor, ErrorUtils.constructNPXMessage("descriptor"));
final Object pk = getIdentifier(entity);
if (!storage.contains(pk, entity.getClass(), descriptor)) {
registerNewObject(entity, descriptor);
return entity;
} else {
return mergeDetachedInternal(entity, descriptor);
}
}
private <T> T mergeDetachedInternal(T entity, Descriptor descriptor) {
assert entity != null;
final Object iri = getIdentifier(entity);
final Class<T> entityCls = (Class<T>) entity.getClass();
// Search the cache
T original = getObjectFromCache(entityCls, iri, descriptor.getContext());
if (original == null) {
// The object is not in the session cache, so search the ontology
final URI idUri = EntityPropertiesUtils.getValueAsURI(iri);
original = storage.find(new LoadingParameters<>(entityCls, idUri, descriptor, true));
}
assert original != null;
registerClone(entity, original, descriptor);
try {
// Merge only the changed attributes
final ObjectChangeSet chSet = ChangeSetFactory.createObjectChangeSet(original, entity, descriptor);
changeManager.calculateChanges(chSet);
final EntityType<?> et = getMetamodel().entity(entityCls);
for (ChangeRecord record : chSet.getChanges().values()) {
final Field field = et.getFieldSpecification(record.getAttributeName()).getJavaField();
storage.merge(entity, field, descriptor);
}
} catch (OWLEntityExistsException e) {
unregisterObject(entity);
throw e;
} catch (IllegalAccessException e) {
throw new OWLPersistenceException(e);
}
if (cacheManager.contains(entityCls, iri, descriptor.getContext())) {
cacheManager.evict(entityCls, iri, descriptor.getContext());
}
setHasChanges();
return entity;
}
/**
* {@inheritDoc}
*/
@Override
void registerEntityWithPersistenceContext(Object entity, UnitOfWorkImpl uow) {
parent.registerEntityWithPersistenceContext(entity, uow);
}
@Override
void deregisterEntityFromPersistenceContext(Object entity, UnitOfWork uow) {
parent.deregisterEntityFromPersistenceContext(entity, uow);
}
/**
* {@inheritDoc}
*/
public Object registerExistingObject(Object entity, Descriptor descriptor) {
if (entity == null) {
return null;
}
if (cloneToOriginals.containsValue(entity)) {
return getCloneForOriginal(entity);
}
Object clone = this.cloneBuilder.buildClone(entity, descriptor);
assert clone != null;
registerClone(clone, entity, descriptor);
return clone;
}
private void registerClone(Object clone, Object original, Descriptor descriptor) {
cloneMapping.put(clone, clone);
cloneToOriginals.put(clone, original);
final Object identifier = EntityPropertiesUtils.getPrimaryKey(clone, getMetamodel());
keysToClones.put(identifier, clone);
registerEntityWithPersistenceContext(clone, this);
registerEntityWithOntologyContext(descriptor, clone);
}
/**
* Release this Unit of Work. Releasing an active Unit of Work with uncommitted changes causes all pending changes
* to be discarded.
*/
public void release() {
clear();
storage.close();
this.isActive = false;
LOG.debug("UnitOfWork released.");
}
@Override
public <T> void revertObject(T object) {
Objects.requireNonNull(object, ErrorUtils.constructNPXMessage("object"));
if (!isObjectManaged(object) && !getDeletedObjects().containsKey(object)) {
throw new IllegalArgumentException("The specified enity " + object
+ " is not managed by this persistence context.");
}
final Descriptor descriptor = getDescriptor(object);
if (descriptor == null) {
throw new IllegalArgumentException("Unable to find entity " + object
+ " in this persistence context.");
}
// To revert the object's state, just swap original and clone for change
// calculation and merging so that the state of the original is merged
// into the state of the clone
final Object original = getOriginal(object);
final ObjectChangeSet chSet = ChangeSetFactory.createObjectChangeSet(object, original,
descriptor);
try {
final boolean anyChanges = changeManager.calculateChanges(chSet);
if (anyChanges) {
mergeManager.mergeChangesOnObject(original, chSet);
}
} catch (IllegalAccessException | IllegalArgumentException e) {
throw new OWLPersistenceException(e);
}
}
@Override
public void registerNewObject(Object entity, Descriptor descriptor) {
Objects.requireNonNull(entity, ErrorUtils.constructNPXMessage("entity"));
Objects.requireNonNull(descriptor, ErrorUtils.constructNPXMessage("descriptor"));
registerNewObjectInternal(entity, descriptor);
}
/**
* Registers the specified entity for persist in this Unit of Work.
*
* @param entity The entity to register
* @param descriptor Entity descriptor, specifying optionally contexts into which the entity will be persisted
*/
private void registerNewObjectInternal(Object entity, Descriptor descriptor) {
assert entity != null;
Object id = getIdentifier(entity);
if (id == null) {
final EntityType<?> eType = getMetamodel().entity(entity.getClass());
EntityPropertiesUtils.verifyIdentifierIsGenerated(entity, eType);
}
if (doesEntityExist(entity, id, descriptor) && !entity.getClass().isEnum()) {
throw new OWLEntityExistsException("An entity with URI " + id
+ " is already persisted in repository " + descriptor);
}
storage.persist(id, entity, descriptor);
if (id == null) {
// If the ID was null, extract it from the entity
// It is present now
id = getIdentifier(entity);
}
// Original is null until commit
cloneMapping.put(entity, entity);
getNewObjectsCloneToOriginal().put(entity, null);
registerEntityWithPersistenceContext(entity, this);
registerEntityWithOntologyContext(descriptor, entity);
getNewObjectsKeyToClone().put(id, entity);
checkForCollections(entity);
this.hasNew = true;
}
/**
* Remove the specified entity from the ontology.
*
* @param entity Managed entity to delete
*/
public void removeObject(Object entity) {
if (entity == null) {
return;
}
if (!isObjectManaged(entity)) {
throw new IllegalArgumentException(
"Cannot remove entity which is not managed in the current persistence context.");
}
if (getDeletedObjects().containsKey(entity)) {
return;
}
final Object primaryKey = getIdentifier(entity);
final Descriptor descriptor = getDescriptor(entity);
if (hasNew() && getNewObjectsCloneToOriginal().containsKey(entity)) {
unregisterObject(entity);
getNewObjectsKeyToClone().remove(primaryKey);
} else {
getDeletedObjects().put(entity, entity);
this.hasDeleted = true;
}
// unregisterEntityFromOntologyContext(entity);
storage.remove(primaryKey, entity.getClass(), descriptor);
}
/**
* Remove the registered object from this Unit of Work.
*
* @param object Clone of the original object
*/
public void unregisterObject(Object object) {
if (object == null) {
return;
}
cloneMapping.remove(object);
cloneToOriginals.remove(object);
getDeletedObjects().remove(object);
if (hasNew()) {
Object newOriginal = getNewObjectsCloneToOriginal().remove(object);
if (newOriginal != null) {
getNewObjectsOriginalToClone().remove(newOriginal);
}
}
removeIndirectCollections(object);
deregisterEntityFromPersistenceContext(object, this);
unregisterEntityFromOntologyContext(object);
}
public boolean shouldReleaseAfterCommit() {
return shouldReleaseAfterCommit;
}
public void setShouldClearAfterCommit(boolean shouldClearCache) {
this.shouldClearCacheAfterCommit = shouldClearCache;
}
public void setEntityManager(AbstractEntityManager entityManager) {
this.entityManager = entityManager;
}
public void writeUncommittedChanges() {
if (!hasChanges()) {
return;
}
commitUnitOfWork();
}
@Override
public Metamodel getMetamodel() {
return parent.getMetamodel();
}
@Override
public boolean isTypeManaged(Class<?> cls) {
return parent.isTypeManaged(cls);
}
@Override
public boolean isInTransaction() {
return entityManager != null && entityManager.getTransaction().isActive();
}
/**
* Returns {@code true} if this UoW is currently committing changes.
*/
public boolean isInCommit() {
return inCommit;
}
@Override
public <T> void loadEntityField(T entity, Field field) {
Objects.requireNonNull(entity, ErrorUtils.constructNPXMessage("entity"));
Objects.requireNonNull(field, ErrorUtils.constructNPXMessage("field"));
if (EntityPropertiesUtils.getFieldValue(field, entity) != null) {
return;
}
final Descriptor entityDescriptor = getDescriptor(entity);
if (entityDescriptor == null) {
throw new OWLPersistenceException(
"Unable to find repository identifier for entity " + entity
+ ". Is it managed by this UoW?");
}
storage.loadFieldValue(entity, field, entityDescriptor);
final Object orig = EntityPropertiesUtils.getFieldValue(field, entity);
final Object entityOriginal = getOriginal(entity);
if (entityOriginal != null) {
EntityPropertiesUtils.setFieldValue(field, entityOriginal, orig);
}
final Descriptor fieldDescriptor = getFieldDescriptor(entity, field, entityDescriptor);
final Object clone = cloneLoadedFieldValue(entity, field, fieldDescriptor, orig);
EntityPropertiesUtils.setFieldValue(field, entity, clone);
}
private <T> Descriptor getFieldDescriptor(T entity, Field field, Descriptor entityDescriptor) {
final EntityType<?> et = getMetamodel().entity(entity.getClass());
final FieldSpecification<?, ?> fieldSpec = et
.getFieldSpecification(field.getName());
return entityDescriptor.getAttributeDescriptor(fieldSpec);
}
private <T> Object cloneLoadedFieldValue(T entity, Field field, final Descriptor fieldDescriptor,
final Object fieldValueOrig) {
Object clone;
if (fieldValueOrig == null) {
clone = null;
} else {
if (isTypeManaged(field.getType())) {
clone = registerExistingObject(fieldValueOrig, fieldDescriptor);
final URI fieldContext = fieldDescriptor.getContext();
putObjectIntoCache(getIdentifier(clone), fieldValueOrig, fieldContext);
} else {
clone = cloneBuilder.buildClone(entity, field, fieldValueOrig, fieldDescriptor);
}
}
return clone;
}
@Override
public void removeObjectFromCache(Object toRemove, URI context) {
Objects.requireNonNull(toRemove, ErrorUtils.constructNPXMessage("toRemove"));
final Object primaryKey = getIdentifier(toRemove);
cacheManager.evict(toRemove.getClass(), primaryKey, context);
}
@Override
public boolean isConsistent(URI context) {
return storage.isConsistent(context);
}
@Override
public List<URI> getContexts() {
return storage.getContexts();
}
@Override
public void setUseTransactionalOntologyForQueryProcessing() {
this.useTransactionalOntology = true;
}
@Override
public boolean useTransactionalOntologyForQueryProcessing() {
return useTransactionalOntology;
}
@Override
public void setUseBackupOntologyForQueryProcessing() {
this.useTransactionalOntology = false;
}
@Override
public boolean useBackupOntologyForQueryProcessing() {
return !useTransactionalOntology;
}
@Override
public Query createNativeQuery(String sparql) {
return queryFactory.createNativeQuery(sparql);
}
@Override
public <T> TypedQuery<T> createNativeQuery(String sparql, Class<T> resultClass) {
return queryFactory.createNativeQuery(sparql, resultClass);
}
@Override
public Query createQuery(String query) {
return queryFactory.createQuery(query);
}
@Override
public <T> TypedQuery<T> createQuery(String query, Class<T> resultClass) {
return queryFactory.createQuery(query, resultClass);
}
/**
* Check if the specified entity contains a collection. If so, replace it with its indirect representation so that
* changes in that collection can be tracked.
*
* @param entity The entity to check
*/
private void checkForCollections(Object entity) {
Field[] fields = entity.getClass().getDeclaredFields();
for (Field f : fields) {
setIndirectCollectionIfPresent(entity, f);
}
}
/**
* Create and set indirect collection on the specified entity field.</p>
* <p>
* If the specified field is of Collection type and it is not already an indirect collection, create new one and set
* it as the value of the specified field on the specified entity.
*
* @param entity The entity collection will be set on
* @param field The field to set
* @throws IllegalArgumentException Reflection
*/
public void setIndirectCollectionIfPresent(Object entity, Field field) {
Objects.requireNonNull(entity, ErrorUtils.constructNPXMessage("entity"));
Objects.requireNonNull(field, ErrorUtils.constructNPXMessage("field"));
Object value = EntityPropertiesUtils.getFieldValue(field, entity);
if (value == null || value instanceof IndirectCollection) {
return;
}
if (value instanceof Collection || value instanceof Map) {
EntityPropertiesUtils.setFieldValue(field, entity, createIndirectCollection(value, entity, field));
}
}
/**
* Creates an indirect collection, which wraps the specified collection instance and propagates changes to the
* persistence context.
*
* @param collection Collection to be proxied
* @param owner Collection owner instance
* @param field Field filled with the collection
* @return Indirect collection
*/
public IndirectCollection<?> createIndirectCollection(Object collection, Object owner, Field field) {
return collectionFactory.createIndirectCollection(collection, owner, field);
}
/**
* Remove indirect collection implementations from the specified entity (if present).
*
* @param entity The entity to remove indirect collections from
*/
private void removeIndirectCollections(Object entity) {
Field[] fields = entity.getClass().getDeclaredFields();
for (Field f : fields) {
final Object ob = EntityPropertiesUtils.getFieldValue(f, entity);
if (ob == null) {
continue;
}
if (ob instanceof IndirectCollection) {
IndirectCollection<?> indCol = (IndirectCollection<?>) ob;
EntityPropertiesUtils.setFieldValue(f, entity, indCol.getReferencedCollection());
}
}
}
/**
* Get entity with the specified primary key from the cache. </p>