KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > ojb > broker > PersistenceBrokerTest


1 package org.apache.ojb.broker;
2
3 import java.sql.Statement JavaDoc;
4 import java.util.Collection JavaDoc;
5 import java.util.Enumeration JavaDoc;
6 import java.util.HashSet JavaDoc;
7 import java.util.Iterator JavaDoc;
8 import java.util.List JavaDoc;
9 import java.util.Set JavaDoc;
10 import java.util.Vector JavaDoc;
11
12 import org.apache.commons.lang.SerializationUtils;
13 import org.apache.commons.lang.math.NumberRange;
14 import org.apache.ojb.broker.accesslayer.OJBIterator;
15 import org.apache.ojb.broker.core.DelegatingPersistenceBroker;
16 import org.apache.ojb.broker.metadata.ClassDescriptor;
17 import org.apache.ojb.broker.query.Criteria;
18 import org.apache.ojb.broker.query.Query;
19 import org.apache.ojb.broker.query.QueryByCriteria;
20 import org.apache.ojb.broker.query.QueryByIdentity;
21 import org.apache.ojb.broker.query.QueryFactory;
22 import org.apache.ojb.broker.query.ReportQueryByCriteria;
23 import org.apache.ojb.broker.util.ObjectModification;
24 import org.apache.ojb.junit.PBTestCase;
25
26 /**
27  * Junit test driver for elematary PB tests.
28  */

