KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > triactive > jdo > PersistenceManagerImpl


1 /*
2  * Copyright 2004 (C) TJDO.
3  * All rights reserved.
4  *
5  * This software is distributed under the terms of the TJDO License version 1.0.
6  * See the terms of the TJDO License in the documentation provided with this software.
7  *
8  * $Id: PersistenceManagerImpl.java,v 1.14 2004/01/18 05:46:55 jackknifebarber Exp $
9  */

10
11 package com.triactive.jdo;
12
13 import com.triactive.jdo.PersistenceManagerFactoryImpl;
14 import com.triactive.jdo.model.ClassMetaData;
15 import com.triactive.jdo.state.StateManagerImpl;
16 import com.triactive.jdo.store.ClassTable;
17 import com.triactive.jdo.store.OID;
18 import com.triactive.jdo.store.SCOID;
19 import com.triactive.jdo.store.StoreManager;
20 import com.triactive.jdo.store.StoreManagerFactory;
21 import com.triactive.jdo.util.WeakValueMap;
22 import java.io.PrintWriter JavaDoc;
23 import java.security.AccessController JavaDoc;
24 import java.security.PrivilegedAction JavaDoc;
25 import java.sql.Connection JavaDoc;
26 import java.sql.SQLException JavaDoc;
27 import java.util.ArrayList JavaDoc;
28 import java.util.Arrays JavaDoc;
29 import java.util.Collection JavaDoc;
30 import java.util.Collections JavaDoc;
31 import java.util.HashSet JavaDoc;
32 import java.util.Iterator JavaDoc;
33 import java.util.Map JavaDoc;
34 import java.util.Set JavaDoc;
35 import javax.jdo.Extent;
36 import javax.jdo.JDOFatalInternalException;
37 import javax.jdo.JDOFatalUserException;
38 import javax.jdo.JDOUserException;
39 import javax.jdo.JDOUnsupportedOptionException;
40 import javax.jdo.PersistenceManagerFactory;
41 import javax.jdo.Query;
42 import javax.jdo.spi.PersistenceCapable;
43 import org.apache.log4j.Category;
44
45
46 /**
47  * Implements the PersistenceManager interface.
48  *
49  * @author <a HREF="mailto:mmartin5@austin.rr.com">Mike Martin</a>
50  * @version $Revision: 1.14 $
51  */

