001: /**********************************************************************
002: Copyright (c) 2005 Andy Jefferson and others. All rights reserved.
003: Licensed under the Apache License, Version 2.0 (the "License");
004: you may not use this file except in compliance with the License.
005: You may obtain a copy of the License at
006:
007: http://www.apache.org/licenses/LICENSE-2.0
008:
009: Unless required by applicable law or agreed to in writing, software
010: distributed under the License is distributed on an "AS IS" BASIS,
011: WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012: See the License for the specific language governing permissions and
013: limitations under the License.
014:
015:
016: Contributors:
017: ...
018: **********************************************************************/package org.jpox.sco;
019:
020: import java.io.ObjectStreamException;
021: import java.util.Collection;
022: import java.util.Comparator;
023: import java.util.Iterator;
024: import java.util.SortedSet;
025:
026: import org.jpox.ClassLoaderResolver;
027: import org.jpox.ObjectManager;
028: import org.jpox.StateManager;
029: import org.jpox.exceptions.JPOXDataStoreException;
030: import org.jpox.exceptions.JPOXUserException;
031: import org.jpox.metadata.AbstractMemberMetaData;
032: import org.jpox.metadata.FieldPersistenceModifier;
033: import org.jpox.sco.exceptions.IncompatibleFieldTypeException;
034: import org.jpox.sco.exceptions.NullsNotAllowedException;
035: import org.jpox.sco.exceptions.QueryUnownedSCOException;
036: import org.jpox.sco.queued.AddOperation;
037: import org.jpox.sco.queued.ClearOperation;
038: import org.jpox.sco.queued.QueuedOperation;
039: import org.jpox.sco.queued.RemoveOperation;
040: import org.jpox.state.FetchPlanState;
041: import org.jpox.state.StateManagerFactory;
042: import org.jpox.store.DatastoreClass;
043: import org.jpox.store.DatastoreIdentifier;
044: import org.jpox.store.expression.QueryExpression;
045: import org.jpox.store.mapping.CollectionMapping;
046: import org.jpox.store.mapping.JavaTypeMapping;
047: import org.jpox.store.query.Queryable;
048: import org.jpox.store.query.ResultObjectFactory;
049: import org.jpox.store.scostore.CollectionStore;
050: import org.jpox.util.JPOXLogger;
051: import org.jpox.util.Localiser;
052: import org.jpox.util.StringUtils;
053:
054: /**
055: * A mutable second-class TreeSet object.
056: * This class extends TreeSet, using that class to contain the current objects, and the backing SetStore
057: * to be the interface to the datastore. A "backing store" is not present for datastores that dont use
058: * DatastoreClass, or if the container is serialised or non-persistent.
059: *
060: * <H3>Modes of Operation</H3>
061: * The user can operate the list in 2 modes.
062: * The <B>cached</B> mode will use an internal cache of the elements (in the "delegate") reading them at
063: * the first opportunity and then using the cache thereafter.
064: * The <B>non-cached</B> mode will just go direct to the "backing store" each call.
065: *
066: * <H3>Mutators</H3>
067: * When the "backing store" is present any updates are passed direct to the datastore as well as to the "delegate".
068: * If the "backing store" isn't present the changes are made to the "delegate" only.
069: *
070: * <H3>Accessors</H3>
071: * When any accessor method is invoked, it typically checks whether the container has been loaded from its
072: * "backing store" (where present) and does this as necessary. Some methods (<B>size()</B>) just check if
073: * everything is loaded and use the delegate if possible, otherwise going direct to the datastore.
074: *
075: * @version $Revision: 1.91 $
076: */
077: public class TreeSet extends java.util.TreeSet implements
078: SCOCollection, SCOMtoN, Cloneable, Queryable {
079: protected static final Localiser LOCALISER = Localiser
080: .getInstance("org.jpox.Localisation");
081:
082: private transient Object owner;
083: private transient StateManager ownerSM;
084: private transient String fieldName;
085: private transient int fieldNumber;
086: private transient Class elementType;
087: private transient boolean allowNulls;
088:
089: /** The "backing store" */
090: protected CollectionStore backingStore;
091:
092: /** The internal "delegate". */
093: protected java.util.TreeSet delegate;
094:
095: /** Whether to use caching. */
096: protected boolean useCache = true;
097:
098: /** Status flag whether the collection is loaded into the cache. */
099: protected boolean isCacheLoaded = false;
100:
101: /** Whether the SCO is in "direct" or "queued" mode. */
102: boolean queued = false;
103:
104: /** Queued operations when using "queued" mode. */
105: private java.util.ArrayList queuedOperations = null;
106:
107: /**
108: * Constructor, using the StateManager of the "owner" and the field name.
109: * @param ownerSM The owner StateManager
110: * @param fieldName The name of the field of the SCO.
111: */
112: public TreeSet(StateManager ownerSM, String fieldName) {
113: this .ownerSM = ownerSM;
114: this .fieldName = fieldName;
115: this .allowNulls = false;
116:
117: if (ownerSM == null) {
118: this .delegate = new java.util.TreeSet();
119: }
120:
121: if (ownerSM != null) {
122: AbstractMemberMetaData fmd = ownerSM.getClassMetaData()
123: .getMetaDataForMember(fieldName);
124: owner = ownerSM.getObject();
125: fieldNumber = fmd.getAbsoluteFieldNumber();
126: allowNulls = SCOUtils
127: .allowNullsInContainer(allowNulls, fmd);
128: if (ownerSM.getStoreManager().usesDatastoreClass()) {
129: queued = SCOUtils.useContainerQueueing(ownerSM);
130: useCache = SCOUtils.useContainerCache(ownerSM,
131: fieldName);
132: }
133:
134: if (ownerSM.getStoreManager().usesDatastoreClass()
135: && !SCOUtils.collectionHasSerialisedElements(fmd)
136: && fmd.getPersistenceModifier() == FieldPersistenceModifier.PERSISTENT) {
137: ClassLoaderResolver clr = ownerSM.getObjectManager()
138: .getClassLoaderResolver();
139: DatastoreClass ownerTable = ownerSM.getStoreManager()
140: .getDatastoreClass(owner.getClass().getName(),
141: clr);
142: JavaTypeMapping m = ownerTable.getFieldMapping(fmd);
143: if (!(m instanceof CollectionMapping)) {
144: throw new IncompatibleFieldTypeException(ownerSM,
145: fieldName, java.util.TreeSet.class
146: .getName(), fmd.getTypeName());
147: }
148:
149: this .backingStore = (CollectionStore) ownerSM
150: .getStoreManager().getStore(clr, fmd,
151: java.util.TreeSet.class);
152: this .elementType = clr.classForName(this .backingStore
153: .getElementType());
154: }
155:
156: // Set up our delegate, using a suitable comparator
157: Comparator comparator = SCOUtils.getComparator(fmd, ownerSM
158: .getObjectManager().getClassLoaderResolver());
159: if (comparator != null) {
160: this .delegate = new java.util.TreeSet(comparator);
161: } else {
162: this .delegate = new java.util.TreeSet();
163: }
164:
165: if (JPOXLogger.PERSISTENCE.isDebugEnabled()) {
166: JPOXLogger.PERSISTENCE.debug(SCOUtils
167: .getContainerInfoMessage(ownerSM, fieldName,
168: this , useCache, queued, allowNulls,
169: SCOUtils.useCachedLazyLoading(ownerSM,
170: fieldName)));
171: }
172: }
173: }
174:
175: /**
176: * Method to initialise the SCO from an existing value.
177: * @param o The object to set from
178: * @param forInsert Whether the object needs inserting in the datastore with this value
179: * @param forUpdate Whether to update the datastore with this value
180: */
181: public void initialise(Object o, boolean forInsert,
182: boolean forUpdate) {
183: Collection c = (Collection) o;
184: if (c != null) {
185: // Check for the case of serialised PC elements, and assign StateManagers to the elements without
186: AbstractMemberMetaData fmd = ownerSM.getClassMetaData()
187: .getMetaDataForMember(fieldName);
188: if (SCOUtils.collectionHasSerialisedElements(fmd)
189: && fmd.getCollection().getElementClassMetaData() != null) {
190: ObjectManager om = ownerSM.getObjectManager();
191: Iterator iter = c.iterator();
192: while (iter.hasNext()) {
193: Object pc = iter.next();
194: StateManager objSM = om.findStateManager(pc);
195: if (objSM == null) {
196: objSM = StateManagerFactory
197: .newStateManagerForEmbedded(om, pc,
198: false);
199: objSM.addEmbeddedOwner(ownerSM, fieldNumber);
200: }
201: }
202: }
203:
204: if (backingStore != null && useCache && !isCacheLoaded) {
205: // Mark as loaded
206: isCacheLoaded = true;
207: }
208:
209: if (forInsert) {
210: if (JPOXLogger.PERSISTENCE.isDebugEnabled()) {
211: JPOXLogger.PERSISTENCE.debug(LOCALISER.msg(
212: "023007", StringUtils.toJVMIDString(ownerSM
213: .getObject()), fieldName, ""
214: + c.size()));
215: }
216: addAll(c);
217: } else if (forUpdate) {
218: if (JPOXLogger.PERSISTENCE.isDebugEnabled()) {
219: JPOXLogger.PERSISTENCE.debug(LOCALISER.msg(
220: "023008", StringUtils.toJVMIDString(ownerSM
221: .getObject()), fieldName, ""
222: + c.size()));
223: }
224: clear();
225: addAll(c);
226: } else {
227: if (JPOXLogger.PERSISTENCE.isDebugEnabled()) {
228: JPOXLogger.PERSISTENCE.debug(LOCALISER.msg(
229: "023007", StringUtils.toJVMIDString(ownerSM
230: .getObject()), fieldName, ""
231: + c.size()));
232: }
233: delegate.clear();
234: delegate.addAll(c);
235: }
236: }
237: }
238:
239: /**
240: * Method to initialise the SCO for use.
241: */
242: public void initialise() {
243: if (useCache
244: && !SCOUtils.useCachedLazyLoading(ownerSM, fieldName)) {
245: // Load up the container now if not using lazy loading
246: loadFromStore();
247: }
248: }
249:
250: // ----------------------- Implementation of SCO methods -------------------
251:
252: /**
253: * Accessor for the unwrapped value that we are wrapping.
254: * @return The unwrapped value
255: */
256: public Object getValue() {
257: // TODO Cater for delegate not being used
258: return delegate;
259: }
260:
261: /**
262: * Accessor for the element type.
263: * @return the element type contained in the collection
264: */
265: public Class getElementType() {
266: return elementType;
267: }
268:
269: /**
270: * Method to effect the load of the data in the SCO.
271: * Used when the SCO supports lazy-loading to tell it to load all now.
272: */
273: public void load() {
274: if (useCache) {
275: loadFromStore();
276: }
277: }
278:
279: /**
280: * Method to load all elements from the "backing store" where appropriate.
281: */
282: protected void loadFromStore() {
283: if (backingStore != null && !isCacheLoaded) {
284: if (JPOXLogger.PERSISTENCE.isDebugEnabled()) {
285: JPOXLogger.PERSISTENCE.debug(LOCALISER.msg("023006",
286: StringUtils.toJVMIDString(ownerSM.getObject()),
287: fieldName));
288: }
289: delegate.clear();
290: Iterator iter = backingStore.iterator(ownerSM);
291: while (iter.hasNext()) {
292: delegate.add(iter.next());
293: }
294:
295: isCacheLoaded = true;
296: }
297: }
298:
299: /**
300: * Method to flush the changes to the datastore when operating in queued mode.
301: * Does nothing in "direct" mode.
302: */
303: public void flush() {
304: if (queued) {
305: if (queuedOperations != null) {
306: if (JPOXLogger.PERSISTENCE.isDebugEnabled()) {
307: JPOXLogger.PERSISTENCE.debug(LOCALISER.msg(
308: "023005", StringUtils.toJVMIDString(ownerSM
309: .getObject()), fieldName));
310: }
311: Iterator iter = queuedOperations.iterator();
312: while (iter.hasNext()) {
313: QueuedOperation op = (QueuedOperation) iter.next();
314: op.perform(backingStore, ownerSM);
315: }
316:
317: queuedOperations.clear();
318: queuedOperations = null;
319: }
320: }
321: }
322:
323: /**
324: * Convenience method to add a queued operation to the operations we perform at commit.
325: * @param op The operation
326: */
327: protected void addQueuedOperation(QueuedOperation op) {
328: if (queuedOperations == null) {
329: queuedOperations = new java.util.ArrayList();
330: }
331: queuedOperations.add(op);
332: }
333:
334: /**
335: * Method to update an embedded element in this collection.
336: * @param element The element
337: * @param fieldNumber Number of field in the element
338: * @param value New value for this field
339: */
340: public void updateEmbeddedElement(Object element, int fieldNumber,
341: Object value) {
342: if (backingStore != null) {
343: backingStore.updateEmbeddedElement(ownerSM, element,
344: fieldNumber, value);
345: }
346: }
347:
348: /**
349: * Accessor for the field name.
350: * @return The field name
351: */
352: public String getFieldName() {
353: return fieldName;
354: }
355:
356: /**
357: * Accessor for the owner object.
358: * @return The owner object
359: */
360: public Object getOwner() {
361: return owner;
362: }
363:
364: /**
365: * Method to unset the owner and field information.
366: */
367: public synchronized void unsetOwner() {
368: if (ownerSM != null) {
369: owner = null;
370: ownerSM = null;
371: fieldName = null;
372: backingStore = null;
373: }
374: }
375:
376: /**
377: * Utility to mark the object as dirty
378: **/
379: public void makeDirty() {
380: /*
381: * Although we are never really "dirty", the owning object must be
382: * marked dirty so that the proper state change occurs and its
383: * jdoPreStore() gets called properly.
384: */
385: if (ownerSM != null) {
386: ownerSM.getObjectManager().getApiAdapter().makeFieldDirty(
387: owner, fieldName);
388: }
389: }
390:
391: /**
392: * Method to return a detached copy of the container.
393: * Recurse sthrough the elements so that they are likewise detached.
394: * @param state State for detachment process
395: * @return The detached container
396: */
397: public Object detachCopy(FetchPlanState state) {
398: java.util.Collection detached = new java.util.TreeSet();
399: SCOUtils.detachCopyForCollection(ownerSM, toArray(), state,
400: detached);
401: return detached;
402: }
403:
404: /**
405: * Method to return an attached copy of the passed (detached) value. The returned attached copy
406: * is a SCO wrapper. Goes through the existing elements in the store for this owner field and
407: * removes ones no longer present, and adds new elements. All elements in the (detached)
408: * value are attached.
409: * @param value The new (collection) value
410: */
411: public void attachCopy(Object value) {
412: java.util.Collection c = (java.util.Collection) value;
413:
414: // Attach all of the elements in the new collection
415: AbstractMemberMetaData fmd = ownerSM.getClassMetaData()
416: .getMetaDataForMember(fieldName);
417: boolean elementsWithoutIdentity = SCOUtils
418: .collectionHasElementsWithoutIdentity(fmd);
419:
420: java.util.Collection attachedElements = new java.util.HashSet(c
421: .size());
422: SCOUtils.attachCopyForCollection(ownerSM, c.toArray(),
423: attachedElements, elementsWithoutIdentity);
424:
425: // Update the attached collection with the detached elements
426: SCOUtils.updateCollectionWithCollectionElements(this ,
427: attachedElements);
428: }
429:
430: // ------------------------ Query Statement methods ------------------------
431:
432: /**
433: * Method to generate a QueryStatement for the SCO.
434: * @return The QueryStatement
435: */
436: public synchronized QueryExpression newQueryStatement() {
437: return newQueryStatement(elementType, null);
438: }
439:
440: /**
441: * Method to return a QueryStatement, using the specified candidate class.
442: * @param candidateClass the candidate class
443: * @param candidateAlias Alias for the candidate
444: * @return The QueryStatement
445: */
446: public synchronized QueryExpression newQueryStatement(
447: Class candidateClass, DatastoreIdentifier candidateAlias) {
448: if (backingStore == null) {
449: throw new QueryUnownedSCOException();
450: }
451:
452: return backingStore.newQueryStatement(ownerSM, candidateClass
453: .getName(), candidateAlias);
454: }
455:
456: /**
457: * Method to return a ResultObjectFactory for the SCO.
458: * @param stmt The QueryStatement
459: * @param ignoreCache Whether to ignore the cache
460: * @param resultClass Whether to create objects of a particular class
461: * @param useFetchPlan whether to use the fetch plan to retrieve fields in the same query
462: * @return The ResultObjectFactory
463: **/
464: public synchronized ResultObjectFactory newResultObjectFactory(
465: QueryExpression stmt, boolean ignoreCache,
466: Class resultClass, boolean useFetchPlan) {
467: if (backingStore == null) {
468: throw new QueryUnownedSCOException();
469: }
470:
471: return backingStore.newResultObjectFactory(ownerSM, stmt,
472: ignoreCache, useFetchPlan);
473: }
474:
475: // ------------------ Implementation of TreeSet methods --------------------
476:
477: /**
478: * Creates and returns a copy of this object.
479: * @return The cloned object
480: */
481: public Object clone() {
482: if (useCache) {
483: loadFromStore();
484: }
485:
486: return delegate.clone();
487: }
488:
489: /**
490: * Accessor for the comparator.
491: * @return The comparator
492: */
493: public Comparator comparator() {
494: return delegate.comparator();
495: }
496:
497: /**
498: * Accessor for whether an element is contained in this Set.
499: * @param element The element
500: * @return Whether it is contained.
501: **/
502: public boolean contains(Object element) {
503: if (useCache && isCacheLoaded) {
504: // If the "delegate" is already loaded, use it
505: return delegate.contains(element);
506: } else if (backingStore != null) {
507: return backingStore.contains(ownerSM, element);
508: }
509:
510: return delegate.contains(element);
511: }
512:
513: /**
514: * Accessor for whether a collection is contained in this Set.
515: * @param c The collection
516: * @return Whether it is contained.
517: **/
518: public synchronized boolean containsAll(java.util.Collection c) {
519: if (useCache) {
520: loadFromStore();
521: } else if (backingStore != null) {
522: java.util.TreeSet tree = new java.util.TreeSet(c);
523: Iterator iter = iterator();
524: while (iter.hasNext()) {
525: tree.remove(iter.next());
526: }
527:
528: return tree.isEmpty();
529: }
530:
531: return delegate.containsAll(c);
532: }
533:
534: /**
535: * Equality operator.
536: * @param o The object to compare against.
537: * @return Whether this object is the same.
538: **/
539: public synchronized boolean equals(Object o) {
540: if (useCache) {
541: loadFromStore();
542: }
543:
544: if (o == this ) {
545: return true;
546: }
547: if (!(o instanceof java.util.Set)) {
548: return false;
549: }
550: java.util.Set c = (java.util.Set) o;
551:
552: return c.size() == size() && containsAll(c);
553: }
554:
555: /**
556: * Accessor for the first element in the sorted set.
557: * @return The first element
558: **/
559: public Object first() {
560: if (useCache && isCacheLoaded) {
561: // If the "delegate" is already loaded, use it
562: return delegate.first();
563: } else if (useCache) {
564: loadFromStore();
565: } else {
566: // Use Iterator to get element
567: Iterator iter = iterator();
568: return iter.next();
569: }
570:
571: return delegate.first();
572: }
573:
574: /**
575: * Hashcode operator.
576: * @return The Hash code.
577: **/
578: public synchronized int hashCode() {
579: if (useCache) {
580: loadFromStore();
581: }
582: return delegate.hashCode();
583: }
584:
585: /**
586: * Accessor for whether the TreeSet is empty.
587: * @return Whether it is empty.
588: **/
589: public boolean isEmpty() {
590: return size() == 0;
591: }
592:
593: /**
594: * Accessor for an iterator for the Set.
595: * @return The iterator
596: **/
597: public Iterator iterator() {
598: // Populate the cache if necessary
599: if (useCache) {
600: loadFromStore();
601: }
602: return new SCOCollectionIterator(this , ownerSM, delegate,
603: backingStore, useCache);
604: }
605:
606: /**
607: * Method to retrieve the head elements up to the specified element.
608: * @param toElement the element to return up to.
609: * @return The set of elements meeting the input
610: */
611: public SortedSet headSet(Object toElement) {
612: if (useCache && isCacheLoaded) {
613: // If the "delegate" is already loaded, use it
614: return delegate.headSet(toElement);
615: } else if (useCache) {
616: loadFromStore();
617: } else {
618: // TODO Provide a datastore method to do this
619: throw new JPOXUserException(
620: "JPOX doesn't currently support TreeSet.headSet() when not using cached collections");
621: }
622:
623: return delegate.headSet(toElement);
624: }
625:
626: /**
627: * Method to retrieve the subset of elements between the specified elements.
628: * @param fromElement The start element
629: * @param toElement The end element
630: * @return The set of elements meeting the input
631: */
632: public SortedSet subSet(Object fromElement, Object toElement) {
633: if (useCache && isCacheLoaded) {
634: // If the "delegate" is already loaded, use it
635: return delegate.subSet(fromElement, toElement);
636: } else if (useCache) {
637: loadFromStore();
638: } else {
639: // TODO Provide a datastore method to do this
640: throw new JPOXUserException(
641: "JPOX doesn't currently support TreeSet.subSet() when not using cached collections");
642: }
643:
644: return delegate.subSet(fromElement, toElement);
645: }
646:
647: /**
648: * Method to retrieve the set of elements after the specified element.
649: * @param fromElement The start element
650: * @return The set of elements meeting the input
651: */
652: public SortedSet tailSet(Object fromElement) {
653: if (useCache && isCacheLoaded) {
654: // If the "delegate" is already loaded, use it
655: return delegate.headSet(fromElement);
656: } else if (useCache) {
657: loadFromStore();
658: } else {
659: // TODO Provide a datastore method to do this
660: throw new JPOXUserException(
661: "JPOX doesn't currently support TreeSet.tailSet() when not using cached collections");
662: }
663:
664: return delegate.headSet(fromElement);
665: }
666:
667: /**
668: * Accessor for the last element in the sorted set.
669: * @return The last element
670: **/
671: public Object last() {
672: if (useCache && isCacheLoaded) {
673: // If the "delegate" is already loaded, use it
674: return delegate.last();
675: } else if (useCache) {
676: loadFromStore();
677: } else {
678: // Use Iterator to get element
679: Iterator iter = iterator();
680: Object last = null;
681: while (iter.hasNext()) {
682: last = iter.next();
683: }
684: return last;
685: }
686:
687: return delegate.last();
688: }
689:
690: /**
691: * Accessor for the size of the TreeSet.
692: * @return The size.
693: **/
694: public int size() {
695: if (useCache && isCacheLoaded) {
696: // If the "delegate" is already loaded, use it
697: return delegate.size();
698: } else if (backingStore != null) {
699: return backingStore.size(ownerSM);
700: }
701:
702: return delegate.size();
703: }
704:
705: /**
706: * Method to return the list as an array.
707: * @return The array
708: **/
709: public Object[] toArray() {
710: if (useCache) {
711: loadFromStore();
712: } else if (backingStore != null) {
713: return SCOUtils.toArray(backingStore, ownerSM);
714: }
715: return delegate.toArray();
716: }
717:
718: /**
719: * Method to return the list as an array.
720: * @param a The runtime types of the array being defined by this param
721: * @return The array
722: **/
723: public Object[] toArray(Object a[]) {
724: if (useCache) {
725: loadFromStore();
726: } else if (backingStore != null) {
727: return SCOUtils.toArray(backingStore, ownerSM, a);
728: }
729: return delegate.toArray(a);
730: }
731:
732: // ------------------------------ Mutator methods --------------------------
733:
734: /**
735: * Method to add an element to the TreeSet.
736: * @param element The new element
737: * @return Whether it was added ok.
738: **/
739: public boolean add(Object element) {
740: // Reject inappropriate elements
741: if (element == null && !allowNulls) {
742: throw new NullsNotAllowedException(ownerSM, fieldName);
743: }
744:
745: if (useCache) {
746: loadFromStore();
747: }
748:
749: boolean backingSuccess = true;
750: if (backingStore != null) {
751: if (ownerSM.getRelationshipManager() != null) {
752: // Relationship management
753: ownerSM.getRelationshipManager().relationAdd(
754: fieldNumber, element);
755: }
756: if (queued && !ownerSM.getObjectManager().isFlushing()) {
757: addQueuedOperation(new AddOperation(element));
758: } else {
759: try {
760: backingStore.add(ownerSM, element,
761: (useCache ? delegate.size() : -1));
762: } catch (JPOXDataStoreException dse) {
763: JPOXLogger.PERSISTENCE.warn(LOCALISER.msg("023013",
764: "add", fieldName, dse));
765: backingSuccess = false;
766: }
767: }
768: }
769:
770: // Only make it dirty after adding the field to the datastore so we give it time
771: // to be inserted - otherwise jdoPreStore on this object would have been called before completing the addition
772: makeDirty();
773:
774: boolean delegateSuccess = delegate.add(element);
775: return (backingStore != null ? backingSuccess : delegateSuccess);
776: }
777:
778: /**
779: * Method to add a collection to the TreeSet.
780: * @param elements The collection
781: * @return Whether it was added ok.
782: **/
783: public boolean addAll(Collection elements) {
784: if (useCache) {
785: loadFromStore();
786: }
787:
788: boolean backingSuccess = true;
789: if (backingStore != null) {
790: if (ownerSM.getRelationshipManager() != null) {
791: // Relationship management
792: Iterator iter = elements.iterator();
793: while (iter.hasNext()) {
794: ownerSM.getRelationshipManager().relationAdd(
795: fieldNumber, iter.next());
796: }
797: }
798: if (queued && !ownerSM.getObjectManager().isFlushing()) {
799: Iterator iter = elements.iterator();
800: while (iter.hasNext()) {
801: addQueuedOperation(new AddOperation(iter.next()));
802: }
803: } else {
804: try {
805: backingSuccess = backingStore
806: .addAll(ownerSM, elements,
807: (useCache ? delegate.size() : -1));
808: } catch (JPOXDataStoreException dse) {
809: JPOXLogger.PERSISTENCE.warn(LOCALISER.msg("023013",
810: "addAll", fieldName, dse));
811: backingSuccess = false;
812: }
813: }
814: }
815:
816: // Only make it dirty after adding the field to the datastore so we give it time
817: // to be inserted - otherwise jdoPreStore on this object would have been called before completing the addition
818: makeDirty();
819:
820: boolean delegateSuccess = delegate.addAll(elements);
821: return (backingStore != null ? backingSuccess : delegateSuccess);
822: }
823:
824: /**
825: * Method to clear the TreeSet
826: **/
827: public void clear() {
828: makeDirty();
829:
830: if (backingStore != null) {
831: if (queued && !ownerSM.getObjectManager().isFlushing()) {
832: addQueuedOperation(new ClearOperation());
833: } else {
834: backingStore.clear(ownerSM);
835: }
836: }
837: delegate.clear();
838: }
839:
840: /**
841: * Method to remove an element from the TreeSet.
842: * @param element The element
843: * @return Whether it was removed ok.
844: **/
845: public boolean remove(Object element) {
846: return remove(element, true);
847: }
848:
849: /**
850: * Method to remove an element from the collection, and observe the flag for whether to allow cascade delete.
851: * @param element The element
852: * @param allowCascadeDelete Whether to allow cascade delete
853: */
854: public boolean remove(Object element, boolean allowCascadeDelete) {
855: makeDirty();
856:
857: if (useCache) {
858: loadFromStore();
859: }
860:
861: int size = (useCache ? delegate.size() : -1);
862: boolean delegateSuccess = delegate.remove(element);
863:
864: boolean backingSuccess = true;
865: if (backingStore != null) {
866: if (ownerSM.getRelationshipManager() != null) {
867: ownerSM.getRelationshipManager().relationRemove(
868: fieldNumber, element);
869: }
870: if (queued && !ownerSM.getObjectManager().isFlushing()) {
871: backingSuccess = contains(element);
872: if (backingSuccess) {
873: addQueuedOperation(new RemoveOperation(element,
874: allowCascadeDelete));
875: }
876: } else {
877: try {
878: backingSuccess = backingStore.remove(ownerSM,
879: element, size, allowCascadeDelete);
880: } catch (JPOXDataStoreException dse) {
881: JPOXLogger.PERSISTENCE.warn(LOCALISER.msg("023013",
882: "remove", fieldName, dse));
883: backingSuccess = false;
884: }
885: }
886: }
887:
888: return (backingStore != null ? backingSuccess : delegateSuccess);
889: }
890:
891: /**
892: * Method to remove all elements from the collection from the TreeSet.
893: * @param elements The collection of elements to remove
894: * @return Whether it was removed ok.
895: **/
896: public boolean removeAll(java.util.Collection elements) {
897: makeDirty();
898:
899: if (useCache) {
900: loadFromStore();
901: }
902:
903: int size = (useCache ? delegate.size() : -1);
904: boolean delegateSuccess = delegate.removeAll(elements);
905:
906: boolean backingSuccess = true;
907: if (backingStore != null) {
908: if (ownerSM.getRelationshipManager() != null) {
909: // Relationship management
910: Iterator iter = elements.iterator();
911: while (iter.hasNext()) {
912: ownerSM.getRelationshipManager().relationRemove(
913: fieldNumber, iter.next());
914: }
915: }
916: if (queued && !ownerSM.getObjectManager().isFlushing()) {
917: backingSuccess = false;
918: Iterator iter = elements.iterator();
919: while (iter.hasNext()) {
920: Object element = iter.next();
921: boolean contained = contains(element);
922: if (contained) {
923: backingSuccess = true;
924: addQueuedOperation(new RemoveOperation(iter
925: .next()));
926: }
927: }
928: } else {
929: try {
930: backingSuccess = backingStore.removeAll(ownerSM,
931: elements, size);
932: } catch (JPOXDataStoreException dse) {
933: JPOXLogger.PERSISTENCE.warn(LOCALISER.msg("023013",
934: "removeAll", fieldName, dse));
935: backingSuccess = false;
936: }
937: }
938: }
939:
940: return (backingStore != null ? backingSuccess : delegateSuccess);
941: }
942:
943: /**
944: * Method to retain a Collection of elements (and remove all others).
945: * @param c The collection to retain
946: * @return Whether they were retained successfully.
947: **/
948: public synchronized boolean retainAll(java.util.Collection c) {
949: makeDirty();
950:
951: if (useCache) {
952: loadFromStore();
953: }
954:
955: boolean modified = false;
956: Iterator iter = iterator();
957: while (iter.hasNext()) {
958: Object element = iter.next();
959: if (!c.contains(element)) {
960: iter.remove();
961: modified = true;
962: }
963: }
964: return modified;
965: }
966:
967: /**
968: * The writeReplace method is called when ObjectOutputStream is preparing
969: * to write the object to the stream. The ObjectOutputStream checks
970: * whether the class defines the writeReplace method. If the method is
971: * defined, the writeReplace method is called to allow the object to
972: * designate its replacement in the stream. The object returned should be
973: * either of the same type as the object passed in or an object that when
974: * read and resolved will result in an object of a type that is compatible
975: * with all references to the object.
976: *
977: * @return the replaced object
978: * @throws ObjectStreamException
979: */
980: protected Object writeReplace() throws ObjectStreamException {
981: if (useCache) {
982: loadFromStore();
983: return new java.util.TreeSet(delegate);
984: } else {
985: // TODO Cater for non-cached collection, load elements in a DB call.
986: return new java.util.TreeSet(delegate);
987: }
988: }
989: }
|