KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > ojb > broker > sequence > SequenceManagerTest


1 package org.apache.ojb.broker.sequence;
2
3 import org.apache.commons.lang.SerializationUtils;
4 import org.apache.ojb.broker.metadata.ClassDescriptor;
5 import org.apache.ojb.broker.metadata.DescriptorRepository;
6 import org.apache.ojb.broker.metadata.FieldDescriptor;
7 import org.apache.ojb.broker.metadata.JdbcConnectionDescriptor;
8 import org.apache.ojb.broker.metadata.MetadataManager;
9 import org.apache.ojb.broker.metadata.SequenceDescriptor;
10 import org.apache.ojb.broker.query.Criteria;
11 import org.apache.ojb.broker.query.Query;
12 import org.apache.ojb.broker.query.QueryByCriteria;
13 import org.apache.ojb.broker.util.sequence.SequenceManager;
14 import org.apache.ojb.broker.util.sequence.SequenceManagerException;
15 import org.apache.ojb.broker.util.sequence.SequenceManagerFactory;
16 import org.apache.ojb.broker.util.sequence.SequenceManagerHelper;
17 import org.apache.ojb.broker.util.sequence.SequenceManagerHighLowImpl;
18 import org.apache.ojb.broker.util.sequence.SequenceManagerNextValImpl;
19 import org.apache.ojb.broker.util.sequence.SequenceManagerSeqHiLoImpl;
20 import org.apache.ojb.broker.util.sequence.SequenceManagerStoredProcedureImpl;
21 import org.apache.ojb.broker.PersistenceBroker;
22 import org.apache.ojb.broker.PersistenceBrokerFactory;
23 import org.apache.ojb.broker.PBKey;
24 import org.apache.ojb.broker.TestHelper;
25 import org.apache.ojb.broker.PersistenceBrokerException;
26 import org.apache.ojb.broker.ObjectRepository;
27 import org.apache.ojb.broker.BookArticle;
28 import org.apache.ojb.broker.Article;
29 import org.apache.ojb.broker.CdArticle;
30 import org.apache.ojb.junit.OJBTestCase;
31
32 import java.io.Serializable JavaDoc;
33 import java.util.ArrayList JavaDoc;
34 import java.util.Collection JavaDoc;
35 import java.util.Iterator JavaDoc;
36 import java.util.List JavaDoc;
37 import java.util.TreeSet JavaDoc;
38
39 /**
40  * Tests to verify SequenceManager implementations - All sequence
41  * manager implementations have to pass these tests without failures.
42  * <br>
43  * Note: For the multi-threaded tests, the keys will be generated once for all tests.
44  *
45  * @author <a HREF="mailto:armin@codeAuLait.de">Armin Waibel</a>
46  * @version $Id: SequenceManagerTest.java,v 1.26.4.1 2005/07/24 23:57:42 arminw Exp $
47  */