52
53 public class PersistenceManagerImpl implements PersistenceManager
54 {
55     private static final Category LOG = Category.getInstance(PersistenceManagerImpl.class);
56
57     private final PersistenceManagerFactoryImpl pmf;
58     private final ClassLoader JavaDoc origContextClassLoader;
59
60     private StoreManager srm;
61     private Transaction tx;
62     private boolean ignoreCache;
63     private boolean multithreaded;
64     private int dataStoreModCount = 0;
65     private Object JavaDoc userObject = null;
66     private boolean closed = false;
67
68     private Map weakSMCache = new WeakValueMap();
69     private Set JavaDoc txCache = new HashSet JavaDoc();
70
71     private PersistenceCapable lookingForStateManagerFor = null;
72     private StateManager foundStateManager = null;
73     private StateManager dirtyStateManager = null;
74     private Connection JavaDoc nonTxConnection = null;
75
76     public PersistenceManagerImpl(PersistenceManagerFactoryImpl pmf, String JavaDoc userName, String JavaDoc password)
77     {
78         this.pmf = pmf;
79
80         origContextClassLoader = getContextClassLoaderPrivileged();
81
82         srm = StoreManagerFactory.getStoreManager(pmf, userName, password);
83         tx = new NonmanagedTransaction(this, userName, password);
84
85         setIgnoreCache(pmf.getIgnoreCache());
86         setMultithreaded(pmf.getMultithreaded());
87     }
88
89
90     /**
91      * Calls getContextClassLoader() for the current thread in a doPrivileged
92      * block.
93      *
94      * @return
95      * The context class loader of the current thread.
96      *
97      * @exception SecurityException
98      * If getContextClassLoader() fails.
99      */

100
101     private ClassLoader JavaDoc getContextClassLoaderPrivileged() throws SecurityException JavaDoc
102     {
103         return (ClassLoader JavaDoc)AccessController.doPrivileged(
104             new PrivilegedAction JavaDoc()
105             {
106                 public Object JavaDoc run()
107                 {
108                     return Thread.currentThread().getContextClassLoader();
109                 }
110             }
111         );
112     }
113     
114
115     private Class JavaDoc classForName(String JavaDoc name, Class JavaDoc contextClass) throws ClassNotFoundException JavaDoc
116     {
117         if (contextClass != null)
118         {
119             try
120             {
121                 return Class.forName(name, true, contextClass.getClassLoader());
122             }
123             catch (ClassNotFoundException JavaDoc e) {}
124         }
125
126         try
127         {
128             return Class.forName(name, true, getContextClassLoaderPrivileged());
129         }
130         catch (ClassNotFoundException JavaDoc e)
131         {
132             return Class.forName(name, true, origContextClassLoader);
133         }
134     }
135
136
137     public StoreManager getStoreManager()
138     {
139         return srm;
140     }
141
142     public synchronized void dataStoreModified()
143     {
144         ++dataStoreModCount;
145     }
146
147     public int dataStoreModifyCount()
148     {
149         return dataStoreModCount;
150     }
151
152     public Connection JavaDoc getConnection(boolean forWriting) throws SQLException JavaDoc
153     {
154         return tx.getConnection(forWriting);
155     }
156
157     public synchronized void releaseConnection(Connection JavaDoc conn) throws SQLException JavaDoc
158     {
159         tx.releaseConnection(conn);
160     }
161
162     public synchronized void enlistInTransaction(StateManager sm)
163     {
164         if (!tx.isActive())
165             throw new TransactionNotActiveException();
166
167         if (LOG.isDebugEnabled())
168             LOG.debug("Enlisting in transactional cache:" + sm);
169
170         if (!txCache.add(sm))
171             LOG.debug("Already enlisted:" + sm);
172     }
173
174     public synchronized void evictFromTransaction(StateManager sm)
175     {
176         if (LOG.isDebugEnabled())
177             LOG.debug("Evicting from transactional cache:" + sm);
178
179         if (!txCache.remove(sm))
180             throw new JDOFatalInternalException("Not enlisted in transaction: " + sm);
181     }
182
183     public synchronized void removeStateManager(StateManager sm)
184     {
185         txCache.remove(sm);
186
187         Object JavaDoc id = sm.getObjectId();
188
189         if (id != null)
190             weakSMCache.remove(id);
191     }
192
193     private void assertIsOpen()
194     {
195         if (closed)
196             throw new JDOFatalUserException("Persistence manager has been closed");
197     }
198
199     private static boolean isPersistenceCapableClass(Class JavaDoc cls)
200     {
201         return ClassMetaData.forClass(cls) != null;
202     }
203
204     public boolean isClosed()
205     {
206         return closed;
207     }
208
209     private synchronized void closeInternal()
210     {
211         srm = null;
212         tx = null;
213         userObject = null;
214         closed = true;
215     }
216
217     /** Called by the PMF to forcibly close this PM. */
218     void forceClose()
219     {
220         try
221         {
222             if (tx.isActive())
223                 tx.rollback();
224         }
225         catch (Exception JavaDoc e)
226         {
227             LOG.warn("Failed forcing closure of " + this, e);
228         }
229         finally
230         {
231             closeInternal();
232         }
233     }
234
235     public synchronized void close()
236     {
237         if (tx.isActive())
238             throw new TransactionActiveException();
239
240         closeInternal();
241         pmf.pmClosed(this);
242     }
243
244     public javax.jdo.Transaction currentTransaction()
245     {
246         assertIsOpen();
247
248         return tx;
249     }
250
251     private void internalEvict(Object JavaDoc obj)
252     {
253         StateManager sm = findStateManager(obj);
254
255         if (sm != null)
256             sm.evict();
257     }
258
259     public synchronized void evict(Object JavaDoc pc)
260     {
261         assertIsOpen();
262
263         internalEvict(pc);
264     }
265
266     public synchronized void evictAll(Object JavaDoc[] pcs)
267     {
268         evictAll(Arrays.asList(pcs));
269     }
270
271     public synchronized void evictAll(Collection JavaDoc pcs)
272     {
273         assertIsOpen();
274
275         ArrayList JavaDoc failures = new ArrayList JavaDoc();
276
277         Iterator JavaDoc i = pcs.iterator();
278
279         while (i.hasNext())
280         {
281             try
282             {
283                 internalEvict(i.next());
284             }
285             catch (RuntimeException JavaDoc e)
286             {
287                 failures.add(e);
288             }
289         }
290
291         if (!failures.isEmpty())
292             throw new JDOUserException("One or more instances could not be evicted", (Exception JavaDoc[])failures.toArray(new Exception JavaDoc[failures.size()]));
293     }
294
295     public synchronized void evictAll()
296     {
297         assertIsOpen();
298
299         /*
300          * Evict all PClean instances. This is done by calling evict() on all
301          * transactional instances, which is a no-op for all transactional
302          * states except PClean.
303          */

304         ArrayList JavaDoc failures = new ArrayList JavaDoc();
305         Iterator JavaDoc i = txCache.iterator();
306
307         while (i.hasNext())
308         {
309             try
310             {
311                 ((StateManager)i.next()).evict();
312             }
313             catch (RuntimeException JavaDoc e)
314             {
315                 failures.add(e);
316             }
317         }
318
319         if (!failures.isEmpty())
320             throw new JDOUserException("One or more instances could not be evicted", (Exception JavaDoc[])failures.toArray(new Exception JavaDoc[failures.size()]));
321     }
322
323     private void internalRefresh(Object JavaDoc obj)
324     {
325         StateManager sm = findStateManager(obj);
326
327         if (sm != null)
328             sm.refresh();
329     }
330
331     public synchronized void refresh(Object JavaDoc pc)
332     {
333         assertIsOpen();
334
335         internalRefresh(pc);
336     }
337
338     public synchronized void refreshAll(Object JavaDoc[] pcs)
339     {
340         refreshAll(Arrays.asList(pcs));
341     }
342
343     public synchronized void refreshAll(Collection JavaDoc pcs)
344     {
345         assertIsOpen();
346
347         ArrayList JavaDoc failures = new ArrayList JavaDoc();
348
349         Iterator JavaDoc i = pcs.iterator();
350
351         while (i.hasNext())
352         {
353             try
354             {
355                 internalRefresh(i.next());
356             }
357             catch (RuntimeException JavaDoc e)
358             {
359                 failures.add(e);
360             }
361         }
362
363         if (!failures.isEmpty())
364             throw new JDOUserException("One or more instances could not be refreshed", (Exception JavaDoc[])failures.toArray(new Exception JavaDoc[failures.size()]));
365     }
366
367     public synchronized void refreshAll()
368     {
369         assertIsOpen();
370
371         ArrayList JavaDoc failures = new ArrayList JavaDoc();
372
373         Iterator JavaDoc i = tx.isActive() ? txCache.iterator() : new ArrayList JavaDoc(weakSMCache.values()).iterator();
374
375         while (i.hasNext())
376         {
377             try
378             {
379                 ((StateManager)i.next()).refresh();
380             }
381             catch (RuntimeException JavaDoc e)
382             {
383                 failures.add(e);
384             }
385         }
386
387         if (!failures.isEmpty())
388             throw new JDOUserException("One or more instances could not be refreshed", (Exception JavaDoc[])failures.toArray(new Exception JavaDoc[failures.size()]));
389     }
390
391     private void internalRetrieve(Object JavaDoc obj, boolean DFGOnly)
392     {
393         StateManager sm = findStateManager(obj);
394
395         if (sm != null)
396             sm.retrieve(DFGOnly);
397     }
398
399     public synchronized void retrieve(Object JavaDoc pc)
400     {
401         assertIsOpen();
402
403         internalRetrieve(pc, false);
404     }
405
406     public synchronized void retrieveAll(Object JavaDoc[] pcs)
407     {
408         retrieveAll(pcs, false);
409     }
410
411     public synchronized void retrieveAll(Object JavaDoc[] pcs, boolean DFGOnly)
412     {
413         retrieveAll(Arrays.asList(pcs), DFGOnly);
414     }
415
416     public synchronized void retrieveAll(Collection JavaDoc pcs)
417     {
418         retrieveAll(pcs, false);
419     }
420
421     public synchronized void retrieveAll(Collection JavaDoc pcs, boolean DFGOnly)
422     {
423         assertIsOpen();
424
425         ArrayList JavaDoc failures = new ArrayList JavaDoc();
426
427         Iterator JavaDoc i = pcs.iterator();
428
429         while (i.hasNext())
430         {
431             try
432             {
433                 internalRetrieve(i.next(), DFGOnly);
434             }
435             catch (RuntimeException JavaDoc e)
436             {
437                 failures.add(e);
438             }
439         }
440
441         if (!failures.isEmpty())
442             throw new JDOUserException("One or more instances could not be retrieved", (Exception JavaDoc[])failures.toArray(new Exception JavaDoc[failures.size()]));
443     }
444
445     private void internalMakePersistent(Object JavaDoc obj)
446     {
447         if (obj == null)
448             return;
449
450         PersistenceCapable pc = asPC(obj);
451         StateManager sm = findStateManager(pc);
452         boolean wasUnmanaged = false;
453
454         /*
455          * If the object is currently unmanaged (Transient) it first has to
456          * transition thru a TransientClean state in order to get to
457          * PersistentNew. If the makePersistent() subsequently fails we'll
458          * rollback its state to unmanaged Transient.
459          */

460         if (sm == null)
461         {
462             wasUnmanaged = true;
463             sm = new StateManagerImpl(this, pc); // makeTransactional
464
}
465
466         try
467         {
468             if (sm.makePersistent())
469                 weakSMCache.put(sm.getObjectId(), sm);
470         }
471         finally
472         {
473             if (wasUnmanaged && !sm.isPersistent(pc))
474                 sm.makeNontransactional();
475         }
476     }
477
478     public synchronized void makePersistent(Object JavaDoc obj)
479     {
480         assertIsOpen();
481
482         internalMakePersistent(obj);
483     }
484
485     public synchronized void makePersistentAll(Object JavaDoc[] pcs)
486     {
487         makePersistentAll(Arrays.asList(pcs));
488     }
489
490     public synchronized void makePersistentAll(Collection JavaDoc pcs)
491     {
492         assertIsOpen();
493
494         ArrayList JavaDoc failures = new ArrayList JavaDoc();
495
496         Iterator JavaDoc i = pcs.iterator();
497
498         while (i.hasNext())
499         {
500             try
501             {
502                 internalMakePersistent(i.next());
503             }
504             catch (RuntimeException JavaDoc e)
505             {
506                 failures.add(e);
507             }
508         }
509
510         if (!failures.isEmpty())
511             throw new JDOUserException("One or more instances could not be made persistent", (Exception JavaDoc[])failures.toArray(new Exception JavaDoc[failures.size()]));
512     }
513
514     private void internalDeletePersistent(Object JavaDoc obj)
515     {
516         if (obj != null)
517             getStateManager(obj).deletePersistent();
518     }
519
520     public synchronized void deletePersistent(Object JavaDoc obj)
521     {
522         assertIsOpen();
523
524         internalDeletePersistent(obj);
525     }
526
527     public synchronized void deletePersistentAll(Object JavaDoc[] pcs)
528     {
529         deletePersistentAll(Arrays.asList(pcs));
530     }
531
532     public synchronized void deletePersistentAll(Collection JavaDoc pcs)
533     {
534         assertIsOpen();
535
536         ArrayList JavaDoc failures = new ArrayList JavaDoc();
537
538         Iterator JavaDoc i = pcs.iterator();
539
540         while (i.hasNext())
541         {
542             try
543             {
544                 internalDeletePersistent(i.next());
545             }
546             catch (RuntimeException JavaDoc e)
547             {
548                 failures.add(e);
549             }
550         }
551
552         if (!failures.isEmpty())
553             throw new JDOUserException("One or more instances could not be deleted", (Exception JavaDoc[])failures.toArray(new Exception JavaDoc[failures.size()]));
554     }
555
556     private void internalMakeTransient(Object JavaDoc obj)
557     {
558         StateManager sm = findStateManager(obj);
559
560         if (sm != null)
561             sm.makeTransient();
562     }
563
564     public synchronized void makeTransient(Object JavaDoc pc)
565     {
566         assertIsOpen();
567
568         internalMakeTransient(pc);
569     }
570
571     public synchronized void makeTransientAll(Object JavaDoc[] pcs)
572     {
573         makeTransientAll(Arrays.asList(pcs));
574     }
575
576     public synchronized void makeTransientAll(Collection JavaDoc pcs)
577     {
578         assertIsOpen();
579
580         ArrayList JavaDoc failures = new ArrayList JavaDoc();
581
582         Iterator JavaDoc i = pcs.iterator();
583
584         while (i.hasNext())
585         {
586             try
587             {
588                 internalMakeTransient(i.next());
589             }
590             catch (RuntimeException JavaDoc e)
591             {
592                 failures.add(e);
593             }
594         }
595
596         if (!failures.isEmpty())
597             throw new JDOUserException("One or more instances could not be made transient", (Exception JavaDoc[])failures.toArray(new Exception JavaDoc[failures.size()]));
598     }
599
600     private void internalMakeTransactional(Object JavaDoc obj)
601     {
602         if (obj == null)
603             return;
604
605         PersistenceCapable pc = asPC(obj);
606         StateManager sm = findStateManager(pc);
607
608         if (sm == null)
609             sm = new StateManagerImpl(this, pc);
610         else
611             sm.makeTransactional();
612     }
613
614     public synchronized void makeTransactional(Object JavaDoc pc)
615     {
616         assertIsOpen();
617
618         internalMakeTransactional(pc);
619     }
620
621     public synchronized void makeTransactionalAll(Object JavaDoc[] pcs)
622     {
623         makeTransactionalAll(Arrays.asList(pcs));
624     }
625
626     public synchronized void makeTransactionalAll(Collection JavaDoc pcs)
627     {
628         assertIsOpen();
629
630         ArrayList JavaDoc failures = new ArrayList JavaDoc();
631
632         Iterator JavaDoc i = pcs.iterator();
633
634         while (i.hasNext())
635         {
636             try
637             {
638                 internalMakeTransactional(i.next());
639             }
640             catch (RuntimeException JavaDoc e)
641             {
642                 failures.add(e);
643             }
644         }
645
646         if (!failures.isEmpty())
647             throw new JDOUserException("One or more instances could not be made transactional", (Exception JavaDoc[])failures.toArray(new Exception JavaDoc[failures.size()]));
648     }
649
650     private void internalMakeNontransactional(Object JavaDoc obj)
651     {
652         if (obj != null)
653             getStateManager(obj).makeNontransactional();
654     }
655
656     public synchronized void makeNontransactional(Object JavaDoc pc)
657     {
658         assertIsOpen();
659
660         internalMakeNontransactional(pc);
661     }
662
663     public synchronized void makeNontransactionalAll(Object JavaDoc[] pcs)
664     {
665         makeNontransactionalAll(Arrays.asList(pcs));
666     }
667
668     public synchronized void makeNontransactionalAll(Collection JavaDoc pcs)
669     {
670         assertIsOpen();
671
672         ArrayList JavaDoc failures = new ArrayList JavaDoc();
673
674         Iterator JavaDoc i = pcs.iterator();
675
676         while (i.hasNext())
677         {
678             try
679             {
680                 internalMakeNontransactional(i.next());
681             }
682             catch (RuntimeException JavaDoc e)
683             {
684                 failures.add(e);
685             }
686         }
687
688         if (!failures.isEmpty())
689             throw new JDOUserException("One or more instances could not be made non-transactional", (Exception JavaDoc[])failures.toArray(new Exception JavaDoc[failures.size()]));
690     }
691
692     public Object JavaDoc newObjectIdInstance(Class JavaDoc clazz, String JavaDoc str)
693     {
694         return new OID(str);
695     }
696
697     public synchronized Query newQuery()
698     {
699         assertIsOpen();
700
701         return srm.getQuery(this, null);
702     }
703
704     public synchronized Query newQuery(Object JavaDoc obj)
705     {
706         assertIsOpen();
707
708         return srm.getQuery(this, obj);
709     }
710
711     public synchronized Query newQuery(String JavaDoc language, Object JavaDoc query)
712     {
713         assertIsOpen();
714
715         return srm.getQuery(language, this, query);
716     }
717
718     public synchronized Query newQuery(Class JavaDoc cls)
719     {
720         assertIsOpen();
721
722         Query query = newQuery();
723         query.setClass(cls);
724
725         return query;
726     }
727
728     public synchronized Query newQuery(Extent cln)
729     {
730         assertIsOpen();
731
732         Query query = newQuery();
733         query.setCandidates(cln);
734
735         return query;
736     }
737
738     public synchronized Query newQuery(Class JavaDoc cls, Collection JavaDoc cln)
739     {
740         assertIsOpen();
741
742         Query query = newQuery();
743         query.setClass(cls);
744         query.setCandidates(cln);
745
746         return query;
747     }
748
749     public synchronized Query newQuery(Class JavaDoc cls, String JavaDoc filter)
750     {
751         assertIsOpen();
752
753         Query query = newQuery();
754         query.setClass(cls);
755         query.setFilter(filter);
756
757         return query;
758     }
759
760     public synchronized Query newQuery(Class JavaDoc cls, Collection JavaDoc cln, String JavaDoc filter)
761     {
762         assertIsOpen();
763
764         Query query = newQuery();
765         query.setClass(cls);
766         query.setCandidates(cln);
767         query.setFilter(filter);
768
769         return query;
770     }
771
772     public synchronized Query newQuery(Extent cln, String JavaDoc filter)
773     {
774         assertIsOpen();
775
776         Query query = newQuery();
777         query.setCandidates(cln);
778         query.setFilter(filter);
779
780         return query;
781     }
782
783     public synchronized Extent getExtent(Class JavaDoc cls, boolean flag)
784     {
785         assertIsOpen();
786
787         return srm.getExtent(this, cls, flag);
788     }
789
790
791     private synchronized StateManager getStateManagerById(Object JavaDoc id, final Class JavaDoc contextClass)
792     {
793         StateManager sm = (StateManager)weakSMCache.get(id);
794
795         if (sm == null)
796         {
797             sm = new StateManagerImpl(this, getClassForObjectID(id, contextClass), id);
798
799             weakSMCache.put(id, sm);
800         }
801
802         return sm;
803     }
804
805
806     public Object JavaDoc getObjectById(Object JavaDoc id, boolean validate)
807     {
808         return getObjectById(id, null, validate);
809     }
810
811
812     public Object JavaDoc getObjectById(Object JavaDoc id, Class JavaDoc contextClass, boolean validate)
813     {
814         assertIsOpen();
815
816         if (id == null)
817             return null;
818
819         StateManager sm = getStateManagerById(id, contextClass);
820
821         if (validate)
822             sm.validate();
823
824         return sm.getObject();
825     }
826
827
828     public Object JavaDoc getObjectById(Object JavaDoc id, Class JavaDoc contextClass, int[] fieldNumbers, FieldManager fm)
829     {
830         assertIsOpen();
831
832         if (id == null)
833             return null;
834
835         StateManager sm = getStateManagerById(id, contextClass);
836
837         sm.offerPrefetchedFields(fieldNumbers, fm);
838
839         return sm.getObject();
840     }
841
842
843     public Object JavaDoc getObjectId(Object JavaDoc pc)
844     {
845         assertIsOpen();
846
847         if (pc == null || !(pc instanceof PersistenceCapable))
848             return null;
849         else
850             return ((PersistenceCapable)pc).jdoGetObjectId();
851     }
852
853     public Object JavaDoc getTransactionalObjectId(Object JavaDoc pc)
854     {
855         assertIsOpen();
856
857         if (pc == null || !(pc instanceof PersistenceCapable))
858             return null;
859         else
860             return ((PersistenceCapable)pc).jdoGetTransactionalObjectId();
861     }
862
863     public synchronized void setUserObject(Object JavaDoc userObject)
864     {
865         assertIsOpen();
866
867         this.userObject = userObject;
868     }
869
870     public synchronized Object JavaDoc getUserObject()
871     {
872         assertIsOpen();
873
874         return userObject;
875     }
876
877     public PersistenceManagerFactory getPersistenceManagerFactory()
878     {
879         return pmf;
880     }
881
882     /**
883      * Returns the class of the object having the given object ID.
884      *
885      * @param id
886      * The JDO identity of some object.
887      * @param contextClass
888      * A class used to establish the class loader context in case the
889      * object's class needs to be loaded.
890      *
891      * @return The class of the corresponding object.
892      *
893      * @exception JDOUserException
894      * If the type of ID is not recognized ({@link OID} or {@link SCOID})
895      * or, for OIDs, the type referred to in the OID is not recognized.
896      */

897
898     private Class JavaDoc getClassForObjectID(Object JavaDoc id, Class JavaDoc contextClass)
899     {
900         if (id instanceof OID)
901         {
902             int classID = ((OID)id).getClassID();
903             ClassTable ct = null;
904
905             try
906             {
907                 ct = (ClassTable)srm.getTable(classID);
908             }
909             catch (ClassCastException JavaDoc e)
910             {
911                 throw new JDOUserException("Not a class table, ID = " + classID, e);
912             }
913
914             if (ct == null)
915             {
916                 /*
917                  * The ClassTable for this class ID has not yet been initialized.
918                  * Ask the store manager which class name it corresponds to.
919                  */

920                 Class JavaDoc c;
921
922                 try
923                 {
924                     c = classForName(srm.getJavaName(classID), contextClass);
925                 }
926                 catch (ClassNotFoundException JavaDoc e)
927                 {
928                     throw new JDOUserException("Class not found, ID = " + classID, e);
929                 }
930
931                 /*
932                  * We know the answer here, but make sure its ClassTable gets
933                  * initialized as a side effect.
934                  */

935                 ct = srm.getTable(c);
936             }
937
938             return ct.getType();
939         }
940         else if (id instanceof SCOID)
941             return ((SCOID)id).getSCOClass();
942         else
943             throw new JDOUserException("Unrecognized object ID class: " + id.getClass().getName());
944     }
945
946     public Class JavaDoc getObjectIdClass(Class JavaDoc cls)
947     {
948         assertIsOpen();
949
950         if (cls == null || !isPersistenceCapableClass(cls))
951             return null;
952         else if (ClassMetaData.forClass(cls).requiresExtent())
953             return OID.class;
954         else
955             return SCOID.class;
956     }
957
958     public void setMultithreaded(boolean flag)
959     {
960         assertIsOpen();
961
962         multithreaded = flag;
963     }
964
965     public boolean getMultithreaded()
966     {
967         assertIsOpen();
968
969         return multithreaded;
970     }
971
972     public void setIgnoreCache(boolean flag)
973     {
974         assertIsOpen();
975
976         ignoreCache = flag;
977     }
978
979     public boolean getIgnoreCache()
980     {
981         assertIsOpen();
982
983         return ignoreCache;
984     }
985
986     private PersistenceCapable asPC(Object JavaDoc obj)
987     {
988         try
989         {
990             return (PersistenceCapable)obj;
991         }
992         catch (ClassCastException JavaDoc e)
993         {
994             throw new ClassNotPersistenceCapableException(obj.getClass());
995         }
996     }
997
998
999     /**
1000     * Returns the StateManager for a given object.
1001     *
1002     * @return
1003     * Always returns a valid non-null StateManager or an exception is
1004     * thrown.
1005     *
1006     * @exception JDOUserException
1007     * If <var>obj</var> is null, not PersistenceCapable, has no state
1008     * manager, or is managed by a different PersistenceManager.
1009     */

1010
1011    private StateManager getStateManager(Object JavaDoc obj)
1012    {
1013        StateManager sm = findStateManager(obj);
1014
1015        if (sm == null)
1016            throw new JDOUserException("Object is not managed", obj);
1017
1018        return sm;
1019    }
1020
1021
1022    /**
1023     * Returns the StateManager for a given object.
1024     *
1025     * @return
1026     * The object's state manager, or <code>null</code> if obj is null or
1027     * has no state manager.
1028     *
1029     * @exception JDOUserException
1030     * If <var>obj</var> is not PersistenceCapable or is managed by a
1031     * different PersistenceManager.
1032     */

1033
1034    public StateManager findStateManager(Object JavaDoc obj)
1035    {
1036        return obj == null ? null : findStateManager(asPC(obj));
1037    }
1038
1039
1040    /**
1041     * Returns an object's StateManager, or null if it has none.
1042     * pc must be non-null.
1043     */

1044
1045    private synchronized StateManager findStateManager(PersistenceCapable pc)
1046    {
1047        StateManager sm = null;
1048
1049        PersistenceCapable previousLookingFor = lookingForStateManagerFor;
1050        StateManager previousFound = foundStateManager;
1051
1052        try
1053        {
1054            lookingForStateManagerFor = pc;
1055            foundStateManager = null;
1056
1057            if (pc.jdoGetPersistenceManager() != null)
1058            {
1059                if (foundStateManager == null)
1060                    throw new JDOUserException("Object managed by a different PersistenceManager", pc);
1061            }
1062
1063            sm = foundStateManager;
1064        }
1065        finally
1066        {
1067            lookingForStateManagerFor = previousLookingFor;
1068            foundStateManager = previousFound;
1069        }
1070
1071        return sm;
1072    }
1073
1074    public synchronized void hereIsStateManager(StateManager sm, Object JavaDoc pc)
1075    {
1076        if (lookingForStateManagerFor == pc)
1077            foundStateManager = sm;
1078    }
1079
1080    public synchronized void markDirty(StateManager sm)
1081    {
1082        if (sm != dirtyStateManager)
1083            flushDirty();
1084
1085        dirtyStateManager = sm;
1086    }
1087
1088    public synchronized void flushDirty()
1089    {
1090        if (dirtyStateManager != null)
1091        {
1092            StateManager sm = dirtyStateManager;
1093            dirtyStateManager = null;
1094            sm.flush();
1095        }
1096    }
1097
1098    /**
1099     * Commit any changes made to objects managed by the persistence manager
1100     * to the database.
1101     */

1102    synchronized void postCommit()
1103    {
1104        ArrayList JavaDoc failures = new ArrayList JavaDoc();
1105
1106        try
1107        {
1108            StateManager[] sms = (StateManager[])txCache.toArray(new StateManager[txCache.size()]);
1109
1110            for (int i = 0; i < sms.length; ++i)
1111            {
1112                try
1113                {
1114                    sms[i].postCommit();
1115                }
1116                catch (RuntimeException JavaDoc e)
1117                {
1118                    failures.add(e);
1119                }
1120            }
1121        }
1122        finally
1123        {
1124            txCache.clear();
1125        }
1126
1127        if (!failures.isEmpty())
1128            throw new CommitStateTransitionException((Exception JavaDoc[])failures.toArray(new Exception JavaDoc[failures.size()]));
1129    }
1130
1131
1132    /**
1133     * Rollback any changes made to objects managed by the persistence manager
1134     * to the database.
1135     */

1136    synchronized void preRollback()
1137    {
1138        ArrayList JavaDoc failures = new ArrayList JavaDoc();
1139
1140        try
1141        {
1142            dirtyStateManager = null;
1143
1144            StateManager[] sms = (StateManager[])txCache.toArray(new StateManager[txCache.size()]);
1145
1146            for (int i = 0; i < sms.length; ++i)
1147            {
1148                try
1149                {
1150                    sms[i].preRollback();
1151                }
1152                catch (RuntimeException JavaDoc e)
1153                {
1154                    failures.add(e);
1155                }
1156            }
1157        }
1158        finally
1159        {
1160            txCache.clear();
1161        }
1162
1163        if (!failures.isEmpty())
1164            throw new RollbackStateTransitionException((Exception JavaDoc[])failures.toArray(new Exception JavaDoc[failures.size()]));
1165    }
1166
1167    public void dump(Object JavaDoc obj, PrintWriter JavaDoc out)
1168    {
1169        getStateManager(obj).dump(out);
1170    }
1171}
1172
Popular Tags