KickJava   Java API By Example, From Geeks To Geeks.

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


1 package org.apache.ojb.broker;
2
3
4 import java.util.Collection JavaDoc;
5 import java.util.Iterator JavaDoc;
6 import java.util.Vector JavaDoc;
7
8 import org.apache.ojb.broker.query.Query;
9 import org.apache.ojb.broker.query.QueryFactory;
10 import org.apache.ojb.junit.PBTestCase;
11
12 /**
13  * Demo Application that shows basic concepts for Applications using the PersistenceBroker
14  * as a mediator for persistence
15  */

16 public class ProxyExamples extends PBTestCase
17 {
18     public static void main(String JavaDoc[] args)
19     {
20         String JavaDoc[] arr = {ProxyExamples.class.getName()};
21         junit.textui.TestRunner.main(arr);
22     }
23
24     public ProxyExamples(String JavaDoc name)
25     {
26         super(name);
27     }
28
29     /**
30      * This example shows how the PersistenceBroker can be used with a highly configurable proxy concept.
31      * The main idea is, not to return materialized objects but rather lazy proxies, that defer materialization
32      * until it is definitely neccesary (e.g. reading an Objects attribute).
33      * <p/>
34      * To achieve such a behaviour, you can define proxies for each persistent class.
35      * As an example see the Repository.xml file in this examples directory.
36      * <p/>
37      * It is not always the best option to use lazy materialization. The usage of proxies can be completely configured
38      * in the xml repository. That is, if you decide not to use proxies, you don't have to change program-code,
39      * but only out-comment the corresponding entry in the repos
40      * itory.
41      */

42     public void testProgrammedProxies() throws Exception JavaDoc
43     {
44         String JavaDoc name = "testDynamicProxies_" + System.currentTimeMillis();
45         Vector JavaDoc myArticles = new Vector JavaDoc();
46 // In the following code we will generate 10 Proxy-objects.
47
ProductGroup pg = new ProductGroup();
48         pg.setGroupName(name);
49         broker.beginTransaction();
50         broker.store(pg);
51         broker.commitTransaction();
52
53         for(int i = 1; i < 10; i++)
54         {
55             Article a = new Article();
56             a.setArticleName(name);
57             a.setProductGroup(pg);
58             broker.beginTransaction();
59             broker.store(a);
60             broker.commitTransaction();
61             Identity id = broker.serviceIdentity().buildIdentity(a);
62             InterfaceArticle A =
63                     (InterfaceArticle) ((PersistenceBrokerInternal)broker).createProxy(Article.class, id);
64             myArticles.add(A);
65 //System.out.println(A);
66
}
67 // In the following code we call methods that reference the real subjects attributes.
68
// To access an articles name as in getArticleName(), the proxy object has to materialze the real subjects from db.
69
// but note: the references to an Articles productgroup are not materialized immediately,
70
// but contain proxy objects, representing ProductGroups.
71
for(int i = 0; i < 9; i++)
72         {
73             InterfaceArticle a = (InterfaceArticle) myArticles.get(i);
74 //System.out.println("Article[" + a.getArticleId() + "] : " + a.getArticleName());
75
assertNotNull(a);
76         }
77 // In the following code we will access the real ProductGroup objects.
78
// thus the Proxies have to materialize them.
79
for(int i = 0; i < 9; i++)
80         {
81             InterfaceArticle a = (InterfaceArticle) myArticles.get(i);
82             assertNotNull(a.getProductGroup());
83             assertNotNull(a.getProductGroup().getName());
84
85 //System.out.println("Article[" + a.getArticleId() + "] is in group " + a.getProductGroup().getName());
86
}
87 // in the following code we will touch fields of the ProductGroup references.
88
// Now proxies in the AllArticlesInGroup collection need to be materialized
89
//System.out.println("now playing with product group no. 2");
90
Object JavaDoc[] pkvals = new Object JavaDoc[1];
91         pkvals[0] = new Integer JavaDoc(2);
92         Identity id = new Identity(ProductGroup.class, ProductGroup.class, pkvals);
93         InterfaceProductGroup group2 = null;
94         try
95         {
96             group2 = (InterfaceProductGroup) ((PersistenceBrokerInternal)broker).createProxy(ProductGroupProxy.class, id);
97         }
98         catch(Exception JavaDoc ignored)
99         {
100         }
101 //System.out.println(group2.toString());
102
broker.beginTransaction();
103         for(int i = 0; i < group2.getAllArticles().size(); i++)
104         {
105             InterfaceArticle a = (InterfaceArticle) group2.getAllArticles().get(i);
106 //System.out.println(a.getArticleName());
107
assertNotNull(a);
108             broker.store(a);
109         }
110         broker.store(group2);
111         broker.commitTransaction();
112     }
113
114 // private Class getDynamicProxyClass(Class clazz)
115
// {
116
// try
117
// {
118
// Class[] interfaces = clazz.getInterfaces();
119
// Class proxyClass = Proxy.getProxyClass(clazz.getClassLoader(), interfaces);
120
// return proxyClass;
121
// }
122
// catch(Throwable t)
123
// {
124
// System.out.println("OJB Warning: can not use dynamic proxy for class " + clazz.getName() + ": " + t.getMessage());
125
// return null;
126
// }
127
//
128
// }
129

130     /**
131      * This example shows how the PersistenceBroker can be used with a highly configurable proxy concept.
132      * The main idea is, not to return materialized objects but rather lazy proxies, that defer materialization
133      * until it is definitely neccesary (e.g. reading an Objects attribute).
134      * <p/>
135      * To achieve such a behaviour, you can define proxies for each persistent class.
136      * As an example see the Repository.xml file in this examples directory.
137      * <p/>
138      * It is not always the best option to use lazy materialization. The usage of proxies can be completely configured
139      * in the xml repository. That is, if you decide not to use proxies, you don't have to change program-code,
140      * but only out-comment the corresponding entry in the repos
141      * itory.
142      */

143     public void testDynamicProxies()
144     {
145         String JavaDoc name = "testDynamicProxies_" + System.currentTimeMillis();
146         Vector JavaDoc myArticles = new Vector JavaDoc();
147 // In the following code we will generate 10 Proxy-objects.
148
ProductGroup pg = new ProductGroup();
149         pg.setGroupName(name);
150         broker.beginTransaction();
151         broker.store(pg);
152         broker.commitTransaction();
153
154         for(int i = 1; i < 10; i++)
155         {
156             Article a = new Article();
157             a.setArticleName(name);
158             a.setProductGroup(pg);
159             broker.beginTransaction();
160             broker.store(a);
161             broker.commitTransaction();
162             Identity id = broker.serviceIdentity().buildIdentity(a);
163             InterfaceArticle A =
164                     (InterfaceArticle) ((PersistenceBrokerInternal)broker).createProxy(Article.class, id);
165             myArticles.add(A);
166 //System.out.println(A);
167
}
168 // In the following code we call methods that reference the real subjects attributes.
169
// To access an articles name as in getArticleName(), the proxy object has to materialze the real subjects from db.
170
// but note: the references to an Articles productgroup are not materialized immediately,
171
// but contain proxy objects, representing ProductGroups.
172
for(int i = 0; i < 9; i++)
173         {
174             InterfaceArticle a = (InterfaceArticle) myArticles.get(i);
175 //System.out.println("Article[" + a.getArticleId() + "] : " + a.getArticleName());
176
}
177 // In the following code we will access the real ProductGroup objects.
178
// thus the Proxies have to materialize them.
179
for(int i = 0; i < 9; i++)
180         {
181             InterfaceArticle a = (InterfaceArticle) myArticles.get(i);
182 //System.out.println("Article[" + a.getArticleId() + "] is in group " + a.getProductGroup().getName());
183
}
184     }
185
186     public void testCollectionProxies() throws Exception JavaDoc
187     {
188         ProductGroupWithCollectionProxy org_pg = new ProductGroupWithCollectionProxy();
189         org_pg.setId(new Integer JavaDoc(7));
190         Identity pgOID = broker.serviceIdentity().buildIdentity(org_pg);
191
192         ProductGroupWithCollectionProxy pg = (ProductGroupWithCollectionProxy) broker.getObjectByIdentity(pgOID);
193         assertEquals(org_pg.getId(), pg.getId());
194
195         Collection JavaDoc col = pg.getAllArticles();
196         int countedSize = col.size(); // force count query
197
Iterator JavaDoc iter = col.iterator();
198         while(iter.hasNext())
199         {
200             InterfaceArticle a = (InterfaceArticle) iter.next();
201         }
202
203         assertEquals("compare counted and loaded size", countedSize, col.size());
204     }
205
206     public void testCollectionProxiesAndExtents() throws Exception JavaDoc
207     {
208         ProductGroupWithCollectionProxy pg = new ProductGroupWithCollectionProxy();
209         pg.setId(new Integer JavaDoc(5));
210         Identity pgOID = broker.serviceIdentity().buildIdentity(pg);
211
212         pg = (ProductGroupWithCollectionProxy) broker.getObjectByIdentity(pgOID);
213         assertEquals(5, pg.getId().intValue());
214
215         Collection JavaDoc col = pg.getAllArticles();
216         int countedSize = col.size(); // force count query
217
Iterator JavaDoc iter = col.iterator();
218         while(iter.hasNext())
219         {
220             InterfaceArticle a = (InterfaceArticle) iter.next();
221         }
222
223         assertEquals("compare counted and loaded size", countedSize, col.size());
224
225         // 7 Articles, 2 Books, 3 Cds
226
assertEquals("check size", col.size(), 12);
227     }
228
229     public void testReferenceProxies()
230     {
231         ArticleWithReferenceProxy a = new ArticleWithReferenceProxy();
232 // a.setArticleId(8888);
233
a.setArticleName("ProxyExamples.testReferenceProxy article");
234
235         Query q = QueryFactory.newQuery(a);
236
237         ProductGroup pg = new ProductGroup();
238 // pg.setId(10);
239
pg.setGroupName("ProxyExamples test group");
240
241         a.setProductGroup(pg);
242         broker.beginTransaction();
243         broker.store(a);
244         broker.commitTransaction();
245         int id = pg.getGroupId().intValue();
246
247         broker.clearCache();
248         ArticleWithReferenceProxy ar = (ArticleWithReferenceProxy) broker.getObjectByQuery(q);
249
250         assertEquals(id, ar.getProductGroup().getId().intValue());
251     }
252
253     /**
254      * Default the transaction isolation level of a JDBC connection is
255      * READ-COMMITED.
256      * So if a proxy uses another broker instance (i.e. JDBC connecction)
257      * than the current one, it's possible that program blocks.
258      */

259     public void testProxiesAndJDBCTransactionIsolation()
260     {
261         boolean commit = false;
262         try
263         {
264             // Start transaction
265
broker.beginTransaction();
266
267             // Create productgroup
268
ProductGroupWithCollectionProxy pg = new ProductGroupWithCollectionProxy();
269             pg.setGroupName("TESTPRODUCTGROUP");
270             broker.store(pg);
271
272             // Create 2 articles for this productgroup
273
for(int j = 1; j <= 2; j++)
274             {
275                 Article ar = new Article();
276                 ar.setArticleName("ARTICLE " + j);
277                 ar.setProductGroup(pg);
278                 broker.store(ar);
279             }
280
281             // Reload the productgroup
282
broker.clearCache();
283             pg = (ProductGroupWithCollectionProxy) broker.getObjectByQuery(QueryFactory.newQuery(pg));
284             assertTrue(pg != null);
285
286             // Try to load the articles
287
// The proxy is using another broker instance (i.e. JDBC cconnection).
288
// Default the JDBC transaction isolationlevel is READ_COMMITTED.
289
// So the program will wait until the inserted articles are committed.
290
Collection JavaDoc articles = pg.getAllArticlesInGroup();
291             assertEquals(2, articles.size());
292
293             // Commit
294
broker.commitTransaction();
295             commit = true;
296         }
297         finally
298         {
299             if(!commit)
300                 broker.abortTransaction();
301         }
302     }
303
304 }
305
Popular Tags