29 public class PersistenceBrokerTest extends PBTestCase
30 {
31     /**
32      * BrokerTests constructor comment.
33      * @param name java.lang.String
34      */

35     public PersistenceBrokerTest(String JavaDoc name)
36     {
37         super(name);
38     }
39
40     public static void main(String JavaDoc[] args)
41     {
42         String JavaDoc[] arr = {PersistenceBrokerTest.class.getName()};
43         junit.textui.TestRunner.main(arr);
44     }
45
46     private boolean checkIdentityEquality(PersistenceBroker p1, PersistenceBroker p2)
47     {
48         return ((DelegatingPersistenceBroker) p1).getInnermostDelegate()
49                 == ((DelegatingPersistenceBroker) p2).getInnermostDelegate();
50     }
51
52     protected Article createArticle(ProductGroup group, String JavaDoc name)
53     {
54         Article a = new Article();
55         a.setArticleName(name);
56         a.setIsSelloutArticle(true);
57         a.setMinimumStock(100);
58         a.setOrderedUnits(17);
59         a.setPrice(0.45);
60         if(group != null)
61         {
62             a.setProductGroup(group);
63             group.add(a);
64         }
65         a.setStock(234);
66         a.setSupplierId(4);
67         a.setUnit("bottle");
68         return a;
69     }
70
71     protected CdArticle createCdArticle(ProductGroup group, String JavaDoc name)
72     {
73         CdArticle a = new CdArticle();
74         a.setArticleName(name);
75         a.setIsSelloutArticle(true);
76         a.setMinimumStock(100);
77         a.setOrderedUnits(17);
78         a.setPrice(9.95);
79         a.setProductGroup(group);
80         a.setStock(234);
81         a.setSupplierId(4);
82         a.setUnit("cd");
83         return a;
84     }
85
86     protected void deleteArticle(Integer JavaDoc id) throws PersistenceBrokerException
87     {
88         Article a = new Article();
89         a.setArticleId(id);
90         deleteArticle(a);
91     }
92
93     protected void deleteArticle(Article articleToDelete) throws PersistenceBrokerException
94     {
95         boolean needsCommit = false;
96         if(!broker.isInTransaction())
97         {
98             broker.beginTransaction();
99             needsCommit = true;
100         }
101         broker.delete(articleToDelete);
102         if(needsCommit)
103         {
104             broker.commitTransaction();
105         }
106     }
107
108     protected Article readArticleByExample(Integer JavaDoc id) throws PersistenceBrokerException
109     {
110
111         Article example = new Article();
112         example.setArticleId(id);
113         return (Article) broker.getObjectByQuery(QueryFactory.newQuery(example));
114
115     }
116
117     protected Article readArticleByIdentity(Article article) throws PersistenceBrokerException
118     {
119         return (Article) broker.getObjectByIdentity(broker.serviceIdentity().buildIdentity(article));
120     }
121
122     protected Article readArticleByIdentity(Integer JavaDoc id) throws PersistenceBrokerException
123     {
124         return (Article) broker.getObjectByIdentity(broker.serviceIdentity().buildIdentity(Article.class, id));
125     }
126
127     protected void storeArticle(Article anArticle) throws PersistenceBrokerException
128     {
129         boolean needsCommit = false;
130         if(!broker.isInTransaction())
131         {
132             broker.beginTransaction();
133             needsCommit = true;
134         }
135         broker.store(anArticle);
136         if(needsCommit)
137         {
138             broker.commitTransaction();
139         }
140     }
141
142      public void testReadUncommitedDataWithinSamePB() throws Exception JavaDoc
143     {
144         String JavaDoc name = "testReadUncommitedDataWithinSamePB" + System.currentTimeMillis();
145         ObjectRepository.Component comp = new ObjectRepository.Component();
146         comp.setName(name);
147
148         broker.beginTransaction();
149         // store data
150
broker.store(comp, ObjectModification.INSERT);
151         Query query = new QueryByCriteria(ObjectRepository.Component.class, null);
152         // now we try to read the uncommitted data
153
Collection JavaDoc all = broker.getCollectionByQuery(query);
154         Iterator JavaDoc iter = all.iterator();
155         ObjectRepository.Component temp;
156         boolean result = false;
157         while (iter.hasNext())
158         {
159             temp = (ObjectRepository.Component) iter.next();
160             // System.out.println(temp.getName());
161
if(name.equals(temp.getName()))
162             {
163                 result = true;
164                 break;
165             }
166         }
167         broker.commitTransaction();
168         assertTrue("Can't read uncommitted data within same PB instance", result);
169     }
170
171     /**
172      * PK fields with primitive data types interpret '0' value as
173      * 'null' by default. But if we don't use primitive data types and read
174      * an object with 0 as PK value and store such an object without
175      * changes, nothing should happen.
176      */

177     public void testNull_0_Complex() throws Exception JavaDoc
178     {
179         Class JavaDoc objClass = ObjectRepository.E.class;
180         ClassDescriptor cld = broker.getClassDescriptor(objClass);
181         Integer JavaDoc someOtherValue = new Integer JavaDoc(1111111111);
182         String JavaDoc insert = "INSERT INTO TABLE_E VALUES(0,"+someOtherValue.intValue()+")";
183         String JavaDoc delete = "DELETE FROM TABLE_E WHERE ID=0";
184         Statement JavaDoc stmt;
185         try
186         {
187             broker.beginTransaction();
188             // cleanup
189
stmt = broker.serviceStatementManager().getGenericStatement(cld, false);
190             stmt.executeUpdate(delete);
191             broker.serviceStatementManager().closeResources(stmt, null);
192             broker.commitTransaction();
193
194             broker.beginTransaction();
195             // prepare test
196
stmt = broker.serviceStatementManager().getGenericStatement(cld, false);
197             // insert object with 0 as PK
198
stmt.executeUpdate(insert);
199             broker.serviceStatementManager().closeResources(stmt, null);
200             broker.commitTransaction();
201
202             // find all objects with 'someSubValue' 111111111
203
Criteria crit = new Criteria();
204             crit.addEqualTo( "someSuperValue", someOtherValue);
205             Query queryAllSubs = new QueryByCriteria(objClass, crit );
206             Collection JavaDoc resultBefore = broker.getCollectionByQuery( queryAllSubs );
207             int matchesBefore = resultBefore.size();
208
209             // materialize object with 0 PK
210
Criteria c = new Criteria();
211             c.addEqualTo( "id", new Integer JavaDoc(0));
212             Query q = new QueryByCriteria(objClass, c );
213             ObjectRepository.E obj = (ObjectRepository.E) broker.getObjectByQuery( q );
214             // store the unchanged read object
215
broker.beginTransaction();
216             broker.store( obj );
217             broker.commitTransaction();
218
219             Collection JavaDoc resultAfter = broker.getCollectionByQuery( queryAllSubs );
220             int matchesAfter = resultAfter.size();
221
222             assertEquals("We don't store new objects, thus we expect same numbers", matchesBefore, matchesAfter);
223         }
224         finally
225         {
226             broker.beginTransaction();
227             // cleanup
228
stmt = broker.serviceStatementManager().getGenericStatement(cld, false);
229             stmt.executeUpdate(delete);
230             broker.serviceStatementManager().closeResources(stmt, null);
231             broker.commitTransaction();
232         }
233     }
234
235     /**
236      * Object with autoincrement 'true' and a NON primitive
237      * data type for the PK field. It should be allowed to set an
238      * new object with PK 0, because PK field is not primitive
239      */

240     public void testNull_0_Complex_2() throws Exception JavaDoc
241     {
242         Class JavaDoc objClass = ObjectRepository.E.class;
243         ClassDescriptor cld = broker.getClassDescriptor(objClass);
244         Integer JavaDoc someOtherValue = new Integer JavaDoc(1111111111);
245         String JavaDoc delete = "DELETE FROM TABLE_E WHERE ID=0";
246         Statement JavaDoc stmt;
247         try
248         {
249             broker.beginTransaction();
250             stmt = broker.serviceStatementManager().getGenericStatement(cld, false);
251             stmt.executeUpdate(delete);
252             broker.serviceStatementManager().closeResources(stmt, null);
253             broker.commitTransaction();
254             broker.clearCache();
255
256             // find all objects with 'someSubValue' 111111111
257
Criteria crit = new Criteria();
258             crit.addEqualTo( "someSuperValue", someOtherValue);
259             Query queryAllSubs = new QueryByCriteria(objClass, crit );
260             Collection JavaDoc resultBefore = broker.getCollectionByQuery( queryAllSubs );
261             int matchesBefore = resultBefore.size();
262
263             ObjectRepository.E obj = new ObjectRepository.E();
264             obj.setId(new Integer JavaDoc(0));
265             obj.setSomeSuperValue(someOtherValue.intValue());
266             broker.beginTransaction();
267             broker.store( obj );
268             broker.commitTransaction();
269
270             broker.clearCache();
271             Collection JavaDoc resultAfter = broker.getCollectionByQuery( queryAllSubs );
272             int matchesAfter = resultAfter.size();
273             assertEquals("We store new object, but was not written to DB", matchesBefore + 1, matchesAfter);
274             // lookup object with 0 PK
275
Criteria c = new Criteria();
276             c.addEqualTo( "id", new Integer JavaDoc(0));
277             Query q = new QueryByCriteria(objClass, c );
278             obj = (ObjectRepository.E) broker.getObjectByQuery( q );
279             assertEquals("We should found object with id 0 for PK field", new Integer JavaDoc(0), obj.getId());
280         }
281         finally
282         {
283             broker.beginTransaction();
284             // cleanup
285
stmt = broker.serviceStatementManager().getGenericStatement(cld, false);
286             stmt.executeUpdate(delete);
287             broker.serviceStatementManager().closeResources(stmt, null);
288             broker.commitTransaction();
289         }
290     }
291
292     public void testPBF() throws Exception JavaDoc
293     {
294         // we don't need this
295
broker.close();
296
297         PersistenceBroker pb_1 = PersistenceBrokerFactory.defaultPersistenceBroker();
298         pb_1.getObjectByQuery(QueryFactory.newQuery(Person.class, (Criteria) null));
299         PersistenceBroker pb_2 = PersistenceBrokerFactory.defaultPersistenceBroker();
300         pb_2.getObjectByQuery(QueryFactory.newQuery(Person.class, (Criteria) null));
301         PersistenceBroker pb_3 = PersistenceBrokerFactory.defaultPersistenceBroker();
302         pb_3.getObjectByQuery(QueryFactory.newQuery(Person.class, (Criteria) null));
303         pb_1.close();
304         pb_2.close();
305         pb_3.close();
306         PersistenceBrokerFactory.releaseAllInstances();
307         PersistenceBroker pbNew = PersistenceBrokerFactory.defaultPersistenceBroker();
308         if(pbNew instanceof DelegatingPersistenceBroker)
309         {
310             if(checkIdentityEquality(pbNew, pb_1)
311                     || checkIdentityEquality(pbNew, pb_2)
312                     || checkIdentityEquality(pbNew, pb_3))
313             {
314                 fail("Reuse of released PB instance");
315             }
316         }
317         assertFalse(pbNew.isClosed());
318         assertFalse(pbNew.isInTransaction());
319         pbNew.close();
320     }
321
322     /**
323      * test the the PB delete() method.
324      */

325     public void testDelete() throws Exception JavaDoc
326     {
327         String JavaDoc name = "testDelete_" + System.currentTimeMillis();
328         Article a = createArticle(null, name);
329         storeArticle(a);
330         broker.clearCache();
331         Article b = readArticleByIdentity(a);
332         assertEquals(
333                 "after inserting an object it should be equal to its re-read pendant",
334                 a.getArticleName(),
335                 b.getArticleName());
336         deleteArticle(b);
337         b = readArticleByIdentity(a);
338         assertNull("should be null after deletion", b);
339         b = readArticleByExample(a.getArticleId());
340         assertNull("should be null after deletion", b);
341     }
342
343     public void testPBisClosed()
344     {
345         PersistenceBroker pb = PersistenceBrokerFactory.defaultPersistenceBroker();
346
347         assertFalse(pb.isClosed());
348         pb.beginTransaction();
349         assertTrue(pb.isInTransaction());
350         pb.commitTransaction();
351         assertFalse(pb.isInTransaction());
352
353         pb.beginTransaction();
354         assertTrue(pb.isInTransaction());
355         pb.abortTransaction();
356         assertFalse(pb.isInTransaction());
357
358         pb.close();
359         assertTrue(pb.isClosed());
360         assertFalse(pb.isInTransaction());
361         try
362         {
363             pb.beginTransaction();
364             fail("We expect an exception, but was not thrown");
365         }
366         catch (Exception JavaDoc e)
367         {
368             assertTrue(true);
369         }
370     }
371
372     public void testLocalTransactionDemarcation()
373     {
374         PersistenceBroker pb = PersistenceBrokerFactory.defaultPersistenceBroker();
375
376         try
377         {
378             pb.beginTransaction();
379             pb.commitTransaction();
380             pb.close();
381
382             pb = PersistenceBrokerFactory.defaultPersistenceBroker();
383             pb.beginTransaction();
384             pb.abortTransaction();
385             pb.abortTransaction();
386             pb.close();
387
388             pb = PersistenceBrokerFactory.defaultPersistenceBroker();
389             pb.beginTransaction();
390             pb.commitTransaction();
391             pb.abortTransaction();
392             pb.close();
393
394             pb = PersistenceBrokerFactory.defaultPersistenceBroker();
395             try
396             {
397                 pb.commitTransaction();
398                 fail("Commit tx without begin shouldn't be possible");
399             }
400             catch(TransactionNotInProgressException e)
401             {
402                 assertTrue(true);
403             }
404
405             try
406             {
407                 pb.beginTransaction();
408                 Query q = QueryFactory.newQuery(Article.class, "Select * from NOT_EXIST");
409                 pb.getObjectByQuery(q);
410                 pb.commitTransaction();
411                 fail("Query should fail");
412             }
413             catch(PersistenceBrokerException e)
414             {
415                 pb.abortTransaction();
416                 assertTrue(true);
417             }
418             finally
419             {
420                 pb.close();
421             }
422         }
423         finally
424         {
425             if(pb != null) pb.close();
426         }
427     }
428
429     /**
430      * test the the PB deleteByQuery() method.
431      */

432     public void testDeleteByQuery() throws Exception JavaDoc
433     {
434         String JavaDoc name = "Funny_testDelete_" + System.currentTimeMillis();
435         ProductGroup pg;
436         pg = new ProductGroup();
437         pg.setGroupName(name);
438
439         broker.beginTransaction();
440         broker.store(pg);
441         broker.commitTransaction();
442
443         Article a = createArticle(pg, name);
444         Article b = createArticle(pg, name);
445         CdArticle c = createCdArticle(pg, name);
446
447         storeArticle(a);
448         storeArticle(b);
449         storeArticle(c);
450
451         broker.clearCache();
452
453         Criteria crit = new Criteria();
454         crit.addEqualTo("productGroupId", pg.getId());
455         crit.addLike("articleName", "%Funny%");
456         Query q = new QueryByCriteria(Article.class, crit);
457
458         // 1. check for matching items
459
broker.clearCache();
460         Collection JavaDoc col = broker.getCollectionByQuery(q);
461         assertEquals("There should be 3 matching items", 3, col.size());
462
463         // 2. perform delete by query
464
broker.deleteByQuery(q);
465
466         // 3. recheck for matching elements
467
col = broker.getCollectionByQuery(q);
468         assertEquals("there should be no more matching items", 0, col.size());
469     }
470
471
472     /**
473      * performs a test of the inheritance mapping to one table.
474      */

475     public void testMappingToOneTableWithAbstractBaseClass()
476     {
477         // first delete all ABs from database
478
Collection JavaDoc abs = null;
479         Criteria c = null;
480         Query q = QueryFactory.newQuery(ObjectRepository.AB.class, c);
481         abs = broker.getCollectionByQuery(q);
482         broker.beginTransaction();
483         if (abs != null)
484         {
485             Iterator JavaDoc iter = abs.iterator();
486             while (iter.hasNext())
487             {
488                 broker.delete(iter.next());
489             }
490         }
491         broker.commitTransaction();
492
493         // Insert 2 A, 1 B and 1 B1
494
ObjectRepository.A a1 = new ObjectRepository.A();
495         a1.setSomeAField("a A_Field value");
496         ObjectRepository.A a2 = new ObjectRepository.A();
497         a1.setSomeAField("another A_Field value");
498
499         ObjectRepository.B b1 = new ObjectRepository.B();
500         b1.setSomeBField("a B_Field value");
501         ObjectRepository.B1 b2 = new ObjectRepository.B1();
502
503         broker.beginTransaction();
504         broker.store(a1);
505         broker.store(a2);
506         broker.store(b1);
507         broker.store(b2);
508         broker.commitTransaction();
509
510         ObjectRepository.AB ab = null;
511
512         // test retrieval by Identity
513
Criteria crit = new Criteria();
514         crit.addEqualTo("id", new Integer JavaDoc(a1.getId()));
515         q = QueryFactory.newQuery(ObjectRepository.AB.class, crit);
516         ab = (ObjectRepository.AB) broker.getObjectByQuery(q);
517
518         assertEquals(ObjectRepository.A.class.getName(), ab.getOjbConcreteClass());
519         assertEquals(ObjectRepository.A.class, ab.getClass());
520
521         crit = new Criteria();
522         crit.addEqualTo("id", new Integer JavaDoc(b1.getId()));
523         q = QueryFactory.newQuery(ObjectRepository.AB.class, crit);
524         ab = (ObjectRepository.AB) broker.getObjectByQuery(q);
525
526         assertEquals(ObjectRepository.B.class.getName(), ab.getOjbConcreteClass());
527         assertEquals(ObjectRepository.B.class, ab.getClass());
528
529         // test retrieval of collections
530
abs = null;
531         Criteria selectAll = null;
532         q = QueryFactory.newQuery(ObjectRepository.AB.class, selectAll);
533         abs = broker.getCollectionByQuery(q);
534         assertEquals("collection size", 4, abs.size());
535         assertEquals("counted size", 4, broker.getCount(q));
536
537         q = QueryFactory.newQuery(ObjectRepository.A.class, selectAll);
538         abs = broker.getCollectionByQuery(q);
539         assertEquals("collection size", 2, abs.size());
540         assertEquals("counted size", 2, broker.getCount(q));
541
542         q = QueryFactory.newQuery(ObjectRepository.B.class, selectAll);
543         abs = broker.getCollectionByQuery(q);
544         assertEquals("collection size", 2, abs.size());
545         assertEquals("counted size", 2, broker.getCount(q));
546     }
547
548     /**
549      * performs a test of an extent with one concrete class that uses
550      * ojbConcreteClass identifier.
551      */

552     public void testExtentWithOneConcreteClassWithOjbConcreteClass() throws Exception JavaDoc
553     {
554         // first delete all ObjectRepository.ABs from database
555
Collection JavaDoc as = null;
556         Criteria c = null;
557         Query q = QueryFactory.newQuery(ObjectRepository.AB.class, c);
558         as = broker.getCollectionByQuery(q);
559         broker.beginTransaction();
560         if (as != null)
561         {
562             Iterator JavaDoc iter = as.iterator();
563             while (iter.hasNext())
564             {
565                 broker.delete(iter.next());
566             }
567         }
568         broker.commitTransaction();
569
570         // Insert 2 ObjectRepository.A
571
ObjectRepository.A a1 = new ObjectRepository.A();
572         ObjectRepository.A a2 = new ObjectRepository.A();
573
574         broker.beginTransaction();
575         broker.store(a1);
576         broker.store(a2);
577         broker.commitTransaction();
578
579         Criteria selectAll = null;
580
581         q = QueryFactory.newQuery(ObjectRepository.AAlone.class, selectAll);
582         as = broker.getCollectionByQuery(q);
583         assertEquals("collection size", 2, as.size());
584         assertEquals("counted size", 2, broker.getCount(q));
585     }
586
587     /**
588      * performs a test of the inheritance mapping to one table.
589      */

590     public void testMappingToOneTable() throws Exception JavaDoc
591     {
592         // first delete all Cs from database
593
Collection JavaDoc cs = null;
594         Criteria crit = null;
595         Query q = QueryFactory.newQuery(ObjectRepository.C.class, crit);
596         cs = broker.getCollectionByQuery(q);
597         broker.beginTransaction();
598         if (cs != null)
599         {
600             Iterator JavaDoc iter = cs.iterator();
601             while (iter.hasNext())
602             {
603                 broker.delete(iter.next());
604             }
605         }
606         broker.commitTransaction();
607
608         ObjectRepository.C c1 = new ObjectRepository.C();
609         ObjectRepository.C c2 = new ObjectRepository.C();
610         ObjectRepository.D d1 = new ObjectRepository.D();
611
612         broker.beginTransaction();
613         broker.store(c1);
614         broker.store(c2);
615         broker.store(d1);
616         broker.commitTransaction();
617
618         ObjectRepository.C candidate = null;
619
620         // test retrieval by Identity
621
crit = new Criteria();
622         crit.addEqualTo("id", new Integer JavaDoc(c1.getId()));
623         q = QueryFactory.newQuery(ObjectRepository.C.class, crit);
624         candidate = (ObjectRepository.C) broker.getObjectByQuery(q);
625
626         assertEquals(ObjectRepository.C.class.getName(), candidate.getOjbConcreteClass());
627         assertEquals(ObjectRepository.C.class, candidate.getClass());
628
629         crit = new Criteria();
630         crit.addEqualTo("id", new Integer JavaDoc(d1.getId()));
631         q = QueryFactory.newQuery(ObjectRepository.C.class, crit);
632         candidate = (ObjectRepository.C) broker.getObjectByQuery(q);
633         assertEquals(ObjectRepository.D.class.getName(), candidate.getOjbConcreteClass());
634         assertEquals(ObjectRepository.D.class, candidate.getClass());
635
636         crit = new Criteria();
637         crit.addEqualTo("id", new Integer JavaDoc(d1.getId()));
638         q = QueryFactory.newQuery(ObjectRepository.D.class, crit);
639         candidate = (ObjectRepository.D) broker.getObjectByQuery(q);
640         assertEquals(ObjectRepository.D.class.getName(), candidate.getOjbConcreteClass());
641         assertEquals(ObjectRepository.D.class, candidate.getClass());
642
643         // test retrieval of collections
644
cs = null;
645         Criteria selectAll = null;
646         q = QueryFactory.newQuery(ObjectRepository.C.class, selectAll);
647         cs = broker.getCollectionByQuery(q);
648         assertEquals("collection size", 3, cs.size());
649         assertEquals("counted size", 3, broker.getCount(q));
650
651         q = QueryFactory.newQuery(ObjectRepository.D.class, selectAll);
652         cs = broker.getCollectionByQuery(q);
653         assertEquals("collection size", 1, cs.size());
654         assertEquals("counted size", 1, broker.getCount(q));
655     }
656
657     /**
658      * performs a test to check if metadata can be read
659      */

660     public void testGetDescriptor() throws Exception JavaDoc
661     {
662         ClassDescriptor cld = broker.getClassDescriptor(Article.class);
663         assertNotNull("classdescriptor should not be null", cld);
664     }
665
666     /**
667      * tests the FieldConversion facility
668      */

669     public void testGuidFieldConversion()
670     {
671         GuidTestEntity gte = new GuidTestEntity();
672         broker.beginTransaction();
673         broker.store(gte);
674         broker.commitTransaction();
675         broker.clearCache();
676
677         GuidTestEntity gte1 = (GuidTestEntity) broker.getObjectByIdentity(new Identity(gte, broker));
678
679         assertEquals(gte, gte1);
680     }
681
682     /**
683      * tests the RowReader mechanism
684      */

685     public void testRowReader()
686     {
687         String JavaDoc name = "testRowReader_" + System.currentTimeMillis();
688         // a little hack, both classes use the same table, so it's possible
689
// to insert Article but read ArticleWithStockDetail
690
Article a = createArticle(null, name);
691         storeArticle(a);
692         Criteria crit = new Criteria();
693         crit.addEqualTo("articleId", a.getArticleId());
694         Query q = QueryFactory.newQuery(ArticleWithStockDetail.class, crit);
695
696         broker.clearCache();
697         ArticleWithStockDetail b = (ArticleWithStockDetail) broker.getObjectByQuery(q);
698         StockDetail detail = b.getDetail();
699         assertNotNull("detail should be loaded by RowReader !", detail);
700         assertEquals(a.getMinimumStock(), detail.getMinimumStock());
701         assertEquals(a.getOrderedUnits(), detail.getOrderedUnits());
702     }
703
704     public void testEscaping() throws Exception JavaDoc
705     {
706         String JavaDoc name = "testEscaping_" + System.currentTimeMillis();
707         Article a = createArticle(null, name);
708         Article b = readArticleByIdentity(a);
709         assertNull("should be null after deletion", b);
710         a.setArticleName("Single quote 'article_" +name);
711         storeArticle(a);
712         broker.clearCache();
713         b = readArticleByIdentity(a);
714         assertEquals(
715                 "after inserting an object it should be equal to its re-read pendant",
716                 a.getArticleName(),
717                 b.getArticleName());
718
719         Collection JavaDoc col;
720         Iterator JavaDoc iter;
721         String JavaDoc aName = a.getArticleName();
722         Criteria criteria = new Criteria();
723         criteria.addEqualTo("articleName", aName);
724         Query query = QueryFactory.newQuery(InterfaceArticle.class, criteria);
725         col = broker.getCollectionByQuery(query);
726         iter = col.iterator();
727         assertTrue("should have one element", iter.hasNext());
728         assertEquals("should be equal", aName, ((InterfaceArticle) iter.next()).getArticleName());
729         assertFalse(iter.hasNext());
730
731         a.setArticleName("2 Single quotes 'article'_" + name);
732         storeArticle(a);
733         broker.clearCache();
734         b = readArticleByIdentity(a);
735         assertEquals(
736                 "after inserting an object it should be equal to its re-read pendant",
737                 a.getArticleName(),
738                 b.getArticleName());
739         aName = a.getArticleName();
740         criteria = new Criteria();
741         criteria.addEqualTo("articleName", aName);
742         query = QueryFactory.newQuery(Article.class, criteria);
743         col = broker.getCollectionByQuery(query);
744         iter = col.iterator();
745         assertTrue("should have one element", iter.hasNext());
746         assertEquals("should be equal", aName, ((InterfaceArticle) iter.next()).getArticleName());
747         assertFalse(iter.hasNext());
748
749         a.setArticleName("double quote \"article_" + name);
750         storeArticle(a);
751         broker.clearCache();
752         b = readArticleByIdentity(a);
753         assertEquals(
754                 "after inserting an object it should be equal to its re-read pendant",
755                 a.getArticleName(),
756                 b.getArticleName());
757         aName = a.getArticleName();
758         criteria = new Criteria();
759         criteria.addEqualTo("articleName", aName);
760         query = QueryFactory.newQuery(Article.class, criteria);
761         col = broker.getCollectionByQuery(query);
762         iter = col.iterator();
763         assertTrue("should have one element", iter.hasNext());
764         assertEquals("should be equal", aName, ((InterfaceArticle) iter.next()).getArticleName());
765         //
766
a.setArticleName("2 double quotes \"article\"_"+name);
767         storeArticle(a);
768         broker.clearCache();
769         b = readArticleByIdentity(a);
770         assertEquals(
771                 "after inserting an object it should be equal to its re-read pendant",
772                 a.getArticleName(),
773                 b.getArticleName());
774         aName = a.getArticleName();
775         criteria = new Criteria();
776         criteria.addEqualTo("articleName", aName);
777         query = QueryFactory.newQuery(Article.class, criteria);
778         col = broker.getCollectionByQuery(query);
779         iter = col.iterator();
780         assertTrue("should have one element", iter.hasNext());
781         assertEquals("should be equal", aName, ((InterfaceArticle) iter.next()).getArticleName());
782         //
783
a.setArticleName("a comma thing ,article,_" + name);
784         storeArticle(a);
785         broker.clearCache();
786         b = readArticleByIdentity(a);
787         assertEquals(
788                 "after inserting an object it should be equal to its re-read pendant",
789                 a.getArticleName(),
790                 b.getArticleName());
791         aName = a.getArticleName();
792         criteria = new Criteria();
793         criteria.addEqualTo("articleName", aName);
794         query = QueryFactory.newQuery(Article.class, criteria);
795         col = broker.getCollectionByQuery(query);
796         iter = col.iterator();
797         assertTrue("should have one element", iter.hasNext());
798         assertEquals("should be equal", aName, ((InterfaceArticle) iter.next()).getArticleName());
799     }
800
801     public void testGetByExampleAndGetByIdentity() throws Exception JavaDoc
802     {
803         String JavaDoc name = "testGetByExampleAndGetByIdentity_" + System.currentTimeMillis();
804         Article a = createArticle(null, name);
805         storeArticle(a);
806         broker.clearCache();
807         Article b = readArticleByIdentity(a);
808         assertEquals(
809                 "after inserting an object it should be equal to its re-read pendant",
810                 a.getArticleName(),
811                 b.getArticleName());
812         broker.clearCache();
813         Article c = readArticleByExample(a.getArticleId());
814         assertEquals(
815                 "after inserting an object it should be equal to its re-read pendant",
816                 a.getArticleName(),
817                 c.getArticleName());
818     }
819
820     /**
821      * Insert the method's description here.
822      * Creation date: (06.12.2000 21:51:22)
823      */

824     public void testGetCollectionByQuery() throws Exception JavaDoc
825     {
826         String JavaDoc name = "testGetCollectionByQuery_" + System.currentTimeMillis();
827
828         Criteria criteria = new Criteria();
829         criteria.addEqualTo("articleName", name);
830         Query query = QueryFactory.newQuery(Article.class, criteria);
831         Collection JavaDoc col = broker.getCollectionByQuery(query);
832         assertEquals("size of collection should be zero", 0, col.size());
833         //2. insert 3 matching items
834
Article a1 = createArticle(null, name);
835         broker.beginTransaction();
836         broker.store(a1);
837         Article a2 = createArticle(null, name);
838         broker.store(a2);
839         Article a3 = createArticle(null, name);
840         broker.store(a3);
841         broker.commitTransaction();
842
843         // 3. check if all items are found
844
broker.clearCache();
845         col = broker.getCollectionByQuery(query);
846         assertEquals("size of collection should be three", 3, col.size());
847
848         assertEquals("size of count should be three", 3, broker.getCount(query));
849
850         Iterator JavaDoc iter = col.iterator();
851         while (iter.hasNext())
852         {
853             assertEquals("should be same value", name, ((InterfaceArticle) iter.next()).getArticleName());
854         }
855     }
856
857     public void testGetCollectionByQueryWithStartAndEnd() throws Exception JavaDoc
858     {
859         String JavaDoc name = "testGetCollectionByQueryWithStartAndEnd_" + System.currentTimeMillis();
860         Criteria criteria = new Criteria();
861         criteria.addEqualTo("articleName", name);
862         // criteria.addEqualTo("isSelloutArticle", new Boolean(true));
863
Query query = QueryFactory.newQuery(Article.class, criteria);
864         Collection JavaDoc col = broker.getCollectionByQuery(query);
865         assertEquals("size of collection should be zero", 0, col.size());
866         //2. insert 5 matching items
867
broker.beginTransaction();
868         Article a1 = createArticle(null, name);
869         broker.store(a1);
870         Article a2 = createArticle(null, name);
871         broker.store(a2);
872         Article a3 = createArticle(null, name);
873         broker.store(a3);
874         Article a4 = createArticle(null, name);
875         broker.store(a4);
876         Article a5 = createArticle(null, name);
877         broker.store(a5);
878         broker.commitTransaction();
879
880         broker.clearCache();
881         // 3. set query start and end
882
query.setStartAtIndex(2);
883         query.setEndAtIndex(5);
884
885         // 4. check if all items are found
886
col = broker.getCollectionByQuery(query);
887         assertEquals("size of collection should be four", 4, col.size());
888
889         NumberRange range = new NumberRange(a1.getArticleId(), a5.getArticleId());
890         Iterator JavaDoc iter = col.iterator();
891         while (iter.hasNext())
892         {
893             InterfaceArticle testIa = (InterfaceArticle) iter.next();
894             assertEquals("should be same value", name, testIa.getArticleName());
895             Integer JavaDoc id = testIa.getArticleId();
896             assertTrue("Id should be a number of the generated articles", range.containsInteger(id));
897         }
898
899         // read one item only
900
// 1. set query start equals end
901
query.setStartAtIndex(4);
902         query.setEndAtIndex(4);
903
904         // 2. check if only one item is found
905
OJBIterator ojbIter = (OJBIterator)broker.getIteratorByQuery(query);
906         assertEquals("size of iterator should be one", 1, ojbIter.size());
907         InterfaceArticle test4 = (InterfaceArticle) ojbIter.next();
908         ojbIter.releaseDbResources();
909         assertTrue("Id should be a number of the generated articles", range.containsInteger(test4.getArticleId()));
910     }
911
912     public void testSorting() throws Exception JavaDoc
913     {
914         String JavaDoc name = "testSorting_" + System.currentTimeMillis();
915         Criteria criteria = new Criteria();
916         criteria.addEqualTo("articleName", name);
917         QueryByCriteria query = QueryFactory.newQuery(Article.class, criteria);
918         query.addOrderByDescending("articleId");
919         Collection JavaDoc col = broker.getCollectionByQuery(query);
920         assertEquals("size of collection should be zero", 0, col.size());
921
922         //2. insert 3 matching items
923
broker.beginTransaction();
924         Article a1 = createArticle(null, name);
925         broker.store(a1);
926         Article a2 = createArticle(null, name);
927         broker.store(a2);
928         Article a3 = createArticle(null, name);
929         broker.store(a3);
930         broker.commitTransaction();
931         // 3. check if all items are found
932
col = broker.getCollectionByQuery(query);
933         assertEquals("size of collection should be three", 3, col.size());
934         Iterator JavaDoc iter = col.iterator();
935
936         assertEquals("should be same value", a3.getArticleId(), ((InterfaceArticle) iter.next()).getArticleId());
937         assertEquals("should be same value", a2.getArticleId(), ((InterfaceArticle) iter.next()).getArticleId());
938         assertEquals("should be same value", a1.getArticleId(), ((InterfaceArticle) iter.next()).getArticleId());
939     }
940
941     /**
942      * testing the sorted collections feature.)
943      */

944     public void testSortedCollectionAttribute()
945     {
946         String JavaDoc name = "testSortedCollectionAttribute_" + System.currentTimeMillis();
947         ProductGroup samplePG = new ProductGroup();
948         Article a1_ = createArticle(samplePG, name);
949         Article a2_ = createArticle(samplePG, name);
950         Article a3_ = createArticle(samplePG, name);
951         // auto insert of referenced Article is enabled
952
// and aX_ was added to PG
953
broker.beginTransaction();
954         broker.store(samplePG);
955         broker.commitTransaction();
956         broker.clearCache();
957
958         InterfaceProductGroup pg = (InterfaceProductGroup) broker.getObjectByQuery(new QueryByIdentity(samplePG));
959         List JavaDoc list = pg.getAllArticles();
960         assertNotNull(list);
961         assertEquals(3, list.size());
962         NumberRange range = new NumberRange(a1_.getArticleId(), a3_.getArticleId());
963         InterfaceArticle a1 = null;
964         InterfaceArticle a2 = null;
965         for(int i = 0; i < list.size(); i++)
966         {
967             a2 = a1;
968             a1 = (InterfaceArticle) list.get(i);
969             if(i>0) assertTrue(a1.getArticleId().intValue() < a2.getArticleId().intValue());
970             assertTrue(range.containsInteger(a1.getArticleId()));
971         }
972     }
973
974     /**
975      * Test the AutoIncrement facility
976      */

977     public void testAutoIncrement() throws Exception JavaDoc
978     {
979         // create new items for a class with autoincrement PK
980
ProductGroup pg1 = new ProductGroup();
981         // Identity id1 = new Identity(pg1, broker);
982
ProductGroup pg2 = new ProductGroup();
983         // Identity id2 = new Identity(pg2, broker);
984
pg1.setName("AutoIncGroup1");
985         pg2.setName("AutoIncGroup2");
986         broker.beginTransaction();
987         broker.store(pg1);
988         broker.store(pg2);
989         broker.commitTransaction();
990         assertEquals("should have assigned to Integers with diff 1", 1, pg2.getId().intValue() - pg1.getId().intValue());
991     }
992
993     /**
994      * do a count by report query
995      */

996     public void testCountByReportQuery() throws Exception JavaDoc
997     {
998         // 7 articles, 2 books, 3 cds
999
Criteria criteria = new Criteria();
1000        criteria.addEqualTo("productGroupId", new Integer JavaDoc(5));
1001        ReportQueryByCriteria query = QueryFactory.newReportQuery(Article.class, criteria);
1002        query.setAttributes(new String JavaDoc[]{"count(*)"});
1003        Iterator JavaDoc iter = broker.getReportQueryIteratorByQuery(query);
1004        Object JavaDoc[] row;
1005        int count = 0;
1006
1007        while (iter.hasNext())
1008        {
1009            row = (Object JavaDoc[]) iter.next();
1010            count += ((Number JavaDoc) row[0]).intValue();
1011        }
1012        assertEquals("Iterator should produce 12 items", 12, count);
1013
1014        // get count
1015
count = broker.getCount(query);
1016        assertEquals("Count should be 12", 12, count);
1017    }
1018
1019    public void testMultiKeyCount() throws Exception JavaDoc
1020    {
1021        Criteria criteria = new Criteria();
1022        QueryByCriteria query1 = QueryFactory.newQuery(Role.class, criteria);
1023        QueryByCriteria query2 = QueryFactory.newQuery(Role.class, criteria,true);
1024        
1025        int count1 = broker.getCount(query1);
1026        int count2 = broker.getCount(query2);
1027        
1028        assertEquals("count and count distinct must match", count1, count2);
1029    }
1030    
1031    /**
1032     * extent aware iterator
1033     */

1034    public void testExtentAwareIteratorByQuery() throws Exception JavaDoc
1035    {
1036        // 7 articles, 2 books, 3 cds
1037
Criteria criteria = new Criteria();
1038        criteria.addEqualTo("productGroupId", new Integer JavaDoc(5));
1039        Query query = QueryFactory.newQuery(Article.class, criteria);
1040        ReportQueryByCriteria reportQuery;
1041        Iterator JavaDoc iter = broker.getIteratorByQuery(query);
1042        Collection JavaDoc result = new Vector JavaDoc();
1043        InterfaceArticle article;
1044        int count;
1045
1046        while (iter.hasNext())
1047        {
1048            article = (InterfaceArticle) iter.next();
1049            result.add(article);
1050        }
1051        assertEquals("Iterator should produce 12 items", 12, result.size());
1052
1053        // get count
1054
count = broker.getCount(query);
1055        assertEquals("Count should be 12", 12, count);
1056
1057        reportQuery = QueryFactory.newReportQuery(Article.class, criteria);
1058        reportQuery.setAttributes(new String JavaDoc[]{"count(*)"});
1059        iter = broker.getReportQueryIteratorByQuery(reportQuery);
1060
1061        while (iter.hasNext())
1062        {
1063            result.add(iter.next());
1064        }
1065    }
1066
1067    public void testGetIteratorByQuery() throws Exception JavaDoc
1068    {
1069        String JavaDoc name = "testGetIteratorByQuery_" + System.currentTimeMillis();
1070        Criteria criteria = new Criteria();
1071        criteria.addEqualTo("articleName", name);
1072        Query query = QueryFactory.newQuery(Article.class, criteria);
1073        Iterator JavaDoc iter = broker.getIteratorByQuery(query);
1074        assertTrue("size of Iterator should be zero", !iter.hasNext());
1075        //2. insert 3 matching items
1076
broker.beginTransaction();
1077        Article a1 = createArticle(null, name);
1078        broker.store(a1);
1079        Article a2 = createArticle(null, name);
1080        broker.store(a2);
1081        Article a3 = createArticle(null, name);
1082        broker.store(a3);
1083        broker.commitTransaction();
1084
1085        // 3. check if all items are found
1086
iter = broker.getIteratorByQuery(query);
1087        int count = 0;
1088        while (iter.hasNext())
1089        {
1090            count++;
1091            assertEquals("should be same value", name, ((InterfaceArticle) iter.next()).getArticleName());
1092        }
1093        assertEquals("Iterator should produce 3 items", 3, count);
1094    }
1095
1096    /**
1097     * Testing the getIteratorBySQL functionality
1098     */

1099    public void testGetIteratorBySQL() throws Exception JavaDoc
1100    {
1101        String JavaDoc name = "testGetIteratorBySQL_" + System.currentTimeMillis();
1102        // prepare test
1103
ProductGroup pg = new ProductGroup();
1104        pg.setGroupName(name);
1105        Article a1_ = createArticle(pg, name);
1106        Article a2_ = createArticle(pg, name);
1107        Article a3_ = createArticle(pg, name);
1108        // auto insert of referenced Article is enabled
1109
// and aX_ was added to PG
1110
broker.beginTransaction();
1111        broker.store(pg);
1112        broker.commitTransaction();
1113        broker.clearCache();
1114
1115        Criteria criteria = new Criteria();
1116        criteria.addEqualTo("productGroupId", pg.getId());
1117        Query query = QueryFactory.newQuery(Article.class, criteria);
1118        Iterator JavaDoc iter1 = broker.getIteratorByQuery(query);
1119        String JavaDoc sql =
1120                "SELECT A.Artikel_Nr FROM Artikel A, Kategorien PG"
1121                + " WHERE A.Kategorie_Nr = PG.Kategorie_Nr"
1122                + " AND PG.Kategorie_Nr = " + pg.getId();
1123
1124        Query q2 = QueryFactory.newQuery(Article.class, sql);
1125        Iterator JavaDoc iter2 = broker.getIteratorByQuery(q2);
1126        while (iter1.hasNext())
1127        {
1128            InterfaceArticle a1 = (InterfaceArticle) iter1.next();
1129            InterfaceArticle a2 = (InterfaceArticle) iter2.next();
1130            assertEquals("iterators should return equal objects", a1.getArticleId(), a2.getArticleId());
1131        }
1132        assertTrue("iter2 should not contain more items than iter1", !iter2.hasNext());
1133    }
1134
1135    /**
1136     * Testing the getReportQueryIteratorBySQL functionality
1137     */

1138    public void testGetReportQueryIteratorBySQL()
1139    {
1140        String JavaDoc sql =
1141                "SELECT * FROM Artikel A, Kategorien PG"
1142                + " WHERE A.Kategorie_Nr = PG.Kategorie_Nr"
1143                + " AND PG.Kategorie_Nr = 2";
1144        Query q = QueryFactory.newQuery(Article.class, sql);
1145
1146        Iterator JavaDoc iter = broker.getReportQueryIteratorByQuery(q);
1147
1148        while (iter.hasNext())
1149        {
1150            Object JavaDoc[] arr = (Object JavaDoc[]) iter.next();
1151            for (int i = 0; i < arr.length; i++)
1152            {
1153                //System.out.print(arr[i] + ", ");
1154
}
1155            //System.out.println();
1156
}
1157    }
1158
1159    public void testGetMultipleIteratorsByQuery() throws Exception JavaDoc
1160    {
1161        String JavaDoc name = "testGetIteratorBySQL_" + System.currentTimeMillis();
1162        // 1. ensure there are 0 items matching the query
1163
Criteria criteria = new Criteria();
1164        criteria.addEqualTo("articleName", name);
1165        Query query = QueryFactory.newQuery(Article.class, criteria);
1166        Iterator JavaDoc iter = broker.getIteratorByQuery(query);
1167        assertTrue("size of Iterator should be zero", !iter.hasNext());
1168        //2. insert 3 matching items
1169
broker.beginTransaction();
1170        Article a1 = createArticle(null, name);
1171        broker.store(a1);
1172        Article a2 = createArticle(null, name);
1173        broker.store(a2);
1174        Article a3 = createArticle(null, name);
1175        broker.store(a3);
1176        broker.commitTransaction();
1177
1178        // 3. return multiple iterators
1179
Iterator JavaDoc i1 = broker.getIteratorByQuery(query);
1180        Iterator JavaDoc i2 = broker.getIteratorByQuery(query);
1181        Iterator JavaDoc i3 = broker.getIteratorByQuery(query);
1182        // 4. TestThreadsNLocks the iterators
1183
for (int i = 0; i < 3; i++)
1184        {
1185            assertTrue("should have more elements", i3.hasNext());
1186            assertTrue("should have more elements", i1.hasNext());
1187            assertTrue("should have more elements", i2.hasNext());
1188            assertEquals("should be same value", name, ((InterfaceArticle) i2.next()).getArticleName());
1189            assertEquals("should be same value", name, ((InterfaceArticle) i1.next()).getArticleName());
1190            assertEquals("should be same value", name, ((InterfaceArticle) i3.next()).getArticleName());
1191        }
1192    }
1193
1194    public void testGetObjectByQuery() throws Exception JavaDoc
1195    {
1196        String JavaDoc name = "testGetIteratorBySQL_" + System.currentTimeMillis();
1197        // ensure article is persistent
1198
Article a = createArticle(null, name);
1199        storeArticle(a);
1200
1201        // build query-by-example and execute
1202
Query query = QueryFactory.newQuery(a);
1203        Article b = (Article) broker.getObjectByQuery(query);
1204        assertEquals(
1205                "after inserting an object it should be equal to its re-read pendant",
1206                a.getArticleName(),
1207                b.getArticleName());
1208
1209        Article c = readArticleByExample(a.getArticleId());
1210        assertEquals(
1211                "after inserting an object it should be equal to its re-read pendant",
1212                a.getArticleName(),
1213                c.getArticleName());
1214
1215        // now TestThreadsNLocks a criteria query
1216
Criteria crit = new Criteria();
1217        crit.addEqualTo("articleId", a.getArticleId());
1218        Query q = QueryFactory.newQuery(Article.class, crit);
1219        InterfaceArticle d = (InterfaceArticle) broker.getObjectByQuery(q);
1220        assertEquals(
1221                "after inserting an object it should be equal to its re-read pendant",
1222                a.getArticleName(),
1223                d.getArticleName());
1224    }
1225
1226    public void testGetPKEnumerationByConstraints() throws Exception JavaDoc
1227    {
1228        String JavaDoc name = "testGetPKEnumerationByConstraints_" + System.currentTimeMillis();
1229        // 1. ensure there are 0 items matching the query
1230
Criteria criteria = new Criteria();
1231        criteria.addEqualTo("articleName", name);
1232        Query query = QueryFactory.newQuery(Article.class, criteria);
1233        Enumeration JavaDoc en = ((PersistenceBrokerInternal)broker).getPKEnumerationByQuery(ArticlePrimaryKey.class, query);
1234        assertTrue("size of collection should be zero", !en.hasMoreElements());
1235
1236        //2. insert 3 matching items
1237
broker.beginTransaction();
1238        Article a1 = createArticle(null, name);
1239        broker.store(a1);
1240        Article a2 = createArticle(null, name);
1241        broker.store(a2);
1242        Article a3 = createArticle(null, name);
1243        broker.store(a3);
1244        broker.commitTransaction();
1245        // 3. check if all items are found
1246
en = ((PersistenceBrokerInternal)broker).getPKEnumerationByQuery(ArticlePrimaryKey.class, query);
1247        int count = 0;
1248        while (en.hasMoreElements())
1249        {
1250            count++;
1251            Article tmp = readArticleByIdentity(new Integer JavaDoc(((ArticlePrimaryKey) en.nextElement()).id));
1252            assertEquals("should be same value", name, tmp.getArticleName());
1253        }
1254        assertEquals("Iterator should produce 3 items", 3, count);
1255    }
1256
1257    public void testInsert() throws Exception JavaDoc
1258    {
1259        String JavaDoc name = "testInsert_" + System.currentTimeMillis();
1260        Article a = createArticle(null, name);
1261        Article b = readArticleByIdentity(a.getArticleId());
1262        assertNull("should be null after deletion", b);
1263        storeArticle(a);
1264        b = readArticleByIdentity(a);
1265        assertEquals(
1266                "after inserting an object it should be equal to its re-read pendant",
1267                a.getArticleName(),
1268                b.getArticleName());
1269        // check if object is not only stored in cache but also in db
1270
b = null;
1271        broker.clearCache();
1272        b = readArticleByIdentity(a.getArticleId());
1273        assertEquals(
1274                "after inserting and flushing the cache an object should still be equal to its re-read pendant",
1275                a.getArticleName(),
1276                b.getArticleName());
1277    }
1278
1279    public void testUpdate() throws Exception JavaDoc
1280    {
1281        String JavaDoc name = "testUpdate_" + System.currentTimeMillis();
1282        Article a = createArticle(null, name);
1283        storeArticle(a);
1284        Article b = readArticleByIdentity(a);
1285        assertEquals(
1286                "after inserting an object it should be equal to its re-read pendant",
1287                a.getArticleName(),
1288                b.getArticleName());
1289        String JavaDoc newname = "TESTUPDATE_"+name;
1290        b.setArticleName(newname);
1291        storeArticle(b);
1292        b = readArticleByIdentity(a.getArticleId());
1293        assertEquals("should be equal after update", newname, b.getArticleName());
1294        // ensure that object is really stored in DB and not only in ObjectCache
1295
broker.clearCache();
1296        b = readArticleByIdentity(a.getArticleId());
1297        assertEquals("should be equal after update and db lookup", newname, b.getArticleName());
1298    }
1299
1300    public void testUpdateWithModification() throws Exception JavaDoc
1301    {
1302        String JavaDoc name = "testUpdateWithModification_" + System.currentTimeMillis();
1303        assertFalse("should not be marked for update yet", ObjectModification.INSERT.needsUpdate());
1304        assertFalse("should not be marked for insert", ObjectModification.UPDATE.needsInsert());
1305        Article a = createArticle(null, name);
1306
1307        broker.beginTransaction();
1308        broker.store(a, ObjectModification.INSERT);
1309        broker.commitTransaction();
1310
1311        Article b = readArticleByIdentity(a.getArticleId());
1312        assertEquals(
1313                "after inserting an object it should be equal to its re-read pendant",
1314                a.getArticleName(),
1315                b.getArticleName());
1316        String JavaDoc newname = "TESTUPDATE_" + name;
1317        b.setArticleName(newname);
1318        broker.beginTransaction();
1319        broker.store(b, ObjectModification.UPDATE);
1320        broker.commitTransaction();
1321
1322        b = null;
1323        b = readArticleByIdentity(a.getArticleId());
1324        assertEquals("should be equal after update", newname, b.getArticleName());
1325    }
1326
1327    /**
1328     * test if reference to Proxy is updated
1329     * @throws Exception
1330     */

1331    public void testUpdateReferencedProxy() throws Exception JavaDoc
1332    {
1333        String JavaDoc name = "testUpdateReferencedProxy_" + System.currentTimeMillis();
1334        ProductGroup pg = new ProductGroup();
1335        pg.setGroupName(name);
1336        Article b = createArticle(pg, name);
1337        broker.beginTransaction();
1338        broker.store(pg);
1339        // not needed (auto insert of reference), anyway... we do it
1340
broker.store(b);
1341        broker.commitTransaction();
1342
1343        broker.clearCache();
1344        b = readArticleByIdentity(b.getArticleId());
1345        InterfaceProductGroup pgb = b.getProductGroup();
1346        assertEquals("should be equal after update", pg.getId(), pgb.getId());
1347    }
1348
1349    public void testChangeFieldsWhileStoringObject()
1350    {
1351        long timestamp = System.currentTimeMillis();
1352
1353        broker.beginTransaction();
1354        Person p = new Person();
1355        p.setFirstname("no_1_" + timestamp);
1356        p.setLastname("no_1_" + timestamp);
1357        broker.store(p);
1358        // change fields
1359
p.setFirstname("no_2_" + timestamp);
1360        p.setLastname("no_2_" + timestamp);
1361        // store changed object again
1362
broker.store(p);
1363        broker.commitTransaction();
1364
1365        Identity id = new Identity(p, broker);
1366        Person result = (Person) broker.getObjectByIdentity(id);
1367        assertNotNull(result);
1368        assertEquals("no_2_" + timestamp, result.getFirstname());
1369        assertEquals("no_2_" + timestamp, result.getLastname());
1370
1371        /*
1372        same with cleared cache
1373        */

1374        timestamp = System.currentTimeMillis() + 1;
1375        broker.beginTransaction();
1376        p = new Person();
1377        p.setFirstname("no_3_" + timestamp);
1378        p.setLastname("no_3_" + timestamp);
1379        broker.store(p);
1380        broker.clearCache();
1381        p.setFirstname("no_4_" + timestamp);
1382        p.setLastname("no_4_" + timestamp);
1383        broker.store(p);
1384        broker.commitTransaction();
1385
1386        broker.clearCache();
1387        id = new Identity(p, broker);
1388        broker.clearCache();
1389        result = (Person) broker.getObjectByIdentity(id);
1390        assertNotNull(result);
1391        assertEquals("no_4_" + timestamp, result.getFirstname());
1392        assertEquals("no_4_" + timestamp, result.getLastname());
1393    }
1394
1395    public void testDoubleStore()
1396    {
1397        long timestamp = System.currentTimeMillis();
1398
1399        Person person = new Person();
1400        person.setFirstname("testDoubleStore_" + timestamp);
1401        person.setLastname("time_" + timestamp);
1402
1403        broker.beginTransaction();
1404        // Identity used to assign PK of object
1405
Identity oid = new Identity(person, broker);
1406        Person serializedPerson = (Person) SerializationUtils.clone(person);
1407        broker.store(person);
1408        broker.store(person);
1409        broker.store(serializedPerson);
1410        broker.commitTransaction();
1411
1412        Criteria crit = new Criteria();
1413        crit.addLike("firstName", "testDoubleStore_" + timestamp);
1414        Query query = QueryFactory.newQuery(Person.class, crit);
1415        Collection JavaDoc result = broker.getCollectionByQuery(query);
1416
1417        assertEquals("Expect to find exact 1 object for "+oid, 1, result.size());
1418    }
1419
1420    public void testDoubleDelete()
1421    {
1422        long timestamp = System.currentTimeMillis();
1423
1424        Person person = new Person();
1425        person.setFirstname("testDoubleDelete_" + timestamp);
1426        person.setLastname("time_" + timestamp);
1427
1428        broker.beginTransaction();
1429        // Identity oid = new Identity(person, broker);
1430
Person serializedPerson = (Person) SerializationUtils.clone(person);
1431        broker.store(person);
1432        broker.commitTransaction();
1433
1434        Criteria crit = new Criteria();
1435        crit.addLike("firstName", "testDoubleDelete_" + timestamp);
1436        Query query = QueryFactory.newQuery(Person.class, crit);
1437        Collection JavaDoc result = broker.getCollectionByQuery(query);
1438        assertEquals("Expect to find exact 1 object", 1, result.size());
1439
1440        broker.beginTransaction();
1441        broker.delete(person);
1442        broker.delete(serializedPerson);
1443        broker.delete(person);
1444        broker.commitTransaction();
1445
1446        broker.beginTransaction();
1447        broker.delete(serializedPerson);
1448        broker.commitTransaction();
1449
1450        result = broker.getCollectionByQuery(query);
1451        assertEquals("Expect to find none objects", 0, result.size());
1452    }
1453
1454    /**
1455     * Test if only one query is executed for each extent.<br>
1456     * If the same query is run multiple times the result will contain duplicates
1457     */

1458    public void testDuplicateExtentQueries()
1459    {
1460        Collection JavaDoc result;
1461        Set JavaDoc set = new HashSet JavaDoc();
1462        Criteria crit = new Criteria();
1463        crit.addGreaterThan("articleId",new Integer JavaDoc(70));
1464        QueryByCriteria qry = new QueryByCriteria(InterfaceArticle.class, crit);
1465
1466        broker.clearCache();
1467        result = broker.getCollectionByQuery(qry);
1468        set.addAll(result);
1469
1470        assertEquals("Both sizes must be equal", set.size(), result.size());
1471    }
1472
1473    /**
1474     * Size returned by Iterator must be same as size of Collection
1475     */

1476    public void testIteratorSize()
1477    {
1478        OJBIterator ojbIter;
1479        Criteria crit;
1480        QueryByCriteria query;
1481        int collSize;
1482        int iterSize;
1483
1484        crit = new Criteria();
1485        query = QueryFactory.newQuery(Article.class, crit);
1486
1487        collSize = broker.getCollectionByQuery(query).size();
1488
1489        ojbIter = (OJBIterator)broker.getIteratorByQuery(query);
1490        iterSize = ojbIter.size();
1491
1492        assertEquals("collSize == iterSize", collSize , iterSize);
1493        ojbIter.releaseDbResources();
1494    }
1495
1496    public void testPaging()
1497    {
1498        OJBIterator ojbIter;
1499        Criteria crit;
1500        QueryByCriteria query;
1501
1502        // All Articles index in range
1503
crit = new Criteria();
1504        query = QueryFactory.newQuery(Article.class, crit);
1505        int fullSize = broker.getCollectionByQuery(query).size();
1506
1507        query.setStartAtIndex(10);
1508        query.setEndAtIndex(14);
1509        ojbIter = (OJBIterator)broker.getIteratorByQuery(query);
1510        assertEquals("index 10 - 14 expecting 5 rows", 5,ojbIter.size());
1511        ojbIter.releaseDbResources();
1512    }
1513
1514    public void testPagingPosition()
1515    {
1516        String JavaDoc name = "testPagingPosition_" + System.currentTimeMillis();
1517        broker.beginTransaction();
1518        for(int i=1; i<21; i++)
1519        {
1520            Article a = createArticle(null, name);
1521            a.setStock(i);
1522            broker.store(a);
1523        }
1524        broker.commitTransaction();
1525
1526        OJBIterator ojbIter;
1527        Criteria crit;
1528        QueryByCriteria query;
1529        Collection JavaDoc fullColl, pagedColl;
1530        InterfaceArticle article;
1531        
1532        // All Articles index in range
1533
crit = new Criteria();
1534        crit.addEqualTo("articleName", name);
1535        query = QueryFactory.newQuery(Article.class, crit);
1536        query.addOrderByAscending("stock");
1537        fullColl = broker.getCollectionByQuery(query);
1538        assertEquals(20, fullColl.size());
1539
1540        // limited query
1541
query.setStartAtIndex(10);
1542        query.setEndAtIndex(14);
1543        pagedColl = broker.getCollectionByQuery(query);
1544                      
1545        ojbIter = (OJBIterator)broker.getIteratorByQuery(query);
1546        
1547        assertEquals("collection- and iterator-size must match", pagedColl.size(), ojbIter.size());
1548        assertEquals("index 10 - 14 expecting 5 rows", 5,ojbIter.size());
1549        
1550        ojbIter.absolute(2);
1551        article = (InterfaceArticle)ojbIter.next();
1552        assertEquals("Article stock=12", article.getStock(), 12);
1553        
1554        ojbIter.relative(-1);
1555        article = (InterfaceArticle)ojbIter.next();
1556        assertEquals("Article id=12", article.getStock(), 12);
1557
1558        ojbIter.relative(-1);
1559        article = (InterfaceArticle)ojbIter.next();
1560        assertEquals("Article id=12", article.getStock(), 12);
1561        
1562        // last
1563
ojbIter.absolute(12);
1564        article = (InterfaceArticle)ojbIter.next();
1565        assertEquals("Article id=15", article.getStock(), 15);
1566
1567        // first
1568
ojbIter.absolute(-12);
1569        article = (InterfaceArticle)ojbIter.next();
1570        assertEquals("Article id=10", article.getStock(), 10);
1571        
1572        ojbIter.releaseDbResources();
1573    }
1574    
1575    public void testPagingIndicesOutOfRange()
1576    {
1577        OJBIterator ojbIter;
1578        Criteria crit;
1579        QueryByCriteria query;
1580        int fullSize;
1581
1582        // All Articles index out of range
1583
crit = new Criteria();
1584        query = QueryFactory.newQuery(Article.class, crit);
1585        fullSize = broker.getCollectionByQuery(query).size();
1586
1587        query.setStartAtIndex(fullSize + 5);
1588        query.setEndAtIndex(fullSize + 14);
1589        ojbIter = (OJBIterator)broker.getIteratorByQuery(query);
1590        assertEquals("indices out of range expecting 0 rows", 0,ojbIter.size());
1591        ojbIter.releaseDbResources();
1592    }
1593
1594    public void testPagingEndIndexOutOfRange()
1595    {
1596        OJBIterator ojbIter;
1597        Criteria crit;
1598        QueryByCriteria query;
1599        int fullSize;
1600
1601        // All Articles index out of range
1602
crit = new Criteria();
1603        query = QueryFactory.newQuery(Article.class, crit);
1604        fullSize = broker.getCollectionByQuery(query).size();
1605
1606        query.setStartAtIndex(fullSize - 9);
1607        query.setEndAtIndex(fullSize + 9);
1608        ojbIter = (OJBIterator)broker.getIteratorByQuery(query);
1609        assertEquals("end index out of range expecting 10 rows", 10,ojbIter.size());
1610        ojbIter.releaseDbResources();
1611    }
1612
1613    public void testPagingEmptyIterator()
1614    {
1615        OJBIterator ojbIter;
1616        Criteria crit;
1617        QueryByCriteria query;
1618
1619        // looking for inexistent Article
1620
crit = new Criteria();
1621        crit.addEqualTo("articleId",new Integer JavaDoc(-777));
1622        query = QueryFactory.newQuery(Article.class, crit);
1623        int fullSize = broker.getCollectionByQuery(query).size();
1624
1625        query.setStartAtIndex(10);
1626        query.setEndAtIndex(14);
1627        ojbIter = (OJBIterator)broker.getIteratorByQuery(query);
1628        assertEquals("index 10 - 14 expecting 0 rows for empty iterator", 0,ojbIter.size());
1629        ojbIter.releaseDbResources();
1630    }
1631}
1632
Popular Tags