KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > versant > core > jdo > PersistenceManagerFactoryBase


1
2 /*
3  * Copyright (c) 1998 - 2005 Versant Corporation
4  * All rights reserved. This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License v1.0
6  * which accompanies this distribution, and is available at
7  * http://www.eclipse.org/legal/epl-v10.html
8  *
9  * Contributors:
10  * Versant Corporation - initial API and implementation
11  */

12 package com.versant.core.jdo;
13
14 import com.versant.core.common.BindingSupportImpl;
15 import com.versant.core.common.Debug;
16 import com.versant.core.common.OID;
17 import com.versant.core.metadata.ModelMetaData;
18 import com.versant.core.metadata.MDStatics;
19 import com.versant.core.metadata.ClassMetaData;
20 import com.versant.core.util.BeanUtils;
21 import com.versant.core.util.WeakBag;
22 import com.versant.core.common.config.ConfigParser;
23 import com.versant.core.common.config.ConfigInfo;
24 import com.versant.core.logging.LogEvent;
25 import com.versant.core.logging.LogEventStore;
26 import com.versant.core.metric.Metric;
27 import com.versant.core.metric.MetricSnapshotPacket;
28 import com.versant.core.server.DataStoreInfo;
29 import com.versant.core.jdo.query.mem.MemQueryCompiler;
30 import com.versant.core.storagemanager.*;
31
32 import javax.jdo.PersistenceManager;
33 import javax.jdo.PersistenceManagerFactory;
34 import java.util.*;
35 import java.sql.Connection JavaDoc;
36 import java.sql.SQLException JavaDoc;
37 import java.lang.reflect.Method JavaDoc;
38 import java.lang.reflect.Field JavaDoc;
39 import java.lang.reflect.InvocationTargetException JavaDoc;
40 import java.lang.reflect.Constructor JavaDoc;
41
42 /**
43  * Base class for our PMF implementations.
44  */

