KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > ojb > broker > metadata > MetadataTest


1 package org.apache.ojb.broker.metadata;
2
3 import java.util.Iterator JavaDoc;
4
5 import junit.framework.TestCase;
6 import org.apache.ojb.broker.Identity;
7 import org.apache.ojb.broker.ObjectRepository;
8 import org.apache.ojb.broker.PBKey;
9 import org.apache.ojb.broker.PersistenceBroker;
10 import org.apache.ojb.broker.PersistenceBrokerException;
11 import org.apache.ojb.broker.PersistenceBrokerFactory;
12 import org.apache.ojb.broker.TestHelper;
13 import org.apache.ojb.broker.cache.ObjectCacheDefaultImpl;
14 import org.apache.ojb.broker.cache.ObjectCacheEmptyImpl;
15 import org.apache.ojb.broker.query.Criteria;
16 import org.apache.ojb.broker.query.Query;
17 import org.apache.ojb.broker.query.QueryFactory;
18 import org.apache.ojb.broker.sequence.Repository;
19 import org.apache.ojb.broker.util.sequence.SequenceManagerHighLowImpl;
20 import org.apache.ojb.odmg.OJB;
21 import org.odmg.Database;
22 import org.odmg.Implementation;
23 import org.odmg.OQLQuery;
24 import org.odmg.Transaction;
25
26 /**
27  * This TestClass tests the RepositoryPersitors facilities for
28  * reading and writing a valid repository.
29  */

