Author: fdesbois Date: 2010-05-07 17:19:41 +0200 (Fri, 07 May 2010) New Revision: 1935 Url: http://nuiton.org/repositories/revision/topia/1935 Log: Clean javadoc + format for 80chars Added: trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/package-info.java Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/EntityState.java trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaContextImpl.java trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaContextImplementor.java trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaFiresSupport.java trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaQuery.java trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaService.java trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaUtil.java trunk/topia-persistence/src/main/resources/i18n/topia-persistence-en_GB.properties trunk/topia-persistence/src/main/resources/i18n/topia-persistence-fr_FR.properties Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/EntityState.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/EntityState.java 2010-05-07 13:15:19 UTC (rev 1934) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/EntityState.java 2010-05-07 15:19:41 UTC (rev 1935) @@ -38,7 +38,7 @@ package org.nuiton.topia.framework; /** - * Used to know the state of entity during transaction + * Used to know the state of entity during transaction. * * @author poussin <poussin@codelutin.com> */ Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaContextImpl.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaContextImpl.java 2010-05-07 13:15:19 UTC (rev 1934) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaContextImpl.java 2010-05-07 15:19:41 UTC (rev 1935) @@ -27,20 +27,6 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaContextFactory; -import org.nuiton.topia.TopiaException; -import org.nuiton.topia.TopiaNotFoundException; -import org.nuiton.topia.event.TopiaContextListener; -import org.nuiton.topia.event.TopiaEntitiesVetoable; -import org.nuiton.topia.event.TopiaEntityListener; -import org.nuiton.topia.event.TopiaEntityVetoable; -import org.nuiton.topia.event.TopiaTransactionListener; -import org.nuiton.topia.event.TopiaTransactionVetoable; -import org.nuiton.topia.persistence.TopiaDAO; -import org.nuiton.topia.persistence.TopiaEntity; -import org.nuiton.topia.persistence.TopiaId; -import org.nuiton.util.ArrayUtil; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.DocumentFactory; @@ -68,6 +54,22 @@ import org.hibernate.event.PreUpdateEventListener; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.hibernate.tool.hbm2ddl.SchemaUpdate; +import org.nuiton.i18n.I18n; +import org.nuiton.topia.TopiaContext; +import org.nuiton.topia.TopiaContextFactory; +import org.nuiton.topia.TopiaException; +import org.nuiton.topia.TopiaNotFoundException; +import org.nuiton.topia.event.TopiaContextListener; +import org.nuiton.topia.event.TopiaEntitiesVetoable; +import org.nuiton.topia.event.TopiaEntityListener; +import org.nuiton.topia.event.TopiaEntityVetoable; +import org.nuiton.topia.event.TopiaTransactionListener; +import org.nuiton.topia.event.TopiaTransactionVetoable; +import org.nuiton.topia.persistence.TopiaDAO; +import org.nuiton.topia.persistence.TopiaDAOImpl; +import org.nuiton.topia.persistence.TopiaEntity; +import org.nuiton.topia.persistence.TopiaId; +import org.nuiton.util.ArrayUtil; import java.beans.PropertyChangeListener; import java.io.BufferedInputStream; @@ -94,30 +96,27 @@ import java.util.Set; import java.util.WeakHashMap; import java.util.zip.GZIPInputStream; -import org.nuiton.topia.persistence.TopiaDAOImpl; -import static org.nuiton.i18n.I18n._; /** + * TODO-fdesbois-20100507 : Need translation of javadoc. + * <p/> * Le TopiaContextImpl est le point d'entre pour acceder aux donnees. Il est * configurer par un fichier de propriete - * <p> - * List des proprietes disponible - * <dl> - * <dt> topia.persistence.properties.file + * <p/> + * List des proprietes disponible <dl> <dt> topia.persistence.properties.file * <dd> le fichier de propriété a utiliser pour configurer hibernate - * - * <dt> topia.persistence.directories - * <dd> la liste des repertoires contenant les mappings hibernates (.hbm.xml) la - * liste de repertoire est separer par des virgules ',' - * - * <dt> topia.persistence.classes - * <dd> la liste des classes que doit géré hibernate. On peut tres bien utiliser - * topia.persistence.directories pour un ensemble d'entié du meme repertoire et - * topia.persistence.classes pour d'autres classes - * </dl> - * + * <p/> + * <dt> topia.persistence.directories <dd> la liste des repertoires contenant + * les mappings hibernates (.hbm.xml) la liste de repertoire est separer par des + * virgules ',' + * <p/> + * <dt> topia.persistence.classes <dd> la liste des classes que doit géré + * hibernate. On peut tres bien utiliser topia.persistence.directories pour un + * ensemble d'entié du meme repertoire et topia.persistence.classes pour + * d'autres classes </dl> + * <p/> * TopiaContextImpl.java - * + * <p/> * Created: 23 déc. 2005 16:58:50 * * @author poussin <poussin@codelutin.com> @@ -139,14 +138,10 @@ public static final String TOPIA_PERSISTENCE_PROPERTIES_FILE = "topia.persistence.properties.file"; - /** - * Le pere de ce context, les contexts initaux n'ont pas de context pere - */ + /** Le pere de ce context, les contexts initaux n'ont pas de context pere */ protected TopiaContextImplementor parentContext; - /** - * L'objet configuration utilisé pour la creation de la factory hibernate - */ + /** L'objet configuration utilisé pour la creation de la factory hibernate */ protected Configuration hibernateConfiguration; /** @@ -155,35 +150,26 @@ */ protected SessionFactory hibernateFactory; - /** - * La session utilisé par le TopiaContextImpl - */ + /** La session utilisé par le TopiaContextImpl */ protected Session hibernate; - /** - * Indique si le contexte a ete ferme - */ + /** Indique si le contexte a ete ferme */ protected boolean closed; - /** - * Propriete de configuration - */ + /** Propriete de configuration */ protected Properties config; - /** - * cache des DAO deja chargé pour ce context - */ + /** cache des DAO deja chargé pour ce context */ protected Map<Class<? extends TopiaEntity>, - TopiaDAO<? extends TopiaEntity>> daoCache = - new HashMap<Class<? extends TopiaEntity>, - TopiaDAO<? extends TopiaEntity>>(); - + TopiaDAO<? extends TopiaEntity>> daoCache = + new HashMap<Class<? extends TopiaEntity>, + TopiaDAO<? extends TopiaEntity>>(); + /** * Set of child context created with {@link #beginTransaction()}. We are - * listener on these context. - * A WeakHashMap is used to remove old context automically when it's not - * used anymore. The {@link #finalize} method will be executed when Garbage - * collector is called when reference is removed. + * listener on these context. A WeakHashMap is used to remove old context + * automically when it's not used anymore. The {@link #finalize} method will + * be executed when Garbage collector is called when reference is removed. * The set is synchronized in case of using multi-threading. * * @see Collections#synchronizedSet(Set) @@ -191,9 +177,9 @@ */ protected final Set<TopiaContextImplementor> childContext = Collections.synchronizedSet( - Collections.newSetFromMap( - new WeakHashMap<TopiaContextImplementor, Boolean>())); - + Collections.newSetFromMap( + new WeakHashMap<TopiaContextImplementor, Boolean>())); + /** key: service name; value: service instance */ protected Map<String, TopiaService> services; @@ -229,16 +215,16 @@ TopiaService service = (TopiaService) newInstance; if (key.equals("topia.service." + service.getServiceName())) { result.put(service.getServiceName(), service); - log.info(_("topia.persistence.service.loaded", key, classService)); -// log.info("Service " + key + " loaded by " + classService); + log.info(I18n._("topia.persistence.service.loaded", + key, classService)); } else { - log.warn(_("topia.persistence.warn.service.not.loaded", key, service.getServiceName())); -// log.warn("Service config key doesn't match service name, disable it: " + key + " != " + service.getServiceName()); + log.warn(I18n._("topia.persistence.warn.service.not.loaded", + key, service.getServiceName())); } } catch (Throwable eee) { if (log.isErrorEnabled()) { - log.error(_("topia.persistence.error.service.unknown", key, classService)); -// log.error("Service class unknow for " + key + ": " + classService); + log.error(I18n._("topia.persistence.error.service.unknown", + key, classService)); } if (log.isDebugEnabled()) { log.debug(eee); @@ -252,8 +238,8 @@ protected void preInitServices(Map<String, TopiaService> services) { for (TopiaService service : services.values()) { if (!service.preInit(this)) { - log.warn(_("topia.persistence.warn.service.not.preInit", service.getServiceName())); -// log.warn("Can't preInit service disable it: " + service.getServiceName()); + log.warn(I18n._("topia.persistence.warn.service.not.preInit", + service.getServiceName())); } } } @@ -261,8 +247,8 @@ protected void postInitServices(Map<String, TopiaService> services) { for (TopiaService service : services.values()) { if (!service.postInit(this)) { - log.warn(_("topia.persistence.warn.service.not.postInit", service.getServiceName())); -// log.warn("Can't postInit service disable it: " + service.getServiceName()); + log.warn(I18n._("topia.persistence.warn.service.not.postInit", + service.getServiceName())); } } } @@ -300,8 +286,8 @@ result = serviceEnabled(name); } catch (Exception eee) { if (log.isWarnEnabled()) { - log.warn(_("topia.persistence.warn.service.not.found", interfaceService, eee.getMessage()), eee); -// log.warn("Can't get service name for: " + interfaceService, eee); + log.warn(I18n._("topia.persistence.warn.service.not.found", + interfaceService, eee.getMessage()), eee); } } return result; @@ -310,6 +296,7 @@ /** * Take one service, this service must be valid service interface with * public static final SERVICE_NAME declaration. + * * @param <E> * @throws TopiaNotFoundException */ @@ -321,14 +308,15 @@ String name = (String) f.get(null); E result = (E) getService(name); if (result == null) { - throw new TopiaNotFoundException(_("topia.persistence.error.service.not.found", interfaceService)); -// throw new TopiaNotFoundException("Service not available: " + interfaceService); + throw new TopiaNotFoundException( + I18n._("topia.persistence.error.service.not.found", + interfaceService)); } return result; } catch (Exception eee) { - - throw new TopiaNotFoundException(_("topia.persistence.error.service.not.retreaved", interfaceService, eee.getMessage()), eee); -// throw new TopiaNotFoundException("Can't get service: " + interfaceService, eee); + throw new TopiaNotFoundException( + I18n._("topia.persistence.error.service.not.retreaved", + interfaceService, eee.getMessage()), eee); } } @@ -368,7 +356,8 @@ @Override public void removeChildContext(TopiaContextImplementor child) { - //On ne retire les fils que si ce contexte n'est pas deja ferme. Permet d'eviter les acces concurrentiels + // On ne retire les fils que si ce contexte n'est pas deja ferme. + // Permet d'eviter les acces concurrentiels if (!closed) { childContext.remove(child); } @@ -408,24 +397,28 @@ true); getFiresSupport().firePostCreateSchema(this); } catch (HibernateException eee) { - throw new TopiaException(_("topia.persistence.error.create.schema", eee.getMessage()), eee); -// throw new TopiaException("Can't create database schema", eee); + throw new TopiaException( + I18n._("topia.persistence.error.create.schema", + eee.getMessage()), eee); } } @Override public void showCreateSchema() throws TopiaException { try { - new SchemaExport(getHibernateConfiguration()).execute(true, false, false, true); + new SchemaExport(getHibernateConfiguration()). + execute(true, false, false, true); } catch (HibernateException eee) { - throw new TopiaException(_("topia.persistence.error.create.schema", eee.getMessage()), eee); -// throw new TopiaException("Can't create database schema", eee); + throw new TopiaException( + I18n._("topia.persistence.error.create.schema", + eee.getMessage()), eee); } } /* (non-Javadoc) * @see org.nuiton.topia.TopiaContext#createSchema() */ + @Override public void updateSchema() throws TopiaException { try { @@ -438,8 +431,9 @@ true); getFiresSupport().firePostUpdateSchema(this); } catch (HibernateException eee) { - throw new TopiaException(_("topia.persistence.error.update.schema", eee.getMessage()), eee); -// throw new TopiaException("Can't create database schema", eee); + throw new TopiaException( + I18n._("topia.persistence.error.update.schema", + eee.getMessage()), eee); } } @@ -448,11 +442,12 @@ * * @see org.nuiton.topia.framework.TopiaContextImplementor#getHibernate() */ + @Override public Session getHibernate() throws TopiaException { if (hibernate == null) { - throw new TopiaException(_("topia.persistence.error.no.hibernate.session")); -// throw new TopiaException("No hibernate session available, you must start a transaction with beginTransaction"); + throw new TopiaException( + I18n._("topia.persistence.error.no.hibernate.session")); } return hibernate; } @@ -462,6 +457,7 @@ * * @see org.nuiton.topia.framework.TopiaContextImplementor#getHibernateFactory() */ + @Override public SessionFactory getHibernateFactory() throws TopiaNotFoundException { if (hibernateFactory == null) { @@ -484,44 +480,74 @@ hibernateConfiguration = new Configuration(); // Ajout du listeners pour les events - TopiaFiresSupport.TopiaHibernateEvent listener = new TopiaFiresSupport.TopiaHibernateEvent( - this); + TopiaFiresSupport.TopiaHibernateEvent listener = + new TopiaFiresSupport.TopiaHibernateEvent(this); - PreInsertEventListener[] preInsertEventListeners = hibernateConfiguration.getEventListeners().getPreInsertEventListeners(); + PreInsertEventListener[] preInsertEventListeners = + hibernateConfiguration.getEventListeners(). + getPreInsertEventListeners(); preInsertEventListeners = ArrayUtil.concatElems( preInsertEventListeners, listener); - PreLoadEventListener[] preLoadEventListeners = hibernateConfiguration.getEventListeners().getPreLoadEventListeners(); + + PreLoadEventListener[] preLoadEventListeners = + hibernateConfiguration.getEventListeners(). + getPreLoadEventListeners(); preLoadEventListeners = ArrayUtil.concatElems( preLoadEventListeners, listener); - PreUpdateEventListener[] preUpdateEventListeners = hibernateConfiguration.getEventListeners().getPreUpdateEventListeners(); + + PreUpdateEventListener[] preUpdateEventListeners = + hibernateConfiguration.getEventListeners(). + getPreUpdateEventListeners(); preUpdateEventListeners = ArrayUtil.concatElems( preUpdateEventListeners, listener); - PreDeleteEventListener[] preDeleteEventListeners = hibernateConfiguration.getEventListeners().getPreDeleteEventListeners(); + + PreDeleteEventListener[] preDeleteEventListeners = + hibernateConfiguration.getEventListeners(). + getPreDeleteEventListeners(); preDeleteEventListeners = ArrayUtil.concatElems( preDeleteEventListeners, listener); - PostInsertEventListener[] postInsertEventListeners = hibernateConfiguration.getEventListeners().getPostInsertEventListeners(); + PostInsertEventListener[] postInsertEventListeners = + hibernateConfiguration.getEventListeners(). + getPostInsertEventListeners(); postInsertEventListeners = ArrayUtil.concatElems( postInsertEventListeners, listener); - PostLoadEventListener[] postLoadEventListeners = hibernateConfiguration.getEventListeners().getPostLoadEventListeners(); + + PostLoadEventListener[] postLoadEventListeners = + hibernateConfiguration.getEventListeners(). + getPostLoadEventListeners(); postLoadEventListeners = ArrayUtil.concatElems( postLoadEventListeners, listener); - PostUpdateEventListener[] postUpdateEventListeners = hibernateConfiguration.getEventListeners().getPostUpdateEventListeners(); + + PostUpdateEventListener[] postUpdateEventListeners = + hibernateConfiguration.getEventListeners(). + getPostUpdateEventListeners(); postUpdateEventListeners = ArrayUtil.concatElems( postUpdateEventListeners, listener); - PostDeleteEventListener[] postDeleteEventListeners = hibernateConfiguration.getEventListeners().getPostDeleteEventListeners(); + + PostDeleteEventListener[] postDeleteEventListeners = + hibernateConfiguration.getEventListeners(). + getPostDeleteEventListeners(); postDeleteEventListeners = ArrayUtil.concatElems( postDeleteEventListeners, listener); - hibernateConfiguration.getEventListeners().setPreInsertEventListeners(preInsertEventListeners); - hibernateConfiguration.getEventListeners().setPreLoadEventListeners(preLoadEventListeners); - hibernateConfiguration.getEventListeners().setPreUpdateEventListeners(preUpdateEventListeners); - hibernateConfiguration.getEventListeners().setPreDeleteEventListeners(preDeleteEventListeners); + hibernateConfiguration.getEventListeners(). + setPreInsertEventListeners(preInsertEventListeners); + hibernateConfiguration.getEventListeners(). + setPreLoadEventListeners(preLoadEventListeners); + hibernateConfiguration.getEventListeners(). + setPreUpdateEventListeners(preUpdateEventListeners); + hibernateConfiguration.getEventListeners(). + setPreDeleteEventListeners(preDeleteEventListeners); - hibernateConfiguration.getEventListeners().setPostInsertEventListeners(postInsertEventListeners); - hibernateConfiguration.getEventListeners().setPostLoadEventListeners(postLoadEventListeners); - hibernateConfiguration.getEventListeners().setPostUpdateEventListeners(postUpdateEventListeners); - hibernateConfiguration.getEventListeners().setPostDeleteEventListeners(postDeleteEventListeners); + hibernateConfiguration.getEventListeners(). + setPostInsertEventListeners(postInsertEventListeners); + hibernateConfiguration.getEventListeners(). + setPostLoadEventListeners(postLoadEventListeners); + hibernateConfiguration.getEventListeners(). + setPostUpdateEventListeners(postUpdateEventListeners); + hibernateConfiguration.getEventListeners(). + setPostDeleteEventListeners(postDeleteEventListeners); // ajout des repertoires contenant les mappings hibernate String[] dirs = getConfig().getProperty( @@ -556,8 +582,9 @@ try { clazz = Class.forName(classname); } catch (ClassNotFoundException eee) { - throw new TopiaNotFoundException(_("topia.persistence.error.class.not.found", classname)); -// throw new TopiaNotFoundException("Persistent class " + classname + " not found"); + throw new TopiaNotFoundException(I18n._( + "topia.persistence.error.class.not.found", + classname)); } persistenceClasses.add(clazz); hibernateConfiguration.addClass(clazz); @@ -580,24 +607,30 @@ * * @see org.nuiton.topia.framework.TopiaContextImplementor#getDAO(java.lang.Class) */ + @Override public <E extends TopiaEntity> TopiaDAO<E> getDAO(Class<E> entityClass) throws TopiaException { if (entityClass == null) { - throw new IllegalArgumentException(_("topia.persistence.error.null.parameter", "getDAO", "entityClass")); -// throw new IllegalArgumentException("null is not valid entity class"); + throw new IllegalArgumentException( + I18n._("topia.persistence.error.null.parameter", + "getDAO", "entityClass")); } if (getRootContext() == this) { - throw new TopiaException(_("topia.persistence.error.rootContext.access")); -// throw new TopiaException("Vous êtes sur le root context vous" + " devez ouvrir une transaction pour pouvoir accèder" + " aux données"); + throw new TopiaException( + I18n._("topia.persistence.error.rootContext.access")); } - if (getHibernateFactory().getClassMetadata(entityClass) == null && getHibernateFactory().getClassMetadata( - entityClass.getName() + "Impl") == null && getHibernateFactory().getClassMetadata( - entityClass.getName() + "Abstract") == null) { - log.info(_("topia.persistence.supported.classes.for.context", getHibernateFactory().getAllClassMetadata().keySet())); -// log.info("Classes supportées par ce TopiaContext: " + getHibernateFactory().getAllClassMetadata().keySet()); - throw new TopiaException(_("topia.persistence.error.unsupported.class", entityClass.getName())); -// throw new TopiaException("La classe " + entityClass.getName() + " n'est pas supportée par ce TopiaContext. Vous avez sans" + " doute oublié d'ajouter son mapping"); + if (getHibernateFactory().getClassMetadata(entityClass) == null && + getHibernateFactory().getClassMetadata( + entityClass.getName() + "Impl") == null && + getHibernateFactory().getClassMetadata( + entityClass.getName() + "Abstract") == null) { + + log.info(I18n._("topia.persistence.supported.classes.for.context", + getHibernateFactory().getAllClassMetadata().keySet())); + throw new TopiaException( + I18n._("topia.persistence.error.unsupported.class", + entityClass.getName())); } TopiaDAO<E> result = (TopiaDAO<E>) daoCache.get(entityClass); @@ -608,11 +641,13 @@ // si on utilise la génération String daoClassname = entityClass.getName() + "DAO"; try { - Class<TopiaDAO<E>> daoClass = (Class<TopiaDAO<E>>) Class.forName(daoClassname); + Class<TopiaDAO<E>> daoClass = + (Class<TopiaDAO<E>>) Class.forName(daoClassname); TopiaDAO<E> spe = daoClass.newInstance(); result = spe; } catch (Exception eee) { - log.warn("specialized DAO " + daoClassname + " not found, use default TopiaDAOHibernate"); + log.warn("specialized DAO " + daoClassname + + " not found, use default TopiaDAOHibernate"); result = new TopiaDAOImpl<E>(); } @@ -627,24 +662,25 @@ * * @see org.nuiton.topia.TopiaContext#beginTransaction() */ + @Override public TopiaContext beginTransaction() throws TopiaException { - checkClosed(_("topia.persistence.error.context.is.closed")); -// checkClosed("Ce contexte a ete ferme, impossible de commencer une transaction"); + checkClosed(I18n._("topia.persistence.error.context.is.closed")); TopiaContextImpl result = new TopiaContextImpl(this); SessionFactory factory = getHibernateFactory(); result.hibernate = factory.openSession(); + // new TopiaInterceptor(result)); // on ne synchronise jamais les données avec la base tant que // l'utilisateur n'a pas fait de commit du context result.hibernate.setFlushMode(FlushMode.MANUAL); - // 20060926 poussin ajouter pour voir si ca regle les problemes de deadlock h2 - // Conclusion, il faut bien ouvrir une transaction maintenant, sinon - // lorsque l'on fait des acces a la base, une transaction par defaut est - // utilisé mais elle n'est jamais vraiment fermé ce qui pose des problemes - // de lock sur les tables. + // 20060926 poussin ajouter pour voir si ca regle les problemes de + // deadlock h2. Conclusion, il faut bien ouvrir une transaction + // maintenant, sinon lorsque l'on fait des acces a la base, une + // transaction par defaut est utilisé mais elle n'est jamais vraiment + // fermé ce qui pose des problemes de lock sur les tables. result.hibernate.beginTransaction(); // 20081217 : add child AFTER hibernate session is opened @@ -652,25 +688,26 @@ // fire event getFiresSupport().fireOnBeginTransaction(result); - return result; } - // Transaction tx = null; - /* * (non-Javadoc) * * @see org.nuiton.topia.TopiaContext#commitTransaction() */ + @Override public void commitTransaction() throws TopiaException { if (getRootContext() == this) { - throw new TopiaException(_("topia.persistence.error.unsupported.operation.on.root.context", "commit")); -// throw new TopiaException("Vous êtes sur le root context le commit est impossible"); + throw new TopiaException(I18n._( + "topia.persistence.error.unsupported.operation.on.root.context", + "commit")); } - checkClosed(_("topia.persistence.error.unsupported.operation.on.closed.context", "commit")); -// checkClosed("Ce contexte a ete ferme, impossible de faire un commit"); + checkClosed(I18n._( + "topia.persistence.error.unsupported.operation.on.closed.context", + "commit")); + try { for (TopiaDAO<? extends TopiaEntity> dao : daoCache.values()) { dao.commitTransaction(); @@ -687,13 +724,15 @@ } hibernate.beginTransaction(); + // it's seem necessary to change session after commit - // NON, NON, NON, il ne faut surtout pas le faire, ca pose plein de probleme + // NON, NON, NON, il ne faut surtout pas le faire, ca pose plein de + // probleme // hibernate = getHibernateFactory().openSession(); // hibernate.setFlushMode(FlushMode.NEVER); } catch (Exception eee) { - throw new TopiaException(_("topia.persistence.error.on.commit", eee.getMessage()), eee); -// throw new TopiaException("Error during commit", eee); + throw new TopiaException(I18n._("topia.persistence.error.on.commit", + eee.getMessage()), eee); } } @@ -702,14 +741,17 @@ * * @see org.nuiton.topia.TopiaContext#rollbackTransaction() */ + @Override public void rollbackTransaction() throws TopiaException { if (getRootContext() == this) { - throw new TopiaException(_("topia.persistence.error.unsupported.operation.on.root.context", "rollback")); -// throw new TopiaException("Vous êtes sur le root context le rollback est impossible"); + throw new TopiaException(I18n._( + "topia.persistence.error.unsupported.operation.on.root.context", + "rollback")); } - checkClosed(_("topia.persistence.error.unsupported.operation.on.closed.context", "rollback")); -// checkClosed("Ce contexte a ete ferme, impossible de faire un rollback"); + checkClosed(I18n._( + "topia.persistence.error.unsupported.operation.on.closed.context", + "rollback")); try { for (TopiaDAO<? extends TopiaEntity> dao : daoCache.values()) { dao.rollbackTransaction(); @@ -733,22 +775,23 @@ } } catch (HibernateException eee) { - throw new TopiaException(_("topia.persistence.error.on.rollback", eee.getMessage()), eee); -// throw new TopiaException(eee); + throw new TopiaException( + I18n._("topia.persistence.error.on.rollback", + eee.getMessage()), eee); } } @Override public void closeContext() throws TopiaException { // Throw exception if context is already closed - checkClosed(_("topia.persistence.error.context.already.closed")); + checkClosed(I18n._("topia.persistence.error.context.already.closed")); // FD-20100421 : Ano #546 : no need to copy childContext, the // {@link #getChildContext()} provides a thread-safe copy to iterate // on it. // TopiaContextImplementor[] children = childContext.toArray( // new TopiaContextImplementor[childContext.size()]); - + // Remove all children context for (TopiaContextImplementor child : getChildContext()) { // Avoid to have exception from checkClosed method on child @@ -775,6 +818,7 @@ /** * Pour le context root on ferme tous les fils, et la factory hibernate + * * @see java.lang.Object#finalize() */ @Override @@ -801,10 +845,13 @@ /* (non-Javadoc) * @see org.nuiton.topia.TopiaContext#findByTopiaId(java.lang.String) */ + @Override public TopiaEntity findByTopiaId(String topiaId) throws TopiaException { - checkClosed(_("topia.persistence.error.unsupported.operation.on.closed.context", "findByTopiaId")); -// checkClosed("Ce contexte a ete ferme, impossible de faire une recherche"); + checkClosed(I18n._( + "topia.persistence.error.unsupported.operation.on.closed.context", + "findByTopiaId")); + TopiaEntity result; Class<TopiaEntity> entityClass = TopiaId.getClassName(topiaId); TopiaDAO<TopiaEntity> dao = getDAO(entityClass); @@ -816,10 +863,13 @@ * (non-Javadoc) * @see org.nuiton.topia.TopiaContext#find(java.lang.String, java.lang.Object[]) */ + @Override public List find(String hql, Object... args) throws TopiaException { - checkClosed(_("topia.persistence.error.unsupported.operation.on.closed.context", "find")); -// checkClosed("Ce contexte a ete ferme, impossible de faire une recherche"); + checkClosed(I18n._( + "topia.persistence.error.unsupported.operation.on.closed.context", + "find")); + try { Query query = getHibernate().createQuery(hql); for (int j = 0; j < args.length; j += 2) { @@ -835,16 +885,18 @@ result = firesSupport.fireEntitiesLoad(this, result); return result; } catch (HibernateException eee) { - throw new TopiaException(_("topia.persistence.error.on.query", hql, eee.getMessage()), eee); -// throw new TopiaException("Error during query execution: " + hql,eee); + throw new TopiaException(I18n._("topia.persistence.error.on.query", + hql, eee.getMessage()), eee); } } @Override public List<?> find(String hql, int startIndex, int endIndex, Object... args) throws TopiaException { - checkClosed(_("topia.persistence.error.unsupported.operation.on.closed.context", "find")); -// checkClosed("Ce contexte a ete ferme, impossible de faire une recherche"); + checkClosed(I18n._( + "topia.persistence.error.unsupported.operation.on.closed.context", + "find")); + try { Query query = getHibernate().createQuery(hql); for (int j = 0; j < args.length; j += 2) { @@ -859,16 +911,17 @@ query.setFirstResult(startIndex); query.setMaxResults(endIndex - startIndex + 1); List result = query.list(); - result = firesSupport.fireEntitiesLoad(this,result); + result = firesSupport.fireEntitiesLoad(this, result); return result; } catch (HibernateException eee) { - throw new TopiaException(_("topia.persistence.error.on.query", hql, eee.getMessage()), eee); -// throw new TopiaException("Error during query execution: " + hql,eee); + throw new TopiaException(I18n._("topia.persistence.error.on.query", + hql, eee.getMessage()), eee); } } /** * Execute HQL operation on data (Update, Delete) + * * @param hql * @param args * @return The number of entities updated or deleted. @@ -876,8 +929,10 @@ */ @Override public int execute(String hql, Object... args) throws TopiaException { - checkClosed(_("topia.persistence.error.unsupported.operation.on.closed.context", "find")); -// checkClosed("Ce contexte a ete ferme, impossible de faire une recherche"); + checkClosed(I18n._( + "topia.persistence.error.unsupported.operation.on.closed.context", + "find")); + try { Query query = getHibernate().createQuery(hql); for (int j = 0; j < args.length; j += 2) { @@ -886,18 +941,21 @@ int result = query.executeUpdate(); return result; } catch (HibernateException eee) { - throw new TopiaException(_("topia.persistence.error.on.query", hql, eee.getMessage()), eee); -// throw new TopiaException("Error during query execution: " + hql,eee); + throw new TopiaException(I18n._("topia.persistence.error.on.query", + hql, eee.getMessage()), eee); } } /* (non-Javadoc) * @see org.nuiton.topia.TopiaContext#add(org.nuiton.topia.persistence.TopiaEntity) */ + @Override public void add(TopiaEntity e) throws TopiaException { - checkClosed(_("topia.persistence.error.unsupported.operation.on.closed.context", "add")); -// checkClosed("Ce contexte a ete ferme, impossible d'ajouter une entite"); + checkClosed(I18n._( + "topia.persistence.error.unsupported.operation.on.closed.context", + "add")); + String id = e.getTopiaId(); Class<TopiaEntity> entityClass = TopiaId.getClassName(id); TopiaDAO<TopiaEntity> dao = getDAO(entityClass); @@ -906,8 +964,10 @@ @Override public void importXML(Reader xml) throws TopiaException { - checkClosed(_("topia.persistence.error.unsupported.operation.on.closed.context", "importXML")); -// checkClosed("Ce contexte a ete ferme, impossible d'effectuer l'import"); + checkClosed(I18n._( + "topia.persistence.error.unsupported.operation.on.closed.context", + "importXML")); + Document doc; SAXReader xmlReader = new SAXReader(); @@ -917,8 +977,9 @@ log.debug("Lecture du document terminee"); } } catch (DocumentException de) { - throw new TopiaException(_("topia.persistence.error.on.loding.xml.doc", de.getMessage()), de); -// throw new TopiaException("Lecture du document impossible", de); + throw new TopiaException( + I18n._("topia.persistence.error.on.loding.xml.doc", + de.getMessage()), de); } if (doc != null) { @@ -930,23 +991,24 @@ try { sessionDom4j.replicate(entity, ReplicationMode.EXCEPTION); } catch (HibernateException he) { - log.warn(_("topia.persistence.error.replicate.entity", entity, he.getMessage()), he); -// log.warn("Echec de replication sur " + entity, he); + log.warn(I18n._("topia.persistence.error.replicate.entity", + entity, he.getMessage()), he); } } // must commit data, otherwise : no effects... sessionDom4j.flush(); } else { - throw new TopiaException(_("topia.persistence.error.empty.doc")); -// throw new TopiaException("Document vide"); + throw new TopiaException( + I18n._("topia.persistence.error.empty.doc")); } } @Override public void exportXML(Writer xml, Object... entityAndcondition) throws TopiaException { - checkClosed(_("topia.persistence.error.unsupported.operation.on.closed.context", "exportXML")); -// checkClosed("Ce contexte a ete ferme, impossible d'effectuer l'export"); + checkClosed(I18n._( + "topia.persistence.error.unsupported.operation.on.closed.context", + "exportXML")); String[] queries = buildQueries(entityAndcondition); @@ -997,29 +1059,35 @@ } }*/ - XMLWriter result = new XMLWriter(xml, OutputFormat.createPrettyPrint()); + XMLWriter result = new XMLWriter(xml, + OutputFormat.createPrettyPrint()); result.write(doc); result.close(); } catch (HibernateException eee) { - throw new TopiaException(_("topia.persistence.error.on.export", eee.getMessage()), eee); -// throw new TopiaException("Can't export XML", eee); + throw new TopiaException(I18n._("topia.persistence.error.on.export", + eee.getMessage()), eee); } catch (IOException eee) { - throw new TopiaException(_("topia.persistence.error.on.export", eee.getMessage()), eee); -// throw new TopiaException("Can't export XML", eee); + throw new TopiaException(I18n._("topia.persistence.error.on.export", + eee.getMessage()), eee); } } @Override - public void replicate(TopiaContext dstCtxt, Object... entityAndCondition) throws TopiaException, IllegalArgumentException { - checkClosed(_("topia.persistence.error.unsupported.operation.on.closed.context", "replicate")); -// checkClosed("Ce contexte a ete ferme, impossible d'effectuer l'export"); + public void replicate(TopiaContext dstCtxt, Object... entityAndCondition) + throws TopiaException, IllegalArgumentException { + checkClosed(I18n._( + "topia.persistence.error.unsupported.operation.on.closed.context", + "replicate")); + TopiaContextImpl dstContextImpl = (TopiaContextImpl) dstCtxt; - dstContextImpl.checkClosed(_("topia.persistence.error.unsupported.operation.on.closed.context", "replicate")); -// dstContextImpl.checkClosed("Ce contexte a ete ferme, impossible d'effectuer l'export"); + dstContextImpl.checkClosed( + I18n._("topia.persistence.error.unsupported.operation.on.closed.context", + "replicate")); + if (getRootContext().equals(dstContextImpl.getRootContext())) { - throw new IllegalArgumentException(_("topia.persistence.error.replicate.on.same.context")); -// throw new IllegalArgumentException("Impossible de dupliquer dans la même base"); + throw new IllegalArgumentException( + I18n._("topia.persistence.error.replicate.on.same.context")); } String[] queries = buildQueries(entityAndCondition); @@ -1032,39 +1100,53 @@ List<?> entities = find(query); replicate0(dstContextImpl, entities.toArray()); if (log.isDebugEnabled()) { - log.debug("replication of entities " + query + " was sucessfully done."); + log.debug("replication of entities " + query + + " was sucessfully done."); } } - } catch (HibernateException e) { - throw new TopiaException(_("topia.persistence.error.on.replicate", e.getMessage()), e); -// throw new TopiaException("Could not duplicate data for reason " + e.getMessage(), e); + } catch (HibernateException eee) { + throw new TopiaException(I18n._( + "topia.persistence.error.on.replicate", + eee.getMessage()), eee); } } @Override - public <T extends TopiaEntity> void replicateEntity(TopiaContext dstCtxt, T entity) throws TopiaException, IllegalArgumentException { - checkClosed(_("topia.persistence.error.unsupported.operation.on.closed.context", "replicateEntity")); -// checkClosed("Ce contexte a ete ferme, impossible d'effectuer l'export"); + public <T extends TopiaEntity> void replicateEntity(TopiaContext dstCtxt, + T entity) + throws TopiaException, IllegalArgumentException { + checkClosed(I18n._( + "topia.persistence.error.unsupported.operation.on.closed.context", + "replicateEntity")); + TopiaContextImpl dstContextImpl = (TopiaContextImpl) dstCtxt; - dstContextImpl.checkClosed(_("topia.persistence.error.unsupported.operation.on.closed.context", "replicateEntity")); -// dstContextImpl.checkClosed("Ce contexte a ete ferme, impossible d'effectuer l'export"); + dstContextImpl.checkClosed(I18n._( + "topia.persistence.error.unsupported.operation.on.closed.context", + "replicateEntity")); + if (getRootContext().equals(dstContextImpl.getRootContext())) { - throw new IllegalArgumentException(_("topia.persistence.error.replicate.on.same.context")); -// throw new IllegalArgumentException("Impossible de dupliquer dans la même base"); + throw new IllegalArgumentException(I18n._( + "topia.persistence.error.replicate.on.same.context")); } replicate0(dstContextImpl, entity); } @Override - public <T extends TopiaEntity> void replicateEntities(TopiaContext dstCtxt, List<T> entities) throws TopiaException, IllegalArgumentException { - checkClosed(_("topia.persistence.error.unsupported.operation.on.closed.context", "replicateEntities")); -// checkClosed("Ce contexte a ete ferme, impossible d'effectuer l'export"); + public <T extends TopiaEntity> void replicateEntities(TopiaContext dstCtxt, + List<T> entities) + throws TopiaException, IllegalArgumentException { + checkClosed(I18n._( + "topia.persistence.error.unsupported.operation.on.closed.context", + "replicateEntities")); + TopiaContextImpl dstContextImpl = (TopiaContextImpl) dstCtxt; - dstContextImpl.checkClosed(_("topia.persistence.error.unsupported.operation.on.closed.context", "replicateEntities")); -// dstContextImpl.checkClosed("Ce contexte a ete ferme, impossible d'effectuer l'export"); + dstContextImpl.checkClosed(I18n._( + "topia.persistence.error.unsupported.operation.on.closed.context", + "replicateEntities")); + if (getRootContext().equals(dstContextImpl.getRootContext())) { - throw new IllegalArgumentException(_("topia.persistence.error.replicate.on.same.context")); -// throw new IllegalArgumentException("Impossible de dupliquer dans la même base"); + throw new IllegalArgumentException(I18n._( + "topia.persistence.error.replicate.on.same.context")); } replicate0(dstContextImpl, entities.toArray()); } @@ -1075,27 +1157,18 @@ } /** - * Backup database in gzip compressed file - * Only work for h2 database + * Backup database in gzip compressed file Only work for h2 database * - * @param file file to write backup + * @param file file to write backup * @param compress if true then use gzip to compress file - * * @see TopiaContext#backup(java.io.File,boolean) */ @Override public void backup(File file, boolean compress) throws TopiaException { - checkClosed(_("topia.persistence.error.unsupported.operation.on.closed.context", "backup")); -// checkClosed("Ce contexte a ete ferme, impossible d'effectuer le backup"); + checkClosed(I18n._( + "topia.persistence.error.unsupported.operation.on.closed.context", + "backup")); try { - // Statement stat = getHibernate().connection().createStatement(); - // ResultSet rs = stat.executeQuery("SCRIPT TO '" + file.getAbsolutePath() + "'"); - - // Bug dans h2 v0.9, on ne peut pas directement passer le fichier dans le SQL - // Il y a un ArrayOutBoundException -> org.h2.command.dml.Script.add:203 - // pour certaines lignes. C dommage, car on est obligé de rammener - // tout en texte, ce qui peut-etre gros pour la memoire :( - String options = ""; if (compress) { options += " COMPRESSION GZIP"; @@ -1105,38 +1178,16 @@ "SCRIPT TO '" + file.getAbsolutePath() + "'" + options); query.list(); - // List<String> lines = query.list(); - - // // en fait on est un peu obligé d'exporter toute la base - // // (creation du schema compris) car sinon lors de la restauration - // // si le schema a ete creer avant il contient aussi les - // // contrainte et du coup les inserts se passent mal :( - // // Si on ne voulait que les inserts, lors de la resauration il - // // faudrait desactiver les contraintes et les reactiver ensuite - // - // OutputStream os = new BufferedOutputStream ( - // new FileOutputStream(file)); - // - // PrintStream out; - // if (compress) { - // out = new PrintStream(new GZIPOutputStream(os)); - // } else { - // out = new PrintStream(os); - // } - // - // for (String line : lines) { - // out.println(line + ";"); - // } - // out.close(); } catch (Exception eee) { - throw new TopiaException(_("topia.persistence.error.on.backup", eee.getMessage()), eee); -// throw new TopiaException("Can't backup", eee); + throw new TopiaException(I18n._( + "topia.persistence.error.on.backup", + eee.getMessage()), eee); } } /** * Read database from gzip compressed file - * + * <p/> * Only work for h2 database * * @see org.nuiton.topia.TopiaContext#restore(java.io.File) @@ -1145,8 +1196,10 @@ public void restore(File file) throws TopiaException { // send event getFiresSupport().firePreRestoreSchema(this); - checkClosed(_("topia.persistence.error.unsupported.operation.on.closed.context", "restore")); -// checkClosed("Ce contexte a ete ferme, impossible d'effectuer le restore"); + checkClosed(I18n._( + "topia.persistence.error.unsupported.operation.on.closed.context", + "restore")); + String sql = null; try { // decompresse file in temporary file @@ -1162,7 +1215,6 @@ String options = ""; if (magic == GZIPInputStream.GZIP_MAGIC) { - // in = new GZIPInputStream(in); options += " COMPRESSION GZIP"; } in.close(); @@ -1173,60 +1225,16 @@ // send event AFTER restore getFiresSupport().firePostRestoreSchema(this); - - // BufferedReader reader = new BufferedReader(new InputStreamReader(in)); - // Connection conn = getHibernate().connection(); - // conn.setAutoCommit(false); - // Statement stat = conn.createStatement(); - // - // while((sql = reader.readLine()) != null) { - // // FIXME remove next line when h2 will do the bug correction (normaly in october 2006) - // // this permit database restauration - //// if (sql.startsWith("ALTER TABLE")) { - //// sql = sql.replaceAll("INDEX CONSTRAINT_INDEX_\\d*", ""); - //// } - // stat.execute(sql); - // } - // stat.close(); - // conn.commit(); - // conn.close(); - - // // by default we supposed that file is not compressed - // File tmp = file; - // if (magic == GZIPInputStream.GZIP_MAGIC) { - // // in fact file is compressed, use temporaly file - // tmp = File.createTempFile("tmp-topia-restore", ".sql"); - // tmp.deleteOnExit(); - // - // // decompresse file in temporary file - // InputStream gzin = new GZIPInputStream(in); - // - // OutputStream out = new BufferedOutputStream( - // new FileOutputStream(tmp)); - // - // byte [] buffer = new byte[64 * 1024]; - // int len = 0; - // while ((len = gzin.read(buffer)) != -1) { - // out.write(buffer, 0, len); - // } - // out.close(); - // gzin.close(); - // } - // - // // restore data - // Statement stat = getHibernate().connection().createStatement(); - // stat.execute("RUNSCRIPT FROM '" + tmp.getAbsolutePath() + "'"); - // - //// SQLQuery query = getHibernate().createSQLQuery("RUNSCRIPT FROM '" + file.getAbsolutePath() + "'"); - //// List result = query.list(); } catch (Exception eee) { - throw new TopiaException(_("topia.persistence.error.on.restore", sql, eee.getMessage()), eee); -// throw new TopiaException("Can't restore. Last sql instruction was:" + sql, eee); + throw new TopiaException(I18n._( + "topia.persistence.error.on.restore", + sql, eee.getMessage()), eee); } } /** * Only h2 supported for now + * * @see org.nuiton.topia.TopiaContext#clear(boolean) */ @Override @@ -1244,8 +1252,8 @@ tx.closeContext(); root.finalize(); } catch (Throwable eee) { - throw new TopiaException(_("topia.persistence.error.on.clear", eee.getMessage()), eee); -// throw new TopiaException("Can't clear topia context", eee); + throw new TopiaException(I18n._( + "topia.persistence.error.on.clear", eee.getMessage()), eee); } } @@ -1255,13 +1263,18 @@ } @Override - public boolean isSchemaExist(Class<? extends TopiaEntity> clazz) throws TopiaException { - checkClosed(_("topia.persistence.error.unsupported.operation.on.closed.context", "replicateEntity")); - boolean result = TopiaUtil.isSchemaExist(hibernateConfiguration, clazz.getName()); + public boolean isSchemaExist(Class<? extends TopiaEntity> clazz) + throws TopiaException { + checkClosed(I18n._( + "topia.persistence.error.unsupported.operation.on.closed.context", + "replicateEntity")); + boolean result = TopiaUtil.isSchemaExist(hibernateConfiguration, + clazz.getName()); return result; } - /* Adders */ + /* Listeners adders */ + @Override public void addTopiaEntityListener(TopiaEntityListener listener) { getFiresSupport().addTopiaEntityListener(listener); @@ -1306,10 +1319,12 @@ getFiresSupport().addTopiaContextListener(listener); } - /* Removers */ + /* Listeners removers */ + @Override public void removeTopiaEntityListener(TopiaEntityListener listener) { - getFiresSupport().removeTopiaEntityListener(TopiaEntity.class, listener); + getFiresSupport().removeTopiaEntityListener(TopiaEntity.class, + listener); } @Override @@ -1321,7 +1336,8 @@ @Override public void removeTopiaEntityVetoable(TopiaEntityVetoable vetoable) { - getFiresSupport().removeTopiaEntityVetoable(TopiaEntity.class, vetoable); + getFiresSupport().removeTopiaEntityVetoable(TopiaEntity.class, + vetoable); } @Override @@ -1332,12 +1348,14 @@ } @Override - public void removeTopiaTransactionListener(TopiaTransactionListener listener) { + public void removeTopiaTransactionListener( + TopiaTransactionListener listener) { getFiresSupport().removeTopiaTransactionListener(listener); } @Override - public void removeTopiaTransactionVetoable(TopiaTransactionVetoable vetoable) { + public void removeTopiaTransactionVetoable( + TopiaTransactionVetoable vetoable) { getFiresSupport().removeTopiaTransactionVetoable(vetoable); } @@ -1362,30 +1380,37 @@ } /** - * Build the list of queries from the given parameter <code>entityAndCondition>/code>. + * Build the list of queries from the given parameter + * <code>entityAndCondition>/code>. + * <p/> + * If no parameter is given, then build the queries for all entities is db, + * with no condition. * - * If no parameter is given, then build the queries for all entities is db, with no condition. - * * @param entityAndCondition the list of tuples (Class,String) * @return the list of queries. - * @throws TopiaException if any pb of db while getting entities classes. - * @throws IllegalArgumentException if any pb with the given parameter (mainly ClassCastException). + * @throws TopiaException if any pb of db while getting entities + * classes. + * @throws IllegalArgumentException if any pb with the given parameter + * (mainly ClassCastException). */ - protected String[] buildQueries(Object... entityAndCondition) throws TopiaException, IllegalArgumentException { + protected String[] buildQueries(Object... entityAndCondition) + throws TopiaException, IllegalArgumentException { Class<?> entityClass; String condition; // si entityAndcondition est vide alors il faut le remplir // avec toutes les entités du mapping (class, null) if (entityAndCondition.length == 0) { - entityAndCondition = new Object[getHibernateFactory().getAllClassMetadata().size() * 2]; + Map classMetadata = getHibernateFactory().getAllClassMetadata(); + entityAndCondition = new Object[classMetadata.size() * 2]; int i = 0; - for (Object className : getHibernateFactory().getAllClassMetadata().keySet()) { + for (Object className : classMetadata.keySet()) { try { entityAndCondition[i++] = Class.forName((String) className); } catch (ClassNotFoundException e) { // should never happen! - throw new TopiaException("class cast exception for entity " + className); + throw new TopiaException( + "class cast exception for entity " + className); } entityAndCondition[i++] = null; @@ -1394,7 +1419,8 @@ // prepare queries to perform beofre opening any transaction if (entityAndCondition.length % 2 != 0) { - throw new IllegalArgumentException("entityAndCondition must be a couple of (Class, String)"); + throw new IllegalArgumentException( + "entityAndCondition must be a couple of (Class, String)"); } String queries[] = new String[entityAndCondition.length / 2]; for (int i = 0; i < entityAndCondition.length;) { @@ -1409,29 +1435,36 @@ } catch (ClassCastException e) { if (i % 2 == 0) { throw new IllegalArgumentException( - "Others arguement must be String not " + entityAndCondition[i - 1], e); + "Others arguement must be String not " + + entityAndCondition[i - 1], e); } else { throw new IllegalArgumentException( - "Others arguement must be Class not " + entityAndCondition[i - 1], e); + "Others arguement must be Class not " + + entityAndCondition[i - 1], e); } } } return queries; } - protected void replicate0(TopiaContextImpl dstContextImpl, Object... entities) throws TopiaException { + protected void replicate0(TopiaContextImpl dstContextImpl, + Object... entities) throws TopiaException { try { for (Object entity : entities) { - // dettach entity to source session, to make possible copy of collection - // without a hibernate exception (list opened in two session...) + // dettach entity to source session, to make possible copy of + // collection without a hibernate exception (list opened in + // two session...) getHibernate().evict(entity); - dstContextImpl.getHibernate().replicate(entity, ReplicationMode.EXCEPTION); + dstContextImpl.getHibernate().replicate(entity, + ReplicationMode.EXCEPTION); } } catch (HibernateException eee) { - throw new TopiaException(_("topia.persistence.error.on.replicate", eee.getMessage()), eee); -// throw new TopiaException("Could not duplicate data for reason " + e.getMessage(), e); + throw new TopiaException(I18n._( + "topia.persistence.error.on.replicate", + eee.getMessage()), eee); } } + } //TopiaContextImpl Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaContextImplementor.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaContextImplementor.java 2010-05-07 13:15:19 UTC (rev 1934) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaContextImplementor.java 2010-05-07 15:19:41 UTC (rev 1935) @@ -36,24 +36,26 @@ */ package org.nuiton.topia.framework; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.cfg.Configuration; import org.nuiton.topia.TopiaContext; import org.nuiton.topia.TopiaException; import org.nuiton.topia.TopiaNotFoundException; import org.nuiton.topia.persistence.TopiaDAO; import org.nuiton.topia.persistence.TopiaEntity; -import org.hibernate.Session; -import org.hibernate.SessionFactory; -import org.hibernate.cfg.Configuration; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; + /** - * @author poussin <poussin@codelutin.com> + * TODO-fdesbois-20100507 : Need more javadoc. * + * @author poussin <poussin@codelutin.com> + * @version $Id$ */ public interface TopiaContextImplementor extends TopiaContext { @@ -64,16 +66,12 @@ */ Set<TopiaContextImplementor> getChildContext(); - /** - * @return Returns the parentContext. - */ + /** @return Returns the parentContext. */ TopiaContextImplementor getParentContext(); TopiaContextImplementor getRootContext(); - /** - * @return Returns the config. - */ + /** @return Returns the config. */ Properties getConfig(); /** @@ -97,7 +95,7 @@ /** * Detect if the table is created on storage for a given persistant class. - * + * * @param clazz the researched class * @return Returns the hibernate. * @throws TopiaException si aucune transaction n'est ouverte @@ -107,11 +105,11 @@ /** * Get DAO for specified class. If Specialized DAO exists then it returned * otherwize TopiaDAO<entityClass> is returned - * + * * @param <E> * @param entityClass * @return a doa - * @throws TopiaException + * @throws TopiaException */ <E extends TopiaEntity> TopiaDAO<E> getDAO(Class<E> entityClass) throws TopiaException; Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaFiresSupport.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaFiresSupport.java 2010-05-07 13:15:19 UTC (rev 1934) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaFiresSupport.java 2010-05-07 15:19:41 UTC (rev 1935) @@ -25,19 +25,26 @@ package org.nuiton.topia.framework; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeSupport; -import java.beans.VetoableChangeSupport; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Set; - import org.apache.commons.collections.map.IdentityMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.hibernate.Session; +import org.hibernate.event.PostDeleteEvent; +import org.hibernate.event.PostDeleteEventListener; +import org.hibernate.event.PostInsertEvent; +import org.hibernate.event.PostInsertEventListener; +import org.hibernate.event.PostLoadEvent; +import org.hibernate.event.PostLoadEventListener; +import org.hibernate.event.PostUpdateEvent; +import org.hibernate.event.PostUpdateEventListener; +import org.hibernate.event.PreDeleteEvent; +import org.hibernate.event.PreDeleteEventListener; +import org.hibernate.event.PreInsertEvent; +import org.hibernate.event.PreInsertEventListener; +import org.hibernate.event.PreLoadEvent; +import org.hibernate.event.PreLoadEventListener; +import org.hibernate.event.PreUpdateEvent; +import org.hibernate.event.PreUpdateEventListener; import org.nuiton.topia.TopiaContext; import org.nuiton.topia.TopiaException; import org.nuiton.topia.TopiaVetoException; @@ -55,29 +62,25 @@ import org.nuiton.topia.persistence.TopiaEntityAbstract; import org.nuiton.util.CategorisedListenerSet; import org.nuiton.util.ListenerSet; -import org.hibernate.Session; -import org.hibernate.event.PostDeleteEvent; -import org.hibernate.event.PostDeleteEventListener; -import org.hibernate.event.PostInsertEvent; -import org.hibernate.event.PostInsertEventListener; -import org.hibernate.event.PostLoadEvent; -import org.hibernate.event.PostLoadEventListener; -import org.hibernate.event.PostUpdateEvent; -import org.hibernate.event.PostUpdateEventListener; -import org.hibernate.event.PreDeleteEvent; -import org.hibernate.event.PreDeleteEventListener; -import org.hibernate.event.PreInsertEvent; -import org.hibernate.event.PreInsertEventListener; -import org.hibernate.event.PreLoadEvent; -import org.hibernate.event.PreLoadEventListener; -import org.hibernate.event.PreUpdateEvent; -import org.hibernate.event.PreUpdateEventListener; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; +import java.beans.PropertyChangeSupport; +import java.beans.VetoableChangeSupport; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; + /** - * Contient l'ensemble de la partie listener et vetoable c'est à dire la gestion, - * les fires, ... - * - * @author ruchaud + * TODO-fdesbois-20100507 : Need translation of javadoc. + * <p/> + * Contient l'ensemble de la partie listener et vetoable c'est à dire la + * gestion, les fires, ... + * + * @author jruchaud <jruchaud@codelutin.com> + * @version $Id$ */ public class TopiaFiresSupport { @@ -87,26 +90,41 @@ final static Object NO_CHANGE = new Object(); /** used to collect entity modification during transaction */ - protected Map<TopiaEntity, EntityState> transactionEntities = new IdentityMap(); + protected Map<TopiaEntity, EntityState> transactionEntities = + new IdentityMap(); - protected Set<PropertyChangeListener> propertyChangeListeners = new HashSet<PropertyChangeListener>(); + protected Set<PropertyChangeListener> propertyChangeListeners = + new HashSet<PropertyChangeListener>(); /* Pour la transaction */ - protected ListenerSet<TopiaTransactionListener> transactionListeners = new ListenerSet<TopiaTransactionListener>(); - protected ListenerSet<TopiaTransactionVetoable> transactionVetoables = new ListenerSet<TopiaTransactionVetoable>(); + protected ListenerSet<TopiaTransactionListener> transactionListeners = + new ListenerSet<TopiaTransactionListener>(); + + protected ListenerSet<TopiaTransactionVetoable> transactionVetoables = + new ListenerSet<TopiaTransactionVetoable>(); + /* Pour les entités */ - protected CategorisedListenerSet<TopiaEntityListener> entityListeners = new CategorisedListenerSet<TopiaEntityListener>(); - protected CategorisedListenerSet<TopiaEntityVetoable> entityVetoables = new CategorisedListenerSet<TopiaEntityVetoable>(); + protected CategorisedListenerSet<TopiaEntityListener> entityListeners = + new CategorisedListenerSet<TopiaEntityListener>(); + + protected CategorisedListenerSet<TopiaEntityVetoable> entityVetoables = + new CategorisedListenerSet<TopiaEntityVetoable>(); + /* Pour les listes d'entités */ - protected ListenerSet<TopiaEntitiesVetoable> entitiesVetoables = new ListenerSet<TopiaEntitiesVetoable>(); + protected ListenerSet<TopiaEntitiesVetoable> entitiesVetoables = + new ListenerSet<TopiaEntitiesVetoable>(); + /* Pour les actions du topia context */ - protected ListenerSet<TopiaContextListener> topiaContextListeners = new ListenerSet<TopiaContextListener>(); - /** + protected ListenerSet<TopiaContextListener> topiaContextListeners = + new ListenerSet<TopiaContextListener>(); + + /** * used to register objects loaded during transaction. + * * @param entity the loaded entity */ public void warnOnLoadEntity(TopiaEntity entity) { @@ -121,8 +139,9 @@ state.addLoad(); } - /** + /** * used to register objects created during transaction. + * * @param entity the created entity */ public void warnOnCreateEntity(TopiaEntity entity) { @@ -137,8 +156,9 @@ state.addCreate(); } - /** + /** * used to register objects loaded during transaction. + * * @param entity the read entity */ public void warnOnReadEntity(TopiaEntity entity) { @@ -153,8 +173,9 @@ state.addRead(); } - /** + /** * used to register objects modified during transaction. + * * @param entity the updated entity */ public void warnOnUpdateEntity(TopiaEntity entity) { @@ -170,8 +191,9 @@ state.addUpdate(); } - /** + /** * used to register objects deleted during transaction. + * * @param entity the deleted entity */ public void warnOnDeleteEntity(TopiaEntity entity) { @@ -187,6 +209,7 @@ } /* Fires sur les transactions */ + public void fireOnBeginTransaction(TopiaContextImplementor context) { if (log.isDebugEnabled()) { log.debug("fireOnBeginTransaction"); @@ -241,8 +264,9 @@ } /* Fires sur les entités */ + public void fireOnPreCreate(TopiaContextImplementor context, - TopiaEntity entity, Object[] state) { + TopiaEntity entity, Object[] state) { if (log.isDebugEnabled()) { log.debug("fireOnPreCreate"); } @@ -258,7 +282,7 @@ } public void fireOnPostCreate(TopiaContextImplementor context, - TopiaEntity entity, Object[] state) { + TopiaEntity entity, Object[] state) { if (log.isDebugEnabled()) { log.debug("fireOnPostCreate"); } @@ -278,7 +302,7 @@ } public void fireOnPreLoad(TopiaContextImplementor context, - TopiaEntity entity, Object[] state) { + TopiaEntity entity, Object[] state) { if (log.isDebugEnabled()) { log.debug("fireOnPreLoad"); } @@ -294,7 +318,7 @@ } public void fireOnPostLoad(TopiaContextImplementor context, - TopiaEntity entity, Object[] state) { + TopiaEntity entity, Object[] state) { if (log.isDebugEnabled()) { log.debug("fireOnPostLoad"); } @@ -316,7 +340,7 @@ } public void fireOnPreUpdate(TopiaContextImplementor context, - TopiaEntity entity, Object[] state) { + TopiaEntity entity, Object[] state) { if (log.isDebugEnabled()) { log.debug("fireOnPreUpdate"); } @@ -332,7 +356,7 @@ } public void fireOnPostUpdate(TopiaContextImplementor context, - TopiaEntity entity, Object[] state) { + TopiaEntity entity, Object[] state) { if (log.isDebugEnabled()) { log.debug("fireOnPostUpdate"); } @@ -352,7 +376,7 @@ } public void fireOnPreDelete(TopiaContextImplementor context, - TopiaEntity entity, Object[] state) { + TopiaEntity entity, Object[] state) { if (log.isDebugEnabled()) { log.debug("fireOnPreDelete"); } @@ -368,7 +392,7 @@ } public void fireOnPostDelete(TopiaContextImplementor context, - TopiaEntity entity, Object[] state) { + TopiaEntity entity, Object[] state) { if (log.isDebugEnabled()) { log.debug("fireOnPostDelete"); } @@ -388,8 +412,9 @@ } /* Fires sur les propriétés */ + public void fireOnPreRead(VetoableChangeSupport vetoables, - TopiaEntity entity, String propertyName, Object value) { + TopiaEntity entity, String propertyName, Object value) { if (log.isDebugEnabled()) { log.debug("fireOnPreRead"); @@ -402,7 +427,8 @@ } public void fireOnPostRead(PropertyChangeSupport listeners, - TopiaEntity entity, String propertyName, Object value) { + TopiaEntity entity, String propertyName, + Object value) { if (log.isDebugEnabled()) { log.debug("fireOnPostRead"); @@ -419,7 +445,8 @@ } public void fireOnPostRead(PropertyChangeSupport listeners, - TopiaEntity entity, String propertyName, int index, Object value) { + TopiaEntity entity, String propertyName, + int index, Object value) { if (log.isDebugEnabled()) { log.debug("fireOnPostRead"); @@ -437,8 +464,8 @@ } public void fireOnPreWrite(VetoableChangeSupport vetoables, - TopiaEntity entity, String propertyName, Object oldValue, - Object newValue) { + TopiaEntity entity, String propertyName, + Object oldValue, Object newValue) { if (log.isDebugEnabled()) { log.debug("fireOnPreWrite"); @@ -451,8 +478,8 @@ } public void fireOnPostWrite(PropertyChangeSupport listeners, - TopiaEntity entity, String propertyName, Object oldValue, - Object newValue) { + TopiaEntity entity, String propertyName, + Object oldValue, Object newValue) { if (log.isDebugEnabled()) { log.debug("fireOnPostWrite"); @@ -482,8 +509,8 @@ } public void fireOnPostWrite(PropertyChangeSupport listeners, - TopiaEntity entity, String propertyName, int index, - Object oldValue, Object newValue) { + TopiaEntity entity, String propertyName, + int index, Object oldValue, Object newValue) { if (log.isDebugEnabled()) { log.debug("fireOnPostWrite"); @@ -501,7 +528,7 @@ /** * Object permettant de faire le lien entre les events hibernate et topia - * + * * @author poussin <poussin@codelutin.com> */ static public class TopiaHibernateEvent implements PreInsertEventListener, @@ -521,10 +548,10 @@ /** * Recherche le context utilisant la session hibernate passe en * parametre - * - * @param parent le context parent + * + * @param parent le context parent * @param hibernate la session hibernate que doit utiliser le - * TopiaContext pour etre retourne + * TopiaContext pour etre retourne * @return le TopiaContext utilisant cette session hibernate ou null si * aucun TopiaContext n'utilise cette session. */ @@ -537,7 +564,7 @@ // on it. // Set<TopiaContextImplementor> contextChilds = new HashSet<TopiaContextImplementor>(parent.getChildContext()); for (TopiaContextImplementor context : parent.getChildContext()) { - + // by sletellier 24/09/09 : Fix concurent acces error // ArrayList<TopiaContextImplementor> children = new ArrayList(parent.getChildContext()); // for (TopiaContextImplementor context : children) { @@ -562,7 +589,7 @@ } private void attachContext(Object entity, - TopiaContextImplementor context) { + TopiaContextImplementor context) { if (entity instanceof TopiaEntityAbstract) { TopiaEntityAbstract entityAbstract = (TopiaEntityAbstract) entity; if (entityAbstract.getTopiaContext() == null) { @@ -580,6 +607,7 @@ } /* Création */ + @Override public boolean onPreInsert(PreInsertEvent event) { TopiaContextImplementor context = getContext(rootContext, event @@ -602,6 +630,7 @@ } /* Chargement */ + @Override public void onPreLoad(PreLoadEvent event) { TopiaContextImplementor context = getContext(rootContext, event @@ -612,7 +641,8 @@ (TopiaEntity) event.getEntity(), event.getState()); //TODO (thimel 20071213) On commente pour le moment @see(TopiaDAOHibernate#filterElements) // } catch (TopiaVetoException tve) { - // //On ne fait pas de remontee d'exception vers Hibernate pour le preLoad, on va agir au niveau du DAO + // //On ne fait pas de remontee d'exception + // vers Hibernate pour le preLoad, on va agir au niveau du DAO // } } } @@ -624,11 +654,12 @@ if (context != null && event.getEntity() instanceof TopiaEntity) { attachContext(event.getEntity(), context); context.getFiresSupport().fireOnPostLoad(context, - (TopiaEntity) event.getEntity(), new Object[] {}); + (TopiaEntity) event.getEntity(), new Object[]{}); } } /* Modification */ + @Override public boolean onPreUpdate(PreUpdateEvent event) { TopiaContextImplementor context = getContext(rootContext, event @@ -648,12 +679,14 @@ context.getFiresSupport().fireOnPostUpdate(context, (TopiaEntity) event.getEntity(), event.getState()); } - // FIXME indexation if (!(entity instanceof NotIndexable) && context.isIndexEnabled()) { - // context.getIndexEnginImplementor().recordForIndexation(id, event.getState()); + // FIXME indexation + // if (!(entity instanceof NotIndexable) && context.isIndexEnabled()) { + // context.getIndexEnginImplementor().recordForIndexation(id, event.getState()); // } } /* Suppression */ + @Override public boolean onPreDelete(PreDeleteEvent event) { TopiaContextImplementor context = getContext(rootContext, event @@ -675,14 +708,16 @@ (TopiaEntity) event.getEntity(), event.getDeletedState()); } - // FIXME indexation if (!(entity instanceof NotIndexable) && context.isIndexEnabled()) { - // context.getIndexEnginImplementor().recordForIndexation(id, null); - // } +// FIXME indexation +// if (!(entity instanceof NotIndexable) && context.isIndexEnabled()) { +// context.getIndexEnginImplementor().recordForIndexation(id, null); +// } } } /** * Notify topia context listeners for create schema pre operation + * * @param context topia context */ public void firePreCreateSchema(TopiaContext context) { @@ -702,6 +737,7 @@ /** * Notify topia context listeners for create schema post operation + * * @param context topia context */ public void firePostCreateSchema(TopiaContext context) { @@ -721,6 +757,7 @@ /** * Notify topia context listeners for create schema pre operation + * * @param context topia context */ public void firePreUpdateSchema(TopiaContext context) { @@ -740,6 +777,7 @@ /** * Notify topia context listeners for create schema post operation + * * @param context topia context */ public void firePostUpdateSchema(TopiaContext context) { @@ -759,6 +797,7 @@ /** * Notify topia context listeners for schema restore pre operation + * * @param context topia context */ public void firePreRestoreSchema(TopiaContext context) { @@ -778,6 +817,7 @@ /** * Notify topia context listeners for schema restore post operation + * * @param context topia context */ public void firePostRestoreSchema(TopiaContext context) { @@ -797,8 +837,9 @@ /** * Notify entities listeners for load operation - * @param <E> type of entities - * @param context context used + * + * @param <E> type of entities + * @param context context used * @param entities entities loaded * @return the list of entities loaded */ @@ -809,12 +850,12 @@ } List<E> result = entities; - for (Iterator<TopiaEntitiesVetoable> l = entitiesVetoables.iterator(); l - .hasNext();) { + for (Iterator<TopiaEntitiesVetoable> it = entitiesVetoables.iterator(); + it.hasNext();) { try { TopiaEntitiesEvent event = new TopiaEntitiesEvent(context, result); - result = l.next().load(event); + result = it.next().load(event); } catch (Exception eee) { throw new TopiaVetoException(eee); } @@ -823,6 +864,7 @@ } /* Getters */ + public CategorisedListenerSet<TopiaEntityListener> getEntityListeners() { return entityListeners; } @@ -848,6 +890,7 @@ } /* Adders */ + public void addTopiaEntityListener(TopiaEntityListener listener) { addTopiaEntityListener(TopiaEntity.class, listener); } @@ -889,6 +932,7 @@ } /* Removers */ + public void removeTopiaEntityListener(TopiaEntityListener listener) { removeTopiaEntityListener(TopiaEntity.class, listener); } Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaQuery.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaQuery.java 2010-05-07 13:15:19 UTC (rev 1934) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaQuery.java 2010-05-07 15:19:41 UTC (rev 1935) @@ -25,14 +25,6 @@ package org.nuiton.topia.framework; -import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.lang.RandomStringUtils; import org.apache.commons.lang.StringUtils; @@ -44,12 +36,21 @@ import org.nuiton.topia.persistence.TopiaEntity; import org.nuiton.util.StringUtil; +import java.lang.reflect.InvocationTargetException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + /** - * Query HQL managment to simplify usage of - * {@link TopiaContext#find(String, Object...) }. - * - * TODO-FD20091224 Complete documentation of this class + JUnit Tests - * + * Query HQL managment to simplify usage of {@link TopiaContext#find(String, + * Object...) }. + * <p/> + * TODO-FD20091224 JUnit Tests + * <p/> * <pre> * This class is used to construct a HQL query and then execute it from a * TopiaContext. The TopiaQuery is linked to a TopiaEntity which @@ -59,37 +60,39 @@ * addGroup, ... * - execution of the query, using executeToEntityList, executeToEntity, * executeToInteger, ... - * + * <p/> * Construction * ============ - * + * <p/> * This class make easier the way to construct a HQL query. - * + * <p/> * Example 1 : * ----------- - * + * <p/> * SQL : * "SELECT * FROM PersonImpl WHERE firstName LIKE 'M%' AND year > 1980" - * + * <p/> * HQL using {@link TopiaContext#find(String, Object...) } : * TopiaContext context = rootContext.beginTransaction(); - * context.find("FROM " + Person.class.getName() + " WHERE firstName LIKE :firstName AND year > :year", + * context.find("FROM " + Person.class.getName() + " WHERE firstName LIKE + * :firstName AND year > :year", * "firstName", "M%", year, 1980); - * - * TopiaQuery : + * <p/> + * TopiaQuery : * TopiaQuery query = TopiaQuery.createQuery(Person.class).add( * Person.FIRST_NAME, Op.LIKE, "M%").add(Person.YEAR, Op.GT, 1980); - * - * But the real advantage is when you have some parameters to test before adding + * <p/> + * But the real advantage is when you have some parameters to test before + * adding * them to the query. With the older method, it was tidious to construct * and add parameters to finally use the find method from TopiaContext. - * + * <p/> * Example 2 : * ----------- - * + * <p/> * HQL using {@link TopiaContext#find(String, Object...) } : * TopiaContext context = rootContext.beginTransaction(); - * + * <p/> * String query = "FROM " + Person.class.getName(); * List<Object> params = new ArrayList<Object>(); * String separator = " WHERE "; @@ -100,7 +103,7 @@ * params.add(company); * separator = " AND "; * } - * + * <p/> * // contact paramater can be null * if (contact != null) { * query += separator + "contact = :contact"; @@ -108,34 +111,37 @@ * params.add(contact); * separator = " AND "; * } - * + * <p/> * context.find(query, params.toArray()); - * + * <p/> * Here we have only two non obligatory params, but imagine if we must have * almost 6 or 7 parameters like this ! - * + * <p/> * TopiaQuery : * TopiaQuery query = TopiaQuery.createQuery(Person.class); - * + * <p/> * if (company != null) { * query.add(Person.COMPANY, company); * } - * + * <p/> * if (contact != null) { * query.add(Person.CONTACT, contact); * } - * + * <p/> * Many ways to create the same query : * ------------------------------------ - * + * <p/> * You can use multiple different manners to create a query, it depends on the * complexicity. More complex is the query, more easier is to construct it. - * - * HQL : "FROM PersonImpl AS P WHERE (P.company IS NULL OR P.company = :company) AND P.firstName LIKE :firstName" - * + * <p/> + * HQL : "FROM PersonImpl AS P WHERE (P.company IS NULL OR P.company = + * :company) + * AND P.firstName LIKE :firstName" + * <p/> * Using TopiaQuery and an Alias (these different queries are equivalent) : * query = TopiaQuery.createQuery(Person.class, "P"); - * 1- query.add("(P.company IS NULL OR P.company = :company") AND P.firstName LIKE :firstName") + * 1- query.add("(P.company IS NULL OR P.company = :company") AND P.firstName + * LIKE :firstName") * .addParam("company", company).addParam("firstName",firstName + "%"); * 2- query.add("P.company IS NULL OR P.company = :company") * .add("P.firstName LIKE :firstName").addParam("company", company) @@ -145,108 +151,112 @@ * .addParam("company", company); * 4- query.addNullOr("P.company", Op.EQ, company). * add("P.firstName", Op.LIKE, firstName + "%"); - * + * <p/> * You can use TopiaQuery to create a subquery in an other TopiaQuery, you have - * to use the method {@link #fullQuery() } to get the full query in HQL and give + * to use the method {@link #fullQuery() } to get the full query in HQL and + * give * it as a string in the other TopiaQuery. - * + * <p/> * Execution * ========= - * + * <p/> * After construction, you can execute the query in different ways. - * + * <p/> * Default method : * ---------------- - * + * <p/> * - execute : as the same result as * {@link TopiaContext#find(String, Object...) } - * + * <p/> * Depends on entity type ; * ------------------------ - * + * <p/> * - executeToEntity : only one result, the first one * - executeToEntityList : all results returned in a List - * - executeToEntityMap : all results returned in a Map with key defined by user + * - executeToEntityMap : all results returned in a Map with key defined by + * user * or topiaId by default - * + * <p/> * For aggregate : * --------------- - * + * <p/> * These methods have in argument the SELECT to execute the query. The previous * SELECT (if defined) will not be deleted, but temporarly not used. - * + * <p/> * - executeToInteger : for example for "SUM", "COUNT" * - executeToString : for example for "MAX" * - executeCount : directly a "count(*)" - * - executeToObject : for other type of possible result (Long, Boolean, Double, ...) - * + * - executeToObject : for other type of possible result (Long, Boolean, + * Double, + * ...) + * <p/> * Property loading * ================ - * + * <p/> * When using Hibernate, some times, Entities linked to the main one will be * lazy initialized, but you want them directly when the query will be executed * to avoid problems when closing context. You can use the method * {@link #addLoad(String...) } to tell the TopiaQuery to load some * properties when executing the query. After that, you don't need to call them * for loading them in Hibernate. - * + * <p/> * The syntax is the same as a property in HQL query using delegation : * "person.company" where person and company are entities. - * + * <p/> * Note : loading only available on collection or entities but not property * on a collection of entities which must be made manually. - * + * <p/> * For a Contact which is linked to a person (entity) and the person linked to * company (entity) you can add to a TopiaQuery<Contact> : * query.addLoad("person.company") - * + * <p/> * For a list of addresses (entity) in the contact you can do : * query.addLoad("addresses") - * + * <p/> * But it's not possible to do for example with meeting (entity) linked to the * contact and responsible (entity) linked to a meeting : * query.addLoad("meetings.responsible") - * + * <p/> * </pre> - * + * <p/> * Created: 21 déc. 2009 * * @author fdesbois * @version $Revision$ * @since 2.3.0 - * - * Mise a jour: $Date$ - * par : $Author$ + * <p/> + * Mise a jour: $Date$ par + * : $Author$ */ public class TopiaQuery { private static final Log log = LogFactory.getLog(TopiaQuery.class); - /** Params for HQL query **/ + /** Params for HQL query * */ protected List<Object> params; - /** Select part of the query **/ + /** Select part of the query * */ protected StringBuilder select; protected boolean distinct; - /** From part of the query **/ + /** From part of the query * */ protected StringBuilder from; - /** Where part of the query **/ + /** Where part of the query * */ protected StringBuilder where; - /** Order By part of the query **/ + /** Order By part of the query * */ protected StringBuilder orderBy; - /** Group By part of the query **/ + /** Group By part of the query * */ protected StringBuilder groupBy; protected Integer startIndex; protected Integer endIndex; - /** Used to determine if parentheses are needed for Where statement **/ + /** Used to determine if parentheses are needed for Where statement * */ protected boolean parentheses; protected List<String> propertiesToLoad; @@ -255,27 +265,26 @@ protected TopiaDAO<? extends TopiaEntity> dao; - /** - * Enum to simmplify using operation in query - */ + /** Enum to simmplify using operation in query */ public enum Op { - /** EQUALS **/ + + /** EQUALS * */ EQ("="), - /** GREATER THAN **/ + /** GREATER THAN * */ GT(">"), - /** GREATER OR EQUALS **/ + /** GREATER OR EQUALS * */ GE(">="), - /** LIKE for String manipulation **/ + /** LIKE for String manipulation * */ LIKE("LIKE"), - /** LESS THAN **/ + /** LESS THAN * */ LT("<"), - /** LESS OR EQUALS **/ + /** LESS OR EQUALS * */ LE("<="), - /** IS NOT NULL **/ + /** IS NOT NULL * */ NOT_NULL("IS NOT NULL"), - /** IS NULL **/ + /** IS NULL * */ NULL("IS NULL"), - /** NOT EQUAL **/ + /** NOT EQUAL * */ NEQ("!="); protected String value; @@ -302,8 +311,8 @@ /** * Create a TopiaQuery based on the {@code entityClass}. The from statement * is automatically set. - * - * @param mainEntityClass + * + * @param mainEntityClass used as from part of the query */ public TopiaQuery(Class<? extends TopiaEntity> mainEntityClass) { this(); @@ -315,11 +324,11 @@ * is automatically set, the select statement must be necessary in some * case, the query will manage this case using the mainAlias by default. * - * @param mainEntityClass - * @param alias for the mainEntityClass + * @param mainEntityClass used as from part of the query + * @param alias for the mainEntityClass */ public TopiaQuery(Class<? extends TopiaEntity> mainEntityClass, - String alias) { + String alias) { this(); setFrom(mainEntityClass, alias); } @@ -337,10 +346,10 @@ } /** - * Create a TopiaQuery from a DAO with an Alias. The main entity will be + * Create a TopiaQuery from a DAO with an Alias. The main entity will be * automatically added to the select part of the query if it is needed. * - * @param dao DAO linked to the entity to threat + * @param dao DAO linked to the entity to threat * @param alias of the main entity in the query */ public TopiaQuery(TopiaDAO<? extends TopiaEntity> dao, String alias) { @@ -365,11 +374,11 @@ * this mainEntity. * * @param mainEntityClass type of the mainEntity - * @param alias for the entity in the query + * @param alias for the entity in the query * @return the TopiaQuery */ public TopiaQuery setFrom(Class<? extends TopiaEntity> mainEntityClass, - String alias) { + String alias) { setFrom(mainEntityClass); mainAlias = alias; from.append(' ').append(alias); @@ -402,11 +411,11 @@ * Add an other entity type to the from in the query with an alias. * * @param entityClass different from the mainEntity in the DAO - * @param alias of the entity in the query + * @param alias of the entity in the query * @return the TopiaQuery */ public TopiaQuery addFrom(Class<? extends TopiaEntity> entityClass, - String alias) { + String alias) { return addFrom(entityClass.getName() + " " + alias); } @@ -423,10 +432,10 @@ } if (select != null) { result.append(selectStatement).append(select); - // Set default select if there is more than one table in from - // part and main alias is defined + // Set default select if there is more than one table in from + // part and main alias is defined } else if (StringUtils.contains(from.toString(), ',') && - StringUtils.isNotEmpty(mainAlias)) { + StringUtils.isNotEmpty(mainAlias)) { result.append(selectStatement).append(mainAlias); } result.append(from); @@ -445,7 +454,7 @@ /** * Add a HQL parameter to the Query. * - * @param id identification of the param in the query + * @param id identification of the param in the query * @param paramValue value of the param * @return the TopiaQuery */ @@ -457,8 +466,8 @@ /** * Add muliple paramaters to the Query. The key of each param will be tested - * if not already exist in the existing params list and will be renamed - * in this case. + * if not already exist in the existing params list and will be renamed in + * this case. * * @param params a list of HQL params with key and value in order. * @return the TopiaQuery @@ -466,8 +475,8 @@ */ public TopiaQuery addParams(List<Object> params) { for (int i = 0; i < params.size(); i += 2) { - String paramName = (String)params.get(i); - addParam(getValueName(paramName), params.get(i+1)); + String paramName = (String) params.get(i); + addParam(getValueName(paramName), params.get(i + 1)); } return this; } @@ -489,9 +498,8 @@ } /** - * Add a property to load when query is executed. - * Used to avoid LazyInitializationException for property needed after - * closing context. + * Add a property to load when query is executed. Used to avoid + * LazyInitializationException for property needed after closing context. * The property is a string like those in HQL query. * <pre> * Exemples : @@ -503,7 +511,7 @@ * --> calling myEntity.getPartyRoles().size(); * </pre> * - * @param properties + * @param properties List of properties to load * @return the TopiaQuery */ public TopiaQuery addLoad(String... properties) { @@ -519,8 +527,8 @@ } /** - * Add a where element to the Query. Could be anything. - * Parentheses are added automatically (even if there are not needed). + * Add a where element to the Query. Could be anything. Parentheses are + * added automatically (even if there are not needed). * * @param where element to add * @return the TopiaQuery @@ -548,16 +556,16 @@ /** * Add an element to the query. The parameter will be automatically added. - * The constraint is needed to determine what type of operation it is. - * Ex : add("boat", Op.EQ, boat) means -> boat = :boat. - * If the paramValue is Null, the paramName will be added to the query - * with the constraint null (IS NULL). + * The constraint is needed to determine what type of operation it is. Ex : + * add("boat", Op.EQ, boat) means -> boat = :boat. If the paramValue is + * Null, the paramName will be added to the query with the constraint null + * (IS NULL). * - * @param paramName the name of the parameter in the query (attribute of - * the entity) + * @param paramName the name of the parameter in the query (attribute of + * the entity) * @param constraint the operation concerned * @param paramValue the value of the parameter (an other entity, a String, - * ...) + * ...) * @return the TopiaQuery */ public TopiaQuery add(String paramName, Op constraint, Object paramValue) { @@ -566,7 +574,7 @@ log.debug("paramValue = " + paramValue); } if (paramValue == null) { - result.append(Op.NULL); + result.append(Op.NULL); } else { String valueName = getValueName(paramName); result.append(constraint).append(" :").append(valueName); @@ -581,20 +589,20 @@ * added for that element. Ex : addNullOr("begin", Op.GT, new Date()) means * begin IS NULL OR begin > :begin (where :begin = new Date()). * - * @param paramName the name of the parameter in the query (attribute of - * the entity) + * @param paramName the name of the parameter in the query (attribute of + * the entity) * @param constraint the operation concerned by the or * @param paramValue the value of the parameter (an other entity, a String, - * ...) + * ...) * @return the TopiaQuery */ public TopiaQuery addNullOr(String paramName, Op constraint, - Object paramValue) { + Object paramValue) { String valueName = getValueName(paramName); - StringBuilder result = + StringBuilder result = new StringBuilder(paramName).append(' ').append(Op.NULL). - append(" OR ").append(paramName).append(constraint). - append(" :").append(valueName); + append(" OR ").append(paramName).append(constraint). + append(" :").append(valueName); addParam(valueName, paramValue); return add(result.toString()); } @@ -603,10 +611,11 @@ int dot = paramName.lastIndexOf('.'); String valueName = paramName; if (dot != -1) { - valueName = paramName.substring(dot+1); + valueName = paramName.substring(dot + 1); } if (getParams().contains(valueName)) { - valueName = valueName + "_" + RandomStringUtils.randomAlphanumeric(4); + valueName = valueName + "_" + + RandomStringUtils.randomAlphanumeric(4); } return valueName; } @@ -625,17 +634,15 @@ /** * Add an element to the query. The parameter will be automatically added. - * The default constrainst operation is Op.EQ for EQUALS. - * Ex : add("boat", boat) means -> boat = :boat. - * If you add more than one values, the statement IN will be used. You - * can also have a null value in the {@code paramValue} list (except if it's - * the only one value, it's ambiguous). + * The default constrainst operation is Op.EQ for EQUALS. Ex : add("boat", + * boat) means -> boat = :boat. If you add more than one values, the + * statement IN will be used. You can also have a null value in the {@code + * paramValue} list (except if it's the only one value, it's ambiguous). * Note : this method do nothing if the {@code paramValue} is not defined. * If you want to add the constraint null on the {@code paramName} use - * {@link #add(String, TopiaQuery.Op, Object) } as : - * add("param", Op.EQ, null); + * {@link #add(String, Op, Object)} as : add("param", Op.EQ, null); * - * @param paramName name of the parameter in the query + * @param paramName name of the parameter in the query * @param paramValue values of the parameter * @return the TopiaQuery * @see TopiaQuery#add(String, Op, Object) @@ -674,12 +681,12 @@ } } // Create buffer for IN statement with values - StringBuilder buffer = new StringBuilder(); + StringBuilder buffer = new StringBuilder(); buffer.append(paramName).append(" IN(").append(values).append(")"); // Add the OR statement for null value if needed if (addNull) { buffer.append(" OR "). - append(paramName).append(' ').append(Op.NULL.toString()); + append(paramName).append(' ').append(Op.NULL.toString()); } else { // no parentheses needed in this case (no OR statement) parentheses = false; @@ -693,7 +700,7 @@ * the property name, and the value is the value of the parameter in the * query. * - * @param properties + * @param properties to add to the query * @return the TopiaQuery */ public TopiaQuery add(Map<String, Object> properties) { @@ -728,8 +735,7 @@ * Add an element to the select in the query. Depends on the result wanted * in execute methods. The main entity will be automatically added only if * an alias is initialize from constructor. If you want only this select - * element, use {@link #setSelect(String...) } - * method instead. + * element, use {@link #setSelect(String...) } method instead. * * @param select element to add * @return the TopiaQuery @@ -743,7 +749,7 @@ // if select is not null, add the new element to the select if (this.select != null) { this.select.append(", "); - // if mainAlias is not null, add it before adding the select in argument + // if mainAlias is not null, add it before adding the select in argument } else if (mainAlias != null) { this.select = new StringBuilder(mainAlias).append(", "); } else { @@ -816,7 +822,7 @@ /** * Helper method for array type. Each value will be separated by a comma. - * + * * @param array of String * @return a String with values of the array separated by a comma */ @@ -836,7 +842,7 @@ * Limit the result of the query with startIndex and endIndex. * * @param start first index to get from the results - * @param end last index to get from the results + * @param end last index to get from the results * @return the TopiaQuery */ public TopiaQuery setLimit(int start, int end) { @@ -847,6 +853,7 @@ /** * Remove limits previously set + * * @return the TopiaQuery */ public TopiaQuery resetLimit() { @@ -862,7 +869,7 @@ * @return the TopiaQuery */ public TopiaQuery setMaxResults(int max) { - return setLimit(0,max-1); + return setLimit(0, max - 1); } /** @@ -871,14 +878,14 @@ * * @param transaction the TopiaContext to use for execution * @return a List of results - * @throws TopiaException + * @throws TopiaException for error on query execution * @see TopiaContext#find(String, Object...) */ public List execute(TopiaContext transaction) throws TopiaException { String query = fullQuery(); if (log.isDebugEnabled()) { log.debug(this); - } + } if (startIndex != null && endIndex != null) { return transaction.find(query, startIndex, endIndex, getParams().toArray()); @@ -890,7 +897,7 @@ * DAO must be defined to use this method. * * @return a List of results - * @throws TopiaException + * @throws TopiaException for error during execution * @see #execute(TopiaContext) */ public List execute() throws TopiaException { @@ -902,12 +909,13 @@ * Execute the query and get a List of entity. Some properties will be * loaded if they are prealably set using ${@link #addLoad(String...) }. * - * @param <E> + * @param <E> entity type * @param transaction the TopiaContext to use for execution - * @param entityClass - * @return a List of TopiaEntity corresponding to the entityClass in argument - * @throws TopiaException - * @throws ClassCastException + * @param entityClass used to check return type of execution results + * @return a List of TopiaEntity corresponding to the entityClass in + * argument + * @throws TopiaException for error on query execution + * @throws ClassCastException if entityClass doesn't match to results */ public <E extends TopiaEntity> List<E> executeToEntityList( TopiaContext transaction, Class<E> entityClass) @@ -925,17 +933,17 @@ // If it's an array, we want only the first element wich is the // entity wanted // We know that the array have at least one element - o = ((Object[])o)[0]; + o = ((Object[]) o)[0]; } if (!entityClass.isAssignableFrom(o.getClass())) { - throw new ClassCastException(o.getClass().getName() + + throw new ClassCastException(o.getClass().getName() + " can't be cast to " + entityClass.getName() + " o : " + o); } - E entity = (E)o; + E entity = (E) o; // Check distinct constraint for complex query where o is firstly an // Object[] (potentially distinct results with existing entity to add) - if (! (distinct && results.contains(entity)) ) { + if (!(distinct && results.contains(entity))) { if (!getPropertiesToLoad().isEmpty()) { loadProperties(entity); } @@ -947,18 +955,18 @@ /** * Execute the query and get a Map of entity with key type in argument. Some - * properties will be loaded if they are - * prealably set using ${@link #addLoad(String...) }. + * properties will be loaded if they are prealably set using ${@link + * #addLoad(String...) }. * - * @param <E> - * @param <K> the type of the map key + * @param <E> entity type + * @param <K> the type of the map key * @param transaction the TopiaContext to use for execution - * @param entityClass - * @param keyName the property name of the key in the entity - * @param keyClass the key class for the result map + * @param entityClass needed to execute the query + * @param keyName the property name of the key in the entity + * @param keyClass the key class for the result map * @return a Map with the key type defined and the entity in value - * @throws TopiaException - * @throws ClassCastException + * @throws TopiaException for error on query execution + * @throws ClassCastException if entityClass doesn't match to results */ public <E extends TopiaEntity, K> Map<K, E> executeToEntityMap( TopiaContext transaction, Class<E> entityClass, @@ -975,22 +983,22 @@ throw new ClassCastException(value.getClass().getName() + " can't be cast to " + keyClass.getName()); } - results.put((K)value, elmt); + results.put((K) value, elmt); } return results; } /** * Execute the query and get a Map of entity with topiaId in key. Some - * properties will be loaded if they are - * prealably set using ${@link #addLoad(String...) }. + * properties will be loaded if they are prealably set using ${@link + * #addLoad(String...) }. * - * @param <E> + * @param <E> entity type * @param transaction the TopiaContext to use for execution - * @param entityClass + * @param entityClass used to check return type of execution results * @return a Map with the key type defined and the entity in value - * @throws TopiaException - * @throws ClassCastException + * @throws TopiaException for error on query execution + * @throws ClassCastException if entityClass doesn't match to results */ public <E extends TopiaEntity> Map<String, E> executeToEntityMap( TopiaContext transaction, Class<E> entityClass) @@ -1001,18 +1009,17 @@ /** * Execute the query and get the first result entity. Some properties will - * be loaded if they are - * prealably set using ${@link #addLoad(String...) }. + * be loaded if they are prealably set using ${@link #addLoad(String...) }. * - * @param <E> + * @param <E> entity type * @param transaction the TopiaContext to use for execution - * @param entityClass + * @param entityClass used to check return type of execution results * @return a TopiaEntity corresponding to the entityClass in argument - * @throws TopiaException - * @throws ClassCastException + * @throws TopiaException for error on query execution + * @throws ClassCastException if entityClass doesn't match to results */ public <E extends TopiaEntity> E executeToEntity(TopiaContext transaction, - Class<E> entityClass) + Class<E> entityClass) throws TopiaException, ClassCastException { setMaxResults(1); List<E> results = executeToEntityList(transaction, entityClass); @@ -1021,13 +1028,13 @@ } /** - * Execute the query and get an Object for result. - * The select is overriden to get only the right value for return. + * Execute the query and get an Object for result. The select is overriden + * to get only the right value for return. * * @param transaction the TopiaContext to use for execution - * @param select the Select overriden + * @param select the Select overriden * @return an Object - * @throws TopiaException + * @throws TopiaException for error on query execution */ public Object executeToObject(TopiaContext transaction, String select) throws TopiaException { @@ -1048,26 +1055,26 @@ /** * Execute the query and get an Integer for result. Used only for query with - * aggration select which return a Long : COUNT, SUM ... - * The select is overriden to get only the right value for return. + * aggration select which return a Long : COUNT, SUM ... The select is + * overriden to get only the right value for return. * * @param transaction the TopiaContext to use for execution - * @param select the Select overriden (ex : SUM(myParam)) + * @param select the Select overriden (ex : SUM(myParam)) * @return an Integer - * @throws TopiaException + * @throws TopiaException for error on query execution */ public int executeToInteger(TopiaContext transaction, String select) throws TopiaException { - Long res = (Long)executeToObject(transaction, select); + Long res = (Long) executeToObject(transaction, select); return res != null ? res.intValue() : 0; } /** * DAO must be defined to use this method. * - * @param select + * @param select part of the query redefined temporarly for execution * @return an Integer - * @throws TopiaException + * @throws TopiaException for error on query execution * @see #executeToInteger(TopiaContext, String) */ public int executeToInteger(String select) throws TopiaException { @@ -1076,26 +1083,26 @@ } /** - * Execute the query and get a String for result. Used for query with MAX, ... - * The select is overriden to get only the right value for return. + * Execute the query and get a String for result. Used for query with MAX, + * ... The select is overriden to get only the right value for return. * * @param transaction the TopiaContext to use for execution - * @param select the Select overriden (ex : MAX(myParam)) + * @param select the Select overriden (ex : MAX(myParam)) * @return a String - * @throws TopiaException + * @throws TopiaException for error on query execution */ public String executeToString(TopiaContext transaction, String select) throws TopiaException { Object res = executeToObject(transaction, select); - return res != null ? (String)res : ""; + return res != null ? (String) res : ""; } /** * DAO must be defined to use this method. * - * @param select + * @param select part of the query redefined temporarly for execution. * @return a String result - * @throws TopiaException + * @throws TopiaException for error on query execution * @see #executeToString(TopiaContext, String) */ public String executeToString(String select) throws TopiaException { @@ -1106,9 +1113,9 @@ /** * DAO must be defined to use this method. * - * @param select + * @param select part of the query redefined temporarly for execution. * @return an Object - * @throws TopiaException + * @throws TopiaException for error on query execution * @see #executeToObject(TopiaContext, String) */ public Object executeToObject(String select) throws TopiaException { @@ -1118,16 +1125,16 @@ /** * Execute a simple count on the query, i.e. the number of results get from - * the query. The order is not considered to count the elements and will - * be temporarly disabled. The distinct constraint will be manage if - * necessary : + * the query. The order is not considered to count the elements and will be + * temporarly disabled. The distinct constraint will be manage if necessary + * : * <pre> * COUNT(DISTINCT mainAlias) * </pre> * * @param transaction the TopiaContext to use for execution * @return an int corresponding to the number of result in the query - * @throws TopiaException + * @throws TopiaException for error on query execution */ public int executeCount(TopiaContext transaction) throws TopiaException { StringBuilder oldOrder = orderBy; @@ -1138,7 +1145,7 @@ // unique) if (distinct && StringUtils.isNotEmpty(mainAlias)) { count.append("DISTINCT ").append(mainAlias); - // When distinct is not set, use * + // When distinct is not set, use <pre>*</pre> } else { count.append('*'); } @@ -1152,7 +1159,7 @@ * DAO must be defined to use this method. * * @return an int corresponding to the number of result in the query - * @throws TopiaException + * @throws TopiaException for error on query execution * @see #executeCount(TopiaContext) */ public int executeCount() throws TopiaException { @@ -1162,20 +1169,19 @@ protected boolean validateDAO() throws TopiaException { if (dao == null) { - throw new TopiaException("DAO not defined in TopiaQuery, " + - "can't execute it without TopiaContext"); - } + throw new TopiaException( + "topia.persistence.error.query.dao.notDefined"); + } return true; } /** * Load all properties for the entity. * - * @param <T> type of the entity extends TopiaEntity * @param entity used to load properties - * @throws TopiaException + * @throws TopiaException for error on query execution */ - protected <T extends TopiaEntity> void loadProperties(T entity) + protected void loadProperties(TopiaEntity entity) throws TopiaException { for (String prop : getPropertiesToLoad()) { if (log.isTraceEnabled()) { @@ -1203,28 +1209,32 @@ /** * Load a property of type TopiaEntity from an other entity. * - * @param <T> type of the entity extends TopiaEntity - * @param entity used to load the property + * @param <T> type of the entity extends TopiaEntity + * @param entity used to load the property * @param property name of the property in the entity * @return a TopiaEntity corresponding to the property loaded - * @throws TopiaException + * @throws TopiaException for error on query execution */ protected <T extends TopiaEntity> TopiaEntity loadEntityProperty(T entity, - String property) throws TopiaException { - return (TopiaEntity)loadProperty(entity, property); + String property) + throws TopiaException { + return (TopiaEntity) loadProperty(entity, property); } /** * Load a property from an entity. * - * @param <T> type of the entity extends TopiaEntity - * @param entity used to load the property + * @param <T> type of the entity extends TopiaEntity + * @param entity used to load the property * @param property name of the property in the entity * @return an Object corresponding to the property loaded - * @throws TopiaException + * @throws TopiaException for error loading property (encapsulate + * IllegalACessException, InvocationTargetException, + * NoSuchMethodException) */ protected <T extends TopiaEntity> Object loadProperty(T entity, - String property) throws TopiaException { + String property) + throws TopiaException { try { Object res = PropertyUtils.getProperty(entity, property); if (log.isTraceEnabled()) { @@ -1237,11 +1247,11 @@ } return res; } catch (IllegalAccessException eee) { - throw new TopiaException("Illegal access on property " + + throw new TopiaException("Illegal access on property " + property + " from entity " + entity.getClass().getName(), eee); } catch (InvocationTargetException eee) { - throw new TopiaException("Invocation error on entity " + + throw new TopiaException("Invocation error on entity " + entity.getClass().getName() + " for property " + property, eee); } catch (NoSuchMethodException eee) { @@ -1252,14 +1262,15 @@ } /** - * This method is used to concat properties from entities. Ex in HQL you - * can have boat.shipOwner.name, these properties are defined as constants - * in each entity associated (SHIP_OWNER in Boat entity, NAME in ShipOwner + * This method is used to concat properties from entities. Ex in HQL you can + * have boat.shipOwner.name, these properties are defined as constants in + * each entity associated (SHIP_OWNER in Boat entity, NAME in ShipOwner * entity) so you just have to call this method as : * <pre> * getProperty("boat", Boat.SHIP_OWNER, ShipOwner.NAME); * // will return boat.shipOwner.name - * </pre><br \> + * </pre> + * <p/> * It's better to use constants instead of directly the string chain to * avoid problems on changing property name in model. Furthermore it's * better to use this method instead of doing : @@ -1277,13 +1288,14 @@ } @Override - protected void finalize() { + protected void finalize() throws Throwable { // Clean StringBuilder statements select = null; from = null; where = null; orderBy = null; groupBy = null; + super.finalize(); } @Override Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaService.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaService.java 2010-05-07 13:15:19 UTC (rev 1934) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaService.java 2010-05-07 15:19:41 UTC (rev 1935) @@ -38,45 +38,48 @@ package org.nuiton.topia.framework; /** - * Permet d'implanter un service Topia. Il faut absolument créer une interface - * pour votre service qui contienne un attribut SERVICE_NAME - * + * Used to implement a service for Topia. You have to provide a static property + * called SERVICE_NAME that identify the service : + * <p/> * <li>public static final String SERVICE_NAME = "monservice"; - * - * la valeur de cette attribut doit être retourné par les implantation de votre - * service par la méthode {@link #getServiceName()} - * + * <p/> + * The value of this attribute need to be returned when using + * {@link #getServiceName()} method. + * * @author poussin <poussin@codelutin.com> + * @version $Id$ */ public interface TopiaService { /** - * Retourne le nom du service, ce nom doit correspondre a ce qui est - * trouvé dans le fichier de configuration, par exemple pour le service - * d'indexation on doit avoir: topia.service.index et cette methode doit - * retourner index - * - * @return le nom du service + * Return the name of the service, this name need to match with + * configuration file, for example for index service, we need to have : + * "topia.service.index" and this method will returned "index". + * + * @return the service name */ String getServiceName(); /** - * Permet de récupérer les entités à persister pour ce service - * @return Liste des entités à persister, séparées par des virgules + * Retrieve entities of this service needed for persistence. + * + * @return List of entities full qualified name separated by a comma */ Class<?>[] getPersistenceClasses(); /** - * Initialise le service avant de creer le context - * @param context le context - * @return si le service doit etre laissé activé ou pas + * Initiliaze the service before create the {@code context}. + * + * @param context TopiaContextImplementor + * @return true if service need to be activated or not */ boolean preInit(TopiaContextImplementor context); /** - * Initialise le service apres avoir creer le context - * @param context le context - * @return si le service doit etre laissé activé ou pas + * Initiliaze the service after create the {@code context}. + * + * @param context TopiaContextImplementor + * @return true if service need to be activated or not */ boolean postInit(TopiaContextImplementor context); Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaUtil.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaUtil.java 2010-05-07 13:15:19 UTC (rev 1934) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaUtil.java 2010-05-07 15:19:41 UTC (rev 1935) @@ -36,11 +36,16 @@ */ package org.nuiton.topia.framework; -import java.util.Iterator; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.cfg.Configuration; +import org.hibernate.connection.ConnectionProvider; +import org.hibernate.connection.ConnectionProviderFactory; +import org.hibernate.dialect.Dialect; import org.hibernate.mapping.PersistentClass; +import org.hibernate.mapping.Table; +import org.hibernate.tool.hbm2ddl.DatabaseMetadata; +import org.hibernate.tool.hbm2ddl.TableMetadata; import org.nuiton.topia.TopiaNotFoundException; import org.nuiton.topia.persistence.TopiaEntity; import org.nuiton.util.RecursiveProperties; @@ -49,31 +54,32 @@ import java.net.URL; import java.sql.Connection; import java.sql.SQLException; +import java.util.Iterator; import java.util.Properties; import java.util.StringTokenizer; import java.util.regex.Pattern; -import org.hibernate.connection.ConnectionProvider; -import org.hibernate.connection.ConnectionProviderFactory; -import org.hibernate.dialect.Dialect; -import org.hibernate.mapping.Table; -import org.hibernate.tool.hbm2ddl.DatabaseMetadata; -import org.hibernate.tool.hbm2ddl.TableMetadata; -/** @author poussin <poussin@codelutin.com> */ +/** + * TODO-fdesbois-20100507 : Need javadoc + translations for existing methods. + * + * @author poussin <poussin@codelutin.com> + * @version $Id$ + */ public class TopiaUtil { /** to use log facility, just put in your code: log.info(\"...\"); */ static private Log log = LogFactory.getLog(TopiaUtil.class); /** - * Permet de récupérer le fichier de propriété ayant le nom passé - * en argument. + * Permet de récupérer le fichier de propriété ayant le nom passé en + * argument. * * @param pathOrUrl le nom du fichier de propriété à charger, s'il est null * ou vide retourne un objet Properties vide. * @return Un nouvel objet de propriete * @throws TopiaNotFoundException Si pathOrUrl n'est pas null ou vide et que - * le fichier devant contenir les propriétés n'est pas retrouvé. + * le fichier devant contenir les propriétés + * n'est pas retrouvé. */ static public Properties getProperties(String pathOrUrl) throws TopiaNotFoundException { @@ -81,15 +87,17 @@ } /** - * Permet de récupérer le fichier de propriété ayant le nom passé - * en argument. + * Permet de récupérer le fichier de propriété ayant le nom passé en + * argument. * - * @param parent l'objet properties utilisé comme parent de l'objet retourné + * @param parent l'objet properties utilisé comme parent de l'objet + * retourné * @param pathOrUrl le nom du fichier de propriété à charger, s'il est null * ou vide retourne un objet Properties vide. * @return Un nouvel objet de propriete * @throws TopiaNotFoundException Si pathOrUrl n'est pas null ou vide et que - * le fichier devant contenir les propriétés n'est pas retrouvé. + * le fichier devant contenir les propriétés + * n'est pas retrouvé. */ static public Properties getProperties(Properties parent, String pathOrUrl) throws TopiaNotFoundException { @@ -112,15 +120,17 @@ /** * Compute a regex pattern given a format string. * <p/> - * A {@link String#format(String, Object...)} will be apply to <code>format</code>, with - * for parameters the list of <code>klass</code> transformed in topia pattern via method - * {@link #getTopiaIdPattern(Class)} ready to be capture (enclosed by ()). + * A {@link String#format(String, Object...)} will be apply to + * <code>format</code>, with for parameters the list of <code>klass</code> + * transformed in topia pattern via method {@link #getTopiaIdPattern(Class)} + * ready to be capture (enclosed by ()). * * @param format the format * @param classes the list of class to use * @return the pattern computed */ - public static Pattern getTopiaPattern(String format, Class<? extends TopiaEntity>... classes) { + public static Pattern getTopiaPattern(String format, + Class<? extends TopiaEntity>... classes) { String[] entityPatterns = new String[classes.length]; for (int i = 0; i < classes.length; i++) { Class<? extends TopiaEntity> aClass = classes[i]; @@ -134,7 +144,8 @@ } /** - * Compute the pattern to be used to capture a topia id for a given entity class. + * Compute the pattern to be used to capture a topia id for a given entity + * class. * * @param klass the entity class * @return the pattern to capture a topia id for the given entity class. @@ -150,32 +161,38 @@ } /** - * Test si une entite donnee correspondant a une configuration existe en base. + * Test si une entite donnee correspondant a une configuration existe en + * base. * * @param configuration la configuration hibernate - * @param entityName le nom de l'entite a tester - * + * @param entityName le nom de l'entite a tester * @return <tt>true</tt> si le schema de la table existe */ - public static boolean isSchemaExist(Configuration configuration, String entityName) { + public static boolean isSchemaExist(Configuration configuration, + String entityName) { boolean exist = false; try { - PersistentClass classMapping = configuration.getClassMapping(entityName); + PersistentClass classMapping = + configuration.getClassMapping(entityName); if (classMapping == null) { Iterator<?> itr = configuration.getClassMappings(); while (itr.hasNext()) { log.info("available mapping " + itr.next()); } - throw new IllegalArgumentException("could not find entity with name " + entityName); + throw new IllegalArgumentException( + "could not find entity with name " + entityName); } Table testTable = classMapping.getTable(); if (testTable == null) { - throw new IllegalArgumentException("could not find entity with name " + entityName); + throw new IllegalArgumentException( + "could not find entity with name " + entityName); } - ConnectionProvider connectionProvider = ConnectionProviderFactory.newConnectionProvider(configuration.getProperties()); + ConnectionProvider connectionProvider = + ConnectionProviderFactory.newConnectionProvider( + configuration.getProperties()); Dialect dialect = Dialect.getDialect(configuration.getProperties()); @@ -185,7 +202,9 @@ DatabaseMetadata meta = new DatabaseMetadata(connection, dialect); - TableMetadata tmd = meta.getTableMetadata(testTable.getName(), testTable.getSchema(), testTable.getCatalog(), testTable.isQuoted()); + TableMetadata tmd = meta.getTableMetadata( + testTable.getName(), testTable.getSchema(), + testTable.getCatalog(), testTable.isQuoted()); if (tmd != null) { //table exist Added: trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/package-info.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/package-info.java (rev 0) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/package-info.java 2010-05-07 15:19:41 UTC (rev 1935) @@ -0,0 +1,21 @@ +/** + * Contains two interfaces, one {@link TopiaContextImplementor}for internal + * manipulations of {@link TopiaContext} and one {@link TopiaService}for topia + * services. This package contains also the main implementation {@link TopiaContextImpl} + * for both {@link TopiaContext} for final applications and + * {@link TopiaContextImplementor} for internal. + * <p /> + * You can also use {@link TopiaQuery} class for query manipulation with + * {@link TopiaDAO}. + * <p /> + * {@link TopiaUtil} is a helper class used for TopiaContext manipulations. + * + * @author fdesbois <fdesbois@codelutin.com> + * @version $Id$ + * @see TopiaContext + * @see TopiaDAO + */ +package org.nuiton.topia.framework; + +import org.nuiton.topia.persistence.TopiaDAO; +import org.nuiton.topia.TopiaContext; \ No newline at end of file Property changes on: trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/package-info.java ___________________________________________________________________ Added: svn:keywords + Author Date Id Revision HeadURL Modified: trunk/topia-persistence/src/main/resources/i18n/topia-persistence-en_GB.properties =================================================================== --- trunk/topia-persistence/src/main/resources/i18n/topia-persistence-en_GB.properties 2010-05-07 13:15:19 UTC (rev 1934) +++ trunk/topia-persistence/src/main/resources/i18n/topia-persistence-en_GB.properties 2010-05-07 15:19:41 UTC (rev 1935) @@ -15,6 +15,7 @@ topia.persistence.error.on.replicate= topia.persistence.error.on.restore= topia.persistence.error.on.rollback= +topia.persistence.error.query.dao.notDefined=DAO not defined in TopiaQuery, can't execute it without TopiaContext topia.persistence.error.replicate.entity= topia.persistence.error.replicate.on.same.context= topia.persistence.error.rootContext.access= Modified: trunk/topia-persistence/src/main/resources/i18n/topia-persistence-fr_FR.properties =================================================================== --- trunk/topia-persistence/src/main/resources/i18n/topia-persistence-fr_FR.properties 2010-05-07 13:15:19 UTC (rev 1934) +++ trunk/topia-persistence/src/main/resources/i18n/topia-persistence-fr_FR.properties 2010-05-07 15:19:41 UTC (rev 1935) @@ -14,6 +14,7 @@ topia.persistence.error.on.replicate=Une erreur est apparue pendant la replication \: %1$s topia.persistence.error.on.restore=Une erreur est apparue pendant le restore \: %1$s topia.persistence.error.on.rollback=Une erreur est apparue pendant le rollback \: %1$s +topia.persistence.error.query.dao.notDefined=Aucun dao n'est d\u00E9fini dans la TopiaQuery, impossible de l'ex\u00E9cuter sans TopiaContext. topia.persistence.error.replicate.entity=Echec de replication de l'entite %1$s\npour la raison suivante \: %2$s topia.persistence.error.replicate.on.same.context=Impossible de dupliquer dans la m\u00EAme base topia.persistence.error.rootContext.access=Vous \u00EAtes sur le root context, vous devez ouvrir une transaction pour pouvoir acc\u00E9der aux donn\u00E9es.