forked from datanucleus/datanucleus-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
StateManagerImpl.java
6248 lines (5657 loc) · 230 KB
/
StateManagerImpl.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) 2002 Kelly Grizzle and others. All rights reserved.
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.
Contributors:
2003 Erik Bengtson - removed exist() operation
2003 Andy Jefferson - added localiser
2003 Erik Bengtson - added new constructor for App ID
2003 Erik Bengtson - fixed loadDefaultFetchGroup to call jdoPostLoad
2003 Erik Bengtson - fixed evict to call jdoPreClear
2004 Andy Jefferson - converted to use Logger
2004 Andy Jefferson - reordered methods to put in categories, split String utilities across to StringUtils.
2004 Andy Jefferson - added Lifecycle Listener callbacks
2004 Andy Jefferson - removed JDK 1.4 methods so that we support 1.3 also
2005 Martin Taal - Contrib of detach() method for "detachOnClose" functionality.
2007 Xuan Baldauf - Contrib of initialiseForHollowPreConstructed()
2007 Xuan Baldauf - Contrib of internalXXX() methods for fields
2007 Xuan Baldauf - remove the fields "jdoLoadedFields" and "jdoModifiedFields".
2007 Xuan Baldauf - remove the fields "retrievingDetachedState" and "resettingDetachedState".
2007 Xuan Baldauf - remove the field "updatingEmbeddedFieldsWithOwner"
2008 Andy Jefferson - removed all deps on org.datanucleus.store.mapped
...
**********************************************************************/
package org.datanucleus.state;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.BitSet;
import java.util.List;
import org.datanucleus.ClassLoaderResolver;
import org.datanucleus.DetachState;
import org.datanucleus.ExecutionContext;
import org.datanucleus.ExecutionContext.EmbeddedOwnerRelation;
import org.datanucleus.FetchPlan;
import org.datanucleus.FetchPlanForClass;
import org.datanucleus.FetchPlanState;
import org.datanucleus.PersistableObjectType;
import org.datanucleus.PropertyNames;
import org.datanucleus.api.ApiAdapter;
import org.datanucleus.cache.CachedPC;
import org.datanucleus.cache.L2CachePopulateFieldManager;
import org.datanucleus.cache.L2CacheRetrieveFieldManager;
import org.datanucleus.cache.Level2Cache;
import org.datanucleus.enhancement.Detachable;
import org.datanucleus.enhancement.ExecutionContextReference;
import org.datanucleus.enhancement.Persistable;
import org.datanucleus.enhancement.StateManager;
import org.datanucleus.enhancer.EnhancementHelper;
import org.datanucleus.exceptions.ClassNotResolvedException;
import org.datanucleus.exceptions.NotYetFlushedException;
import org.datanucleus.exceptions.NucleusException;
import org.datanucleus.exceptions.NucleusObjectNotFoundException;
import org.datanucleus.exceptions.NucleusUserException;
import org.datanucleus.flush.DeleteOperation;
import org.datanucleus.flush.PersistOperation;
import org.datanucleus.flush.UpdateMemberOperation;
import org.datanucleus.identity.IdentityReference;
import org.datanucleus.identity.IdentityUtils;
import org.datanucleus.metadata.AbstractClassMetaData;
import org.datanucleus.metadata.AbstractMemberMetaData;
import org.datanucleus.metadata.IdentityType;
import org.datanucleus.metadata.MetaData;
import org.datanucleus.metadata.RelationType;
import org.datanucleus.metadata.VersionMetaData;
import org.datanucleus.metadata.VersionStrategy;
import org.datanucleus.store.FieldValues;
import org.datanucleus.store.ObjectReferencingStoreManager;
import org.datanucleus.store.StoreManager;
import org.datanucleus.store.federation.FederatedStoreManager;
import org.datanucleus.store.fieldmanager.AbstractFetchDepthFieldManager.EndOfFetchPlanGraphException;
import org.datanucleus.store.fieldmanager.AttachFieldManager;
import org.datanucleus.store.fieldmanager.DeleteFieldManager;
import org.datanucleus.store.fieldmanager.DetachFieldManager;
import org.datanucleus.store.fieldmanager.FieldManager;
import org.datanucleus.store.fieldmanager.LoadFieldManager;
import org.datanucleus.store.fieldmanager.MakeTransientFieldManager;
import org.datanucleus.store.fieldmanager.PersistFieldManager;
import org.datanucleus.store.fieldmanager.SingleTypeFieldManager;
import org.datanucleus.store.fieldmanager.SingleValueFieldManager;
import org.datanucleus.store.fieldmanager.UnsetOwnerFieldManager;
import org.datanucleus.store.types.SCO;
import org.datanucleus.store.types.SCOCollection;
import org.datanucleus.store.types.SCOContainer;
import org.datanucleus.store.types.SCOMap;
import org.datanucleus.store.types.SCOUtils;
import org.datanucleus.store.types.containers.ContainerHandler;
import org.datanucleus.store.types.converters.TypeConversionHelper;
import org.datanucleus.util.ClassUtils;
import org.datanucleus.util.Localiser;
import org.datanucleus.util.NucleusLogger;
import org.datanucleus.util.StringUtils;
/**
* Implementation of a StateManager, supporting the bytecode enhancement contract of DataNucleus.
* Implemented here as one StateManager per Object so adds on functionality particular to each object.
* All Persistable objects will have a StateManager when they have had communication with the ExecutionContext.
* They will typically always have an identity also. The exception to that is for embedded/serialised objects.
*
* <H3>Embedded/Serialised Objects</H3>
* An object that is being embedded/serialised in an owning object will NOT have an identity unless the object is subject to a makePersistent() call also.
* When an object is embedded/serialised and a field is changed, the field will NOT be marked as dirty (unless it is also an object in its own right with an identity).
* When a field is changed any owning objects are updated so that they can update their tables accordingly.
*
* <H3>Performance and Memory</H3>
* StateManagers are very performance-critical, because for each Persistable object made persistent,
* there will be one StateManager instance, adding up to the total memory footprint of that object.
* In heap profiling analysis (cerca 2008), StateManagerImpl showed to consume bytes 169 per StateManager by itself
* and about 500 bytes per StateManager when taking PC-individual child-object (like the id) referred by the StateManager into account.
* With small Java objects this can mean a substantial memory overhead and for applications using such small objects can be critical.
* For this reason the StateManager should always be minimal in memory consumption.
* Any fields that are only present for some cases should, in general, either be offloaded to the ExecutionContext, or to a separate object if multiple fields.
* The fields <I>loadedFields</I> and <I>dirtyFields</I> could, arguably, be made BitSet but it isn't clear of the benefit in the typical use-case
* of smaller array sizes (number of fields in a class), as per https://www.baeldung.com/java-boolean-array-bitset-performance
*
* <H3>Commit/Rollback</H3>
* When the managed object is changed it is saved as <I>savedPC</I> and its state as <I>savedPersistenceFlags</I> and <I>savedLoadedFields</I>.
* These fields allow it to be rolled-back to an earlier state. Refer to the <I>saveFields</I> and <I>restoreFields</I> methods.
*/
public class StateManagerImpl implements DNStateManager<Persistable>
{
protected static final SingleTypeFieldManager HOLLOWFIELDMANAGER = new SingleTypeFieldManager();
/** Whether we are in the process of INSERTING the object to persistence. */
protected static final int FLAG_INSERTING = 2<<21;
/** Whether we are in the process of INSERTING the object from persistence, running callbacks. */
protected static final int FLAG_INSERTING_CALLBACKS = 2<<20;
/** Whether we are in the process of DELETING the object from persistence. */
protected static final int FLAG_DELETING = 2<<19;
/** Whether we are managing an embedded object. */
protected static final int FLAG_EMBEDDED = 2<<18;
/** Whether we are currently validating the object in the datastore. */
protected static final int FLAG_VALIDATING = 2<<17;
/** Whether to restore values at StateManager. If true, overwrites the restore values at tx level. */
protected static final int FLAG_RESTORE_VALUES = 2<<16;
/** Flag to signify that we are currently storing the persistable object, so we don't detach it on serialisation. */
protected static final int FLAG_STORING_PC = 2<<15;
/** Whether the managed object needs the inheritance level validating before loading fields. */
protected static final int FLAG_NEED_INHERITANCE_VALIDATION = 2<<14;
protected static final int FLAG_POSTINSERT_UPDATE = 2<<13;
protected static final int FLAG_LOADINGFPFIELDS = 2<<12;
protected static final int FLAG_POSTLOAD_PENDING = 2<<11;
protected static final int FLAG_CHANGING_STATE = 2<<10;
/** if the persistable object is new and was flushed to the datastore. */
protected static final int FLAG_FLUSHED_NEW = 2<<9;
protected static final int FLAG_BECOMING_DELETED = 2<<8;
/** Flag whether this SM is updating the ownership of its embedded/serialised field(s). */
protected static final int FLAG_UPDATING_EMBEDDING_FIELDS_WITH_OWNER = 2<<7;
/** Flag for {@link #flags} whether we are retrieving detached state from the detached object. */
protected static final int FLAG_RETRIEVING_DETACHED_STATE = 2<<6;
/** Flag for {@link #flags} whether we are resetting the detached state. */
protected static final int FLAG_RESETTING_DETACHED_STATE = 2<<5;
/** Flag for {@link #flags} whether we are in the process of attaching the object. */
protected static final int FLAG_ATTACHING = 2<<4;
/** Flag for {@link #flags} whether we are in the process of detaching the object. */
protected static final int FLAG_DETACHING = 2<<3;
/** Flag for {@link #flags} whether we are in the process of making transient the object. */
protected static final int FLAG_MAKING_TRANSIENT = 2<<2;
/** Flag for {@link #flags} whether we are in the process of flushing changes to the object. */
protected static final int FLAG_FLUSHING = 2<<1;
/** Flag for {@link #flags} whether we are in the process of disconnecting the object. */
protected static final int FLAG_DISCONNECTING = 2<<0;
/** The persistable instance managed by this StateManager. */
protected Persistable myPC;
/** Bit-packed flags for operational settings (packed into "int" for memory benefit). */
protected int flags;
/** The ExecutionContext for this StateManager */
protected ExecutionContext myEC;
/** the metadata for the class. */
protected AbstractClassMetaData cmd;
/** The object identity in the JVM. Will be "myID" (if set) or otherwise a temporary id based on this StateManager. */
protected Object myInternalID;
/** The object identity in the datastore */
protected Object myID;
/** The actual LifeCycleState for the persistable instance */
protected LifeCycleState myLC;
/** Optimistic version, when starting any transaction. */
protected Object myVersion;
/** Optimistic version, after insert/update but not yet committed (i.e incremented). */
protected Object transactionalVersion;
/** Flags for state stored with the object. Maps onto org.datanucleus.enhancement.Persistable "dnFlags". */
protected byte persistenceFlags;
/** Fetch plan for the class of the managed object. */
protected FetchPlanForClass myFP;
/**
* Indicator for whether the persistable instance is dirty.
* Note that "dirty" in this case is not equated to being in the P_DIRTY state.
* The P_DIRTY state means that at least one field in the object has been written by the user during
* the current transaction, whereas for this parameter, a field is "dirty" if it's been written by the
* user but not yet updated in the data store. The difference is, it's possible for an object's state
* to be P_DIRTY, yet have no "dirty" fields because flush() has been called at least once during the transaction.
*/
protected boolean dirty = false;
/** indicators for which fields are currently dirty in the persistable instance. */
protected boolean[] dirtyFields;
/** indicators for which fields are currently loaded in the persistable instance. */
protected boolean[] loadedFields;
/** Current FieldManager. */
protected FieldManager currFM = null;
/** Saved state, for use during any rollback for reinstating the object. */
protected SavedState savedState = null;
private static final EnhancementHelper HELPER;
static
{
HELPER = (EnhancementHelper) AccessController.doPrivileged(new PrivilegedAction()
{
public Object run()
{
try
{
return EnhancementHelper.getInstance();
}
catch (SecurityException e)
{
throw new NucleusUserException(Localiser.msg("026000"), e).setFatal();
}
}
});
}
/**
* Constructor for object of specified type managed by the provided ExecutionContext.
* @param ec ExecutionContext
* @param cmd the metadata for the class.
*/
public StateManagerImpl(ExecutionContext ec, AbstractClassMetaData cmd)
{
connect(ec, cmd);
}
/* (non-Javadoc)
* @see org.datanucleus.state.AbstractStateManager#connect(org.datanucleus.ExecutionContext, org.datanucleus.metadata.AbstractClassMetaData)
*/
@Override
public void connect(ExecutionContext ec, AbstractClassMetaData cmd)
{
int fieldCount = cmd.getMemberCount();
this.cmd = cmd;
this.myEC = ec;
dirtyFields = new boolean[fieldCount];
loadedFields = new boolean[fieldCount];
dirty = false;
myFP = myEC.getFetchPlan().getFetchPlanForClass(cmd);
myVersion = null;
transactionalVersion = null;
persistenceFlags = 0;
ec.setAttachDetachReferencedObject(this, null);
}
/**
* Disconnect from the ExecutionContext and persistable object.
*/
public void disconnect()
{
if (NucleusLogger.PERSISTENCE.isDebugEnabled())
{
NucleusLogger.PERSISTENCE.debug(Localiser.msg("026011", IdentityUtils.getPersistableIdentityForId(getInternalObjectId()), this));
}
// Transitioning to TRANSIENT state, so if any postLoad action is pending we do it before.
// This usually happens when we make transient instances using the fetch plan and some
// fields were loaded during this action which triggered a dnPostLoad event
if (isPostLoadPending())
{
flags &= ~FLAG_CHANGING_STATE; //hack to make sure postLoad does not return without processing
setPostLoadPending(false);
postLoad();
}
// Call unsetOwner() on all loaded SCO fields.
int[] fieldNumbers = ClassUtils.getFlagsSetTo(loadedFields, cmd.getSCOMutableMemberPositions(), true);
if (fieldNumbers != null && fieldNumbers.length > 0)
{
provideFields(fieldNumbers, new UnsetOwnerFieldManager());
}
// Disconnect any embedded related StateManagers, since we own them
List<EmbeddedOwnerRelation> subSMRelations = myEC.getEmbeddedInformationForOwner(this);
if (subSMRelations != null && !subSMRelations.isEmpty())
{
for (EmbeddedOwnerRelation embRel : subSMRelations)
{
DNStateManager embSM = embRel.getEmbeddedSM();
if (embSM.isConnected())
{
embSM.disconnect();
}
}
}
myEC.removeStateManagerFromCache(this);
persistenceFlags = Persistable.READ_WRITE_OK;
myPC.dnReplaceFlags();
flags |= FLAG_DISCONNECTING;
try
{
replaceStateManager(myPC, null);
}
finally
{
flags &= ~FLAG_DISCONNECTING;
}
savedState = null;
preDeleteLoadedFields = null;
myPC = null;
myID = null;
myInternalID = null;
myLC = null;
myEC = null;
myFP = null;
myVersion = null;
persistenceFlags = 0;
flags = 0;
transactionalVersion = null;
currFM = null;
dirty = false;
cmd = null;
dirtyFields = null;
loadedFields = null;
// TODO Remove the object from any pooling (when we enable it) via nucCtx.getStateManagerFactory().disconnectStateManager(this);
}
@Override
public boolean isConnected()
{
return myPC != null;
}
/**
* Initialises a state manager to manage a hollow instance having the given object ID and the given (optional) field values.
* This constructor is used for creating new instances of existing persistent objects, and consequently shouldn't be used
* when the StoreManager controls the creation of such objects (such as in an ODBMS).
* @param id the JDO identity of the object.
* @param fv the initial field values of the object (optional)
* @param pcClass Class of the object that this will manage the state for
*/
public void initialiseForHollow(Object id, FieldValues fv, Class pcClass)
{
myID = id;
myLC = myEC.getNucleusContext().getApiAdapter().getLifeCycleState(LifeCycleState.HOLLOW);
persistenceFlags = Persistable.LOAD_REQUIRED;
if (IdentityUtils.isDatastoreIdentity(id) || id == null)
{
// Create new PC
myPC = HELPER.newInstance(pcClass, this);
}
else
{
// Create new PC, and copy the key class to fields
myPC = HELPER.newInstance(pcClass, this, myID);
markPKFieldsAsLoaded();
}
// Put in L1 cache just in case referred to by other objects in the FieldValues
// e.g when we retrieve objects with circular references in the same result set from a query
myEC.putObjectIntoLevel1Cache(this);
if (fv != null)
{
loadFieldValues(fv);
// TODO If this object has unique key(s) then they will likely be loaded from the fieldValues, so could put in L1 cache here
}
}
/**
* Initialises a state manager to manage the given hollow instance having the given object ID.
* Unlike the {@link #initialiseForHollow} method, this method does not create a new instance and instead
* takes a pre-constructed instance (such as from an ODBMS).
* @param id the identity of the object.
* @param pc the object to be managed.
*/
public void initialiseForHollowPreConstructed(Object id, Persistable pc)
{
myID = id;
myLC = myEC.getNucleusContext().getApiAdapter().getLifeCycleState(LifeCycleState.HOLLOW);
persistenceFlags = Persistable.LOAD_REQUIRED;
myPC = pc;
replaceStateManager(myPC, this); // Assign this StateManager to the PC
myPC.dnReplaceFlags();
// TODO Add to the cache
}
/**
* Initialises a state manager to manage the passed persistent instance having the given object ID.
* Used where we have retrieved a PC object from a datastore directly (not field-by-field), for example on an object datastore.
* This initialiser will not add StateManagers to all related PCs. This must be done by any calling process.
* This simply adds the StateManager to the specified object and records the id, setting all fields of the object as loaded.
* @param id the identity of the object.
* @param pc The object to be managed
*/
public void initialiseForPersistentClean(Object id, Persistable pc)
{
myID = id;
myLC = myEC.getNucleusContext().getApiAdapter().getLifeCycleState(LifeCycleState.P_CLEAN);
persistenceFlags = Persistable.LOAD_REQUIRED;
myPC = pc;
replaceStateManager(myPC, this); // Assign this StateManager to the PC
myPC.dnReplaceFlags();
// Mark all fields as loaded
for (int i=0; i<loadedFields.length; ++i)
{
loadedFields[i] = true;
}
// Add the object to the cache
myEC.putObjectIntoLevel1Cache(this);
}
/**
* Initialises a state manager to manage a provided Persistable instance that will be EMBEDDED/SERIALISED into another Persistable object.
* The instance will not be assigned an identity in the process since it is a SCO.
* @param pc The Persistable to manage (see copyPc also)
* @param copyPc Whether the SM should manage a copy of the passed PC or that one
*/
public void initialiseForEmbedded(Persistable pc, boolean copyPc)
{
myID = null; // Embedded, so don;t need an ID since we're not persisting it
myLC = myEC.getNucleusContext().getApiAdapter().getLifeCycleState(LifeCycleState.P_CLEAN);
persistenceFlags = Persistable.LOAD_REQUIRED;
flags |= FLAG_EMBEDDED;
myPC = pc;
replaceStateManager(myPC, this); // Set SM for embedded PC to be this
if (copyPc)
{
// Create a new PC with the same field values
Persistable pcCopy = myPC.dnNewInstance(this);
pcCopy.dnCopyFields(myPC, cmd.getAllMemberPositions());
// Swap the managed PC to be the copy and not the input
replaceStateManager(pcCopy, this);
myPC = pcCopy;
// Reset dnFlags in the input object to Persistable.READ_WRITE_OK and clear its state manager.
pc.dnReplaceFlags();
replaceStateManager(pc, null);
}
// Mark all fields as loaded since we are using the passed Persistable
for (int i=0;i<loadedFields.length;i++)
{
loadedFields[i] = true;
}
}
/**
* Initialises a state manager to manage an embedded instance of the specified type.
* This constructor is used for creating new instances of existing (embedded) persistent objects, and consequently shouldn't be used
* when the StoreManager controls the creation of such objects (such as in an ODBMS).
* TODO Consider passing in a FieldValues and set the fields
* @param pcClass Class of the (embedded) object that this will manage the state for
*/
public void initialiseForEmbedded(Class<Persistable> pcClass)
{
myID = null; // Embedded, so don't need an ID since we're not persisting it
myLC = myEC.getNucleusContext().getApiAdapter().getLifeCycleState(LifeCycleState.P_CLEAN); // TODO Should be HOLLOW?
persistenceFlags = Persistable.LOAD_REQUIRED;
flags |= FLAG_EMBEDDED;
// Create new (embedded) PC
myPC = HELPER.newInstance(pcClass, this);
// Mark all fields as loaded for now, to be populated later
for (int i=0;i<loadedFields.length;i++)
{
loadedFields[i] = true;
}
}
/**
* Initialises a state manager to manage a transient instance that is becoming newly persistent.
* A new object ID for the instance is obtained from the store manager and the object is inserted in the data store.
* <p>
* This constructor is used for assigning state managers to existing instances that are transitioning to a persistent state.
* @param pc the instance being make persistent.
* @param preInsertChanges Any changes to make before inserting
*/
public void initialiseForPersistentNew(Persistable pc, FieldValues preInsertChanges)
{
myPC = pc;
myLC = myEC.getNucleusContext().getApiAdapter().getLifeCycleState(LifeCycleState.P_NEW);
persistenceFlags = Persistable.READ_OK;
for (int i=0; i<loadedFields.length; ++i)
{
loadedFields[i] = true;
}
replaceStateManager(myPC, this); // Assign this StateManager to the PC
myPC.dnReplaceFlags();
saveFields();
// Populate all fields that have "value-strategy" and are not datastore populated
populateValueGenerationMembers();
if (preInsertChanges != null)
{
// Apply any pre-insert field updates
preInsertChanges.fetchFields(this);
}
if (cmd.getIdentityType() == IdentityType.APPLICATION)
{
// Make sure any PK fields that are Persistable are persisted first, so we have an id to assign our identity
int[] pkFieldNumbers = cmd.getPKMemberPositions();
for (int i=0;i<pkFieldNumbers.length;i++)
{
int fieldNumber = pkFieldNumbers[i];
AbstractMemberMetaData pkMmd = cmd.getMetaDataForManagedMemberAtAbsolutePosition(fieldNumber);
if (myEC.getMetaDataManager().getMetaDataForClass(pkMmd.getType(), getExecutionContext().getClassLoaderResolver()) != null)
{
try
{
if (myEC.getMultithreaded())
{
myEC.threadLock();
}
FieldManager prevFM = currFM;
try
{
currFM = new SingleValueFieldManager();
myPC.dnProvideField(fieldNumber);
Persistable pkFieldPC = (Persistable) ((SingleValueFieldManager) currFM).fetchObjectField(fieldNumber);
if (pkFieldPC == null)
{
throw new NucleusUserException(Localiser.msg("026016", pkMmd.getFullFieldName()));
}
if (!myEC.getApiAdapter().isPersistent(pkFieldPC))
{
// Make sure the PC field is persistent - can cause the insert of our object being managed by this SM via flush() when bidir relation
Object persistedFieldPC = null;
if (pkMmd.isEmbedded())
{
persistedFieldPC = myEC.persistObjectInternal(pkFieldPC, null, PersistableObjectType.EMBEDDED_PC, this, fieldNumber);
}
else
{
persistedFieldPC = myEC.persistObjectInternal(pkFieldPC, null, PersistableObjectType.PC);
}
replaceField(myPC, fieldNumber, persistedFieldPC, false);
}
}
finally
{
currFM = prevFM;
}
}
finally
{
if (myEC.getMultithreaded())
{
myEC.threadUnlock();
}
}
}
}
}
// Set the identity of this object
setIdentity(false);
if (myEC.getTransaction().isActive())
{
myEC.enlistInTransaction(this);
}
// Now in PERSISTENT_NEW so call any callbacks/listeners
getCallbackHandler().postCreate(myPC);
if (myEC.getManageRelations())
{
// Managed Relations : register non-null bidir fields for later processing
ClassLoaderResolver clr = myEC.getClassLoaderResolver();
int[] relationPositions = cmd.getRelationMemberPositions(clr);
if (relationPositions != null)
{
for (int i=0;i<relationPositions.length;i++)
{
AbstractMemberMetaData mmd = cmd.getMetaDataForManagedMemberAtAbsolutePosition(relationPositions[i]);
if (RelationType.isBidirectional(mmd.getRelationType(clr)))
{
Object value = provideField(relationPositions[i]);
if (value != null)
{
// Store the field with value of null so it gets checked
myEC.getRelationshipManager(this).relationChange(relationPositions[i], null, value);
}
}
}
}
}
}
/**
* Initialises a state manager to manage a Transactional Transient instance.
* A new object ID for the instance is obtained from the store manager and the object is inserted in the data store.
* <p>
* This constructor is used for assigning state managers to Transient
* instances that are transitioning to a transient clean state.
* @param pc the instance being make persistent.
*/
public void initialiseForTransactionalTransient(Persistable pc)
{
myPC = pc;
myLC = null;
persistenceFlags = Persistable.READ_OK;
for (int i=0; i<loadedFields.length; ++i)
{
loadedFields[i] = true;
}
myPC.dnReplaceFlags();
// Populate all fields that have "value-strategy" and are not datastore populated
populateValueGenerationMembers();
// Set the identity
setIdentity(false);
// for non transactional read, tx might be not active
// TODO add verification if is non transactional read = true
if (myEC.getTransaction().isActive())
{
myEC.enlistInTransaction(this);
}
}
/**
* Initialises the StateManager to manage a Persistable object in detached state.
* @param pc the detach object.
* @param id the identity of the object.
* @param version the detached version
*/
public void initialiseForDetached(Persistable pc, Object id, Object version)
{
this.myID = id;
this.myPC = pc;
setVersion(version);
// This lifecycle state is not always correct. It is certainly "detached"
// but we dont know if it is CLEAN or DIRTY. We need this setting here since all objects
// have a lifecycle state and other methods e.g isPersistent() depend on it.
this.myLC = myEC.getNucleusContext().getApiAdapter().getLifeCycleState(LifeCycleState.DETACHED_CLEAN);
this.myPC.dnReplaceFlags();
replaceStateManager(myPC, this);
}
/**
* Initialises the StateManager to manage a Persistable object that is not persistent but is about to be deleted.
* @param pc the object to delete
*/
public void initialiseForPNewToBeDeleted(Persistable pc)
{
this.myID = null;
this.myPC = pc;
this.myLC = myEC.getNucleusContext().getApiAdapter().getLifeCycleState(LifeCycleState.P_NEW);
for (int i=0; i<loadedFields.length; ++i) // Mark all fields as loaded
{
loadedFields[i] = true;
}
replaceStateManager(myPC, this);
}
/**
* Initialise StateManager, assigning the specified id to the object.
* This is used when getting objects out of the L2 Cache, where they have no StateManager
* assigned, and returning them as associated with a particular ExecutionContext.
* @param cachedPC The cached PC object
* @param id Id to assign to the Persistable object
*/
public void initialiseForCachedPC(CachedPC cachedPC, Object id)
{
// Create a new copy of the input object type, performing the majority of the initialisation
initialiseForHollow(id, null, cachedPC.getObjectClass());
myLC = myEC.getNucleusContext().getApiAdapter().getLifeCycleState(LifeCycleState.P_CLEAN);
persistenceFlags = Persistable.READ_OK;
int[] fieldsToLoad = ClassUtils.getFlagsSetTo(cachedPC.getLoadedFields(), myFP.getMemberNumbers(), true);
if (fieldsToLoad != null)
{
// Put this object in L1 cache for easy referencing
myEC.putObjectIntoLevel1Cache(this);
L2CacheRetrieveFieldManager l2RetFM = constructL2CacheRetrieveFieldManager(this, cachedPC);
this.replaceFields(fieldsToLoad, l2RetFM);
for (int i=0;i<fieldsToLoad.length;i++)
{
loadedFields[fieldsToLoad[i]] = true;
}
int[] fieldsNotLoaded = l2RetFM.getFieldsNotLoaded();
if (fieldsNotLoaded != null)
{
for (int i=0;i<fieldsNotLoaded.length;i++)
{
loadedFields[fieldsNotLoaded[i]] = false;
}
}
}
if (cachedPC.getVersion() != null)
{
// Make sure we start from the same version as was cached
setVersion(cachedPC.getVersion());
}
// Make sure any SCO fields are wrapped
replaceAllLoadedSCOFieldsWithWrappers();
if (myEC.getTransaction().isActive())
{
myEC.enlistInTransaction(this);
}
if (areFieldsLoaded(myFP.getMemberNumbers()))
{
// Should we call postLoad when getting the object out of the L2 cache ? Seems incorrect IMHO
postLoad();
}
}
/**
* Method to create a L2Cache retrieval FM.
* @param stateManager The SM
* @param cachedPC The Cached object
* @return The L2Cache retrieval FM
*/
public L2CacheRetrieveFieldManager constructL2CacheRetrieveFieldManager(DNStateManager stateManager, CachedPC cachedPC)
{
// having this method enables custom implementation of this class
return new L2CacheRetrieveFieldManager(stateManager, cachedPC);
}
/**
* Method to create a L2Cache population FM.
* @param stateManager The SM
* @param cachedPC The Cached object
* @return The L2Cache population FM
*/
public L2CachePopulateFieldManager constructL2CachePopulateFieldManager(DNStateManager stateManager, CachedPC cachedPC)
{
// having this method enables custom implementation of this class
return new L2CachePopulateFieldManager(stateManager, cachedPC);
}
/**
* Convenience method to populate all members in the PC object that need their value generating (according to metadata) and that aren't datastore-attributed.
* This applies not just to PK members (main use-case) but also to any other member (DN extension).
* Members can be populated only if they are null, dependent on metadata.
* This method is called once on a PC object, when makePersistent is called.
*/
protected void populateValueGenerationMembers()
{
int[] valueGenMemberPositions = cmd.getValueGenerationMemberPositions();
if (valueGenMemberPositions != null)
{
for (int i=0;i<valueGenMemberPositions.length;i++)
{
int memberPos = valueGenMemberPositions[i];
AbstractMemberMetaData mmd = cmd.getMetaDataForManagedMemberAtAbsolutePosition(memberPos);
// Check for the strategy (not really required now TODO Remove check), and if it is a datastore attributed strategy
if (mmd.getValueStrategy() != null && !getStoreManager().isValueGenerationStrategyDatastoreAttributed(cmd, memberPos))
{
// Assign the strategy value where required.
// Default JDO/JPA behaviour is to always provide a strategy value when it is marked as using a strategy
boolean applyStrategy = true;
if (!mmd.getType().isPrimitive() &&
mmd.hasExtension(MetaData.EXTENSION_MEMBER_STRATEGY_WHEN_NOTNULL) &&
mmd.getValueForExtension(MetaData.EXTENSION_MEMBER_STRATEGY_WHEN_NOTNULL).equalsIgnoreCase("false") &&
this.provideField(memberPos) != null)
{
// extension to only provide a value-strategy value where the field is null at persistence.
applyStrategy = false;
}
if (applyStrategy)
{
// Apply a strategy value for this field
Object obj = getStoreManager().getValueGenerationStrategyValue(myEC, cmd, mmd);
this.replaceField(memberPos, obj);
}
}
}
}
}
@Override
public AbstractClassMetaData getClassMetaData()
{
return cmd;
}
@Override
public ExecutionContext getExecutionContext()
{
return myEC;
}
@Override
public ExecutionContextReference getExecutionContextReference()
{
return myEC;
}
@Override
public StoreManager getStoreManager()
{
return myEC.getNucleusContext().isFederated() ? ((FederatedStoreManager)myEC.getStoreManager()).getStoreManagerForClass(cmd) : myEC.getStoreManager();
}
@Override
public FetchPlanForClass getFetchPlanForClass()
{
return myFP;
}
public LifeCycleState getLifecycleState()
{
return myLC;
}
protected CallbackHandler getCallbackHandler()
{
return myEC.getCallbackHandler();
}
public Persistable getObject()
{
return myPC;
}
public String getObjectAsPrintable()
{
return StringUtils.toJVMIDString(myPC);
}
public String toString()
{
return "StateManager[pc=" + StringUtils.toJVMIDString(myPC) + ", lifecycle=" + myLC + (isEmbedded() ? ", EMBEDDED" : "") + "]";
}
/**
* Accessor for whether the instance is newly persistent yet hasnt yet been flushed to the datastore.
* @return Whether not yet flushed to the datastore
*/
public boolean isWaitingToBeFlushedToDatastore()
{
// Return true if object is new and not yet flushed to datastore
return myLC.stateType() == LifeCycleState.P_NEW && !isFlushedNew();
}
/**
* Accessor for whether we are in the process of restoring the values.
* @return Whether we are restoring values
*/
public boolean isRestoreValues()
{
return (flags&FLAG_RESTORE_VALUES) != 0;
}
protected boolean isChangingState()
{
return (flags&FLAG_CHANGING_STATE) != 0;
}
public boolean isInserting()
{
return (flags&FLAG_INSERTING) != 0;
}
@Override
public void setInserting()
{
flags |= FLAG_INSERTING;
flags &= ~FLAG_INSERTING_CALLBACKS;
}
@Override
public void setInsertingCallbacks()
{
flags &= ~FLAG_INSERTING;
flags |= FLAG_INSERTING_CALLBACKS;
}
public boolean isDeleting()
{
return (flags&FLAG_DELETING) != 0;
}
public void markForInheritanceValidation()
{
flags |= FLAG_NEED_INHERITANCE_VALIDATION;
}
/**
* Sets the value for the version column in a transaction not yet committed
* @param version The version
*/
public void setTransactionalVersion(Object version)
{
this.transactionalVersion = version;
}
/**
* Return the object representing the transactional version of the calling instance.
* @param pc the calling persistable instance
* @return the object representing the version of the calling instance
*/
public Object getTransactionalVersion(Object pc)
{
return this.transactionalVersion;
}
/**
* Sets the value for the version column in the datastore
* @param version The version
*/
public void setVersion(Object version)
{
this.myVersion = version;
this.transactionalVersion = version;
}
/* (non-Javadoc)
* @see org.datanucleus.store.DNStateManager#setFlushedNew(boolean)
*/
public void setFlushedNew(boolean flag)
{
if (flag)
{
flags |= FLAG_FLUSHED_NEW;
}
else
{
flags &= ~FLAG_FLUSHED_NEW;
}
}
/* (non-Javadoc)
* @see org.datanucleus.store.DNStateManager#isFlushedNew()
*/
public boolean isFlushedNew()
{
return (flags&FLAG_FLUSHED_NEW)!=0;
}
/* (non-Javadoc)
* @see org.datanucleus.store.DNStateManager#isFlushedToDatastore()
*/
public boolean isFlushedToDatastore()
{
return !dirty;
}
/* (non-Javadoc)
* @see org.datanucleus.store.DNStateManager#setFlushing(boolean)
*/
public void setFlushing(boolean flushing)
{
if (flushing)