30 public class MetadataTest extends TestCase
31 {
32     public static final String JavaDoc TEST_CLASS_DESCRIPTOR = "Test_ClassDescriptor.xml";
33     public static final String JavaDoc TEST_CONNECTION_DESCRIPTOR = "Test_ConnectionDescriptor.xml";
34     public static final String JavaDoc TEST_REPOSITORY = "Test_Repository.xml";
35
36     /**
37      * A persistent object class
38      */

39     private static final Class JavaDoc TEST_CLASS = Repository.SMKey.class;
40
41     public static void main(String JavaDoc[] args)
42     {
43         String JavaDoc[] arr = {MetadataTest.class.getName()};
44         junit.textui.TestRunner.main(arr);
45     }
46
47     public MetadataTest(String JavaDoc name)
48     {
49         super(name);
50     }
51
52     public void setUp()
53     {
54     }
55
56     public void tearDown()
57     {
58         try
59         {
60             MetadataManager.getInstance().setEnablePerThreadChanges(false);
61         }
62         catch (Exception JavaDoc e)
63         {
64         }
65     }
66
67     public void testFindFirstConcreteClassDescriptor()
68     {
69         DescriptorRepository dr = MetadataManager.getInstance().getRepository();
70         ClassDescriptor cld = dr.getDescriptorFor(Repository.SMInterface.class);
71         ClassDescriptor firstConcrete = dr.findFirstConcreteClass(cld);
72         assertFalse(firstConcrete.isInterface());
73         assertFalse(firstConcrete.isAbstract());
74         firstConcrete = dr.findFirstConcreteClass(cld);
75         firstConcrete = dr.findFirstConcreteClass(cld);
76     }
77
78     public void testDescriptorRepository_1()
79     {
80         MetadataManager mm = MetadataManager.getInstance();
81         DescriptorRepository dr = mm.copyOfGlobalRepository();
82         // get an class/interface with extents
83
ClassDescriptor cld = dr.getDescriptorFor(Repository.SMMax.class);
84
85         int extentSize = cld.getExtentClasses().size();
86         Class JavaDoc topLevelInterface = dr.getTopLevelClass(Repository.SMMax.class);
87         Class JavaDoc topLevelExtent = dr.getTopLevelClass(Repository.SMMaxA.class);
88         assertEquals(Repository.SMMax.class, topLevelInterface);
89         assertEquals(Repository.SMMax.class, topLevelExtent);
90         assertEquals(2, extentSize);
91
92         dr.removeExtent(Repository.SMMaxA.class.getName());
93         int extentSizeNew = cld.getExtentClasses().size();
94         Class JavaDoc topLevelInterfaceNew = dr.getTopLevelClass(Repository.SMMax.class);
95         Class JavaDoc topLevelExtentNew = dr.getTopLevelClass(Repository.SMMaxA.class);
96         assertEquals(Repository.SMMax.class, topLevelInterfaceNew);
97         assertEquals(Repository.SMMaxA.class, topLevelExtentNew);
98         assertEquals(1, extentSizeNew);
99     }
100
101     public void testDescriptorRepository_2()
102     {
103         MetadataManager mm = MetadataManager.getInstance();
104         DescriptorRepository dr = mm.copyOfGlobalRepository();
105         // get an class/interface with extents
106
ClassDescriptor cld = dr.getDescriptorFor(Repository.SMMax.class);
107         int allSubClasses = dr.getAllConcreteSubclassDescriptors(cld).size();
108         int allExtents = cld.getExtentClasses().size();
109         int allExtentNames = cld.getExtentClassNames().size();
110         assertEquals(allExtents, allExtentNames);
111
112         dr.remove(Repository.SMMaxA.class);
113         // after removing SMMaxA, SMMax interface lost 4 concrete extents (sub-classes)
114
// be carefully in changing SMM*** metadata, could make fail this test
115
int allSubClassesNew = dr.getAllConcreteSubclassDescriptors(cld).size();
116         int allExtentsNew = cld.getExtentClasses().size();
117         int allExtentNamesNew = cld.getExtentClassNames().size();
118         assertEquals(allExtentsNew, allExtentNamesNew);
119         assertEquals(allSubClasses - 4, allSubClassesNew);
120     }
121
122     public void testClassDescriptor_1()
123     {
124         MetadataManager mm = MetadataManager.getInstance();
125         DescriptorRepository dr = mm.copyOfGlobalRepository();
126         ClassDescriptor cld = dr.getDescriptorFor(ObjectRepository.Component.class);
127
128         FieldDescriptor[] a = cld.getAutoIncrementFields();
129         assertEquals("autoincrement field should be found", 1, a.length);
130         FieldDescriptor target = cld.getFieldDescriptorByName("id");
131         cld.removeFieldDescriptor(target);
132         a = cld.getAutoIncrementFields();
133         assertEquals("autoincrement PK should be deleted", 0, a.length);
134         assertNull(cld.getFieldDescriptorByName("id"));
135
136         cld.addFieldDescriptor(target);
137         a = cld.getAutoIncrementFields();
138         assertEquals("autoincrement field should be found", 1, a.length);
139         assertNotNull(cld.getFieldDescriptorByName("id"));
140
141     }
142
143     public void testLoadingProfiles() throws Exception JavaDoc
144     {
145         PersistenceBroker broker = null;
146         MetadataManager mm = MetadataManager.getInstance();
147         try
148         {
149             mm.setEnablePerThreadChanges(true);
150             DescriptorRepository dr_1 = mm.readDescriptorRepository(TEST_CLASS_DESCRIPTOR);
151             // add some profiles
152
mm.addProfile("global", mm.copyOfGlobalRepository());
153             mm.addProfile("test", dr_1);
154
155             // now load a specific profile
156
mm.loadProfile("test");
157             broker = PersistenceBrokerFactory.defaultPersistenceBroker();
158             CldTestObject obj = new CldTestObject();
159             obj.setName("testLoadingProfiles");
160             try
161             {
162                 broker.beginTransaction();
163                 broker.store(obj);
164                 broker.commitTransaction();
165                 try
166                 {
167                     // try to find persistent object, only available in global
168
// repository profile
169
Class JavaDoc clazz = broker.getClassDescriptor(TEST_CLASS).getClassOfObject();
170                     assertNull("We should not found this class-descriptor in profile", clazz);
171                 }
172                 catch (PersistenceBrokerException e)
173                 {
174                     assertTrue(true);
175                 }
176             }
177             finally
178             {
179                 broker.close();
180             }
181
182             //***************************************
183
mm.removeProfile("test");
184             try
185             {
186                 mm.loadProfile("test");
187                 fail("Loading of profile should fail, but doesn't");
188             }
189             catch (Exception JavaDoc e)
190             {
191                 // we expect exception
192
}
193             // now we load copy of global DescriptorRepository
194
mm.loadProfile("global");
195             broker = PersistenceBrokerFactory.defaultPersistenceBroker();
196             Class JavaDoc clazz = broker.getClassDescriptor(TEST_CLASS).getClassOfObject();
197
198             ObjectRepository.Component compChild = new ObjectRepository.Component();
199             compChild.setName("MetadataTest_child");
200
201             ObjectRepository.Component compParent = new ObjectRepository.Component();
202             compParent.setName("MetadataTest_parent");
203             compChild.setParentComponent(compParent);
204
205             broker.beginTransaction();
206             broker.store(compChild);
207             broker.commitTransaction();
208
209             Identity oid = new Identity(compChild, broker);
210             broker.clearCache();
211             compChild = (ObjectRepository.Component) broker.getObjectByIdentity(oid);
212
213             assertNotNull(compChild);
214             assertNotNull(compChild.getParentComponent());
215
216             broker.close();
217             assertEquals(TEST_CLASS, clazz);
218             mm.removeAllProfiles();
219             try
220             {
221                 mm.loadProfile("global");
222                 fail("Loading of profile should fail, but doesn't");
223             }
224             catch (Exception JavaDoc e)
225             {
226             }
227
228             broker = PersistenceBrokerFactory.defaultPersistenceBroker();
229             clazz = broker.getClassDescriptor(TEST_CLASS).getClassOfObject();
230             broker.close();
231             assertEquals(TEST_CLASS, clazz);
232         }
233         finally
234         {
235             mm.setEnablePerThreadChanges(false);
236             if(broker != null) broker.close();
237         }
238
239
240     }
241
242     public void testRuntimeMergeConnectionDescriptor() throws Exception JavaDoc
243     {
244
245         MetadataManager mm = MetadataManager.getInstance();
246         ConnectionRepository cr = mm.readConnectionRepository(TEST_CONNECTION_DESCRIPTOR);
247         mm.mergeConnectionRepository(cr);
248
249         ConnectionRepository mergedCR = mm.connectionRepository();
250         JdbcConnectionDescriptor jcd = mergedCR.getDescriptor(new PBKey("runtime"));
251         assertNotNull("Runtime merge of ConnectionRepository failed", jcd);
252     }
253
254     public void testRuntimeMergeDescriptorRepository() throws Exception JavaDoc
255     {
256         MetadataManager mm = MetadataManager.getInstance();
257         DescriptorRepository dr = mm.readDescriptorRepository(TEST_CLASS_DESCRIPTOR);
258         mm.mergeDescriptorRepository(dr);
259
260         DescriptorRepository mergedDR = mm.getRepository();
261         ClassDescriptor cld = mergedDR.getDescriptorFor(MetadataTest.CldTestObject.class);
262         assertNotNull("Runtime merge of DescriptorRepository failed", cld);
263     }
264
265     /**
266      * test to check PB create with PBKey
267      */

268     public void testLookupPB1()
269     {
270         PBKey key1 = new PBKey(TestHelper.DEF_JCD_ALIAS);
271         PBKey key2 = new PBKey(TestHelper.DEF_JCD_ALIAS, TestHelper.DEF_USER, TestHelper.DEF_PASSWORD);
272         PBKey key3 = new PBKey(TestHelper.FAR_AWAY_JCD_ALIAS);
273         Query query = QueryFactory.newQuery(TEST_CLASS, new Criteria());
274
275         PersistenceBroker broker = PersistenceBrokerFactory.createPersistenceBroker(key1);
276         broker.getCount(query);
277         broker.close();
278
279         broker = PersistenceBrokerFactory.createPersistenceBroker(key2);
280         broker.getCount(query);
281         broker.close();
282
283         broker = PersistenceBrokerFactory.createPersistenceBroker(key3);
284         broker.getCount(query);
285         broker.close();
286     }
287
288     /**
289      * test to check PB create with PBKey
290      */

291     public void testLookupPB2()
292     {
293         PBKey key1 = new PBKey(TestHelper.DEF_JCD_ALIAS, "!!TestCase: This should fail!!", "nothing");
294         Query query = QueryFactory.newQuery(TEST_CLASS, new Criteria());
295         PersistenceBroker broker = PersistenceBrokerFactory.createPersistenceBroker(key1);
296         // hsql is not very strict in user handling
297
try
298         {
299             broker.getCount(query);
300             fail("We excect a exception, because we pass a PBKey with user and password that doesn't exist");
301         }
302         catch (Exception JavaDoc e)
303         {
304             assertTrue(true);
305         }
306         broker.close();
307     }
308
309     /**
310      * test to check database open
311      */

312     public void testLookupDatabase() throws Exception JavaDoc
313     {
314         String JavaDoc queryStr = "select allArticle from " + TEST_CLASS.getName();
315         Implementation odmg = OJB.getInstance();
316         Transaction tx;
317         Database db = odmg.newDatabase();
318         db.open(TestHelper.DEF_JCD_ALIAS, Database.OPEN_READ_WRITE);
319         db.close();
320         db = odmg.newDatabase();
321         db.open(TestHelper.DEF_JCD_ALIAS + "#" +
322                 TestHelper.DEF_USER + "#" +
323                 TestHelper.DEF_PASSWORD, Database.OPEN_READ_WRITE);
324         tx = odmg.newTransaction();
325         tx.begin();
326         OQLQuery query = odmg.newOQLQuery();
327         query.create(queryStr);
328         query.execute();
329         tx.commit();
330         db.close();
331
332         db = odmg.newDatabase();
333         db.open(TestHelper.DEF_JCD_ALIAS, Database.OPEN_READ_WRITE);
334         tx = odmg.newTransaction();
335         tx.begin();
336         OQLQuery query2 = odmg.newOQLQuery();
337         query2.create(queryStr);
338         query2.execute();
339         tx.commit();
340         db.close();
341     }
342
343     public void testTimeToCopyRepository()
344     {
345         DescriptorRepository dr = null;
346         int loop = 5;
347         long period = System.currentTimeMillis();
348         for (int i = 0; i < loop; i++)
349         {
350             dr = MetadataManager.getInstance().copyOfGlobalRepository();
351         }
352         period = System.currentTimeMillis() - period;
353         int descriptors = 0;
354         Iterator JavaDoc it = dr.iterator();
355         while (it.hasNext())
356         {
357             it.next();
358             ++descriptors;
359         }
360         System.out.println("# Time to create a copy of " + descriptors + " class-descriptors: " + period / loop + " ms #");
361     }
362
363     public void testObjectCacheDeclarations()
364     {
365         DescriptorRepository dr = MetadataManager.getInstance()
366                                     .readDescriptorRepository(TEST_REPOSITORY);
367         ConnectionRepository cr = MetadataManager.getInstance().readConnectionRepository(TEST_REPOSITORY);
368
369         ObjectCacheDescriptor ocd;
370         ocd = ((JdbcConnectionDescriptor)cr.getAllDescriptor().get(0)).getObjectCacheDescriptor();
371         assertNotNull(ocd);
372         assertNotNull(ocd.getObjectCache());
373         assertEquals(ObjectCacheEmptyImpl.class, ocd.getObjectCache());
374         assertNotNull(ocd.getAttribute("attr_con"));
375         assertNull("Wrong custom attribute found", ocd.getAttribute("attr_class"));
376         assertEquals("555", ocd.getAttribute("attr_con"));
377
378         ocd = dr.getDescriptorFor(CacheObject.class).getObjectCacheDescriptor();
379         assertNotNull(ocd);
380         assertNotNull(ocd.getObjectCache());
381         assertEquals(ObjectCacheDefaultImpl.class, ocd.getObjectCache());
382         assertNotNull(ocd.getAttribute("attr_class"));
383         assertNull("Wrong custom attribute found", ocd.getAttribute("attr_con"));
384         assertEquals("444", ocd.getAttribute("attr_class"));
385     }
386
387     public void testReadConnectionDescriptor()
388     {
389         JdbcConnectionDescriptor jcd = MetadataManager.getInstance().connectionRepository().
390                 getDescriptor(new PBKey("testConnection", "a user", "a password"));
391         /* descriptor snip
392
393         <jdbc-connection-descriptor
394         jcd-alias="testConnection"
395         default-connection="false"
396         platform="Oracle"
397         jdbc-level="1.0"
398         driver="a driver"
399         protocol="a protocol"
400         subprotocol="a subprotocol"
401         dbalias="myDbalias"
402         username="a user"
403         password="a password"
404         eager-release="true"
405         batch-mode="true"
406         useAutoCommit="0"
407         ignoreAutoCommitExceptions="true"
408     >
409
410         <object-cache class="org.apache.ojb.broker.cache.ObjectCacheEmptyImpl">
411             <attribute attribute-name="cacheKey1" attribute-value="cacheValue1"/>
412             <attribute attribute-name="cacheKey2" attribute-value="cacheValue2"/>
413         </object-cache>
414
415         <connection-pool
416             maxActive="1"
417             maxIdle="2"
418             maxWait="3"
419             minEvictableIdleTimeMillis="4"
420             numTestsPerEvictionRun="5"
421             testOnBorrow="true"
422             testOnReturn="true"
423             testWhileIdle="true"
424             timeBetweenEvictionRunsMillis="6"
425             whenExhaustedAction="2"
426             validationQuery="a query"
427             logAbandoned="true"
428             removeAbandoned="true"
429             removeAbandonedTimeout="8"
430         />
431
432         <sequence-manager className="org.apache.ojb.broker.util.sequence.SequenceManagerHighLowImpl">
433             <attribute attribute-name="key1" attribute-value="value1"/>
434             <attribute attribute-name="key2" attribute-value="value2"/>
435         </sequence-manager>
436     </jdbc-connection-descriptor>
437         */

438         // don't set it to true!!! This may break everything (2 default connections)
439
assertEquals(false, jcd.isDefaultConnection());
440
441         assertNotNull(jcd.getDbms());
442         assertEquals("Oracle", jcd.getDbms());
443         assertEquals(1.0d, jcd.getJdbcLevel(), 0.1);
444
445         assertNotNull(jcd.getDriver());
446         assertEquals("a driver", jcd.getDriver());
447
448         assertNotNull(jcd.getProtocol());
449         assertEquals("a protocol", jcd.getProtocol());
450
451         assertNotNull(jcd.getSubProtocol());
452         assertEquals("a subprotocol", jcd.getSubProtocol());
453
454         assertNotNull(jcd.getDbAlias());
455         assertEquals("myDbalias", jcd.getDbAlias());
456
457         assertNotNull(jcd.getUserName());
458         assertEquals("a user", jcd.getUserName());
459
460         assertNotNull(jcd.getPassWord());
461         assertEquals("a password", jcd.getPassWord());
462
463         assertEquals(true, jcd.getEagerRelease());
464
465         assertEquals(true, jcd.getBatchMode());
466
467         assertEquals(0, jcd.getUseAutoCommit());
468         assertEquals(true, jcd.isIgnoreAutoCommitExceptions());
469
470         ObjectCacheDescriptor ocd = jcd.getObjectCacheDescriptor();
471         assertNotNull(ocd);
472         assertNotNull(ocd.getObjectCache());
473         assertEquals(ocd.getObjectCache(), ObjectCacheEmptyImpl.class);
474         assertNotNull(ocd.getAttribute("cacheKey1"));
475         assertNotNull(ocd.getAttribute("cacheKey2"));
476         assertEquals("cacheValue1", ocd.getAttribute("cacheKey1"));
477         assertEquals("cacheValue2", ocd.getAttribute("cacheKey2"));
478
479         ConnectionPoolDescriptor cpd = jcd.getConnectionPoolDescriptor();
480         assertEquals(1, cpd.getMaxActive());
481         assertEquals(2, cpd.getMaxIdle());
482         assertEquals(3, cpd.getMaxWait());
483         assertEquals(4, cpd.getMinEvictableIdleTimeMillis());
484         assertEquals(5, cpd.getNumTestsPerEvictionRun());
485         assertEquals(true, cpd.isTestOnBorrow());
486         assertEquals(true, cpd.isTestOnReturn());
487         assertEquals(true, cpd.isTestWhileIdle());
488         assertEquals(6, cpd.getTimeBetweenEvictionRunsMillis());
489         assertEquals(2, cpd.getWhenExhaustedAction());
490
491         assertNotNull(cpd.getValidationQuery());
492         assertEquals("a query", cpd.getValidationQuery());
493
494         assertEquals(true, cpd.isLogAbandoned());
495         assertEquals(true, cpd.isRemoveAbandoned());
496         assertEquals(8, cpd.getRemoveAbandonedTimeout());
497
498         SequenceDescriptor seq = jcd.getSequenceDescriptor();
499         assertEquals(SequenceManagerHighLowImpl.class.getName(), seq.getSequenceManagerClass().getName());
500
501         assertNotNull(seq.getAttribute("key1"));
502         assertEquals("value1", seq.getAttribute("key1"));
503
504         assertNotNull(seq.getAttribute("key2"));
505         assertEquals("value2", seq.getAttribute("key2"));
506     }
507
508
509     // ======================================================================
510
// inner test class
511
// ======================================================================
512
public static class CldTestObject
513     {
514         int id;
515         String JavaDoc name;
516
517         public CldTestObject()
518         {
519         }
520
521         public CldTestObject(int id, String JavaDoc name)
522         {
523             this.id = id;
524             this.name = name;
525         }
526
527         public int getId()
528         {
529             return id;
530         }
531
532         public void setId(int id)
533         {
534             this.id = id;
535         }
536
537         public String JavaDoc getName()
538         {
539             return name;
540         }
541
542         public void setName(String JavaDoc name)
543         {
544             this.name = name;
545         }
546     }
547
548     public static class CacheObject
549     {
550         Integer JavaDoc objId;
551         String JavaDoc name;
552
553         public Integer JavaDoc getObjId()
554         {
555             return objId;
556         }
557
558         public void setObjId(Integer JavaDoc objId)
559         {
560             this.objId = objId;
561         }
562
563         public String JavaDoc getName()
564         {
565             return name;
566         }
567
568         public void setName(String JavaDoc name)
569         {
570             this.name = name;
571         }
572     }
573 }
574
Popular Tags