KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > infoglue > cms > controllers > kernel > impl > simple > BaseController


1 /* ===============================================================================
2  *
3  * Part of the InfoGlue Content Management Platform (www.infoglue.org)
4  *
5  * ===============================================================================
6  *
7  * Copyright (C)
8  *
9  * This program is free software; you can redistribute it and/or modify it under
10  * the terms of the GNU General Public License version 2, as published by the
11  * Free Software Foundation. See the file LICENSE.html for more information.
12  *
13  * This program is distributed in the hope that it will be useful, but WITHOUT
14  * ANY WARRANTY, including the implied warranty of MERCHANTABILITY or FITNESS
15  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License along with
18  * this program; if not, write to the Free Software Foundation, Inc. / 59 Temple
19  * Place, Suite 330 / Boston, MA 02111-1307 / USA.
20  *
21  * ===============================================================================
22  */

23
24 package org.infoglue.cms.controllers.kernel.impl.simple;
25
26 import java.util.ArrayList JavaDoc;
27 import java.util.Collection JavaDoc;
28 import java.util.Collections JavaDoc;
29 import java.util.Iterator JavaDoc;
30 import java.util.List JavaDoc;
31 import java.util.Map JavaDoc;
32
33 import org.apache.log4j.Logger;
34 import org.exolab.castor.jdo.Database;
35 import org.exolab.castor.jdo.OQLQuery;
36 import org.exolab.castor.jdo.PersistenceException;
37 import org.exolab.castor.jdo.QueryResults;
38 import org.infoglue.cms.entities.kernel.BaseEntityVO;
39 import org.infoglue.cms.entities.kernel.IBaseEntity;
40 import org.infoglue.cms.entities.kernel.ValidatableEntityVO;
41 import org.infoglue.cms.entities.management.InterceptionPointVO;
42 import org.infoglue.cms.entities.management.InterceptorVO;
43 import org.infoglue.cms.exception.Bug;
44 import org.infoglue.cms.exception.ConstraintException;
45 import org.infoglue.cms.exception.SystemException;
46 import org.infoglue.cms.security.InfoGluePrincipal;
47 import org.infoglue.cms.security.interceptors.InfoGlueInterceptor;
48 import org.infoglue.cms.util.ConstraintExceptionBuffer;
49 import org.infoglue.cms.util.validators.Constants;
50 import org.infoglue.cms.util.validators.ConstraintRule;
51 import org.infoglue.cms.util.validators.EmailValidator;
52 import org.infoglue.cms.util.validators.StringValidator;
53
54 /**
55  * BaseController.java
56  * Created on 2002-aug-28
57  * @author Stefan Sik, ss@frovi.com
58  * @author Mattias Bogeblad, mattias.bogeblad@sprawlsolutions.se
59  *
60  * Baseclass for ControllerClasses.
61  * Various methods to load, create and delete entities
62  *
63  * TODO:
64  * Now that all entities implements BaseEntity clear all reflection and simplify
65  * arguments...
66  *
67  * -matbog 2002-09-15: Added and modified new read-only methods for fetching a VO-object.
68  * These method must be called instead of the old ones when just fetching a entity
69  * or all entities from a table.
70  */

