KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > bsf > smartValueObject > demo > DemoMediator


1 package org.bsf.smartValueObject.demo;
2
3 import org.apache.commons.beanutils.BeanUtils;
4 import org.apache.commons.logging.Log;
5 import org.apache.commons.logging.LogFactory;
6 import org.bsf.smartValueObject.SmartAccess;
7 import org.bsf.smartValueObject.mediator.ConcurrencyException;
8 import org.bsf.smartValueObject.mediator.Mediator;
9 import org.bsf.smartValueObject.mediator.MediatorException;
10 import org.bsf.smartValueObject.mediator.ChangeSummary;
11
12 import java.io.PrintWriter JavaDoc;
13 import java.io.StringWriter JavaDoc;
14 import java.lang.reflect.Field JavaDoc;
15 import java.util.*;
16
17 /**
18  * Mock Mediator for the Demo.
19  *
20  */

21 public class DemoMediator implements Mediator, java.io.Serializable JavaDoc {
22
23     private static Log log = LogFactory.getLog(DemoMediator.class);
24    /** Our storage, to avoid EJB local entities. */
25     private Map storageCompany;
26     /** Our storage, to avoid EJB local entities. */
27     private Map storageSubsidiary;
28     /** Class of the VO (would be configured on runtime). */
29     private Class JavaDoc voClazzCompany = CompanyVO.class;
30     /** The index field in the VO (would be configured on runtime). */
31     private String JavaDoc indexField = "id";
32     private Map versionCache;
33
34     private CompanyLocalHome companyHome;
35     private SubsidiaryLocalHome subsidiaryHome;
36
37
38     public DemoMediator() {
39         storageCompany = new HashMap();
40         storageSubsidiary = new HashMap();
41
42         companyHome = new CompanyLocalHome();
43         subsidiaryHome = new SubsidiaryLocalHome();
44
45         versionCache = new HashMap();
46     }
47
48     /**
49      * Retrieves graph based on given prototype.
50      *
51      * @param prototype
52      * @return
53      * @throws MediatorException
54      */

55     public Object JavaDoc getGraph(Object JavaDoc prototype)
56             throws MediatorException {
57         log.debug("getGraph(" + prototype + ")");
58         verifyGraph(prototype);
59
60         CompanyVO company = (CompanyVO) prototype;
61
62         CompanyEntity ce = getCompanyEntityByVO(company);
63         if (ce == null)
64             throw new MediatorException("Object not found");
65
66         CompanyVO result = newCompanyVO(ce);
67
68         // cache version
69
Long JavaDoc id = getVersionCache(result);
70         if (id != null) {
71             SmartAccess.setVersionId(result, id.longValue());
72         } else {
73             updateVersionCache(result);
74         }
75         return result;
76     }
77
78
79     /**
80      * Stores graph and return summary of changes.
81      *
82      * @param graph
83      * @return update log.
84      * @throws MediatorException
85      */

86     public ChangeSummary updateGraph(Object JavaDoc graph)
87             throws MediatorException {
88         log.info("updateGraph(" + graph + ")");
89         String JavaDoc status = "No updates performed.";
90         verifyGraph(graph);
91         checkConcurrency(graph);
92         CompanyVO company = (CompanyVO) graph;
93         CompanyVO newCompany = null;
94
95         if (SmartAccess.isGraphDirty(company)) {
96             StringWriter JavaDoc writer = new StringWriter JavaDoc();
97             CompanyEntity ce = updateCompany(company, new PrintWriter JavaDoc(writer));
98             newCompany = newCompanyVO(ce);
99             updateVersionCache(newCompany);
100             status = writer.toString();
101             return new ChangeSummary(getPK(newCompany), status);
102         } else {
103             log.info("Nothing to do.");
104             return new ChangeSummary(null, "Nothing");
105         }
106     }
107
108     /**
109      * Deletes a graph.
110      * @param graph the root element of the graph.
111      * @throws MediatorException
112      */

113     public void deleteGraph(Object JavaDoc graph)
114             throws MediatorException {
115         verifyGraph(graph);
116         checkConcurrency(graph);
117         CompanyVO company = (CompanyVO) graph;
118         removeCompany(company);
119         removeVersionCache(company);
120     }
121
122     /**
123      * Creates new company based on VO.
124      * @param vo
125      * @throws MediatorException
126      */

127     private CompanyEntity newCompany(CompanyVO vo, PrintWriter JavaDoc logger) throws MediatorException {
128         log.debug("newCompany(" + vo + ")");
129         CompanyEntity ce = companyHome.create();
130         copyProperties(ce, vo);
131         logger.println("created company entity " + ce);
132
133         Collection subsidiaries = vo.getSubsidiaries();
134         Iterator created = SmartAccess.createdIterator(subsidiaries);
135         while (created.hasNext()) {
136             SubsidiaryVO subvo = (SubsidiaryVO) created.next();
137             SubsidiaryEntity se = newSubsidiary(subvo);
138             ce.getSubsidiaries().add(se);
139             logger.println("added subsidiary " + subvo);
140         }
141         return ce;
142     }
143
144     /**
145      * Updates (or creates) company based on VO.
146      * @param vo
147      * @throws MediatorException
148      */

149     private CompanyEntity updateCompany(CompanyVO vo, PrintWriter JavaDoc logger) throws MediatorException {
150         log.debug("updateCompany(" + vo + ")");
151         Object JavaDoc pk = getPK(vo);
152         CompanyEntity ce = null;
153         if (pk == null && vo.getName() != null) {
154            return newCompany(vo, logger);
155         } else if ((ce = companyHome.findByPk(pk)) == null) {
156             if (vo.getName() != null) {
157                 return newCompany(vo, logger);
158             } else {
159                 throw new MediatorException("object for update not found (" +
160                         vo + ") and missing attribute" +
161                         " (name) to create new object");
162             }
163         }
164
165         if (SmartAccess.isDirty(vo)) {
166             copyProperties(ce, vo);
167             logger.println("Updated company " + vo);
168         }
169
170         Collection c = vo.getSubsidiaries();
171
172         Iterator modified = SmartAccess.modifiedIterator(c);
173         while (modified.hasNext()) {
174             SubsidiaryVO subsidiaryVO = (SubsidiaryVO) modified.next();
175
176             if (SmartAccess.isDeleted(subsidiaryVO)) {
177                 ce.getSubsidiaries().remove(getSubsidiaryEntitybyVO(subsidiaryVO));
178                 removeSubsidiary(subsidiaryVO);
179                 logger.println("Removed " + subsidiaryVO);
180             } else if (SmartAccess.isCreated(subsidiaryVO)) {
181                 SubsidiaryEntity se = newSubsidiary(subsidiaryVO);
182                 ce.getSubsidiaries().add(se);
183                 logger.println("Added " + subsidiaryVO);
184             } else {
185                 updateSubsidiary(subsidiaryVO);
186                 logger.println("Updated " + subsidiaryVO);
187             }
188         }
189
190         return ce;
191     }
192
193     /**
194      * Removes company based on VO.
195      * @param vo
196      * @throws MediatorException
197      */

198     private void removeCompany(CompanyVO vo) throws MediatorException {
199         CompanyEntity ce = getCompanyEntityByVO(vo);
200         if (ce == null)
201             throw new MediatorException("Object not found");
202
203         Collection subsidiares = ce.getSubsidiaries();
204         for (Iterator iterator = subsidiares.iterator(); iterator.hasNext();) {
205             SubsidiaryEntity entity = (SubsidiaryEntity) iterator.next();
206             subsidiaryHome.remove(entity.getId());
207         }
208         ce.getSubsidiaries().clear();
209         companyHome.remove(ce.getId());
210     }
211
212     /**
213      * Creates new subsidiary based on VO.
214      * @param vo
215      * @return
216      * @throws MediatorException
217      */

218     private SubsidiaryEntity newSubsidiary(SubsidiaryVO vo) throws MediatorException {
219         log.debug("newSubsidiary(" + vo + ")");
220         SubsidiaryEntity se = subsidiaryHome.create();
221         copyProperties(se, vo);
222         return se;
223     }
224
225     /**
226      * Updates subsidiary based on VO.
227      * @param vo
228      * @throws MediatorException
229      */

230     private void updateSubsidiary(SubsidiaryVO vo) throws MediatorException {
231         log.debug("updateSubsidiary(" + vo + ")");
232         SubsidiaryEntity se = getSubsidiaryEntitybyVO(vo);
233         copyProperties(se, vo);
234     }
235
236     /**
237      * Removes subsidiary based on VO.
238      * @param vo
239      * @throws MediatorException
240      */

241     private void removeSubsidiary(SubsidiaryVO vo) throws MediatorException {
242         log.debug("removeSubsidiary(" + vo + ")");
243         subsidiaryHome.remove(getPK(vo));
244     }
245
246     /**
247      * Gets primary key from object (from the field specied in indexField).
248      * @param o
249      * @return
250      * @throws MediatorException
251      */

252     private Object JavaDoc getPK(Object JavaDoc o) throws MediatorException {
253         Object JavaDoc pk;
254         try {
255             Field JavaDoc field = o.getClass().getField(indexField);
256             pk = field.get(o);
257         } catch (Exception JavaDoc e) {
258             throw new MediatorException("Could not find pk", e);
259         }
260         return pk;
261     }
262
263     /**
264      * Gets company entity from VO.
265      * @param vo
266      * @return
267      * @throws MediatorException
268      */

269     private CompanyEntity getCompanyEntityByVO(CompanyVO vo) throws MediatorException {
270         Object JavaDoc pk = getPK(vo);
271         if (pk == null)
272             throw new MediatorException("No pk for object " + vo + " found");
273
274         CompanyEntity ce = companyHome.findByPk(pk);
275         return ce;
276     }
277
278     /**
279      * Gets subsidiary entitiy from VO.
280      * @param vo
281      * @return
282      * @throws MediatorException
283      */

284     private SubsidiaryEntity getSubsidiaryEntitybyVO(SubsidiaryVO vo) throws MediatorException {
285         Object JavaDoc pk = getPK(vo);
286         if (pk == null)
287             throw new MediatorException("No pk for object " + vo + " found");
288
289         SubsidiaryEntity se = subsidiaryHome.findByPk(pk);
290         return se;
291     }
292
293     /**
294      * Verifies if the graph argument is valid.
295      * @param graph
296      * @throws MediatorException
297      */

298     private void verifyGraph(Object JavaDoc graph) throws MediatorException {
299         if (graph == null || graph.getClass().getName() != voClazzCompany.getName()) {
300             throw new MediatorException("Invalid graph object");
301         }
302
303         if (!SmartAccess.isVersionable(graph)) {
304             throw new MediatorException("Object not versionable");
305         }
306
307         if (!graph.getClass().getName().equals(voClazzCompany.getName())) {
308             throw new MediatorException("Object not a root object");
309         }
310     }
311
312     private void updateVersionCache(Object JavaDoc vo) throws MediatorException {
313         Object JavaDoc key = getPK(vo);
314         Map cache = (Map) versionCache.get(vo.getClass());
315         if (cache == null) {
316             cache = new HashMap();
317             versionCache.put(vo.getClass(), cache);
318         }
319         cache.put(key, new Long JavaDoc(SmartAccess.getVersionId(vo)));
320     }
321
322     private Long JavaDoc getVersionCache(Object JavaDoc vo) throws MediatorException {
323         Object JavaDoc key = getPK(vo);
324         Map cache = (Map) versionCache.get(vo.getClass());
325         if (cache == null) {
326             return null;
327         } else {
328             return (Long JavaDoc) cache.get(key);
329         }
330     }
331
332     private void removeVersionCache(Object JavaDoc vo) throws MediatorException {
333         Object JavaDoc key = getPK(vo);
334         Map cache = (Map) versionCache.get(vo.getClass());
335         if (cache != null)
336             cache.remove(key);
337     }
338
339     private void checkConcurrency(Object JavaDoc vo) throws MediatorException {
340         Long JavaDoc id = getVersionCache(vo);
341         if (id == null)
342             return; // no version id, ok (we assume object has not been created yet)
343

344         if (SmartAccess.getVersionId(vo) != id.longValue())
345             throw new ConcurrencyException();
346     }
347
348     /**
349      * Wrapper around BeanUtils.copyProperties.
350      * @param dst
351      * @param src
352      * @throws MediatorException
353      */

354     private static void copyProperties(Object JavaDoc dst, Object JavaDoc src) throws MediatorException {
355         try {
356             BeanUtils.copyProperties(dst, src);
357         } catch (Exception JavaDoc e) {
358             throw new MediatorException("Error copying properties", e);
359         }
360
361     }
362
363     /**
364      * Creates new CompanyVO object.
365      * @return
366      */

367     private static CompanyVO newCompanyVO() {
368         return new CompanyVO();
369     }
370
371     /**
372      * Creates new SubsidiaryVO object.
373      * @return
374      */

375     private static SubsidiaryVO newSubsidiaryVO() {
376         return new SubsidiaryVO();
377     }
378
379     /**
380      * Creates new SubsidiaryVO object and initializes its field with
381      * the given SubsidiaryEntity.
382      *
383      * @param se
384      * @return
385      * @throws MediatorException
386      */

387     private static SubsidiaryVO newSubsidiaryVO(SubsidiaryEntity se) throws MediatorException {
388         SubsidiaryVO vo = newSubsidiaryVO();
389         copyProperties(vo, se);
390         SmartAccess.reset(vo);
391         return vo;
392     }
393
394     private static CompanyVO newCompanyVO(CompanyEntity ce) throws MediatorException {
395         CompanyVO result = newCompanyVO();
396         copyProperties(result, ce);
397         Collection subsidiaries = ce.getSubsidiaries();
398         for (Iterator iterator = subsidiaries.iterator(); iterator.hasNext();) {
399             SubsidiaryEntity entity = (SubsidiaryEntity) iterator.next();
400             SubsidiaryVO vo = newSubsidiaryVO(entity);
401             result.addSubsidiary(vo);
402         }
403
404         SmartAccess.resetGraph(result);
405         return result;
406     }
407
408     /**
409      * Mock class for real entity.
410      */

411     public static class CompanyEntity implements java.io.Serializable JavaDoc {
412         private Long JavaDoc id;
413         private String JavaDoc name;
414         private java.util.Date JavaDoc creationDate;
415         private Collection subsidiaries = new ArrayList();
416
417         public CompanyEntity(Long JavaDoc id) {
418             this.id = id;
419         }
420
421         public Long JavaDoc getId() {
422             return id;
423         }
424
425         public String JavaDoc getName() {
426             return name;
427         }
428
429         public void setName(String JavaDoc name) {
430             this.name = name;
431         }
432
433         public Collection getSubsidiaries() {
434             return subsidiaries;
435         }
436
437         public java.util.Date JavaDoc getCreationDate() {
438             return creationDate;
439         }
440
441         public void setCreationDate(java.util.Date JavaDoc creationDate) {
442             this.creationDate = creationDate;
443         }
444     }
445
446     /**
447      * Mock class for real entity.
448      */

449     public static class SubsidiaryEntity implements java.io.Serializable JavaDoc {
450         private Long JavaDoc id;
451         private String JavaDoc name;
452         private Long JavaDoc workforce;
453
454         public SubsidiaryEntity(Long JavaDoc id) {
455             this.id = id;
456         }
457
458         public Long JavaDoc getId() {
459             return id;
460         }
461
462         public String JavaDoc getName() {
463             return name;
464         }
465
466         public void setName(String JavaDoc name) {
467             this.name = name;
468         }
469
470         public Long JavaDoc getWorkforce() {
471             return workforce;
472         }
473
474         public void setWorkforce(Long JavaDoc workforce) {
475             this.workforce = workforce;
476         }
477     }
478
479     /**
480      * LocalHome mock for Company.
481      */

482      private class CompanyLocalHome implements java.io.Serializable JavaDoc {
483         private long counter = 0;
484
485         public CompanyEntity findByPk(Object JavaDoc pk) {
486              return (CompanyEntity) storageCompany.get(pk);
487         }
488
489         public CompanyEntity create() {
490             CompanyEntity ce = new CompanyEntity(new Long JavaDoc(counter++));
491             persist(ce);
492             return ce;
493         }
494
495         public void persist(CompanyEntity ce) {
496             storageCompany.put(ce.getId(), ce);
497         }
498
499         public void remove(Object JavaDoc pk) {
500             storageCompany.remove(pk);
501         }
502      }
503
504     /**
505      * LocalHome mock for Subsidiary.
506      */

507     private class SubsidiaryLocalHome implements java.io.Serializable JavaDoc {
508         private long counter = 0;
509
510         public SubsidiaryEntity findByPk(Object JavaDoc pk) {
511             return (SubsidiaryEntity) storageSubsidiary.get(pk);
512         }
513
514         public SubsidiaryEntity create() {
515             SubsidiaryEntity se = new SubsidiaryEntity(new Long JavaDoc(counter++));
516             persist(se);
517             return se;
518         }
519
520         public void persist(SubsidiaryEntity se) {
521             storageSubsidiary.put(se.getId(), se);
522         }
523
524         public void remove(Object JavaDoc pk) {
525             log.debug("SubsidiaryLocalHome.remove(" + pk + ")");
526             if (storageSubsidiary.remove(pk) == null)
527                 log.debug("SubsidiaryLocalHome.remove failed");
528         }
529     }
530 }
531
Popular Tags