45 public abstract class PersistenceManagerFactoryBase
46         implements VersantPMFInternal {
47
48     protected Properties props;
49     protected LogEventStore pes;
50     protected ClassLoader JavaDoc loader;
51     protected StorageCache cache;
52     protected StorageManagerFactory smf;
53     protected StorageManagerFactory innermostSmf;
54     protected boolean jdbc;
55     protected ModelMetaData jmd;
56     protected MemQueryCompiler memQueryCompiler;
57     protected PMPool pmPool;
58     protected WeakBag activePMs = new WeakBag();
59     protected Object JavaDoc userObject;
60     protected ConfigInfo config;
61
62     // the fields in the block below are used to configure PMs
63
protected boolean retainValues;
64     protected boolean restoreValues;
65     protected boolean optimistic;
66     protected boolean nontransactionalRead;
67     protected boolean nontransactionalWrite;
68     protected boolean ignoreCache;
69     protected boolean multithreaded;
70     protected boolean allowPmCloseWithOpenTx;
71     protected boolean interceptDfgFieldAccess;
72     protected boolean checkModelConsistencyOnCommit;
73     protected int pmCacheRefType;
74     protected int datastoreTxLocking;
75     protected int retainConnectionInOptTx;
76     protected LifecycleListenerManager listeners;
77
78     protected int pmCreatedCount;
79     protected int pmClosedCount;
80     protected int pmClosedAutoCount;
81     protected int pmClosedAutoTxCount;
82
83     private Field JavaDoc jdbcClassIdField;
84     private Method JavaDoc jdbcFindClassMethod;
85
86     private Object JavaDoc entityManagerFactory;
87
88     public PersistenceManagerFactoryBase(Properties props,
89             ClassLoader JavaDoc loader) {
90         boolean ok = false;
91         try {
92             this.props = props = (Properties)props.clone();
93
94             config = new ConfigParser().parse(props);
95
96             if (config.hyperdrive) {
97
98                 this.loader = new HyperdriveLoader(loader);
99
100             } else {
101                 this.loader = loader;
102             }
103
104
105
106             pes = createLogEventStore();
107             cache = createStorageCache();
108             smf = createStorageManagerFactory();
109
110             for (innermostSmf = smf; ; ) {
111                 StorageManagerFactory next =
112                         innermostSmf.getInnerStorageManagerFactory();
113                 if (next == null) break;
114                 innermostSmf = next;
115             }
116             jdbc = innermostSmf.getClass().getName().indexOf(
117                     "JdbcStorageManagerFactory") >= 0;
118
119             jmd = smf.getModelMetaData();
120             jmd.checkForNonPCClasses();
121             jmd.forceClassRegistration();
122
123             memQueryCompiler = new MemQueryCompiler(jmd, this.loader);
124
125             retainValues = config.retainValues;
126             restoreValues = config.restoreValues;
127             optimistic = config.optimistic;
128             nontransactionalRead = config.nontransactionalRead;
129             nontransactionalWrite = config.nontransactionalWrite;
130             ignoreCache = config.ignoreCache;
131             multithreaded = config.multithreaded;
132             allowPmCloseWithOpenTx = config.allowPmCloseWithOpenTx;
133             interceptDfgFieldAccess = config.interceptDfgFieldAccess;
134             checkModelConsistencyOnCommit = config.checkModelConsistencyOnCommit;
135             pmCacheRefType = config.pmCacheRefType;
136             datastoreTxLocking = config.datastoreTxLocking;
137             retainConnectionInOptTx = config.retainConnectionInOptTx;
138
139             if (config.pmpoolEnabled) {
140                 pmPool = new PMPool(this, config.pmpoolMaxIdle, pes);
141             } else {
142                 pmPool = null;
143             }
144             ok = true;
145         } finally {
146             if (!ok) {
147                 try {
148                     close();
149                 } catch (Throwable JavaDoc e) {
150                     // ignore - already busy with an exception
151
}
152             }
153         }
154     }
155
156     /**
157      * Create our StorageManagerFactory.
158      */

159     protected abstract StorageManagerFactory createStorageManagerFactory();
160
161     /**
162      * Create and configure our LogEventStore.
163      */

164     protected LogEventStore createLogEventStore() {
165         LogEventStore pes = new LogEventStore();
166         BeanUtils.setProperties(pes, config.perfProps);
167         return pes;
168     }
169
170     /**
171      * Create our StorageCache implementation.
172      */

173     protected StorageCache createStorageCache() {
174         if (config.useCache) {
175             LRUStorageCache lruCache = new LRUStorageCache();
176             lruCache.setQueryCacheEnabled(config.queryCacheEnabled);
177             lruCache.setMaxQueries(config.maxQueriesToCache);
178             lruCache.setMaxObjects(config.cacheMaxObjects);
179             return lruCache;
180         } else {
181             return new NOPStorageCache();
182         }
183     }
184
185     /**
186      * Get the properties that we were created from.
187      */

188     public Properties getInitProperties() {
189         return props;
190     }
191
192     public synchronized void close() {
193         List list = getPersistenceManagers();
194         for (Iterator i = list.iterator(); i.hasNext(); ) {
195             PersistenceManager pm = (PersistenceManager)i.next();
196             if (!pm.isClosed()) {
197                 try {
198                     if (pm.currentTransaction().isActive()) {
199                         pm.currentTransaction().rollback();
200                     }
201                 } catch (Exception JavaDoc e) {
202                     // ignore
203
}
204                 try {
205                     pm.close();
206                 } catch (Exception JavaDoc e) {
207                     // ignore
208
}
209             }
210         }
211         if (cache != null) {
212             Object JavaDoc ctx = cache.beginTx();
213             cache.evictAll(ctx);
214             cache.endTx(ctx);
215             cache = null;
216         }
217         if (smf != null) {
218             smf.destroy();
219             smf = null;
220         }
221         jmd = null;
222         pmPool = null;
223     }
224
225     public PersistenceManager getPersistenceManager() {
226         VersantPersistenceManagerImp pm;
227         if (pmPool != null) {
228             pm = pmPool.getPM();
229         } else {
230             pm = createVersantPersistenceManagerImp();
231         }
232         configurePM(pm);
233         synchronized (activePMs) {
234             activePMs.clean();
235             pm.setActiveReference(activePMs.add(pm));
236         }
237         return pm.getProxy();
238     }
239
240     /**
241      * Restore a PM to default settings.
242      */

243     protected void configurePM(VersantPersistenceManagerImp pm) {
244         pm.setRetainValues(retainValues);
245         pm.setRestoreValues(restoreValues);
246         pm.setOptimistic(optimistic);
247         pm.setNontransactionalRead(nontransactionalRead);
248         pm.setNontransactionalWrite(nontransactionalWrite);
249         pm.setIgnoreCache(ignoreCache);
250         pm.setMultithreadedImp(multithreaded);
251         pm.setInterceptDfgFieldAccess(interceptDfgFieldAccess || !optimistic);
252         pm.setCheckModelConsistencyOnCommit(checkModelConsistencyOnCommit);
253         pm.getCache().setCurrentRefType(pmCacheRefType);
254         pm.setDatastoreTxLocking(datastoreTxLocking);
255         switch (retainConnectionInOptTx) {
256             case MDStatics.TRUE:
257                 pm.setRetainConnectionInOptTx(true);
258                 break;
259             case MDStatics.FALSE:
260                 pm.setRetainConnectionInOptTx(false);
261                 break;
262         }
263         pm.setListeners(listeners);
264     }
265
266     /**
267      * Create a new, unconfigured, PM.
268      *
269      * @see #configurePM(VersantPersistenceManagerImp)
270      */

271     public synchronized VersantPersistenceManagerImp createVersantPersistenceManagerImp() {
272         VersantPersistenceManagerImp pm = null;
273         try {
274             pm = newVersantPersistenceManagerImp(smf.getStorageManager());
275             if (pes.isFiner()) {
276                 ServerLogEvent ev = new ServerLogEvent(
277                         ServerLogEvent.PM_CREATED, null);
278                 ev.zeroTotalMs();
279                 pes.log(ev);
280             }
281             pmCreatedCount++;
282             return pm;
283         } catch (Exception JavaDoc e) {
284             throw handleException(e);
285         }
286     }
287
288     protected VersantPersistenceManagerImp newVersantPersistenceManagerImp(
289             StorageManager sm) {
290         return new VersantPersistenceManagerImp(this, jmd,
291                 sm, new LocalPMCache(101), memQueryCompiler);
292     }
293
294     public void pmClosedNotification(VersantPersistenceManagerImp pm,
295             boolean fromFinalizer, boolean txWasActive) {
296         activePMs.remove(pm.getActiveReference());
297         pm.setActiveReference(null);
298         if (fromFinalizer) {
299             try {
300                 pm.destroy();
301             } catch (Exception JavaDoc e) {
302                 // ignore
303
}
304             if (txWasActive && pes.isWarning() || pes.isFine()) {
305                 ServerLogEvent ev = new ServerLogEvent(
306                         txWasActive
307                             ? ServerLogEvent.PM_CLOSED_AUTO_TX
308                             : ServerLogEvent.PM_CLOSED_AUTO,
309                         null);
310                 ev.zeroTotalMs();
311                 pes.log(ev);
312             }
313         } else if (pmPool == null || pm.isMustNotPool()) {
314             pm.destroy();
315             if (pes.isFiner()) {
316                 ServerLogEvent ev = new ServerLogEvent(
317                         ServerLogEvent.PM_CLOSED, null);
318                 ev.zeroTotalMs();
319                 pes.log(ev);
320             }
321         } else {
322             pmPool.returnPM(pm);
323         }
324     }
325
326     public PersistenceManager getPersistenceManager(String JavaDoc userid,
327             String JavaDoc password) {
328         return getPersistenceManager();
329     }
330
331     public void setConnectionUserName(String JavaDoc userName) {
332         // ignore
333
}
334
335     public String JavaDoc getConnectionUserName() {
336         return (String JavaDoc)props.get(ConfigParser.STD_CON_USER_NAME);
337     }
338
339     public void setConnectionPassword(String JavaDoc password) {
340         // ignore
341
}
342
343     public void setConnectionURL(String JavaDoc URL) {
344         // ignore
345
}
346
347     public String JavaDoc getConnectionURL() {
348         return (String JavaDoc)props.get(ConfigParser.STD_CON_URL);
349     }
350
351     public void setConnectionDriverName(String JavaDoc driverName) {
352         // ignore
353
}
354
355     public String JavaDoc getConnectionDriverName() {
356         return (String JavaDoc)props.get(ConfigParser.STD_CON_DRIVER_NAME);
357     }
358
359     public void setConnectionFactoryName(String JavaDoc connectionFactoryName) {
360         // ignore
361
}
362
363     public String JavaDoc getConnectionFactoryName() {
364         return (String JavaDoc)props.get(ConfigParser.STD_CON_FACTORY_NAME);
365     }
366
367     public void setConnectionFactory(Object JavaDoc connectionFactory) {
368         // ignore
369
}
370
371     public Object JavaDoc getConnectionFactory() {
372         throw notImplemented();
373     }
374
375     public void setConnectionFactory2Name(String JavaDoc connectionFactoryName) {
376         // ignore
377
}
378
379     public String JavaDoc getConnectionFactory2Name() {
380         return (String JavaDoc)props.get(ConfigParser.STD_CON2_FACTORY_NAME);
381     }
382
383     public void setConnectionFactory2(Object JavaDoc connectionFactory) {
384         // ignore
385
}
386
387     public Object JavaDoc getConnectionFactory2() {
388         throw notImplemented();
389     }
390
391     public void setMultithreaded(boolean flag) {
392         multithreaded = flag;
393     }
394
395     public boolean getMultithreaded() {
396         return multithreaded;
397     }
398
399     public void setOptimistic(boolean flag) {
400         optimistic = flag;
401     }
402
403     public boolean getOptimistic() {
404         return optimistic;
405     }
406
407     public void setRetainValues(boolean flag) {
408         retainValues = flag;
409     }
410
411     public boolean getRetainValues() {
412         return retainValues;
413     }
414
415     public void setRestoreValues(boolean restoreValues) {
416         this.restoreValues = restoreValues;
417     }
418
419     public boolean getRestoreValues() {
420         return restoreValues;
421     }
422
423     public void setNontransactionalRead(boolean flag) {
424         nontransactionalRead = flag;
425     }
426
427     public boolean getNontransactionalRead() {
428         return nontransactionalRead;
429     }
430
431     public void setNontransactionalWrite(boolean flag) {
432         nontransactionalWrite = flag;
433     }
434
435     public boolean getNontransactionalWrite() {
436         return nontransactionalWrite;
437     }
438
439     public void setIgnoreCache(boolean flag) {
440         ignoreCache = flag;
441     }
442
443     public boolean getIgnoreCache() {
444         return ignoreCache;
445     }
446
447     public Properties getProperties() {
448         Properties p = new Properties();
449         props.setProperty("VendorName", "Versant");
450         props.setProperty("VendorURL", "http://www.versant.com");
451         props.setProperty("VersionNumber", Debug.VERSION);
452         return p;
453     }
454
455     public Collection supportedOptions() {
456         HashSet o = new HashSet();
457         o.add("javax.jdo.option.TransientTransactional");
458         o.add(ConfigParser.OPTION_NON_TRANSACTIONAL_READ);
459         o.add(ConfigParser.OPTION_NON_TRANSACTIONAL_WRITE);
460         o.add(ConfigParser.OPTION_RETAINVALUES);
461         o.add(ConfigParser.OPTION_RESTORE_VALUES);
462         o.add(ConfigParser.OPTION_OPTIMISTIC);
463         o.add(ConfigParser.OPTION_MULTITHREADED);
464         o.add("javax.jdo.option.ApplicationIdentity");
465         o.add("javax.jdo.option.DatastoreIdentity");
466         o.add("javax.jdo.option.ArrayList");
467         o.add("javax.jdo.option.HashMap");
468         o.add("javax.jdo.option.Hashtable");
469         o.add("javax.jdo.option.LinkedList");
470         o.add("javax.jdo.option.TreeMap");
471         o.add("javax.jdo.option.TreeSet");
472         o.add("javax.jdo.option.Vector");
473         o.add("javax.jdo.option.Map");
474         o.add("javax.jdo.option.List");
475         o.add("javax.jdo.option.Array");
476         o.add("javax.jdo.option.NullCollection");
477         o.add("javax.jdo.query.JDOQL");
478         smf.supportedOptions(o);
479         return o;
480     }
481
482     public synchronized Connection JavaDoc getJdbcConnection(String JavaDoc datastore)
483             throws SQLException JavaDoc {
484         if (jdbc) {
485             return (Connection JavaDoc)innermostSmf.getDatastoreConnection();
486         } else {
487             throw BindingSupportImpl.getInstance().invalidOperation(
488                     "Not supported by " + innermostSmf.getClass().getName());
489         }
490     }
491
492     public synchronized void clearConnectionPool(String JavaDoc datastore) {
493         smf.closeIdleDatastoreConnections();
494     }
495
496     public void setUserObject(Object JavaDoc o) {
497         userObject = o;
498     }
499
500     public Object JavaDoc getUserObject() {
501         return userObject;
502     }
503
504     public boolean isInterceptDfgFieldAccess() {
505         return interceptDfgFieldAccess;
506     }
507
508     public void setInterceptDfgFieldAccess(boolean interceptDfgFieldAccess) {
509         this.interceptDfgFieldAccess = interceptDfgFieldAccess;
510     }
511
512     public boolean isAllowPmCloseWithTxOpen() {
513         return allowPmCloseWithOpenTx;
514     }
515
516     public void setAllowPmCloseWithTxOpen(boolean allowed) {
517         allowPmCloseWithOpenTx = allowed;
518     }
519
520     public boolean isCheckModelConsistencyOnCommit() {
521         return checkModelConsistencyOnCommit;
522     }
523
524     public void setCheckModelConsistencyOnCommit(boolean on) {
525         checkModelConsistencyOnCommit = on;
526     }
527
528     public void setServerUserObject(Object JavaDoc o) {
529         setUserObject(o);
530     }
531
532     public Object JavaDoc getServerUserObject() {
533         return getUserObject();
534     }
535
536     public void shutdown() {
537         close();
538     }
539
540     public LogEvent[] getNewPerfEvents(int lastId) {
541         return pes.copyEvents(lastId);
542     }
543
544     public PmfStatus getPmfStatus() {
545         PmfStatus s = new PmfStatus();
546         s.setServer(getConnectionURL());
547         return s;
548     }
549
550     public abstract Metric[] getMetrics();
551
552     public abstract MetricSnapshotPacket getNewMetricSnapshots(int lastId);
553
554     public abstract MetricSnapshotPacket getMostRecentMetricSnapshot(int lastId);
555
556     public abstract void setUserMetric(String JavaDoc name, int value);
557
558     public abstract void incUserMetric(String JavaDoc name, int delta);
559
560     public abstract int getUserMetric(String JavaDoc name);
561
562     public void logEvent(int level, String JavaDoc description, int ms) {
563         switch (level) {
564              case VersantPersistenceManagerFactory.EVENT_ERRORS:
565                  if (!pes.isSevere()) return;
566                  break;
567              case VersantPersistenceManagerFactory.EVENT_NORMAL:
568                  if (!pes.isFine()) return;
569                  break;
570              case VersantPersistenceManagerFactory.EVENT_VERBOSE:
571                  if (!pes.isFiner()) return;
572                  break;
573              case VersantPersistenceManagerFactory.EVENT_ALL:
574                  if (!pes.isFinest()) return;
575                  break;
576          }
577          ServerLogEvent ev = new ServerLogEvent(ServerLogEvent.USER,
578                  description);
579          ev.setTotalMs(ms);
580          pes.log(ev);
581     }
582
583     public void doSystemGC() {
584         System.gc();
585     }
586
587     public PropertyInfo getServerConfiguration() {
588         return null;
589     }
590
591     public String JavaDoc setServerProperty(String JavaDoc[] beanPath, String JavaDoc value) {
592         return null;
593     }
594
595     public RemoteClientStatus[] getRemoteClients() {
596         return new RemoteClientStatus[0];
597     }
598
599     public List getPersistenceManagers() {
600         List list;
601         synchronized (activePMs) {
602             list = activePMs.values();
603         }
604         ArrayList a = new ArrayList(list.size());
605         for (Iterator i = list.iterator(); i.hasNext(); ) {
606             VersantPersistenceManagerImp pm = (VersantPersistenceManagerImp)i.next();
607             PMProxy proxy = pm.getProxy();
608             // proxy may be null if PM has been closed since we got list
609
if (proxy != null) {
610                 a.add(proxy);
611             }
612         }
613         return a;
614     }
615
616     public void evict(Object JavaDoc o) {
617         PmfEvictEvent ev = null;
618         if (pes.isFiner()) {
619             pes.log(ev = new PmfEvictEvent(o));
620         }
621         try {
622             OID oid = jmd.convertToOID(o);
623             Object JavaDoc ctx = cache.beginTx();
624             try {
625                 cache.evict(ctx, new OID[]{oid}, 0, 1, 0);
626             } finally {
627                 cache.endTx(ctx);
628             }
629         } catch (Throwable JavaDoc e) {
630             if (ev != null) ev.setErrorMsg(e);
631             throw handleException(e);
632         } finally {
633             if (ev != null) ev.updateTotalMs();
634         }
635     }
636
637     public void evictAll(Object JavaDoc[] oids) {
638         PmfEvictEvent ev = null;
639         if (pes.isFiner()) {
640             pes.log(ev = new PmfEvictEvent(oids));
641         }
642         try {
643             OID[] a = jmd.convertToOID(oids, oids.length);
644             Object JavaDoc ctx = cache.beginTx();
645             try {
646                 cache.evict(ctx, a, 0, a.length, 0);
647             } finally {
648                 cache.endTx(ctx);
649             }
650         } catch (Throwable JavaDoc e) {
651             if (ev != null) ev.setErrorMsg(e);
652             throw handleException(e);
653         } finally {
654             if (ev != null) ev.updateTotalMs();
655         }
656     }
657
658     public void evictAll(Collection oids) {
659         OID[] a = new OID[oids.size()];
660         int pos = 0;
661         for (Iterator i = oids.iterator(); i.hasNext();) {
662             a[pos++] = jmd.convertToOID(i.next());
663         }
664         PmfEvictEvent ev = null;
665         if (pes.isFiner()) {
666             pes.log(ev = new PmfEvictEvent(a));
667         }
668         try {
669             Object JavaDoc ctx = cache.beginTx();
670             try {
671                 cache.evict(ctx, a, 0, a.length, 0);
672             } finally {
673                 cache.endTx(ctx);
674             }
675         } catch (Throwable JavaDoc e) {
676             if (ev != null) ev.setErrorMsg(e);
677             throw handleException(e);
678         } finally {
679             if (ev != null) ev.updateTotalMs();
680         }
681     }
682
683     public void evictAll(Class JavaDoc cls, boolean includeSubclasses) {
684         PmfEvictEvent ev = null;
685         if (pes.isFiner()) {
686             pes.log(ev = new PmfEvictEvent(cls, includeSubclasses));
687         }
688         try {
689             ClassMetaData cmd = jmd.getClassMetaData(cls);
690             if (cmd == null) {
691                 throw BindingSupportImpl.getInstance().invalidOperation(
692                         "Not a persistent class: " + cls.getName());
693             }
694             ClassMetaData[] a;
695             if (includeSubclasses) {
696                 a = jmd.getClassMetaDataForHeirachy(cmd);
697             } else {
698                 a = new ClassMetaData[]{cmd};
699             }
700             Object JavaDoc ctx = cache.beginTx();
701             try {
702                 cache.evict(ctx, a, a.length);
703             } finally {
704                 cache.endTx(ctx);
705             }
706         } catch (Throwable JavaDoc e) {
707             if (ev != null) ev.setErrorMsg(e);
708             throw handleException(e);
709         } finally {
710             if (ev != null) ev.updateTotalMs();
711         }
712     }
713
714     public void evictAll() {
715         PmfEvictEvent ev = null;
716         if (pes.isFine()) {
717             pes.log(ev = new PmfEvictEvent());
718         }
719         try {
720             Object JavaDoc ctx = cache.beginTx();
721             try {
722                 cache.evictAll(ctx);
723             } finally {
724                 cache.endTx(ctx);
725             }
726         } catch (Throwable JavaDoc e) {
727             if (ev != null) ev.setErrorMsg(e);
728             throw handleException(e);
729         } finally {
730             if (ev != null) ev.updateTotalMs();
731         }
732     }
733
734     public boolean isInCache(Object JavaDoc oid) {
735         return cache.contains(jmd.convertToOID(oid));
736     }
737
738     /**
739      * Get the meta data for cls or throw an exception if there is none.
740      */

741     protected ClassMetaData getClassMetaData(Class JavaDoc cls) {
742         ClassMetaData cmd = jmd.getClassMetaData(cls);
743         if (cmd == null) {
744             throw BindingSupportImpl.getInstance().invalidOperation(
745                     "Class is not persistent: " + cls.getName());
746         }
747         return cmd;
748     }
749
750     public int getClassID(Class JavaDoc cls) {
751         return getClassMetaData(cls).classId;
752     }
753
754     public Class JavaDoc getClassForID(int classid) {
755         ClassMetaData cmd = jmd.getClassMetaData(classid);
756         if (cmd == null) {
757             throw BindingSupportImpl.getInstance().invalidOperation(
758                     "No class found for classid: " + classid);
759         }
760         return cmd.cls;
761     }
762
763     public Object JavaDoc getJdbcClassID(Class JavaDoc cls) {
764         if (jdbc) {
765             ClassMetaData cmd = getClassMetaData(cls);
766             try {
767                 // this must be done with reflection to avoid engine depending
768
// on jdbc
769
if (jdbcClassIdField == null) {
770                     jdbcClassIdField = cmd.storeClass.getClass().getField("jdbcClassId");
771                 }
772                 return jdbcClassIdField.get(cmd.storeClass);
773             } catch (Throwable JavaDoc e) {
774                 throw handleException(e);
775             }
776         } else {
777             throw BindingSupportImpl.getInstance().invalidOperation(
778                     "Class is not stored using JDBC: " + cls.getName());
779         }
780     }
781
782     public Class JavaDoc getClassForJdbcID(Class JavaDoc baseClass, Object JavaDoc jdbcClassid) {
783         if (jdbc) {
784             ClassMetaData cmd = getClassMetaData(baseClass).top;
785             ClassMetaData ans;
786             try {
787                 // this must be done with reflection to avoid engine depending
788
// on jdbc
789
if (jdbcFindClassMethod == null) {
790                     jdbcFindClassMethod = cmd.storeClass.getClass().getMethod(
791                             "findClass", new Class JavaDoc[]{Object JavaDoc.class});
792                 }
793                 ans = (ClassMetaData)jdbcFindClassMethod.invoke(
794                         cmd.storeClass, new Object JavaDoc[]{jdbcClassid});
795             } catch (Throwable JavaDoc e) {
796                 throw handleException(e);
797             }
798             if (ans == null) {
799                 throw BindingSupportImpl.getInstance().invalidOperation(
800                         "No class found in hierarchy " +
801                         cmd.qname + " for jdbc-class-id: " + jdbcClassid);
802             }
803             return ans.cls;
804         } else {
805             throw BindingSupportImpl.getInstance().invalidOperation(
806                     "Class is not stored using JDBC: " + baseClass.getName());
807         }
808     }
809
810     public int getClassIndex(Class JavaDoc cls) {
811         return getClassMetaData(cls).index;
812     }
813
814     public Class JavaDoc getClassForIndex(int index) {
815         try {
816             return jmd.classes[index].cls;
817         } catch (ArrayIndexOutOfBoundsException JavaDoc e) {
818             throw BindingSupportImpl.getInstance().invalidOperation(
819                     "Invalid class index: " + index);
820         }
821     }
822
823     public int[] getClassIndexes(Class JavaDoc[] classes, boolean includeSubclasses) {
824         return jmd.convertToClassIndexes(classes, includeSubclasses);
825     }
826
827     public void registerSCOPersistenceDelegates(Object JavaDoc encoder) {
828         try {
829             // this must be done with reflection so the code will compile
830
// and run on JDK 1.3 VMs
831
Class JavaDoc cls = Class.forName(
832                     "com.versant.core.jdo.sco.PersistenceDelegateManager");
833             Method JavaDoc method = cls.getDeclaredMethod("register",
834                     new Class JavaDoc[]{Class.forName("java.beans.Encoder")});
835             method.invoke(null, new Object JavaDoc[]{encoder});
836         } catch (Exception JavaDoc e) {
837             throw BindingSupportImpl.getInstance().invalidOperation(
838                     "JDK 1.4 or newer VM required");
839         }
840     }
841
842     public int getPmCacheRefType() {
843         return pmCacheRefType;
844     }
845
846     public void setPmCacheRefType(int pmCacheRefType) {
847         this.pmCacheRefType = pmCacheRefType;
848     }
849
850     public void closeActivePMsForTesting() {
851     }
852
853     public DataStoreInfo getDataStoreInfo(String JavaDoc datastore) {
854         return smf.getDataStoreInfo();
855     }
856
857     public void addLifecycleListener(LifecycleListener listener,
858             Class JavaDoc[] classes) {
859         if (classes != null) {
860             BindingSupportImpl.getInstance().runtime("Support for non-null " +
861                     "classes parameter has not been implemented");
862         }
863         if (listeners == null) {
864             listeners = new LifecycleListenerManager(listener);
865         } else {
866             listeners = listeners.add(listener);
867         }
868     }
869
870     public void removeLifecycleListener(LifecycleListener listener) {
871         if (listeners == null) {
872             return;
873         }
874         listeners = listeners.remove(listener);
875     }
876
877     /**
878      * Wrap an exception appropriately and return one to be thrown.
879      */

880     protected RuntimeException JavaDoc handleException(Throwable JavaDoc e) {
881         return handleException(e.toString(), e);
882     }
883
884     /**
885      * Wrap an exception appropriately and return one to be thrown.
886      */

887     protected RuntimeException JavaDoc handleException(String JavaDoc msg, Throwable JavaDoc e) {
888         if (e instanceof InvocationTargetException JavaDoc) {
889             e = ((InvocationTargetException JavaDoc)e).getTargetException();
890         }
891         if (BindingSupportImpl.getInstance().isError(e)
892                 && !BindingSupportImpl.getInstance().isOutOfMemoryError(e)) {
893             throw (Error JavaDoc)e;
894         }
895         if (BindingSupportImpl.getInstance().isOwnException(e)) {
896             return (RuntimeException JavaDoc)e;
897         }
898         return BindingSupportImpl.getInstance().internal(msg, e);
899     }
900
901     /**
902      * Return a 'not implemented' exception.
903      */

904     protected RuntimeException JavaDoc notImplemented() {
905         return BindingSupportImpl.getInstance().notImplemented("");
906     }
907
908     public StorageCache getStorageCache() {
909         return cache;
910     }
911
912     public StorageManagerFactory getStorageManagerFactory() {
913         return smf;
914     }
915
916     public ModelMetaData getJDOMetaData() {
917         return jmd;
918     }
919
920     public LogEventStore getLogEventStore() {
921         return pes;
922     }
923
924     public ClassLoader JavaDoc getClassLoader() {
925         return loader;
926     }
927
928     public abstract boolean isLocal();
929
930     public synchronized Object JavaDoc getEntityManagerFactory() {
931         if (entityManagerFactory != null) return entityManagerFactory;
932
933         try {
934             Class JavaDoc emf = loader.loadClass("com.versant.core.ejb.EntityManagerFactoryImp");
935             Constructor JavaDoc cons = emf.getConstructor(new Class JavaDoc[] {PersistenceManagerFactory.class});
936             entityManagerFactory = cons.newInstance(new Object JavaDoc[] {this});
937         } catch (Throwable JavaDoc e) {
938             //ignore all
939
e.printStackTrace(System.out);
940         }
941         return entityManagerFactory;
942     }
943
944     /**
945      * Classloader that will load hyperdrive classes before delegating to
946      * the parent classloader.
947      */

948
949     public static class HyperdriveLoader extends ClassLoader JavaDoc {
950
951         public HyperdriveLoader(ClassLoader JavaDoc parent) {
952             super(parent);
953         }
954
955     }
956
957
958 }
959
960
Popular Tags