48 public class SequenceManagerTest extends OJBTestCase
49 {
50     private static final String JavaDoc TEST_SEQUENCE_NAME = "TEST_SEQUENCE";
51     /**
52      * Max PK value for {@link Repository.SMMax} test class prepared
53      * in database.
54      */

55     private static final int SMMAX_MAX_PK_VALUE = 131;
56     /**
57      * Error message.
58      */

59     private static final String JavaDoc SMMAX_FAIL_MESSAGE = "Expected " + SMMAX_MAX_PK_VALUE +
60             ", something goes wrong when try to identify max PK id in the prepared database tables" +
61             " - Check the ...SMMAX... database tables for id " + SMMAX_MAX_PK_VALUE +
62             ", if id was found in one of the tables, test fails";
63
64     private static final String JavaDoc DEF_FAIL_MESSAGE = "Found different max PK, expected the same";
65
66     /*
67     attributes for the multi-threaded key generation
68     used in method generateKeys(). See test cases
69     testSequenceGeneration
70     testForLostKeys
71     */

72     private int loops = 1000;
73     private int instances = 10;
74     private Class JavaDoc targetClass = Repository.SMSameTableA.class;
75     // end
76

77     private int numberOfKeys = 200;
78
79     private PersistenceBroker[] brokers;
80     private ThreadGroup JavaDoc threadGroup;
81     private static ArrayList JavaDoc generatedKeys;
82     private static int keyCount;
83
84     public SequenceManagerTest(String JavaDoc s)
85     {
86         super(s);
87     }
88
89     public static void main(String JavaDoc[] args)
90     {
91         String JavaDoc[] arr = {SequenceManagerTest.class.getName()};
92         junit.textui.TestRunner.main(arr);
93     }
94
95     protected void setUp() throws Exception JavaDoc
96     {
97         super.setUp();
98     }
99
100     protected void tearDown() throws Exception JavaDoc
101     {
102         super.tearDown();
103     }
104
105     /**
106      * Test support for classes with multiple autoincrement
107      * fields - e.g. see repository for {@link Repository.SMKey}
108      */

109     public void testMultipleAutoincrement()
110     {
111         String JavaDoc MESSAGE = "Autoincrement field was not incremented: ";
112         String JavaDoc name = "my test key " + System.currentTimeMillis();
113         Repository.SMKey key = new Repository.SMKey();
114         key.setName(name);
115         PersistenceBroker broker = PersistenceBrokerFactory.defaultPersistenceBroker();
116         broker.beginTransaction();
117         broker.store(key);
118         broker.commitTransaction();
119         assertEquals("Value was not store: " + key, name, key.getName());
120         assertNotNull(MESSAGE + key, key.getIntegerKey());
121         assertTrue(MESSAGE + key, (key.getIntKey() != 0));
122         assertNotNull(MESSAGE + key, key.getLongKey());
123         assertNotNull(MESSAGE + key, key.getStringKey());
124 // System.out.println("## SMKey: \n"+key);
125

126         Criteria cr = new Criteria();
127         cr.addEqualTo("name", name);
128         Query query = new QueryByCriteria(Repository.SMKey.class, cr);
129         key = (Repository.SMKey) broker.getObjectByQuery(query);
130
131         assertEquals("Value was not store: ", name, key.getName());
132         assertNotNull(MESSAGE + key, key.getIntegerKey());
133         assertTrue(MESSAGE + key, (key.getIntKey() != 0));
134         assertNotNull(MESSAGE + key, key.getLongKey());
135         assertNotNull(MESSAGE + key, key.getStringKey());
136 // System.out.println("## SMKey: \n"+key);
137

138         broker.close();
139     }
140
141     /**
142      * Test the use of the 'sequence-name' field descriptor
143      * attribute.
144      */

145     public void testSequenceNameAttribute() throws Exception JavaDoc
146     {
147         // sequence name used in the repository
148
String JavaDoc fieldName = "stringKey";
149         PersistenceBroker broker = PersistenceBrokerFactory.defaultPersistenceBroker();
150         FieldDescriptor field = broker.getClassDescriptor(Repository.SMKey.class).getFieldDescriptorByName(fieldName);
151         String JavaDoc result = SequenceManagerHelper.buildSequenceName(broker, field, true);
152
153         assertEquals(TEST_SEQUENCE_NAME, result);
154         broker.close();
155     }
156
157     public void testAutoNaming() throws Exception JavaDoc
158     {
159         String JavaDoc jcdAlias = "testAutoNaming";
160         PBKey tempKey = new PBKey(jcdAlias, TestHelper.DEF_KEY.getUser(), TestHelper.DEF_KEY.getPassword());
161         MetadataManager mm = MetadataManager.getInstance();
162         PersistenceBroker broker = null;
163         try
164         {
165             JdbcConnectionDescriptor jcd = mm.connectionRepository().getDescriptor(TestHelper.DEF_KEY);
166             jcd = (JdbcConnectionDescriptor) SerializationUtils.clone(jcd);
167             // modify jcd copy
168
jcd.setJcdAlias(jcdAlias);
169             SequenceDescriptor sd = jcd.getSequenceDescriptor();
170             assertNotNull("Can not find sequence-descriptor - check test", sd);
171             // don't use autoNaming
172
sd.addAttribute("autoNaming", "false");
173             // add new connection descriptor to global base
174
mm.connectionRepository().addDescriptor(jcd);
175
176             // allow per thread changes of persistent object data
177
mm.setEnablePerThreadChanges(true);
178             DescriptorRepository dr = mm.copyOfGlobalRepository();
179             ClassDescriptor cld = dr.getDescriptorFor(SMAutoNaming.class);
180             FieldDescriptor field = cld.getAutoIncrementFields()[0];
181
182             // set sequence name for persistent object to null
183
field.setSequenceName(null);
184             mm.setDescriptor(dr);
185
186             broker = PersistenceBrokerFactory.createPersistenceBroker(tempKey);
187             try
188             {
189                 /*
190                 persistent object descriptor doesn't has a sequence name
191                 and autoNaming is false --> expect an exception
192                 */

193                 SMAutoNaming obj = new SMAutoNaming("testAutoNaming_1");
194                 sd = broker.serviceConnectionManager().getConnectionDescriptor().getSequenceDescriptor();
195                 assertTrue("false".equals(sd.getAttribute("autoNaming")));
196
197                 broker.beginTransaction();
198                 broker.store(obj);
199                 broker.commitTransaction();
200                 fail("If sequence manager implementation supports 'autoNaming' feature,"
201                         +" this test should cause an exception (else ignore this failure).");
202             }
203             catch (PersistenceBrokerException e)
204             {
205                 assertTrue(true);
206                 broker.abortTransaction();
207             }
208
209             try
210             {
211                 /* attribute 'auto-naming' is still false,
212                 but now we set a sequence name for autoincrement field
213                 --> should pass
214                 */

215                 field.setSequenceName("AA_testAutoNaming_user_set");
216                 SMAutoNaming obj = new SMAutoNaming("testAutoNaming_2");
217                 broker.beginTransaction();
218                 broker.store(obj);
219                 broker.commitTransaction();
220             }
221             catch (PersistenceBrokerException e)
222             {
223                 e.printStackTrace();
224                 broker.close();
225                 throw e;
226             }
227
228             try
229             {
230                 // let OJB re-initialize sequence-manager
231
broker.close();
232                 PersistenceBrokerFactory.releaseAllInstances();
233                 /*
234                 remove sequence name of autoincrement field
235                 but enable automatic sequence name generation
236                 --> should pass
237                 */

238                 field.setSequenceName(null);
239                 sd.addAttribute("autoNaming", "true");
240                 broker = PersistenceBrokerFactory.createPersistenceBroker(tempKey);
241                 SMAutoNaming obj = new SMAutoNaming("testAutoNaming_3");
242                 broker.beginTransaction();
243                 broker.store(obj);
244                 broker.commitTransaction();
245             }
246             catch (PersistenceBrokerException e)
247             {
248                 e.printStackTrace();
249                 fail("Sequence key generation failed");
250             }
251
252         }
253         finally
254         {
255             // cleanup
256
if (broker != null) broker.close();
257             mm.setEnablePerThreadChanges(false);
258         }
259     }
260
261     /**
262      * This test only works, when using
263      * {@link org.apache.ojb.broker.util.sequence.SequenceManagerNextValImpl}
264      * for sequence generation.
265      */

266     public void testDatabaseSequenceGeneration() throws Exception JavaDoc
267     {
268         PersistenceBroker broker = PersistenceBrokerFactory.defaultPersistenceBroker();
269         SequenceManager sm = SequenceManagerFactory.getSequenceManager(broker);
270         if (!(sm instanceof SequenceManagerNextValImpl))
271         {
272             System.out.println("This test only works for SeqMan implementations using "
273                     + SequenceManagerNextValImpl.class + " Skip test case.");
274             broker.close();
275             return;
276         }
277         int count = 0;
278         FieldDescriptor idFld = broker.getClassDescriptor(
279                 Repository.SMDatabaseSequence.class).getAutoIncrementFields()[0];
280         for (int i = 0; i < 10; i++)
281         {
282             Integer JavaDoc val = (Integer JavaDoc) sm.getUniqueValue(idFld);
283             count += val.intValue();
284             System.err.println("count " + count);
285         }
286         assertFalse("No keys generated", count == 0);
287         broker.close();
288     }
289
290     /**
291      * Test the max id search used in the standard sequence manager
292      * implementations.
293      */

294     public void testMaxKeySearch1()
295     {
296         PersistenceBroker broker = PersistenceBrokerFactory.defaultPersistenceBroker();
297         FieldDescriptor field = null;
298
299         // find max from classes using different tables
300
// FieldDescriptor field = broker.getClassDescriptor(Repository.SMMax.class).getAutoIncrementFields()[0];
301
// long result1 = SequenceManagerHelper.getMaxForExtent(broker, field);
302
field = broker.getClassDescriptor(Repository.SMMaxA.class).getAutoIncrementFields()[0];
303         long result2 = SequenceManagerHelper.getMaxForExtent(broker, field);
304         field = broker.getClassDescriptor(Repository.SMMaxAA.class).getAutoIncrementFields()[0];
305         long result3 = SequenceManagerHelper.getMaxForExtent(broker, field);
306         field = broker.getClassDescriptor(Repository.SMMaxAB.class).getAutoIncrementFields()[0];
307         long result4 = SequenceManagerHelper.getMaxForExtent(broker, field);
308         field = broker.getClassDescriptor(Repository.SMMaxAAA.class).getAutoIncrementFields()[0];
309         long result5 = SequenceManagerHelper.getMaxForExtent(broker, field);
310
311         // assertEquals(SMMAX_FAIL_MESSAGE, SMMAX_MAX_PK_VALUE, result1);
312
assertEquals(SMMAX_FAIL_MESSAGE, SMMAX_MAX_PK_VALUE, result2);
313         assertEquals(SMMAX_FAIL_MESSAGE, SMMAX_MAX_PK_VALUE, result3);
314         assertEquals(SMMAX_FAIL_MESSAGE, SMMAX_MAX_PK_VALUE, result4);
315         assertEquals(SMMAX_FAIL_MESSAGE, SMMAX_MAX_PK_VALUE, result5);
316
317         broker.close();
318     }
319
320     /**
321      * Test the max id search used in the standard sequence manager
322      * implementations.
323      */

324     public void testMaxKeySearch2()
325     {
326         PersistenceBroker broker = PersistenceBrokerFactory.defaultPersistenceBroker();
327         // find max from classes using the same table
328
broker.beginTransaction();
329         broker.store(new ObjectRepository.A());
330         broker.store(new ObjectRepository.B());
331         broker.store(new ObjectRepository.B1());
332         broker.store(new ObjectRepository.C());
333         broker.store(new ObjectRepository.D());
334         broker.commitTransaction();
335         long[] result = new long[5];
336         FieldDescriptor field = broker.getClassDescriptor(ObjectRepository.A.class).getAutoIncrementFields()[0];
337         result[0] = SequenceManagerHelper.getMaxForExtent(broker, field);
338         field = broker.getClassDescriptor(ObjectRepository.B.class).getAutoIncrementFields()[0];
339         result[1] = SequenceManagerHelper.getMaxForExtent(broker, field);
340         field = broker.getClassDescriptor(ObjectRepository.C.class).getAutoIncrementFields()[0];
341         result[2] = SequenceManagerHelper.getMaxForExtent(broker, field);
342         field = broker.getClassDescriptor(ObjectRepository.D.class).getAutoIncrementFields()[0];
343         result[3] = SequenceManagerHelper.getMaxForExtent(broker, field);
344         field = broker.getClassDescriptor(ObjectRepository.B1.class).getAutoIncrementFields()[0];
345         result[4] = SequenceManagerHelper.getMaxForExtent(broker, field);
346         broker.close();
347
348         for (int i = 0; i < result.length; i++)
349         {
350             for (int k = 0; k < result.length; k++)
351             {
352                 if (!(result[i] == result[k]))
353                 {
354                     fail(DEF_FAIL_MESSAGE);
355                 }
356             }
357         }
358     }
359
360     /**
361      * Test the max id search used in the standard sequence manager
362      * implementations.
363      */

364     public void testMaxKeySearch3()
365     {
366         PersistenceBroker broker = PersistenceBrokerFactory.defaultPersistenceBroker();
367         long[] result = new long[3];
368         FieldDescriptor field = broker.getClassDescriptor(Article.class).getAutoIncrementFields()[0];
369         result[0] = SequenceManagerHelper.getMaxForExtent(broker, field);
370         // field = broker.getClassDescriptor(AbstractArticle.class).getAutoIncrementFields()[0];
371
// result[1] = SequenceManagerHelper.getMaxForExtent(broker, field);
372
field = broker.getClassDescriptor(BookArticle.class).getAutoIncrementFields()[0];
373         result[1] = SequenceManagerHelper.getMaxForExtent(broker, field);
374         // field = broker.getClassDescriptor(AbstractCdArticle.class).getAutoIncrementFields()[0];
375
// result[2] = SequenceManagerHelper.getMaxForExtent(broker, field);
376
field = broker.getClassDescriptor(CdArticle.class).getAutoIncrementFields()[0];
377         result[2] = SequenceManagerHelper.getMaxForExtent(broker, field);
378         broker.close();
379
380         for (int i = 0; i < result.length; i++)
381         {
382             for (int k = 0; k < result.length; k++)
383             {
384                 if (!(result[i] == result[k]))
385                 {
386                     fail(DEF_FAIL_MESSAGE);
387                 }
388             }
389         }
390     }
391
392     /**
393      * Tests if the generated id's are unique across extents.
394      */

395     public void testUniqueAcrossExtendsWithDifferentTables1() throws Exception JavaDoc
396     {
397         Class JavaDoc classOne = Repository.SMInterfaceExtendAAA.class;
398         Class JavaDoc classTwo = Repository.SMInterfaceExtendBB.class;
399         doKeyAnalysing(classOne, classTwo);
400     }
401
402     /**
403      * Tests if the generated id's are unique across extents.
404      */

405     public void testUniqueAcrossExtendsWithDifferentTables2() throws Exception JavaDoc
406     {
407         Class JavaDoc classOne = Repository.SMInterfaceExtendAA.class;
408         Class JavaDoc classTwo = Repository.SMInterfaceExtendB.class;
409         doKeyAnalysing(classOne, classTwo);
410     }
411
412     /**
413      * Tests if the generated id's are unique across extents.
414      */

415     public void testUniqueAcrossExtendsWithDifferentTables3() throws Exception JavaDoc
416     {
417         Class JavaDoc classOne = Repository.SMInterfaceExtendA.class;
418         Class JavaDoc classTwo = Repository.SMInterfaceExtendAB.class;
419         doKeyAnalysing(classOne, classTwo);
420     }
421
422     /**
423      * Tests if the generated id's are unique across extents.
424      */

425     public void testUniqueAcrossExtendsWithSameTable1() throws Exception JavaDoc
426     {
427         Class JavaDoc classOne = Repository.SMSameTableAA.class;
428         Class JavaDoc classTwo = Repository.SMSameTableBB.class;
429         doKeyAnalysing(classOne, classTwo);
430     }
431
432     /**
433      * Tests if the generated id's are unique across extents.
434      */

435     public void testUniqueAcrossExtendsWithSameTable3() throws Exception JavaDoc
436     {
437         Class JavaDoc classOne = Repository.SMSameTableA.class;
438         Class JavaDoc classTwo = Repository.SMSameTableB.class;
439         doKeyAnalysing(classOne, classTwo);
440     }
441
442     /**
443      * Tests if the generated id's are unique across extents.
444      */

445     public void testUniqueAcrossExtendsWithSameTable4() throws Exception JavaDoc
446     {
447         Class JavaDoc classOne = ObjectRepository.A.class;
448         Class JavaDoc classTwo = ObjectRepository.B.class;
449         doKeyAnalysing(classOne, classTwo);
450     }
451
452     /**
453      * Tests if the generated id's are unique across extents.
454      */

455     public void testUniqueAcrossExtendsWithSameTable5() throws Exception JavaDoc
456     {
457         Class JavaDoc classOne = ObjectRepository.B1.class;
458         Class JavaDoc classTwo = ObjectRepository.C.class;
459         doKeyAnalysing(classOne, classTwo);
460     }
461
462     private void doKeyAnalysing(Class JavaDoc classOne, Class JavaDoc classTwo) throws SequenceManagerException
463     {
464         PersistenceBroker broker = PersistenceBrokerFactory.defaultPersistenceBroker();
465         FieldDescriptor fieldOne = broker.getClassDescriptor(classOne).getAutoIncrementFields()[0];
466         FieldDescriptor fieldTwo = broker.getClassDescriptor(classOne).getAutoIncrementFields()[0];
467
468         List JavaDoc listOne = createKeyList(broker, fieldOne, numberOfKeys);
469         List JavaDoc listTwo = createKeyList(broker, fieldTwo, numberOfKeys);
470         for (int i = 0; i < listOne.size(); i++)
471         {
472             if (listTwo.contains(listOne.get(i)))
473             {
474                 fail("\nFound double generated key " + listOne.get(i) +
475                         " when generate keys for \n" + classOne + " with autoincrement field " + fieldOne +
476                         " and \n" + classTwo + " with autoincrement field " + fieldTwo);
477             }
478         }
479         broker.close();
480     }
481
482     private List JavaDoc createKeyList(PersistenceBroker broker, FieldDescriptor field, int number)
483             throws SequenceManagerException
484     {
485         SequenceManager sm = SequenceManagerFactory.getSequenceManager(broker);
486         List JavaDoc resultList = new ArrayList JavaDoc();
487         int result;
488         for (int i = 0; i < number; i++)
489         {
490             Integer JavaDoc val = (Integer JavaDoc) sm.getUniqueValue(field);
491             result = val.intValue();
492             resultList.add(new Integer JavaDoc(result));
493         }
494         return resultList;
495     }
496
497     /**
498      * test case written by a user
499      */

500     public void testGetUniqueIdWithOneBroker() throws Exception JavaDoc
501     {
502         PersistenceBroker pb = PersistenceBrokerFactory.defaultPersistenceBroker();
503         FieldDescriptor field = pb.getClassDescriptor(targetClass).getAutoIncrementFields()[0];
504         Integer JavaDoc val = (Integer JavaDoc) pb.serviceSequenceManager().getUniqueValue(field);
505         int id1 = val.intValue();
506         val = (Integer JavaDoc) pb.serviceSequenceManager().getUniqueValue(field);
507         int id2 = val.intValue();
508         assertTrue(id1 != id2);
509         assertTrue(id2 > id1);
510         assertTrue("If the sequence manger implementation does not support continuous key generation" +
511                 " per PB instance, you could ignore this failure", (id2 - id1) == 1);
512     }
513
514     /**
515      * Tests the generation of unique sequence numbers
516      * in multi-threaded environment.
517      */

518     public void testSequenceGeneration()
519     {
520         long time = System.currentTimeMillis();
521         generateKeys();
522         time = System.currentTimeMillis() - time;
523         System.out.println(this.getClass().getName() + ": " + time + " (ms) time for key generating");
524         analyseUniqueness(generatedKeys);
525     }
526
527     /**
528      * Tests to detect the lost of sequence numbers
529      * in multi-threaded environments.
530      */

531     public void testForLostKeys()
532     {
533         generateKeys();
534         TreeSet JavaDoc set = new TreeSet JavaDoc((List JavaDoc) generatedKeys.clone());
535         if (set.isEmpty()) fail("No generated keys found");
536         int result = ((Integer JavaDoc) set.last()).intValue() - ((Integer JavaDoc) set.first()).intValue() + 1;
537         assertEquals("Sequence manager lost sequence numbers, this could be a failure or could be" +
538                 " the volitional behaviour of the sequence manager" +
539                 " - retry test case, check test case, check sequence manager implementation.", keyCount, result);
540     }
541
542     /**
543      * Test for unique **continuous** key generation
544      * across different PB instances.
545      *
546      * test case was written by a user - thanks.
547      * this test was *commented out* by default, because
548      * not all sequence manager implementations generate continuous keys
549      * across different PB instances.
550      */

551     public void YYYtest_getUniqueIdWithTwoBrokers() throws Exception JavaDoc
552     {
553         PersistenceBroker pb = PersistenceBrokerFactory.defaultPersistenceBroker();
554         PersistenceBroker pb2 = PersistenceBrokerFactory.defaultPersistenceBroker();
555         FieldDescriptor field = pb.getClassDescriptor(targetClass).getAutoIncrementFields()[0];
556
557         Integer JavaDoc val = (Integer JavaDoc) pb.serviceSequenceManager().getUniqueValue(field);
558         int id1 = val.intValue();
559
560         val = (Integer JavaDoc) pb2.serviceSequenceManager().getUniqueValue(field);
561         int id2 = val.intValue();
562
563         assertTrue(id1 != id2);
564         assertTrue(id2 > id1);
565         assertTrue((id2 - id1) == 1);
566
567         val = (Integer JavaDoc) pb2.serviceSequenceManager().getUniqueValue(field);
568         id1 = val.intValue();
569
570         val = (Integer JavaDoc) pb.serviceSequenceManager().getUniqueValue(field);
571         id2 = val.intValue();
572
573         assertTrue(id1 != id2);
574         assertTrue(id2 > id1);
575         assertTrue((id2 - id1) == 1);
576
577         val = (Integer JavaDoc) pb.serviceSequenceManager().getUniqueValue(field);
578         id1 = val.intValue();
579
580         val = (Integer JavaDoc) pb2.serviceSequenceManager().getUniqueValue(field);
581         id2 = val.intValue();
582
583
584         assertTrue(id1 != id2);
585         assertTrue(id2 > id1);
586         assertTrue((id2 - id1) == 1);
587     }
588
589     /**
590      * Test case for internal use while developing!
591      * Was commented out by default!
592      */

593     public void YYYtestSequenceManagerStoredProcedureImpl() throws Exception JavaDoc
594     {
595         JdbcConnectionDescriptor jcd = MetadataManager.getInstance().connectionRepository().
596                 getDescriptor(PersistenceBrokerFactory.getDefaultKey());
597         SequenceDescriptor old_sd = (SequenceDescriptor) SerializationUtils.clone(jcd.getSequenceDescriptor());
598         PersistenceBroker broker;
599         try
600         {
601             jcd.setSequenceDescriptor(new SequenceDescriptor(jcd, SequenceManagerStoredProcedureImpl.class));
602             PersistenceBrokerFactory.releaseAllInstances();
603             broker = PersistenceBrokerFactory.defaultPersistenceBroker();
604             SequenceManager sm = broker.serviceSequenceManager();
605             if (!(sm instanceof SequenceManagerStoredProcedureImpl))
606             {
607                 fail("testSM_StoredProcedure: Expected sequence manager implemenation was " +
608                         SequenceManagerStoredProcedureImpl.class.getName());
609                 return;
610             }
611             // now we start the tests
612
FieldDescriptor field = broker.getClassDescriptor(targetClass).getAutoIncrementFields()[0];
613             sm.getUniqueValue(field);
614
615             generatedKeys.clear();
616 // comment in
617
// testSequenceGeneration();
618
// testMultipleAutoincrement();
619
// testSequenceNameAttribute();
620
broker.close();
621         }
622         finally
623         {
624             if (old_sd != null)
625             {
626
627                 PersistenceBrokerFactory.releaseAllInstances();
628                 jcd.setSequenceDescriptor(old_sd);
629             }
630         }
631     }
632
633     private void generateKeys()
634     {
635         // we generate the keys only once
636
if (generatedKeys != null && generatedKeys.size() > 1) return;
637
638         prepareKeyGeneration();
639         
640         System.out.println(
641                 this.getClass().getName() + ":\n" + instances + " threads generating " +
642                 loops + " keys per thread,\nusing target class " + targetClass);
643         keyCount = 0;
644         for (int i = 0; i < instances; i++)
645         {
646             SequenceManagerHandle handle = new SequenceManagerHandle(
647                     brokers[i], targetClass, loops);
648             new Thread JavaDoc(threadGroup, handle).start();
649         }
650         while (threadGroup.activeCount() > 0)
651         {
652             try
653             {
654                 Thread.sleep(300);
655                 //System.out.print(".");
656
}
657             catch (InterruptedException JavaDoc e)
658             {
659             }
660         }
661
662         cleanupKeyGeneration();
663
664         System.out.println("Generated keys: " + (generatedKeys != null ? "" + generatedKeys.size() : "no keys generated"));
665     }
666
667     private void cleanupKeyGeneration()
668     {
669         if (brokers != null)
670         {
671             for (int i = 0; i < instances; i++)
672             {
673                 brokers[i].close();
674             }
675         }
676         threadGroup = null;
677         brokers = null;
678     }
679
680     private void prepareKeyGeneration()
681     {
682         if (generatedKeys == null) generatedKeys = new ArrayList JavaDoc();
683         PersistenceBroker broker = PersistenceBrokerFactory.defaultPersistenceBroker();
684         SequenceManager sm = broker.serviceSequenceManager();
685         int seqGrabSize = 0;
686         // we need the SM grab size
687
if (sm instanceof SequenceManagerSeqHiLoImpl || sm instanceof SequenceManagerHighLowImpl)
688         {
689             SequenceDescriptor sd = broker.serviceConnectionManager().getConnectionDescriptor().getSequenceDescriptor();
690             String JavaDoc strSize = sd.getAttribute(SequenceManagerHighLowImpl.PROPERTY_GRAB_SIZE);
691             if (strSize != null)
692             {
693                 seqGrabSize = new Integer JavaDoc(strSize).intValue();
694             }
695         }
696         broker.close();
697
698         // the grab size have to be a factor of the loops number
699
// to pass the 'testForLostKeys' test because we
700
if (loops < seqGrabSize) loops = seqGrabSize;
701         if (seqGrabSize != 0) loops = (loops / seqGrabSize) * seqGrabSize;
702
703         brokers = new PersistenceBroker[instances];
704         for (int i = 0; i < instances; i++)
705         {
706             brokers[i] = PersistenceBrokerFactory.defaultPersistenceBroker();
707         }
708         threadGroup = new ThreadGroup JavaDoc("sequenceManagerTG");
709     }
710
711     private void analyseUniqueness(ArrayList JavaDoc results)
712     {
713         System.out.println(this.getClass().getName() + ": Analyse generated keys");
714         TreeSet JavaDoc set = new TreeSet JavaDoc();
715         //only to test the test
716
//set.add(new Integer(41001));
717
Iterator JavaDoc it = ((List JavaDoc) results.clone()).iterator();
718         Integer JavaDoc key;
719         while (it.hasNext())
720         {
721             key = (Integer JavaDoc) it.next();
722             if (set.contains(key))
723             {
724                 fail("Found double generated key: " + key +
725                         ". Check the used SequenceManager implementation");
726             }
727             set.add(key);
728         }
729         System.out.println(this.getClass().getName() + ": Last generated key was " +
730                 ((set.size() > 0) ? set.last() : " no generated keys found"));
731         set.clear();
732     }
733
734     protected static synchronized void addResultList(List JavaDoc resultList)
735     {
736         System.out.println(" add " + resultList.size() + "generated Keys");
737         if (resultList == null) return;
738         generatedKeys.addAll(resultList);
739     }
740
741     protected static synchronized void countKey()
742     {
743         ++keyCount;
744     }
745
746
747     public void testObjectsFromAbstractBaseClass1() throws Exception JavaDoc
748     {
749         PersistenceBroker broker = PersistenceBrokerFactory.defaultPersistenceBroker();
750         try
751         {
752             SequenceManager sm = broker.serviceSequenceManager();
753             FieldDescriptor fld_1 = broker.getClassDescriptor(SMObjectOne.class).getAutoIncrementFields()[0];
754             FieldDescriptor fld_2 = broker.getClassDescriptor(SMObjectTwo.class).getAutoIncrementFields()[0];
755
756             Object JavaDoc result_1 = sm.getUniqueValue(fld_1);
757             Object JavaDoc result_2 = sm.getUniqueValue(fld_2);
758
759             assertNotNull(result_1);
760             assertNotNull(result_2);
761             assertTrue(result_1 instanceof Integer JavaDoc);
762             assertTrue(result_2 instanceof Integer JavaDoc);
763
764             result_1 = sm.getUniqueValue(fld_1);
765             result_2 = sm.getUniqueValue(fld_2);
766
767             assertNotNull(result_1);
768             assertNotNull(result_2);
769             assertTrue(result_1 instanceof Integer JavaDoc);
770             assertTrue(result_2 instanceof Integer JavaDoc);
771
772             assertFalse("Should not have same ids", result_2.equals(result_1));
773         }
774         finally
775         {
776             if (broker != null) broker.close();
777         }
778     }
779
780     public void testObjectsFromAbstractBaseClass2() throws Exception JavaDoc
781     {
782         long stamp = System.currentTimeMillis();
783         String JavaDoc objectName_One = "testObjectsFromAbstractBaseClass2_objOne_" + stamp;
784         String JavaDoc objectName_Two = "testObjectsFromAbstractBaseClass2_objTwo_" + stamp;
785
786         PersistenceBroker broker = PersistenceBrokerFactory.defaultPersistenceBroker();
787
788         Repository.SMSameTableBB dummy1 = new Repository.SMSameTableBB();
789         Repository.SMInterfaceExtendA dummy2 = new Repository.SMInterfaceExtendA();
790
791         SMObjectOne smOne_1 = new SMObjectOne(objectName_One);
792         SMObjectOne smOne_2 = new SMObjectOne(objectName_One);
793
794         SMObjectTwo smTwo_2 = new SMObjectTwo(objectName_Two);
795         SMObjectTwo smTwo_1 = new SMObjectTwo(objectName_Two);
796         try
797         {
798             broker.beginTransaction();
799
800             broker.store(dummy1);
801             broker.store(dummy2);
802
803             broker.store(smOne_1);
804             broker.store(smOne_2);
805 // broker.clearCache();
806
broker.store(smTwo_2);
807             broker.store(smTwo_1);
808
809             broker.commitTransaction();
810
811             // now check if store was successful
812
broker.clearCache();
813
814             Criteria cr = new Criteria();
815             cr.addEqualTo("name", objectName_One);
816             Query query = new QueryByCriteria(SMObjectOne.class, cr);
817             Collection JavaDoc result = broker.getCollectionByQuery(query);
818
819             broker.clearCache();
820
821             Criteria cr_2 = new Criteria();
822             cr_2.addEqualTo("name", objectName_Two);
823             Query query_2 = new QueryByCriteria(SMObjectTwo.class, cr_2);
824             Collection JavaDoc result_2 = broker.getCollectionByQuery(query_2);
825
826             assertEquals("We have to found 2 SMObjectOne objects", 2, result.size());
827             assertEquals("We have to found 2 SMObjectTwo objects", 2, result_2.size());
828         }
829         finally
830         {
831             if (broker != null) broker.close();
832         }
833     }
834
835     public void testMassStoreOfObjects()
836     {
837         int outerLoops = 10;
838         int innerLoops = 30;
839         String JavaDoc name = "Name_" + System.currentTimeMillis();
840
841         Repository.SMKey key = null;
842         for (int i = outerLoops - 1; i >= 0; i--)
843         {
844             PersistenceBroker broker = PersistenceBrokerFactory.defaultPersistenceBroker();
845             try
846             {
847                 broker.beginTransaction();
848                 for (int j = innerLoops - 1; j >= 0; j--)
849                 {
850                     key = new Repository.SMKey();
851                     key.setName(name);
852                     broker.store(key);
853                 }
854                 broker.commitTransaction();
855             }
856             finally
857             {
858                 if(broker != null) broker.close();
859             }
860         }
861     }
862
863
864     // ******************************************************************************
865
// inner class
866
// ******************************************************************************
867
public static class AbstractSMObject implements Serializable JavaDoc
868     {
869         private Integer JavaDoc objectId;
870
871         public Integer JavaDoc getObjectId()
872         {
873             return objectId;
874         }
875
876         public void setObjectId(Integer JavaDoc objectId)
877         {
878             this.objectId = objectId;
879         }
880     }
881
882     public static class SMObjectOne extends AbstractSMObject
883     {
884         private String JavaDoc name;
885
886         public SMObjectOne()
887         {
888         }
889
890         public SMObjectOne(String JavaDoc name)
891         {
892             this.name = name;
893         }
894
895         public String JavaDoc getName()
896         {
897             return name;
898         }
899
900         public void setName(String JavaDoc name)
901         {
902             this.name = name;
903         }
904     }
905
906     public static class SMObjectTwo extends AbstractSMObject
907     {
908         private String JavaDoc name;
909
910         public SMObjectTwo()
911         {
912         }
913
914         public SMObjectTwo(String JavaDoc name)
915         {
916             this.name = name;
917         }
918
919         public String JavaDoc getName()
920         {
921             return name;
922         }
923
924         public void setName(String JavaDoc name)
925         {
926             this.name = name;
927         }
928     }
929
930     public static class SMAutoNaming extends AbstractSMObject
931     {
932         private String JavaDoc name;
933
934         public SMAutoNaming()
935         {
936         }
937
938         public SMAutoNaming(String JavaDoc name)
939         {
940             this.name = name;
941         }
942
943         public String JavaDoc getName()
944         {
945             return name;
946         }
947
948         public void setName(String JavaDoc name)
949         {
950             this.name = name;
951         }
952     }
953
954 }
955
Popular Tags