71
72 public abstract class BaseController
73 {
74     private final static Logger logger = Logger.getLogger(BaseController.class.getName());
75
76     /**
77      * Gets a logger for the action class.
78      */

79 /*
80     protected Logger logger
81     {
82         return Logger.getLogger(this.getClass().getName());
83     }
84 */

85     /**
86      * This method is called by the controllers to let interceptors listen to events.
87      *
88      * @param hashMap
89      * @param InterceptionPointName
90      * @param infogluePrincipal
91      * @throws ConstraintException
92      * @throws SystemException
93      * @throws Bug
94      * @throws Exception
95      */

96
97     protected void intercept(Map JavaDoc hashMap, String JavaDoc InterceptionPointName, InfoGluePrincipal infogluePrincipal) throws ConstraintException, SystemException, Bug, Exception JavaDoc
98     {
99         InterceptionPointVO interceptionPointVO = InterceptionPointController.getController().getInterceptionPointVOWithName(InterceptionPointName);
100         
101         if(interceptionPointVO == null)
102             throw new SystemException("The InterceptionPoint " + InterceptionPointName + " was not found. The system will not work unless you restore it.");
103
104         List JavaDoc interceptors = InterceptionPointController.getController().getInterceptorsVOList(interceptionPointVO.getInterceptionPointId());
105         Iterator JavaDoc interceptorsIterator = interceptors.iterator();
106         while(interceptorsIterator.hasNext())
107         {
108             InterceptorVO interceptorVO = (InterceptorVO)interceptorsIterator.next();
109             logger.info("Adding interceptorVO:" + interceptorVO.getName());
110             try
111             {
112                 InfoGlueInterceptor infoGlueInterceptor = (InfoGlueInterceptor)Class.forName(interceptorVO.getClassName()).newInstance();
113                 infoGlueInterceptor.intercept(infogluePrincipal, interceptionPointVO, hashMap);
114             }
115             catch(ClassNotFoundException JavaDoc e)
116             {
117                 logger.warn("The interceptor " + interceptorVO.getClassName() + "was not found: " + e.getMessage(), e);
118             }
119         }
120
121     }
122
123     
124     /**
125      * This method is called by the controllers to let interceptors listen to events.
126      *
127      * @param hashMap
128      * @param InterceptionPointName
129      * @param infogluePrincipal
130      * @throws ConstraintException
131      * @throws SystemException
132      * @throws Bug
133      * @throws Exception
134      */

135
136     protected void intercept(Map JavaDoc hashMap, String JavaDoc InterceptionPointName, InfoGluePrincipal infogluePrincipal, Database db) throws ConstraintException, SystemException, Bug, Exception JavaDoc
137     {
138         InterceptionPointVO interceptionPointVO = InterceptionPointController.getController().getInterceptionPointVOWithName(InterceptionPointName, db);
139         
140         if(interceptionPointVO == null)
141             throw new SystemException("The InterceptionPoint " + InterceptionPointName + " was not found. The system will not work unless you restore it.");
142
143         List JavaDoc interceptors = InterceptionPointController.getController().getInterceptorsVOList(interceptionPointVO.getInterceptionPointId(), db);
144         Iterator JavaDoc interceptorsIterator = interceptors.iterator();
145         while(interceptorsIterator.hasNext())
146         {
147             InterceptorVO interceptorVO = (InterceptorVO)interceptorsIterator.next();
148             logger.info("Adding interceptorVO:" + interceptorVO.getName());
149             try
150             {
151                 InfoGlueInterceptor infoGlueInterceptor = (InfoGlueInterceptor)Class.forName(interceptorVO.getClassName()).newInstance();
152                 infoGlueInterceptor.intercept(infogluePrincipal, interceptionPointVO, hashMap, db);
153             }
154             catch(ClassNotFoundException JavaDoc e)
155             {
156                 logger.warn("The interceptor " + interceptorVO.getClassName() + "was not found: " + e.getMessage(), e);
157             }
158         }
159
160     }
161
162     
163     private static Integer JavaDoc getEntityId(Object JavaDoc entity) throws Bug
164     {
165         Integer JavaDoc entityId = new Integer JavaDoc(-1);
166         
167         try
168         {
169             entityId = ((IBaseEntity) entity).getId();
170         }
171         catch (Exception JavaDoc e)
172         {
173             e.printStackTrace();
174             throw new Bug("Unable to retrieve object id");
175         }
176         
177         /*
178         try {
179             entityId = (Integer) entity.getClass().getDeclaredMethod("getId", new Class[0]).invoke(entity, new Object[0]);
180         } catch (IllegalAccessException e) {
181         } catch (InvocationTargetException e) {
182         } catch (NoSuchMethodException e) {
183         }
184
185         */

186         return entityId;
187     }
188
189     /***************************************************
190      * Create, Delete & Update operations
191      ***************************************************/

192
193     // Create entity
194
// The validation belongs here
195
protected static Object JavaDoc createEntity(Object JavaDoc entity) throws SystemException, Bug
196     {
197         Database db = CastorDatabaseService.getDatabase();
198         beginTransaction(db);
199
200         try
201         {
202             db.create(entity);
203             commitTransaction(db);
204             //CmsSystem.log(entity,"Created object", CmsSystem.DBG_NORMAL);
205
//CmsSystem.transactionLogEntry(entity.getClass().getName(), CmsSystem.TRANS_CREATE, getEntityId(entity), entity.toString());
206

207         }
208         catch(Exception JavaDoc e)
209         {
210             logger.error("An error occurred so we should not complete the transaction:" + e, e);
211             //CmsSystem.log(entity,"Failed to create object", CmsSystem.DBG_LOW);
212
rollbackTransaction(db);
213             throw new SystemException(e.getMessage());
214         }
215         return entity;
216     }
217
218
219     // Create entity inside an existing transaction
220
protected static Object JavaDoc createEntity(Object JavaDoc entity, Database db) throws SystemException, Bug, Exception JavaDoc
221     {
222         db.create(entity);
223         return entity;
224     }
225 /*
226     protected static Object createEntity(Object entity, Database db) throws SystemException, Bug
227     {
228         try
229         {
230             db.create(entity);
231             commitTransaction(db);
232             //CmsSystem.log(entity,"Created object", CmsSystem.DBG_NORMAL);
233             //CmsSystem.transactionLogEntry(entity.getClass().getName(), CmsSystem.TRANS_CREATE, getEntityId(entity), entity.toString());
234         }
235         catch(Exception e)
236         {
237             logger.error("An error occurred so we should not complete the transaction:" + e, e);
238             //CmsSystem.log(entity,"Failed to create object", CmsSystem.DBG_LOW);
239             rollbackTransaction(db);
240             throw new SystemException(e.getMessage());
241         }
242         return entity;
243     }
244 */

245
246     // Delete entity
247
public static void deleteEntity(Class JavaDoc entClass, Integer JavaDoc id) throws Bug, SystemException
248     {
249         Database db = CastorDatabaseService.getDatabase();
250         Object JavaDoc entity = null;
251
252         beginTransaction(db);
253
254         try
255         {
256             entity = getObjectWithId(entClass, id, db);
257             
258             // Delete the entity
259
db.remove(entity);
260             commitTransaction(db);
261             //CmsSystem.log(entity,"Deleted object", CmsSystem.DBG_NORMAL);
262
//CmsSystem.transactionLogEntry(entClass.getName(), CmsSystem.TRANS_DELETE, id, entity.toString());
263
}
264         catch(Exception JavaDoc e)
265         {
266             logger.error("An error occurred so we should not complete the transaction:" + e, e);
267             rollbackTransaction(db);
268             throw new SystemException(e.getMessage());
269         }
270     }
271
272
273     // Delete entity
274
public static void deleteEntity(Class JavaDoc entClass, String JavaDoc id) throws Bug, SystemException
275     {
276         Database db = CastorDatabaseService.getDatabase();
277         Object JavaDoc entity = null;
278
279         beginTransaction(db);
280
281         try
282         {
283             entity = getObjectWithId(entClass, id, db);
284             
285             // Delete the entity
286
db.remove(entity);
287             commitTransaction(db);
288             //CmsSystem.log(entity,"Deleted object", CmsSystem.DBG_NORMAL);
289
//CmsSystem.transactionLogEntry(entClass.getName(), CmsSystem.TRANS_DELETE, id, entity.toString());
290
}
291         catch(Exception JavaDoc e)
292         {
293             logger.error("An error occurred so we should not complete the transaction:" + e, e);
294             rollbackTransaction(db);
295             throw new SystemException(e.getMessage());
296         }
297     }
298
299
300     // Delete entity
301
public static void deleteEntity(Class JavaDoc entClass, String JavaDoc id, Database db) throws Bug, SystemException, Exception JavaDoc
302     {
303         Object JavaDoc entity = getObjectWithId(entClass, id, db);
304         // Delete the entity
305
db.remove(entity);
306     }
307
308     
309     // Delete entity
310
public static void deleteEntity(Class JavaDoc entClass, Integer JavaDoc id, Database db) throws Bug, SystemException
311     {
312         Object JavaDoc entity = null;
313
314         try
315         {
316             entity = getObjectWithId(entClass, id, db);
317             // Delete the entity
318
db.remove(entity);
319         }
320         catch(Exception JavaDoc e)
321         {
322             logger.error("An error occurred so we should not complete the transaction:" + e, e);
323             throw new SystemException(e.getMessage());
324         }
325     }
326
327
328     public static BaseEntityVO updateEntity(Class JavaDoc arg, BaseEntityVO vo) throws Bug, SystemException
329     {
330         Database db = CastorDatabaseService.getDatabase();
331
332         IBaseEntity entity = null;
333
334         beginTransaction(db);
335
336         try
337         {
338             entity = (IBaseEntity) getObjectWithId(arg, vo.getId(), db);
339             entity.setVO(vo);
340
341             commitTransaction(db);
342         }
343         catch(Exception JavaDoc e)
344         {
345             logger.error("An error occurred so we should not complete the transaction:" + e, e);
346             rollbackTransaction(db);
347             throw new SystemException(e.getMessage());
348         }
349
350         return entity.getVO();
351     }
352
353     
354     public static BaseEntityVO updateEntity(Class JavaDoc arg, BaseEntityVO vo, Database db) throws Bug, SystemException
355     {
356         IBaseEntity entity = null;
357
358         entity = (IBaseEntity) getObjectWithId(arg, vo.getId(), db);
359         entity.setVO(vo);
360
361         return entity.getVO();
362     }
363
364     
365     /* Update entity and a collection with other entities
366      * Experimental, use with caution
367      *
368      */

369     public static BaseEntityVO updateEntity(Class JavaDoc entClass, BaseEntityVO vo, String JavaDoc collectionMethod, Class JavaDoc manyClass, String JavaDoc[] manyIds) throws ConstraintException, SystemException
370     {
371         Database db = CastorDatabaseService.getDatabase();
372         ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer();
373
374         IBaseEntity entity = null;
375
376         beginTransaction(db);
377
378         try
379         {
380             //add validation here if needed
381
List JavaDoc manyList = new ArrayList JavaDoc();
382             if(manyIds != null)
383             {
384                 for (int i=0; i < manyIds.length; i++)
385                 {
386                     IBaseEntity manyEntity = (IBaseEntity) getObjectWithId(manyClass, new Integer JavaDoc(manyIds[i]), db);
387                     logger.info("!!Using experimental code: BaseController::update. getting " + manyEntity.toString());
388                     manyList.add(manyEntity);
389                 }
390             }
391             
392         
393             entity = (IBaseEntity) getObjectWithId(entClass, vo.getId(), db);
394             entity.setVO(vo);
395             
396             // Now reflect to set the collection
397
Object JavaDoc[] arg = {manyList};
398             Class JavaDoc[] parm = {Collection JavaDoc.class};
399             entity.getClass().getDeclaredMethod(collectionMethod, parm).invoke(entity, arg);
400                         
401             // DONE
402

403             //If any of the validations or setMethods reported an error, we throw them up now before create.
404
ceb.throwIfNotEmpty();
405             
406             commitTransaction(db);
407             //CmsSystem.transactionLogEntry(entity.getClass().getName(), CmsSystem.TRANS_UPDATE, vo.getId(), entity.toString());
408

409         }
410         catch(ConstraintException ce)
411         {
412             logger.warn("An error occurred so we should not complete the transaction:" + ce, ce);
413             rollbackTransaction(db);
414             throw ce;
415         }
416         catch(Exception JavaDoc e)
417         {
418             logger.error("An error occurred so we should not complete the transaction:" + e, e);
419             rollbackTransaction(db);
420             throw new SystemException(e.getMessage());
421         }
422
423         return entity.getVO();
424     }
425
426     /*
427      * Update entity and a collection with other entities
428      * Experimental, use with caution
429      */

430     public static IBaseEntity updateEntity(Class JavaDoc entClass, BaseEntityVO vo, String JavaDoc collectionMethod, Class JavaDoc manyClass, String JavaDoc[] manyIds, Database db) throws ConstraintException, SystemException, Exception JavaDoc
431     {
432         IBaseEntity entity = null;
433
434         List JavaDoc manyList = new ArrayList JavaDoc();
435         if(manyIds != null)
436         {
437             for (int i=0; i < manyIds.length; i++)
438             {
439                 IBaseEntity manyEntity = (IBaseEntity) getObjectWithId(manyClass, new Integer JavaDoc(manyIds[i]), db);
440                 logger.info("!!Using experimental code: BaseController::update. getting " + manyEntity.toString());
441                 manyList.add(manyEntity);
442             }
443         }
444         
445         entity = (IBaseEntity) getObjectWithId(entClass, vo.getId(), db);
446         entity.setVO(vo);
447         
448         // Now reflect to set the collection
449
Object JavaDoc[] arg = {manyList};
450         Class JavaDoc[] parm = {Collection JavaDoc.class};
451         entity.getClass().getDeclaredMethod(collectionMethod, parm).invoke(entity, arg);
452                         
453         return entity;
454     }
455
456
457     /*
458     protected static Object getObjectWithId(Class arg, Integer id) throws SystemException, Bug
459     {
460         Database db = CastorDatabaseService.getDatabase();
461         Object ret = null;
462         try
463         {
464             beginTransaction(db);
465             ret = getObjectWithId(arg, id, db);
466             commitTransaction(db);
467         }
468         catch (Exception e)
469         {
470             rollbackTransaction(db);
471             throw new SystemException("An error occurred when we tried to fetch the object " + arg.getName() + ". Reason:" + e.getMessage(), e);
472         }
473         return ret;
474     }
475     */

476
477     /**
478      * This method fetches one object / entity within a transaction.
479      **/

480     
481     protected static Object JavaDoc getObjectWithId(Class JavaDoc arg, Integer JavaDoc id, Database db) throws SystemException, Bug
482     {
483         Object JavaDoc object = null;
484         try
485         {
486             logger.info("Loading " + arg + " in read/write mode.");
487             object = db.load(arg, id);
488         }
489         catch(Exception JavaDoc e)
490         {
491             throw new SystemException("An error occurred when we tried to fetch the object " + arg.getName() + ". Reason:" + e.getMessage(), e);
492         }
493     
494         if(object == null)
495         {
496             throw new Bug("The object with id [" + id + "] was not found. This should never happen.");
497         }
498         return object;
499     }
500
501
502     /**
503      * This method fetches one object / entity within a transaction.
504      **/

505     
506     protected static Object JavaDoc getObjectWithIdAsReadOnly(Class JavaDoc arg, Integer JavaDoc id, Database db) throws SystemException, Bug
507     {
508         Object JavaDoc object = null;
509         try
510         {
511             object = db.load(arg, id, Database.ReadOnly);
512         }
513         catch(Exception JavaDoc e)
514         {
515             throw new SystemException("An error occurred when we tried to fetch the object " + arg.getName() + ". Reason:" + e.getMessage(), e);
516         }
517     
518         if(object == null)
519         {
520             throw new Bug("The object with id [" + id + "] was not found. This should never happen.");
521         }
522         return object;
523     }
524
525     /**
526      * This method fetches one object / entity within a transaction.
527      **/

528     
529     protected static Object JavaDoc getObjectWithId(Class JavaDoc arg, String JavaDoc id, Database db) throws SystemException, Bug
530     {
531         Object JavaDoc object = null;
532         try
533         {
534             logger.info("Loading " + arg + " in read/write mode.");
535
536             object = db.load(arg, id);
537         }
538         catch(Exception JavaDoc e)
539         {
540             throw new SystemException("An error occurred when we tried to fetch the object " + arg.getName() + ". Reason:" + e.getMessage(), e);
541         }
542     
543         if(object == null)
544         {
545             throw new Bug("The object with id [" + id + "] was not found. This should never happen.");
546         }
547         return object;
548     }
549
550         
551     /**
552      * This method converts a List of entities to a list of value-objects.
553      */

554     
555     public static List JavaDoc toVOList(Collection JavaDoc baseEntities) throws SystemException, Bug
556     {
557         List JavaDoc resultVOList = new ArrayList JavaDoc();
558         
559         if(baseEntities != null)
560         {
561             Object JavaDoc o = null;
562             try
563             {
564                 Iterator JavaDoc iterator = baseEntities.iterator();
565                 while (iterator.hasNext())
566                 {
567                     o = (Object JavaDoc)iterator.next();
568                     // Om metoden getValueObject saknas, kastas ett undantag.
569
resultVOList.add(o.getClass().getDeclaredMethod("getValueObject", new Class JavaDoc[0]).invoke(o, new Object JavaDoc[0]));
570                 }
571             }
572             catch(NoSuchMethodException JavaDoc e)
573             {
574                 throw new Bug("The object in list was of the wrong type: " + o.getClass().getName() + ". This should never happen.", e);
575             }
576             catch(Exception JavaDoc e)
577             {
578                 throw new SystemException("An error occurred when we tried to convert the collection to a valueList. Reason:" + e.getMessage(), e);
579             }
580         }
581             
582         return resultVOList;
583     }
584
585     /**
586      * This method converts a List of entities to a list of value-objects.
587      */

588     
589     public static List JavaDoc toModifiableVOList(Collection JavaDoc baseEntities) throws SystemException, Bug
590     {
591         List JavaDoc resultVOList = new ArrayList JavaDoc();
592         
593         if(baseEntities != null)
594         {
595             Object JavaDoc o = null;
596             try
597             {
598                 Iterator JavaDoc iterator = baseEntities.iterator();
599                 while (iterator.hasNext())
600                 {
601                     o = (Object JavaDoc)iterator.next();
602                     // Om metoden getValueObject saknas, kastas ett undantag.
603
resultVOList.add(o.getClass().getDeclaredMethod("getValueObject", new Class JavaDoc[0]).invoke(o, new Object JavaDoc[0]));
604                 }
605             }
606             catch(NoSuchMethodException JavaDoc e)
607             {
608                 throw new Bug("The object in list was of the wrong type: " + o.getClass().getName() + ". This should never happen.", e);
609             }
610             catch(Exception JavaDoc e)
611             {
612                 throw new SystemException("An error occurred when we tried to convert the collection to a valueList. Reason:" + e.getMessage(), e);
613             }
614         }
615             
616         return resultVOList;
617     }
618
619     /***************************************************
620      * Read only operations
621      ***************************************************/

622
623     /**
624      * This method is used to fetch a ValueObject from the database.
625      */

626
627     public static Object JavaDoc getVOWithId(Class JavaDoc arg, Integer JavaDoc id) throws SystemException, Bug
628     {
629         Database db = CastorDatabaseService.getDatabase();
630         Object JavaDoc ret = null;
631         try
632         {
633             beginTransaction(db);
634             ret = getVOWithId(arg, id, db);
635             commitTransaction(db);
636         }
637         catch (Exception JavaDoc e)
638         {
639             rollbackTransaction(db);
640             throw new SystemException("An error occurred when we tried to fetch the object " + arg.getName() + ". Reason:" + e.getMessage(), e);
641         }
642         return ret;
643     }
644
645     /**
646      * This method fetches one object in read only mode and returns it's value object.
647      */

648     
649     public static BaseEntityVO getVOWithId(Class JavaDoc arg, Integer JavaDoc id, Database db) throws SystemException, Bug
650     {
651         IBaseEntity vo = null;
652         try
653         {
654             vo = (IBaseEntity)db.load(arg, id, Database.ReadOnly);
655         }
656         catch(Exception JavaDoc e)
657         {
658             throw new SystemException("An error occurred when we tried to fetch the object " + arg.getName() + ". Reason:" + e.getMessage(), e);
659         }
660     
661         if(vo == null)
662         {
663             throw new Bug("The object with id [" + id + "] was not found. This should never happen.");
664         }
665         
666         return vo.getVO();
667     }
668     
669     
670     /**
671      * This method is used to fetch a ValueObject from the database.
672      */

673
674     public static Object JavaDoc getVOWithId(Class JavaDoc arg, String JavaDoc id) throws SystemException, Bug
675     {
676         Database db = CastorDatabaseService.getDatabase();
677         Object JavaDoc ret = null;
678         try
679         {
680             beginTransaction(db);
681             ret = getVOWithId(arg, id, db);
682             commitTransaction(db);
683         }
684         catch (Exception JavaDoc e)
685         {
686             rollbackTransaction(db);
687             throw new SystemException("An error occurred when we tried to fetch the object " + arg.getName() + ". Reason:" + e.getMessage(), e);
688         }
689         return ret;
690     }
691     
692     /**
693      * This method fetches one object in read only mode and returns it's value object.
694      */

695     
696     public static BaseEntityVO getVOWithId(Class JavaDoc arg, String JavaDoc id, Database db) throws SystemException, Bug
697     {
698         IBaseEntity vo = null;
699         try
700         {
701             vo = (IBaseEntity)db.load(arg, id, Database.ReadOnly);
702         }
703         catch(Exception JavaDoc e)
704         {
705             throw new SystemException("An error occurred when we tried to fetch the object " + arg.getName() + ". Reason:" + e.getMessage(), e);
706         }
707     
708         if(vo == null)
709         {
710             throw new Bug("The object with id [" + id + "] was not found. This should never happen.");
711         }
712         
713         return vo.getVO();
714     }
715
716
717     /**
718      * This method fetches all object in read only mode and returns a list of value objects.
719      */

720     /*
721     public static List getAllVOObjects(Class arg) throws SystemException, Bug
722     {
723         Database db = CastorDatabaseService.getDatabase();
724         List ret = null;
725         try
726         {
727             beginTransaction(db);
728             ret = getAllVOObjects(arg, db);
729             commitTransaction(db);
730         }
731         catch(Exception e)
732         {
733             rollbackTransaction(db);
734             throw new SystemException("An error occurred when we tried to fetch " + arg.getName() + " Reason:" + e.getMessage(), e);
735         }
736         return ret;
737     }
738     */

739     
740     /**
741      * This method fetches all object in read only mode and returns a list of value objects.
742      */

743     
744     public static List JavaDoc getAllVOObjects(Class JavaDoc arg, String JavaDoc orderByAttribute, String JavaDoc direction) throws SystemException, Bug
745     {
746         Database db = CastorDatabaseService.getDatabase();
747         List JavaDoc ret = null;
748         try
749         {
750             beginTransaction(db);
751             ret = getAllVOObjects(arg, orderByAttribute, direction, db);
752             commitTransaction(db);
753         }
754         catch(Exception JavaDoc e)
755         {
756             rollbackTransaction(db);
757             throw new SystemException("An error occurred when we tried to fetch " + arg.getName() + " Reason:" + e.getMessage(), e);
758         }
759         return ret;
760     }
761
762
763     
764     /**
765      * This method fetches all object in read only mode and returns a list of value objects.
766      */

767
768     public static List JavaDoc getAllVOObjects(Class JavaDoc arg, String JavaDoc orderByField, String JavaDoc direction, Database db) throws SystemException, Bug
769     {
770         ArrayList JavaDoc resultList = new ArrayList JavaDoc();
771         OQLQuery oql;
772         try
773         {
774             
775             logger.info("BaseHelper::GetAllObjects for " + arg.getName());
776             oql = db.getOQLQuery( "SELECT u FROM " + arg.getName() + " u ORDER BY u." + orderByField + " " + direction);
777             QueryResults results = oql.execute(Database.ReadOnly);
778             
779             while (results.hasMore())
780             {
781                 Object JavaDoc o = results.next();
782
783                 // Om metoden getValueObject saknas, kastas ett undantag.
784
resultList.add(o.getClass().getDeclaredMethod("getValueObject", new Class JavaDoc[0]).invoke(o, new Object JavaDoc[0]));
785             }
786         }
787         catch(NoSuchMethodException JavaDoc e)
788         {
789             throw new Bug("The object [" + arg.getName() + "] is of the wrong type. This should never happen.", e);
790         }
791         catch(Exception JavaDoc e)
792         {
793             throw new SystemException("An error occurred when we tried to fetch " + arg.getName() + " Reason:" + e.getMessage(), e);
794         }
795
796         return resultList;
797     }
798     
799     /**
800      * This method fetches all object in read only mode and returns a list of value objects sorted on primary Key.
801      */

802      
803     public List JavaDoc getAllVOObjects(Class JavaDoc arg, String JavaDoc primaryKey) throws SystemException, Bug
804     {
805         Database db = CastorDatabaseService.getDatabase();
806         List JavaDoc ret = null;
807         try
808         {
809             beginTransaction(db);
810             ret = getAllVOObjects(arg, primaryKey, db);
811             commitTransaction(db);
812         }
813         catch(Exception JavaDoc e)
814         {
815             rollbackTransaction(db);
816             throw new SystemException("An error occurred when we tried to fetch " + arg.getName() + " Reason:" + e.getMessage(), e);
817         }
818         return ret;
819     }
820
821
822     /**
823      * This method fetches all object in read only mode and returns a list of value objects.
824      */

825
826     public List JavaDoc getAllVOObjects(Class JavaDoc arg, String JavaDoc primaryKey, Database db) throws SystemException, Bug
827     {
828         ArrayList JavaDoc resultList = new ArrayList JavaDoc();
829         OQLQuery oql;
830         try
831         {
832             oql = db.getOQLQuery( "SELECT u FROM " + arg.getName() + " u ORDER BY u." + primaryKey);
833             QueryResults results = oql.execute(Database.ReadOnly);
834             
835             while (results.hasMore())
836             {
837                 IBaseEntity baseEntity = (IBaseEntity)results.next();
838                 resultList.add(baseEntity.getVO());
839             }
840         }
841         catch(ClassCastException JavaDoc e)
842         {
843             throw new Bug("The object [" + arg.getName() + "] is of the wrong type. This should never happen.", e);
844         }
845         catch(Exception JavaDoc e)
846         {
847             throw new SystemException("An error occurred when we tried to fetch " + arg.getName() + " Reason:" + e.getMessage(), e);
848         }
849
850         return resultList;
851     }
852
853     /**
854      * This method fetches all object in read only mode and returns a list of objects.
855      */

856
857     public List JavaDoc getAllObjects(Class JavaDoc arg, String JavaDoc primaryKey, Database db) throws SystemException, Bug
858     {
859         ArrayList JavaDoc resultList = new ArrayList JavaDoc();
860         OQLQuery oql;
861         try
862         {
863             oql = db.getOQLQuery( "SELECT u FROM " + arg.getName() + " u ORDER BY u." + primaryKey);
864             QueryResults results = oql.execute(Database.ReadOnly);
865             
866             while (results.hasMore())
867             {
868                 IBaseEntity baseEntity = (IBaseEntity)results.next();
869                 resultList.add(baseEntity);
870             }
871         }
872         catch(ClassCastException JavaDoc e)
873         {
874             throw new Bug("The object [" + arg.getName() + "] is of the wrong type. This should never happen.", e);
875         }
876         catch(Exception JavaDoc e)
877         {
878             throw new SystemException("An error occurred when we tried to fetch " + arg.getName() + " Reason:" + e.getMessage(), e);
879         }
880
881         return resultList;
882     }
883
884     //---------------------------------------------------------------------
885
// Dynamic Query specific operations
886
//---------------------------------------------------------------------
887
/**
888      * Executes a Query with no parameters
889      *
890      * @param query An OQL Query
891      * @return A VO list of the query results
892      * @throws SystemException If an error occurs
893      */

894     protected static List JavaDoc executeQuery(String JavaDoc query) throws SystemException
895     {
896         return executeQuery(query, Collections.EMPTY_LIST);
897     }
898
899     /**
900      * Executes a Query with no parameters
901      *
902      * @param query An OQL Query
903      * @return A VO list of the query results
904      * @throws SystemException If an error occurs
905      */

906     protected static List JavaDoc executeQuery(String JavaDoc query, Database db) throws SystemException
907     {
908         return executeQuery(query, Collections.EMPTY_LIST, db);
909     }
910
911     /**
912      * Executes a Query, also binds the provided parameters
913      *
914      * @param query An OQL Query
915      * @param params A List of paramters
916      * @return A VO list of the query results
917      * @throws SystemException If an error occurs
918      */

919     protected static List JavaDoc executeQuery(String JavaDoc query, List JavaDoc params) throws SystemException
920     {
921         Database db = beginTransaction();
922
923         try
924         {
925             List JavaDoc results = new ArrayList JavaDoc();
926             results = Collections.list(createQuery(db, query, params).execute(Database.ReadOnly));
927             commitTransaction(db);
928             return toVOList(results);
929         }
930         catch (Exception JavaDoc e)
931         {
932             logger.error("Error executing " + query, e);
933             rollbackTransaction(db);
934             throw new SystemException(e.getMessage(), e);
935         }
936     }
937
938     
939     /**
940      * Executes a Query, also binds the provided parameters
941      *
942      * @param query An OQL Query
943      * @param params A List of paramters
944      * @param db A transaction object
945      * @return A VO list of the query results
946      * @throws SystemException If an error occurs
947      */

948     protected static List JavaDoc executeQuery(String JavaDoc query, List JavaDoc params, Database db) throws SystemException
949     {
950         try
951         {
952             List JavaDoc resultList = new ArrayList JavaDoc();
953             
954             OQLQuery oql = createQuery(db, query, params);
955             QueryResults results = oql.execute();
956             resultList = Collections.list(results);
957
958             results.close();
959             oql.close();
960
961             return resultList;
962         }
963         catch (Exception JavaDoc e)
964         {
965             logger.error("Error executing " + query, e);
966             throw new SystemException(e.getMessage(), e);
967         }
968     }
969
970     
971     /**
972      * Creates an OQLQuery for the provided Database and binds the parameters to it.
973      *
974      * @param db The Database to create the OQLQuery on
975      * @param query The String OQL query
976      * @param params A List of Objects to bind to the query sequentially
977      * @return An OQLQuery instance that can be executer
978      * @throws PersistenceException
979      */

980     protected static OQLQuery createQuery(Database db, String JavaDoc query, List JavaDoc params) throws PersistenceException
981     {
982         OQLQuery oql = db.getOQLQuery(query);
983         if (params != null)
984             for (Iterator JavaDoc i = params.iterator(); i.hasNext();)
985                 oql.bind(i.next());
986
987         return oql;
988     }
989
990
991     /***************************************************
992      * Validation and integrity check of entities - cre 2002-09-18 / SS
993      * *************************************************/

994
995     public static ConstraintExceptionBuffer validateEntity(ValidatableEntityVO vo)
996     {
997         // This method loops through the rulelist and creates
998
// validators according to the settings in each rule.
999
// The old validators are used to do the actual validation
1000
// but I have changed them to use less constructor
1001
// parameter passing in favour for setters.
1002

1003        //CmsSystem.log("ValidationController::validate()", CmsSystem.DBG_HIGH);
1004
ConstraintExceptionBuffer ceb = new ConstraintExceptionBuffer();
1005        
1006        // Prepare the object for validation
1007
vo.PrepareValidation();
1008        
1009        // Loop through rules and create validators
1010
Iterator JavaDoc iterator = vo.getConstraintRules().iterator();
1011        while (iterator.hasNext())
1012        {
1013            ConstraintRule cr = (ConstraintRule) iterator.next();
1014            Integer JavaDoc intId = vo.getId();
1015            logger.info("Validating object id: " + intId);
1016
1017            // an ugly switch for now.
1018
switch (cr.getConstraintType())
1019            {
1020                case Constants.EMAIL:
1021                {
1022                    if (cr.getValue() != null)
1023                    {
1024                        // Create validator
1025
EmailValidator v = new EmailValidator(cr.getFieldName());
1026                        
1027                        // Set properties
1028
v.setObjectClass(vo.getConstraintRuleList().getEntityClass());
1029                        v.setRange(cr.getValidRange());
1030                        v.setIsRequired(cr.required);
1031                        v.setMustBeUnique(cr.unique);
1032                        v.setExcludeId(intId);
1033
1034                        // Do the limbo
1035
v.validate((String JavaDoc) cr.getValue(), ceb);
1036                        
1037                        // <todo>
1038
// Note: the actual value validated should be extracted
1039
// from the vo using the fieldname with reflection.
1040
// </todo>
1041

1042                    }
1043                    break;
1044                }
1045                case Constants.STRING:
1046                {
1047                    if (cr.getValue() != null)
1048                    {
1049                        StringValidator v = new StringValidator(cr.getFieldName());
1050                        v.setObjectClass(vo.getConstraintRuleList().getEntityClass());
1051                        v.setRange(cr.getValidRange());
1052                        v.setIsRequired(cr.required);
1053                        v.setMustBeUnique(cr.unique);
1054                        v.setExcludeId(intId);
1055
1056                        v.validate((String JavaDoc) cr.getValue(), ceb);
1057                    }
1058                    break;
1059                }
1060                case Constants.FLOAT:
1061                {
1062                    break;
1063                }
1064                case Constants.INTEGER:
1065                {
1066                    break;
1067                }
1068                case Constants.PROPERNOUN:
1069                {
1070                    break;
1071                }
1072                
1073            } // switch
1074

1075        } // while
1076

1077        return ceb;
1078    }
1079
1080
1081
1082    /***************************************************
1083     * Transaction specifik operations
1084     ***************************************************/

1085
1086    /**
1087     * Creates a new database and starts a transaction
1088     * @return A reference to a castor database with a new transaction
1089     * @throws SystemException if a database error occurs.
1090     */

1091    protected static Database beginTransaction() throws SystemException
1092    {
1093        Database db = CastorDatabaseService.getDatabase();
1094        beginTransaction(db);
1095        return db;
1096    }
1097
1098    /**
1099     * Begins a transaction on the named database
1100     */

1101         
1102    protected static void beginTransaction(Database db) throws SystemException
1103    {
1104        try
1105        {
1106            //logger.info("Opening a new Transaction in cms...");
1107
db.begin();
1108        }
1109        catch(Exception JavaDoc e)
1110        {
1111            throw new SystemException("An error occurred when we tried to begin an transaction. Reason:" + e.getMessage(), e);
1112        }
1113    }
1114       
1115    /**
1116     * Ends a transaction on the named database
1117     */

1118     
1119    protected static void commitTransaction(Database db) throws SystemException
1120    {
1121        try
1122        {
1123            //logger.info("Closing a transaction in cms...");
1124

1125            db.commit();
1126            db.close();
1127        }
1128        catch(Exception JavaDoc e)
1129        {
1130            throw new SystemException("An error occurred when we tried to commit an transaction. Reason:" + e.getMessage(), e);
1131        }
1132    }
1133 
1134 
1135    /**
1136     * Rollbacks a transaction on the named database
1137     */

1138     
1139    protected static void rollbackTransaction(Database db) throws SystemException
1140    {
1141        try
1142        {
1143            //logger.info("rollbackTransaction a transaction in cms...");
1144

1145            if (db != null && db.isActive())
1146            {
1147                db.rollback();
1148                db.close();
1149            }
1150        }
1151        catch(Exception JavaDoc e)
1152        {
1153            logger.warn("An error occurred when we tried to rollback an transaction. Reason:" + e.getMessage());
1154        }
1155    }
1156
1157    /**
1158     * Rollbacks a transaction on the named database
1159     */

1160     
1161    protected static void closeDatabase(Database db) throws SystemException
1162    {
1163        try
1164        {
1165            if (db != null)
1166            {
1167                db.close();
1168            }
1169        }
1170        catch(Exception JavaDoc e)
1171        {
1172            logger.warn("An error occurred when we tried to rollback an transaction. Reason:" + e.getMessage());
1173        }
1174    }
1175
1176    public abstract BaseEntityVO getNewVO();
1177}
Popular Tags