r2955 - in trunk: src/site/rst topia-it/src/main/java/org/nuiton/topia/it/legacy topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util topia-junit/src/main/java/org/nuiton/topia/junit topia-persistence/src/main/java/org/nuiton/topia/persistence topia-persistence/src/main/java/org/nuiton/topia/persistence/internal topia-service-migration/src/main/java/org/nuiton/topia/migration topia-templates/src/main/java/org/nuiton/topia/templates
Author: tchemit Date: 2013-12-20 17:19:35 +0100 (Fri, 20 Dec 2013) New Revision: 2955 Url: http://nuiton.org/projects/topia/repository/revisions/2955 Log: refs #2893: Refactor packages (second pass) Added: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/internal/AbstractTopiaDao.java trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/internal/DefaultTopiaIdFactory.java trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/internal/HibernateProvider.java trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/internal/LegacyTopiaIdFactory.java Removed: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/AbstractTopiaDao.java trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/DefaultTopiaIdFactory.java trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/HibernateProvider.java trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/LegacyTopiaIdFactory.java trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/SearchFields.java Modified: trunk/src/site/rst/changelog_3.0.rst trunk/src/site/rst/migrate_to_3.0.rst trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/AbstractTopiaTestDao.java trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/AbstractTopiaTestPersistenceContext.java trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/GeneratedPersonneTopiaDao.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityHelperTest.java trunk/topia-junit/src/main/java/org/nuiton/topia/junit/AbstractDatabaseResource.java trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaEntity.java trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaEntityAbstract.java trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/internal/AbstractTopiaApplicationContext.java trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/internal/AbstractTopiaPersistenceContext.java trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TopiaMigrationEngine.java trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityDaoTransformer.java trunk/topia-templates/src/main/java/org/nuiton/topia/templates/PersistenceContextTransformer.java trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaGeneratorUtil.java trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaTagValues.java Modified: trunk/src/site/rst/changelog_3.0.rst =================================================================== --- trunk/src/site/rst/changelog_3.0.rst 2013-12-20 16:07:29 UTC (rev 2954) +++ trunk/src/site/rst/changelog_3.0.rst 2013-12-20 16:19:35 UTC (rev 2955) @@ -33,7 +33,7 @@ souhaitez conserver l'uniformité avec une base de données existante ou si vous utilisez topia-service-security, vous devez explicitement le spécifier à Topia 3.0 via la configuration : - ``topia.persistence.topiaIdFactoryClassName=org.nuiton.topia.persistence.LegacyTopiaIdFactory`` + ``topia.persistence.topiaIdFactoryClassName=org.nuiton.topia.persistence.internal.LegacyTopiaIdFactory`` Le classe **TopiaID** est dépréciée, elle sera supprimée dans les prochaines versions. Modified: trunk/src/site/rst/migrate_to_3.0.rst =================================================================== --- trunk/src/site/rst/migrate_to_3.0.rst 2013-12-20 16:07:29 UTC (rev 2954) +++ trunk/src/site/rst/migrate_to_3.0.rst 2013-12-20 16:19:35 UTC (rev 2955) @@ -98,7 +98,7 @@ souhaitez conserver l'uniformité avec une base de données existante ou si vous utilisez topia-service-security, vous devez explicitement le spécifier à Topia 3.0 via la configuration : - ``topia.persistence.topiaIdFactoryClassName=org.nuiton.topia.persistence.LegacyTopiaIdFactory`` + ``topia.persistence.topiaIdFactoryClassName=org.nuiton.topia.persistence.internal.LegacyTopiaIdFactory`` TopiaContextImplementor est déprécié Modified: trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/AbstractTopiaTestDao.java =================================================================== --- trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/AbstractTopiaTestDao.java 2013-12-20 16:07:29 UTC (rev 2954) +++ trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/AbstractTopiaTestDao.java 2013-12-20 16:19:35 UTC (rev 2955) @@ -24,7 +24,7 @@ * #L% */ -import org.nuiton.topia.persistence.AbstractTopiaDao; +import org.nuiton.topia.persistence.internal.AbstractTopiaDao; import org.nuiton.topia.persistence.TopiaEntity; /** Modified: trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/AbstractTopiaTestPersistenceContext.java =================================================================== --- trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/AbstractTopiaTestPersistenceContext.java 2013-12-20 16:07:29 UTC (rev 2954) +++ trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/AbstractTopiaTestPersistenceContext.java 2013-12-20 16:19:35 UTC (rev 2955) @@ -26,7 +26,7 @@ import org.nuiton.topia.persistence.internal.AbstractTopiaPersistenceContext; import org.nuiton.topia.persistence.support.TopiaListenableSupport; -import org.nuiton.topia.persistence.HibernateProvider; +import org.nuiton.topia.persistence.internal.HibernateProvider; import org.nuiton.topia.persistence.internal.TopiaHibernateSessionRegistry; import org.nuiton.topia.persistence.TopiaIdFactory; Modified: trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/GeneratedPersonneTopiaDao.java =================================================================== --- trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/GeneratedPersonneTopiaDao.java 2013-12-20 16:07:29 UTC (rev 2954) +++ trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/GeneratedPersonneTopiaDao.java 2013-12-20 16:19:35 UTC (rev 2955) @@ -28,7 +28,7 @@ import java.util.Map; import org.nuiton.topia.persistence.TopiaException; -import org.nuiton.topia.persistence.AbstractTopiaDao; +import org.nuiton.topia.persistence.internal.AbstractTopiaDao; import org.nuiton.topia.persistence.TopiaEntity; import org.nuiton.topia.persistence.TopiaEntityEnum; import org.nuiton.topia.it.legacy.topiatest.Personne; Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityHelperTest.java =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityHelperTest.java 2013-12-20 16:07:29 UTC (rev 2954) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityHelperTest.java 2013-12-20 16:19:35 UTC (rev 2955) @@ -31,7 +31,7 @@ import org.junit.Test; import org.nuiton.topia.persistence.TopiaException; import org.nuiton.topia.it.legacy.TopiaTestEntityEnum; -import org.nuiton.topia.persistence.DefaultTopiaIdFactory; +import org.nuiton.topia.persistence.internal.DefaultTopiaIdFactory; import org.nuiton.topia.persistence.TopiaEntity; import org.nuiton.topia.persistence.TopiaEntityEnum; import org.nuiton.topia.persistence.TopiaIdFactory; Modified: trunk/topia-junit/src/main/java/org/nuiton/topia/junit/AbstractDatabaseResource.java =================================================================== --- trunk/topia-junit/src/main/java/org/nuiton/topia/junit/AbstractDatabaseResource.java 2013-12-20 16:07:29 UTC (rev 2954) +++ trunk/topia-junit/src/main/java/org/nuiton/topia/junit/AbstractDatabaseResource.java 2013-12-20 16:19:35 UTC (rev 2955) @@ -32,7 +32,7 @@ import org.junit.runner.Description; import org.nuiton.topia.persistence.TopiaConfigurationConstants; import org.nuiton.topia.persistence.internal.AbstractTopiaApplicationContext; -import org.nuiton.topia.persistence.HibernateProvider; +import org.nuiton.topia.persistence.internal.HibernateProvider; import org.nuiton.topia.persistence.TopiaException; import org.nuiton.topia.persistence.TopiaPersistenceContext; Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/AbstractTopiaDao.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/AbstractTopiaDao.java 2013-12-20 16:07:29 UTC (rev 2954) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/AbstractTopiaDao.java 2013-12-20 16:19:35 UTC (rev 2955) @@ -1,1021 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -/* * - * TopiaDAOAbstract.java - * - * Created: 31 déc. 2005 13:10:34 - * - * @author poussin <poussin@codelutin.com> - * @version $Revision$ - * - * Last update: $Date$ - * by : $Author$ - */ - -package org.nuiton.topia.persistence; - -import com.google.common.base.Optional; -import com.google.common.base.Preconditions; -import com.google.common.collect.Iterables; -import com.google.common.collect.Iterators; -import org.apache.commons.beanutils.PropertyUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.topia.persistence.support.TopiaJpaSupport; -import org.nuiton.topia.persistence.support.TopiaListenableSupport; -import org.nuiton.topia.persistence.support.TopiaSqlSupport; -import org.nuiton.topia.persistence.event.TopiaEntityListener; -import org.nuiton.topia.persistence.event.TopiaEntityVetoable; -import org.nuiton.topia.persistence.internal.support.TopiaFiresSupport; -import org.nuiton.topia.persistence.util.TopiaUtil; -import org.nuiton.topia.persistence.pager.TopiaPagerBean; -import org.nuiton.util.PagerBeanUtil; - -import java.lang.reflect.InvocationTargetException; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Set; - -/** - * This class has the common methods usable for each Dao managed by Topia. It is not JPA implementation dependent, it - * only relies on {@link TopiaJpaSupport}. - * <p/> - * This class is directly extended by the GeneratedXyzTopiaDao which groups all the Xyz specific methods. - * <p/> - * Instances are created bt the model's specific {@link TopiaPersistenceContext}, which implements the - * {@link TopiaDaoSupplier} contract. - * - * @param <E> the managed entity type - * @author bpoussin <poussin@codelutin.com> - * @author Arnaud Thimel <thimel@codelutin.com> - * @author Tony CHEMIT <chemit@codelutin.com> - */ -public abstract class AbstractTopiaDao<E extends TopiaEntity> implements TopiaDao<E> { - - private static Log log = LogFactory.getLog(AbstractTopiaDao.class); - - /** - * Default batch size used to iterate on data. - * - * @since 2.6.14 - */ - protected int batchSize = 1000; - - protected TopiaJpaSupport topiaJpaSupport; - - protected TopiaSqlSupport topiaSqlSupport; - - protected TopiaListenableSupport topiaListenableSupport; - - protected TopiaIdFactory topiaIdFactory; - - protected TopiaFiresSupport topiaFiresSupport; - - protected TopiaDaoSupplier topiaDaoSupplier; - - public abstract TopiaEntityEnum getTopiaEntityEnum(); - - public abstract Class<E> getEntityClass(); - - /** - * When AbstractTopiaContext create the TopiaDAOHibernate, it must call this - * method just after. - */ - public void init( - TopiaJpaSupport topiaJpaSupport, - TopiaSqlSupport topiaSqlSupport, - TopiaListenableSupport topiaListenableSupport, - TopiaIdFactory topiaIdFactory, - TopiaFiresSupport topiaFiresSupport, - TopiaDaoSupplier topiaDaoSupplier) { - if (log.isDebugEnabled()) { - log.debug("init dao for " + getEntityClass()); - } - this.topiaJpaSupport = topiaJpaSupport; - this.topiaSqlSupport = topiaSqlSupport; - this.topiaListenableSupport = topiaListenableSupport; - this.topiaIdFactory = topiaIdFactory; - this.topiaFiresSupport = topiaFiresSupport; - this.topiaDaoSupplier = topiaDaoSupplier; - } - - public TopiaFiresSupport getTopiaFiresSupport() { - return topiaFiresSupport; - } - - @Override - public int getBatchSize() { - return batchSize; - } - - @Override - public void setBatchSize(int batchSize) { - this.batchSize = batchSize; - } - - protected String newFromClause() { - return newFromClause(null); - } - - protected String newFromClause(String alias) { - String hql = "from " + getTopiaEntityEnum().getImplementationFQN(); - if (StringUtils.isNotBlank(alias)) { - hql += " " + alias; - } - return hql; - } - - @Override - public E newInstance() { - if (log.isTraceEnabled()) { - log.trace("entityClass = " + getEntityClass()); - } - Class<E> implementation = (Class<E>) - getTopiaEntityEnum().getImplementation(); - try { - E newInstance = implementation.newInstance(); - return newInstance; - } catch (InstantiationException e) { - throw new TopiaException( - "Impossible de trouver ou d'instancier la classe " - + implementation); - } catch (IllegalAccessException e) { - throw new TopiaException( - "Impossible de trouver ou d'instancier la classe " - + implementation); - } - } - - @Override - public TopiaPagerBean newPager(int pageSize) { - TopiaPagerBean pager = newPager(newFromClause(), null, pageSize); - return pager; - } - - @Override - public TopiaPagerBean newPager(String hql, Map<String, Object> params, int pageSize) { - TopiaPagerBean pager = new TopiaPagerBean(); - - if (hqlContainsOrderBy(hql)) { - - // must remove the order by clause, otherwise some sql queries won't work. - hql = hql.substring(0, hql.toLowerCase().indexOf("order by")); - } - long count = count("SELECT COUNT(*) " + hql, params); - pager.setRecords(count); - pager.setPageSize(pageSize); - PagerBeanUtil.computeRecordIndexesAndPagesNumber(pager); - return pager; - } - - @Override - public void addTopiaEntityListener(TopiaEntityListener listener) { - topiaListenableSupport.addTopiaEntityListener(getEntityClass(), listener); - } - - @Override - public void addTopiaEntityVetoable(TopiaEntityVetoable vetoable) { - topiaListenableSupport.addTopiaEntityVetoable(getEntityClass(), vetoable); - } - - @Override - public void removeTopiaEntityListener(TopiaEntityListener listener) { - topiaListenableSupport.removeTopiaEntityListener(getEntityClass(), listener); - } - - @Override - public void removeTopiaEntityVetoable(TopiaEntityVetoable vetoable) { - topiaListenableSupport.removeTopiaEntityVetoable(getEntityClass(), vetoable); - } - - @Override - public E create(E entity) { - // first set topiaId - if (StringUtils.isBlank(entity.getTopiaId())) { - - // only set id if not already on - String topiaId = topiaIdFactory.newTopiaId(getEntityClass(), entity); - entity.setTopiaId(topiaId); - } - - if (entity instanceof TopiaEntityContextable) { - TopiaEntityContextable contextable = (TopiaEntityContextable) entity; - contextable.setTopiaDAOSupplier(this.topiaDaoSupplier); - } - - // save entity - topiaJpaSupport.save(entity); - topiaFiresSupport.warnOnCreateEntity(entity); - return entity; - } - - @Override - public E create(String propertyName, Object propertyValue, Object... otherPropertyNamesAndValues) { - Map<String, Object> properties = - TopiaUtil.convertPropertiesArrayToMap(propertyName, propertyValue, otherPropertyNamesAndValues); - E result = create(properties); - return result; - } - - @Override - public E create(Map<String, Object> properties) { - - E result = newInstance(); - - try { - for (Map.Entry<String, Object> e : properties.entrySet()) { - String propertyName = e.getKey(); - Object value = e.getValue(); - PropertyUtils.setProperty(result, propertyName, value); - } - } catch (IllegalAccessException eee) { - throw new IllegalArgumentException( - "Can't put properties on new Object", eee); - } catch (InvocationTargetException eee) { - throw new IllegalArgumentException( - "Can't put properties on new Object", eee); - } catch (NoSuchMethodException eee) { - throw new IllegalArgumentException( - "Can't put properties on new Object", eee); - } - - create(result); - - return result; - } - - @Override - public E create() { - E result = newInstance(); - create(result); - return result; - } - - @Override - public Iterable<E> createAll(Iterable<E> entities) { - for (E entity : entities) { - create(entity); - } - return entities; - } - - @Override - public E update(E entity) { - topiaJpaSupport.saveOrUpdate(entity); - topiaFiresSupport.warnOnUpdateEntity(entity); - return entity; - } - - @Override - public Iterable<E> updateAll(Iterable<E> entities) { - for (E entity : entities) { - update(entity); - } - return entities; - } - - @Override - public void delete(E entity) { - topiaJpaSupport.delete(entity); - entity.notifyDeleted(); - topiaFiresSupport.warnOnDeleteEntity(entity); - } - - @Override - public void deleteAll(Iterable<E> entities) { - for (E entity : entities) { - delete(entity); - } - } - - protected HqlAndParametersBuilder<E> newHqlAndParametersBuilder() { - HqlAndParametersBuilder<E> result = new HqlAndParametersBuilder<E>(getEntityClass()); - return result; - } - - protected HqlAndParametersBuilder<E> getHqlForProperties(String propertyName, - Object propertyValue, - Object... otherPropertyNamesAndValues) { - Map<String, Object> properties = - TopiaUtil.convertPropertiesArrayToMap(propertyName, propertyValue, otherPropertyNamesAndValues); - HqlAndParametersBuilder<E> result = getHqlForProperties(properties); - return result; - } - - protected HqlAndParametersBuilder<E> getHqlForNoConstraint() { - Map<String, Object> properties = Collections.emptyMap(); - HqlAndParametersBuilder<E> result = getHqlForProperties(properties); - return result; - } - - protected HqlAndParametersBuilder<E> getHqlForProperties(Map<String, Object> properties) { - HqlAndParametersBuilder<E> result = newHqlAndParametersBuilder(); - for (Map.Entry<String, Object> property : properties.entrySet()) { - result.addEquals(property.getKey(), property.getValue()); - } - return result; - } - - protected InnerTopiaQueryBuilderRunQueryStep<E> forHql(String hql) { - Map<String, Object> properties = Collections.emptyMap(); - InnerTopiaQueryBuilderRunQueryStep<E> result = forHql(hql, properties); - return result; - } - - protected InnerTopiaQueryBuilderRunQueryStep<E> forHql(String hql, Map<String, Object> hqlParameters) { - InnerTopiaQueryBuilderRunQueryStep<E> result = new InnerTopiaQueryBuilderRunQueryStep<E>(this, hql, hqlParameters); - return result; - } - - protected InnerTopiaQueryBuilderRunQueryStep<E> forHql(String hql, String parameterName, - Object parameterValue, - Object... otherParameterNamesAndValues) { - Map<String, Object> hqlParameters = - TopiaUtil.convertPropertiesArrayToMap(parameterName, parameterValue, otherParameterNamesAndValues); - InnerTopiaQueryBuilderRunQueryStep<E> result = forHql(hql, hqlParameters); - return result; - } - - @Override - public InnerTopiaQueryBuilderAddCriteriaOrRunQueryStep<E> forProperties(Map<String, Object> properties) { - HqlAndParametersBuilder<E> hqlAndParametersBuilder = getHqlForProperties(properties); - InnerTopiaQueryBuilderAddCriteriaOrRunQueryStep<E> result = new InnerTopiaQueryBuilderAddCriteriaOrRunQueryStep<E>(this, hqlAndParametersBuilder); - return result; - } - - @Override - public InnerTopiaQueryBuilderAddCriteriaOrRunQueryStep<E> forProperties(String propertyName, - Object propertyValue, - Object... otherPropertyNamesAndValues) { - HqlAndParametersBuilder<E> hqlAndParametersBuilder = getHqlForProperties(propertyName, propertyValue, otherPropertyNamesAndValues); - InnerTopiaQueryBuilderAddCriteriaOrRunQueryStep<E> result = new InnerTopiaQueryBuilderAddCriteriaOrRunQueryStep<E>(this, hqlAndParametersBuilder); - return result; - } - - @Override - public InnerTopiaQueryBuilderAddCriteriaOrRunQueryStep<E> newQueryBuilder() { - HqlAndParametersBuilder<E> hqlAndParametersBuilder = newHqlAndParametersBuilder(); - InnerTopiaQueryBuilderAddCriteriaOrRunQueryStep<E> result = new InnerTopiaQueryBuilderAddCriteriaOrRunQueryStep<E>(this, hqlAndParametersBuilder); - return result; - } - - @Override - public TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> forContains(String propertyName, Object propertyValue) { - TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> result = newQueryBuilder().addContains(propertyName, propertyValue); - return result; - } - - @Override - public TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> forEquals(String propertyName, Object propertyValue) { - TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> result = newQueryBuilder().addEquals(propertyName, propertyValue); - return result; - } - - @Override - public TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> forIn(String propertyName, Iterable<?> propertyValues) { - TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> result = newQueryBuilder().addIn(propertyName, propertyValues); - return result; - } - - protected boolean exists(String hql, Map<String, Object> hqlParameters) { - List<E> entities = topiaJpaSupport.find(hql, 0, 0, hqlParameters); - boolean result = !entities.isEmpty(); - return result; - } - - protected long count(String hql, Map<String, Object> hqlParameters) { - Preconditions.checkArgument(hql.toLowerCase().trim().startsWith("select count(")); - Long result = findUnique(hql, hqlParameters); - return result; - } - - protected <K> K findUnique(String hql, Map<String, Object> hqlParameters) throws TopiaNoResultException, TopiaNonUniqueResultException { - K result = findUniqueOrNull(hql, hqlParameters); - if (result == null) { - throw new TopiaNoResultException(hql, hqlParameters); - } - return result; - } - - protected <K> Optional<K> tryFindUnique(String hql, Map<String, Object> hqlParameters) throws TopiaNonUniqueResultException { - K uniqueOrNull = findUniqueOrNull(hql, hqlParameters); - Optional<K> result = Optional.fromNullable(uniqueOrNull); - return result; - } - - protected <K> K findUniqueOrNull(String hql, Map<String, Object> hqlParameters) throws TopiaNonUniqueResultException { - List<K> results = find(hql, hqlParameters, 0, 1); - // If there is more than 1 result, throw an exception - if (results.size() > 1) { - throw new TopiaNonUniqueResultException(hql, hqlParameters); - } - // otherwise return the first one, or null - K result = Iterables.getOnlyElement(results, null); - return result; - } - - protected <K> K findFirst(String hql, Map<String, Object> hqlParameters) throws QueryMissingOrderException { - K result = findFirstOrNull(hql, hqlParameters); - if (result == null) { - throw new TopiaNoResultException(hql, hqlParameters); - } - return result; - } - - protected <K> Optional<K> tryFindFirst(String hql, Map<String, Object> hqlParameters) throws QueryMissingOrderException { - K firstOrNull = findFirstOrNull(hql, hqlParameters); - Optional<K> result = Optional.fromNullable(firstOrNull); - return result; - } - - protected <K> K findFirstOrNull(String hql, Map<String, Object> hqlParameters) throws QueryMissingOrderException { - if (!hqlContainsOrderBy(hql)) { - throw new QueryMissingOrderException(hql, hqlParameters); - } - K result = findAnyOrNull(hql, hqlParameters); - return result; - } - - protected <K> K findAny(String hql, Map<String, Object> hqlParameters) throws TopiaNoResultException { - K result = findAnyOrNull(hql, hqlParameters); - if (result == null) { - throw new TopiaNoResultException(hql, hqlParameters); - } - return result; - } - - protected <K> Optional<K> tryFindAny(String hql, Map<String, Object> hqlParameters) { - K anyOrNull = findAnyOrNull(hql, hqlParameters); - Optional<K> result = Optional.fromNullable(anyOrNull); - return result; - } - - protected <K> K findAnyOrNull(String hql, Map<String, Object> hqlParameters) { - Preconditions.checkNotNull(hql); - Preconditions.checkNotNull(hqlParameters); - List<K> results = find(hql, hqlParameters, 0, 0); - K result = Iterables.getOnlyElement(results, null); - return result; - } - - protected <K> List<K> findAll(String hql, Map<String, Object> hqlParameters) { - Preconditions.checkNotNull(hql); - Preconditions.checkNotNull(hqlParameters); - List<K> result = topiaJpaSupport.findAll(hql, hqlParameters); - return result; - } - - protected <K> List<K> find(String hql, Map<String, Object> hqlParameters, int startIndex, int endIndex) { - Preconditions.checkNotNull(hql); - Preconditions.checkNotNull(hqlParameters); - List<K> result = topiaJpaSupport.find(hql, startIndex, endIndex, hqlParameters); - return result; - } - - public <K> List<K> find(String hql, Map<String, Object> hqlParameters, TopiaPagerBean pager) { - Preconditions.checkNotNull(hql); - Preconditions.checkNotNull(hqlParameters); - Preconditions.checkNotNull(pager); - - if (StringUtils.isNotBlank(pager.getSortColumn())) { - - // can't have a order by clause in hql query - Preconditions.checkState( - !hqlContainsOrderBy(hql), - "An 'order by' clause was already found in hql, can't use the order of the pager"); - - hql += " order by " + pager.getSortColumn(); - if (!pager.isSortAscendant()) { - hql += " desc"; - } - } - - List<K> result = topiaJpaSupport.find( - hql, - (int) pager.getRecordStartIndex(), - (int) pager.getRecordEndIndex() - 1, - hqlParameters); - - return result; - } - - protected <K> Iterable<K> findAllLazy(String hql, Map<String, Object> hqlParameters) { - - Iterable<K> result= findAllLazy(hql, hqlParameters, batchSize); - return result; - } - - protected <K> Iterable<K> findAllLazy(String hql, Map<String, Object> hqlParameters, int batchSize) { - - Preconditions.checkNotNull(hql); - Preconditions.checkNotNull(hqlParameters); - - final Iterator<K> iterator = new FindAllIterator<E, K>(this, - batchSize, - hql, - hqlParameters); - - Iterable<K> result = new Iterable<K>() { - @Override - public Iterator<K> iterator() { - return iterator; - } - }; - - return result; - } - - @Override - public TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> forTopiaIdEquals(String topiaId) { - Preconditions.checkArgument(StringUtils.isNotBlank(topiaId), "given topiaId is blank"); - TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> result = forEquals(TopiaEntity.PROPERTY_TOPIA_ID, topiaId); - return result; - } - - @Override - public TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> forTopiaIdIn(Iterable<String> topiaIds) { - Preconditions.checkNotNull(topiaIds, "given topiaIds is null"); - TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> result = forIn(TopiaEntity.PROPERTY_TOPIA_ID, (Iterable) topiaIds); - return result; - } - - @Override - public E findByTopiaId(String topiaId) throws TopiaNoResultException { - // AThimel 30/10/13 Not using findUnique to avoid querying several elements (cf. findUnique implementation) - E result = forTopiaIdEquals(topiaId).findAny(); - return result; - } - - @Override - public Optional<E> tryFindByTopiaId(String topiaId) { - Optional<E> result = forTopiaIdEquals(topiaId).tryFindAny(); - return result; - } - - @Override - public List<String> findAllIds() { - List<String> result = newQueryBuilder().findAllIds(); - return result; - } - - @Override - public List<E> findAll() { - List<E> result = newQueryBuilder().findAll(); - return result; - } - - @Override - public Iterable<E> findAllLazy() { - String hql = "from " + getTopiaEntityEnum().getImplementationFQN() + " order by id"; - Map<String, Object> hqlParameters = Collections.emptyMap(); - Iterable<E> result = findAllLazy(hql, hqlParameters); - return result; - } - - @Override - public Iterator<E> iterator() { - Iterator<E> result = findAllLazy().iterator(); - return result; - } - - @Override - public long count() { - long result = newQueryBuilder().count(); - return result; - } - - protected boolean hqlContainsOrderBy(String hql) { - return hql.toLowerCase().contains("order by"); - } - - protected boolean hqlContainsCount(String hql) { - return hql.toLowerCase().contains("count("); - } - -// /** -// * package locale method because this is hibernate specific method and -// * we don't want expose it. -// * -// * @return the meta-data of the entity -// * @throws org.nuiton.topia.persistence.TopiaException if any pb -// */ -// protected ClassMetadata getClassMetadata() { -// ClassMetadata meta = topiaHibernateSupport.getHibernateFactory().getClassMetadata(getEntityClass()); -// if (meta == null) { -// String implementationFQN = getTopiaEntityEnum().getImplementationFQN(); -// meta = topiaHibernateSupport.getHibernateFactory().getClassMetadata(implementationFQN); -// } -// return meta; -// } - - public static class FindAllIterator<E extends TopiaEntity, K> implements Iterator<K> { - - protected Iterator<K> data; - - protected final AbstractTopiaDao<E> dao; - - protected final String hql; - - protected final Map<String, Object> params; - - protected final TopiaPagerBean pager; - - public FindAllIterator(AbstractTopiaDao<E> dao, - int batchSize, - String hql, - Map<String, Object> params) { - - if (!dao.hqlContainsOrderBy(hql)) { - throw new QueryMissingOrderException(hql, params); - } - - this.dao = dao; - this.hql = hql; - this.params = params; - pager = dao.newPager(hql, params, batchSize); - - // empty iterator (will be changed at first next call) - data = Iterators.emptyIterator(); - } - - - public boolean hasNext() { - boolean result = data.hasNext() || // no more data - pager.getPageIndex() < pager.getPagesNumber(); - return result; - } - - - public K next() { - if (!hasNext()) { - throw new NoSuchElementException(); - } - - if (!data.hasNext()) { - - // must load iterator - - // increments page index - pager.setPageIndex(pager.getPageIndex() + 1); - PagerBeanUtil.computeRecordIndexesAndPagesNumber(pager); - - // load new window of data - List<K> values = dao.find(hql, params, pager); - data = values.iterator(); - - } - - K next = data.next(); - return next; - } - - - public void remove() { - throw new UnsupportedOperationException( - "This iterator does not support remove operation."); - } - } - - public static class InnerTopiaQueryBuilderAddCriteriaOrRunQueryStep<E extends TopiaEntity> implements TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> { - - protected AbstractTopiaDao<E> topiaDAO; - - protected HqlAndParametersBuilder<E> hqlAndParametersBuilder; - - protected InnerTopiaQueryBuilderAddCriteriaOrRunQueryStep(AbstractTopiaDao<E> topiaDAO, HqlAndParametersBuilder<E> hqlAndParametersBuilder) { - this.topiaDAO = topiaDAO; - this.hqlAndParametersBuilder = hqlAndParametersBuilder; - } - - @Override - public InnerTopiaQueryBuilderRunQueryStep<E> setOrderByArguments(Set<String> orderByArguments) { - hqlAndParametersBuilder.setOrderByArguments(orderByArguments); - return getNextStep(); - } - - @Override - public InnerTopiaQueryBuilderRunQueryStep<E> setOrderByArguments(String... orderByArguments) { - hqlAndParametersBuilder.setOrderByArguments(orderByArguments); - return getNextStep(); - } - - @Override - public TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> addEquals(String property, Object value) { - hqlAndParametersBuilder.addEquals(property, value); - return this; - } - - @Override - public TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> addNotEquals(String property, Object value) { - hqlAndParametersBuilder.addNotEquals(property, value); - return this; - } - - @Override - public TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> addIn(String property, Iterable<?> values) { - hqlAndParametersBuilder.addIn(property, values); - return this; - } - - @Override - public TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> addNotIn(String property, Iterable<?> values) { - hqlAndParametersBuilder.addNotIn(property, values); - return this; - } - - @Override - public TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> addContains(String property, Object value) { - hqlAndParametersBuilder.addContains(property, value); - return this; - } - - @Override - public TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> addNotContains(String property, Object value) { - hqlAndParametersBuilder.addNotContains(property, value); - return this; - } - - @Override - public TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> addNull(String property) { - hqlAndParametersBuilder.addNull(property); - return this; - } - - @Override - public TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> addNotNull(String property) { - hqlAndParametersBuilder.addNotNull(property); - return this; - } - - @Override - public TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> addTopiaIdEquals(String property, String topiaId) { - hqlAndParametersBuilder.addTopiaIdEquals(property, topiaId); - return this; - } - - @Override - public TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> addTopiaIdIn(String property, Iterable<String> topiaIds) { - hqlAndParametersBuilder.addTopiaIdIn(property, topiaIds); - return this; - } - - @Override - public TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> addTopiaIdNotEquals(String property, String topiaId) { - hqlAndParametersBuilder.addTopiaIdNotEquals(property, topiaId); - return this; - } - - @Override - public TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> addTopiaIdNotIn(String property, Iterable<String> topiaIds) { - hqlAndParametersBuilder.addTopiaIdNotIn(property, topiaIds); - return this; - } - - // shortcuts to next step - - @Override - public boolean exists() { - return getNextStep().exists(); - } - - @Override - public E findAnyOrNull() { - return getNextStep().findAnyOrNull(); - } - - @Override - public E findUniqueOrNull() { - return getNextStep().findUniqueOrNull(); - } - - @Override - public E findAny() { - return getNextStep().findAny(); - } - - @Override - public E findUnique() { - return getNextStep().findUnique(); - } - - @Override - public E findFirst() { - return getNextStep().findFirst(); - } - - @Override - public E findFirstOrNull() { - return getNextStep().findFirstOrNull(); - } - - @Override - public Optional<E> tryFindAny() { - return getNextStep().tryFindAny(); - } - - @Override - public Optional<E> tryFindFirst() { - return getNextStep().tryFindFirst(); - } - - @Override - public Optional<E> tryFindUnique() { - return getNextStep().tryFindUnique(); - } - - @Override - public List<E> findAll() { - return getNextStep().findAll(); - } - - @Override - public List<E> find(int startIndex, int endIndex) { - return getNextStep().find(startIndex, endIndex); - } - - @Override - public List<E> find(TopiaPagerBean pager) { - return getNextStep().find(pager); - } - - @Override - public Iterable<E> findAllLazy() { - return getNextStep().findAllLazy(); - } - - @Override - public Iterable<E> findAllLazy(int batchSize) { - return getNextStep().findAllLazy(batchSize); - } - - @Override - public long count() { - return getNextStep().count(); - } - - @Override - public List<String> findIds(int startIndex, int endIndex) { - return getNextStep().findIds(startIndex, endIndex); - } - - @Override - public List<String> findIds(TopiaPagerBean pager) { - return getNextStep().findIds(pager); - } - - @Override - public List<String> findAllIds() { - return getNextStep().findAllIds(); - } - - protected InnerTopiaQueryBuilderRunQueryStep<E> getNextStep() { - String hql = hqlAndParametersBuilder.getHql(); - Map<String, Object> hqlParameters = hqlAndParametersBuilder.getHqlParameters(); - InnerTopiaQueryBuilderRunQueryStep<E> nextStep = new InnerTopiaQueryBuilderRunQueryStep<E>(topiaDAO, hql, hqlParameters); - return nextStep; - } - - } - - public static class InnerTopiaQueryBuilderRunQueryStep<E extends TopiaEntity> implements TopiaQueryBuilderRunQueryStep<E> { - - protected final String hql; - - protected final Map<String, Object> hqlParameters; - - protected final AbstractTopiaDao<E> topiaDAO; - - protected InnerTopiaQueryBuilderRunQueryStep(AbstractTopiaDao<E> topiaDAO, String hql, Map<String, Object> hqlParameters) { - this.hql = hql; - this.hqlParameters = hqlParameters; - this.topiaDAO = topiaDAO; - } - - @Override - public boolean exists() { - return topiaDAO.exists(hql, hqlParameters); - } - - @Override - public long count() { - String hqlWithSelectClause = "select count(topiaId) " + hql; - return topiaDAO.count(hqlWithSelectClause, hqlParameters); - } - - @Override - public E findUnique() throws TopiaNoResultException, TopiaNonUniqueResultException { - return topiaDAO.findUnique(hql, hqlParameters); - } - - @Override - public E findUniqueOrNull() throws TopiaNonUniqueResultException { - return topiaDAO.findUniqueOrNull(hql, hqlParameters); - } - - @Override - public Optional<E> tryFindUnique() throws TopiaNonUniqueResultException { - return topiaDAO.tryFindUnique(hql, hqlParameters); - } - - @Override - public E findFirst() throws QueryMissingOrderException, TopiaNoResultException { - return topiaDAO.findFirst(hql, hqlParameters); - } - - @Override - public E findFirstOrNull() throws QueryMissingOrderException { - return topiaDAO.findFirstOrNull(hql, hqlParameters); - } - - @Override - public Optional<E> tryFindFirst() throws QueryMissingOrderException { - return topiaDAO.tryFindFirst(hql, hqlParameters); - } - - @Override - public E findAny() throws TopiaNoResultException { - return topiaDAO.findAny(hql, hqlParameters); - } - - @Override - public E findAnyOrNull() { - return topiaDAO.findAnyOrNull(hql, hqlParameters); - } - - @Override - public Optional<E> tryFindAny() { - return topiaDAO.tryFindAny(hql, hqlParameters); - } - - @Override - public List<E> findAll() { - return topiaDAO.findAll(hql, hqlParameters); - } - - @Override - public Iterable<E> findAllLazy() { - return topiaDAO.findAllLazy(hql, hqlParameters); - } - - @Override - public Iterable<E> findAllLazy(int batchSize) { - return topiaDAO.findAllLazy(hql, hqlParameters, batchSize); - } - - @Override - public List<E> find(int startIndex, int endIndex) { - return topiaDAO.find(hql, hqlParameters, startIndex, endIndex); - } - - @Override - public List<E> find(TopiaPagerBean pager) { - return topiaDAO.find(hql, hqlParameters, pager); - } - - @Override - public List<String> findAllIds() { - String hqlWithSelectClause = "select topiaId " + hql; - return topiaDAO.findAll(hqlWithSelectClause, hqlParameters); - } - - @Override - public List<String> findIds(int startIndex, int endIndex) { - String hqlWithSelectClause = "select topiaId " + hql; - return topiaDAO.find(hqlWithSelectClause, hqlParameters, startIndex, endIndex); - } - - @Override - public List<String> findIds(TopiaPagerBean pager) { - String hqlWithSelectClause = "select topiaId " + hql; - return topiaDAO.find(hqlWithSelectClause, hqlParameters, pager); - } - } - -} Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/DefaultTopiaIdFactory.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/DefaultTopiaIdFactory.java 2013-12-20 16:07:29 UTC (rev 2954) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/DefaultTopiaIdFactory.java 2013-12-20 16:19:35 UTC (rev 2955) @@ -1,72 +0,0 @@ -package org.nuiton.topia.persistence; - -/* - * #%L - * ToPIA :: Persistence - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2013 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -import org.apache.commons.lang3.StringUtils; - -import java.util.UUID; - -/** - * Default implementation of {@link TopiaIdFactory}. Generates an FQN followed - * by an random UUID. - * - * @author Brendan Le Ny <leny@codelutin.com> - * @since 3.0 - */ -public class DefaultTopiaIdFactory implements TopiaIdFactory { - - @Override - public <E extends TopiaEntity> String newTopiaId(Class<E> entityClass, TopiaEntity topiaEntity) { - if (!entityClass.isInterface()) { - throw new IllegalArgumentException( - "Only interface is permit to create id: " + entityClass); - } - String result = entityClass.getName() + getSeparator() + UUID.randomUUID().toString(); - return result; - } - - @Override - public <E extends TopiaEntity> Class<E> getClassName(String topiaId) { -// String className = Iterables.get(Splitter.on(getSeparator()).split(topiaId), 0); - String className = StringUtils.substringBefore(topiaId, getSeparator()); - try { - Class<E> entityClass = (Class<E>) Class.forName(className); - return entityClass; - } catch (ClassNotFoundException e) { - throw new TopiaException("can't find class for topiaId = '" + topiaId + "'", e); - } - } - - @Override - public String getSeparator() { - return "_"; - } - - @Override - public String getRandomPart(String topiaId) { - return StringUtils.substringBefore(topiaId, getSeparator()); - } - -} Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/HibernateProvider.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/HibernateProvider.java 2013-12-20 16:07:29 UTC (rev 2954) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/HibernateProvider.java 2013-12-20 16:19:35 UTC (rev 2955) @@ -1,260 +0,0 @@ -package org.nuiton.topia.persistence; - -/* - * #%L - * ToPIA :: Persistence - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2013 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -import java.io.File; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; - -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.hibernate.SessionFactory; -import org.hibernate.cfg.Configuration; -import org.hibernate.engine.spi.SessionFactoryImplementor; -import org.hibernate.event.service.spi.EventListenerRegistry; -import org.hibernate.event.spi.EventType; -import org.hibernate.service.ServiceRegistry; -import org.hibernate.service.ServiceRegistryBuilder; -import org.hibernate.service.jdbc.connections.spi.ConnectionProvider; -import org.hibernate.service.spi.ServiceRegistryImplementor; -import org.hibernate.service.spi.Stoppable; -import org.nuiton.topia.persistence.internal.TopiaHibernateSessionRegistry; -import org.nuiton.topia.persistence.support.TopiaServiceSupport; -import org.nuiton.topia.persistence.internal.support.TopiaHibernateEventListener; -import org.nuiton.topia.persistence.util.TopiaUtil; - -import com.google.common.collect.Lists; - -/** - * @author Arnaud Thimel <thimel@codelutin.com> - */ -public class HibernateProvider { - - private static final Log log = LogFactory.getLog(HibernateProvider.class); - - protected SessionFactory hibernateSessionFactory; - protected Configuration hibernateConfiguration; - - protected Map<String, String> configuration; - protected TopiaServiceSupport topiaServiceSupport; - protected TopiaHibernateSessionRegistry sessionRegistry; - - /** - * List of persistent classes - */ - protected List<Class<?>> persistentClasses = Lists.newArrayList(); - - public HibernateProvider(Map<String, String> configuration, - TopiaServiceSupport topiaServiceSupport, - TopiaHibernateSessionRegistry sessionRegistry) { - this.configuration = configuration; - this.topiaServiceSupport = topiaServiceSupport; - this.sessionRegistry = sessionRegistry; - } - - protected String getProperty(String key) { - return getProperty(key, null); - } - - protected String getProperty(String key, String defaultValue) { - String result = defaultValue; - if (configuration.containsKey(key)) { - result = configuration.get(key); - } - - return result; - } - - public List<Class<?>> getPersistentClasses() { - if (persistentClasses.isEmpty()) { - // Force configuration load - getHibernateConfiguration(); - } - return persistentClasses; - } - - public Configuration getHibernateConfiguration() { - if (hibernateConfiguration == null) { - hibernateConfiguration = new Configuration(); - - // ajout des repertoires contenant les mappings hibernate - String[] dirs = getProperty( - TopiaConfigurationConstants.CONFIG_PERSISTENCE_DIRECTORIES, "").split(","); - for (String dir : dirs) { - dir = dir.trim(); - if (StringUtils.isNotEmpty(dir)) { - if (log.isDebugEnabled()) { - log.debug("Load persistence from dir : " + dir); - } - hibernateConfiguration.addDirectory(new File(dir)); - } - } - - // ajout des classes dites persistentes - Set<Class<?>> hibernatePersistanceClasses = new HashSet<Class<?>>(); - for (TopiaService service : topiaServiceSupport.getServices().values()) { - Class<?>[] classes = service.getPersistenceClasses(); - - // certains service n'ont pas de classe persistantes - if (classes != null) { - // sletellier 20110411 : http://www.nuiton.org/issues/show/1454 - hibernatePersistanceClasses.addAll(Arrays.asList(classes)); -// for (Class<?> clazz : classes) { -// hibernateConfiguration.addClass(clazz); -// } - } - } - - String listPersistenceClasses = getProperty( - TopiaConfigurationConstants.CONFIG_PERSISTENCE_CLASSES, ""); - - String[] classes = listPersistenceClasses.split(","); - for (String classname : classes) { - classname = classname.trim(); - if (StringUtils.isNotEmpty(classname)) { - if (log.isDebugEnabled()) { - log.debug("Load persistent class : " + classname); - } - - // XXX echatellier 20111007 ce qui est dommage ici, c'est - // la definition de cette classe ne sert a rien (apart security) - // car pour hibernate hibernateConfiguration.addClass(persistanceClass) - // il ne se sert pas de la classe en fait et fait seulement - // un classname.replace( '.', '/' ) + ".hbm.xml"; - // pour obtenir le mapping et la reinstancier ensuite - - Class<?> clazz; - try { - clazz = Class.forName(classname); - } catch (ClassNotFoundException eee) { - if (log.isDebugEnabled()) { - log.debug("Class " + classname + " not found"); - } - throw new TopiaNotFoundException( - String.format("Persistence class %1$s not found", - classname)); - } - persistentClasses.add(clazz); - - // sletellier 20110411 : http://www.nuiton.org/issues/show/1454 -// hibernateConfiguration.addClass(clazz); - hibernatePersistanceClasses.add(clazz); - } - } - - // sletellier 20110411 : http://www.nuiton.org/issues/show/1454 - // Add persistance classes in hibernate config - for (Class<?> persistanceClass : hibernatePersistanceClasses) { - hibernateConfiguration.addClass(persistanceClass); - } - - Properties prop = new Properties(); - prop.putAll(hibernateConfiguration.getProperties()); - prop.putAll(configuration); - - // Strange behavior, all properties are already loaded from - // constructor. Difficult to use this behavior, need to have - // TOPIA_PERSISTENCE_PROPERTIES_FILE in config. - Properties propertiesFromClasspath = - TopiaUtil.getProperties(getProperty(TopiaConfigurationConstants.CONFIG_PERSISTENCE_PROPERTIES_FILE)); - - if (!propertiesFromClasspath.isEmpty()) { - if (log.isDebugEnabled()) { - log.debug("Load properties from file : " + - propertiesFromClasspath); - } - prop.putAll(propertiesFromClasspath); - } - - hibernateConfiguration.setProperties(prop); - - // tchemit 2011-05-26 When using hibernate > 3.3, need to make sure all mappings are loaded (the one from directory files are not still done). - hibernateConfiguration.buildMappings(); - } - return hibernateConfiguration; - } - - public void close() { - if (hibernateSessionFactory != null) { - hibernateSessionFactory.close(); - // close connection provider if possible (http://nuiton.org/issues/2757) - SessionFactoryImplementor sessionFactoryImplementor = (SessionFactoryImplementor) hibernateSessionFactory; - ServiceRegistryImplementor serviceRegistry = sessionFactoryImplementor.getServiceRegistry(); - ConnectionProvider service = serviceRegistry.getService(ConnectionProvider.class); - - // TODO AThimel 18/12/13 Check this code compatibility with Hibernate 4.3.0.Final -// ConnectionProvider service = hibernateSessionFactory.getSessionFactoryOptions().getServiceRegistry().getService(ConnectionProvider.class); - if (service instanceof Stoppable) { - Stoppable stoppable = (Stoppable) service; - stoppable.stop(); - } - } - } - - public SessionFactory getSessionFactory() { - - if (hibernateSessionFactory == null) { - - // init service registry - Properties properties = getHibernateConfiguration().getProperties(); - ServiceRegistryBuilder builder = new ServiceRegistryBuilder().applySettings(properties); - ServiceRegistry serviceRegistry = builder.buildServiceRegistry(); - - hibernateSessionFactory = getHibernateConfiguration().buildSessionFactory(serviceRegistry); - - // TODO AThimel 18/12/13 Check this code compatibility with Hibernate 4.3.0.Final -// StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder(); -// Properties properties = getHibernateConfiguration().getProperties(); -// StandardServiceRegistry standardServiceRegistry = builder.applySettings(properties).build(); -// -// hibernateSessionFactory = getHibernateConfiguration().buildSessionFactory(standardServiceRegistry); - - // we can't reuse original serviceRegistry instance - // we must call getServiceRegistry on factory to get a working one - ServiceRegistry serviceRegistryInit = ((SessionFactoryImplementor) hibernateSessionFactory).getServiceRegistry(); - EventListenerRegistry eventListenerRegistry = serviceRegistryInit.getService(EventListenerRegistry.class); - - TopiaHibernateEventListener listener = new TopiaHibernateEventListener(sessionRegistry); - eventListenerRegistry.appendListeners(EventType.PRE_INSERT, listener); - eventListenerRegistry.appendListeners(EventType.PRE_LOAD, listener); - eventListenerRegistry.appendListeners(EventType.PRE_UPDATE, listener); - eventListenerRegistry.appendListeners(EventType.PRE_DELETE, listener); - eventListenerRegistry.appendListeners(EventType.POST_INSERT, listener); - eventListenerRegistry.appendListeners(EventType.POST_LOAD, listener); - eventListenerRegistry.appendListeners(EventType.POST_UPDATE, listener); - eventListenerRegistry.appendListeners(EventType.POST_DELETE, listener); - - // following listeners must be called before hibernate - eventListenerRegistry.prependListeners(EventType.SAVE_UPDATE, listener); - } - return hibernateSessionFactory; - } - -} Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/LegacyTopiaIdFactory.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/LegacyTopiaIdFactory.java 2013-12-20 16:07:29 UTC (rev 2954) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/LegacyTopiaIdFactory.java 2013-12-20 16:19:35 UTC (rev 2955) @@ -1,83 +0,0 @@ -package org.nuiton.topia.persistence; - -/* - * #%L - * ToPIA :: Persistence - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2013 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -import org.apache.commons.lang3.StringUtils; - -/** - * Implements {@link TopiaIdFactory} with Topia 2.x and before ids. - * Suitable if you already have a database and your application need - * to generate ids like the old ones. - * - * @since 3.0 - */ -public class LegacyTopiaIdFactory implements TopiaIdFactory { - - @Override - public <E extends TopiaEntity> String newTopiaId(Class<E> entityClass, TopiaEntity topiaEntity) { - if (!entityClass.isInterface()) { - throw new IllegalArgumentException( - "Only interface is permit to create id: " + entityClass); - } - double random = Math.random(); - while (Double.toString(random).contains("E-")) { - random = Math.random(); - } - return entityClass.getName() + getSeparator() + System.currentTimeMillis() + '#' + random; - } - - /** - * Extrait la classe du topiaId. - * - * @param topiaId - * @return class - * @throws TopiaNotFoundException - */ - @Override - public <E extends TopiaEntity> Class<E> getClassName(String topiaId) { - String className = StringUtils.substringBefore(topiaId, getSeparator()); -// int i = topiaId.indexOf('#'); -// if (i > 0) { -// className = topiaId.substring(0, i); -// } - try { - Class result = Class.forName(className); - return result; - } catch (ClassNotFoundException eee) { - throw new TopiaNotFoundException("Can't find class for " + topiaId, - eee); - } - } - - @Override - public String getSeparator() { - return "#"; - } - - @Override - public String getRandomPart(String topiaId) { - return StringUtils.substringBefore(topiaId, getSeparator()); - } -} Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/SearchFields.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/SearchFields.java 2013-12-20 16:07:29 UTC (rev 2954) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/SearchFields.java 2013-12-20 16:19:35 UTC (rev 2955) @@ -1,77 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -/* * -* SearchFields.java -* -* Created: 7 juin 2006 -* -* @author Arnaud Thimel <thimel@codelutin.com> -* @version $Revision$ -* -* Mise a jour: $Date$ -* par : $Author$ -*/ - -package org.nuiton.topia.persistence; - -import static java.lang.annotation.RetentionPolicy.RUNTIME; -import static java.lang.annotation.ElementType.TYPE; - -import java.lang.annotation.Retention; -import java.lang.annotation.Target; - -/** - * - * TODO-fdesbois-20100508 : javadoc : where is it used for ? which service use it ? - * - * Ces annotations permettent de savoir quels sont les champs sur lesquels - * la recherche pourra s'effectuer. - */ -@Retention(RUNTIME) -@Target(TYPE) -public @interface SearchFields { - - /** - * @return la liste des champs textes - */ - String[] txtFields() default {}; - - /** - * @return la liste des champs numeriques - */ - String[] numFields() default {}; - - /** - * @return la liste des champs booleens - */ - String[] boolFields() default {}; - - /** - * @return la liste des champs date - */ - String[] dateFields() default {}; - -} //SearchFields Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaEntity.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaEntity.java 2013-12-20 16:07:29 UTC (rev 2954) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaEntity.java 2013-12-20 16:19:35 UTC (rev 2955) @@ -57,7 +57,6 @@ * @author fdesbois <fdesbois@codelutin.com> * @version $Id$ */ -@SearchFields public interface TopiaEntity extends Serializable { String PROPERTY_TOPIA_ID = "topiaId"; Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaEntityAbstract.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaEntityAbstract.java 2013-12-20 16:07:29 UTC (rev 2954) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaEntityAbstract.java 2013-12-20 16:19:35 UTC (rev 2955) @@ -25,6 +25,7 @@ package org.nuiton.topia.persistence; +import org.nuiton.topia.persistence.internal.AbstractTopiaDao; import org.nuiton.topia.persistence.internal.support.TopiaFiresSupport; import java.beans.PropertyChangeListener; Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/internal/AbstractTopiaApplicationContext.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/internal/AbstractTopiaApplicationContext.java 2013-12-20 16:07:29 UTC (rev 2954) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/internal/AbstractTopiaApplicationContext.java 2013-12-20 16:19:35 UTC (rev 2955) @@ -51,8 +51,6 @@ import org.nuiton.topia.persistence.support.TopiaListenableSupport; import org.nuiton.topia.persistence.support.TopiaServiceSupport; import org.nuiton.topia.persistence.util.TopiaUtil; -import org.nuiton.topia.persistence.DefaultTopiaIdFactory; -import org.nuiton.topia.persistence.HibernateProvider; import org.nuiton.topia.persistence.TopiaEntity; import org.nuiton.topia.persistence.TopiaIdFactory; Copied: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/internal/AbstractTopiaDao.java (from rev 2954, trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/AbstractTopiaDao.java) =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/internal/AbstractTopiaDao.java (rev 0) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/internal/AbstractTopiaDao.java 2013-12-20 16:19:35 UTC (rev 2955) @@ -0,0 +1,1035 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2010 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ + +/* * + * TopiaDAOAbstract.java + * + * Created: 31 déc. 2005 13:10:34 + * + * @author poussin <poussin@codelutin.com> + * @version $Revision$ + * + * Last update: $Date$ + * by : $Author$ + */ + +package org.nuiton.topia.persistence.internal; + +import com.google.common.base.Optional; +import com.google.common.base.Preconditions; +import com.google.common.collect.Iterables; +import com.google.common.collect.Iterators; +import org.apache.commons.beanutils.PropertyUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.topia.persistence.HqlAndParametersBuilder; +import org.nuiton.topia.persistence.QueryMissingOrderException; +import org.nuiton.topia.persistence.TopiaDao; +import org.nuiton.topia.persistence.TopiaDaoSupplier; +import org.nuiton.topia.persistence.TopiaEntity; +import org.nuiton.topia.persistence.TopiaEntityContextable; +import org.nuiton.topia.persistence.TopiaEntityEnum; +import org.nuiton.topia.persistence.TopiaException; +import org.nuiton.topia.persistence.TopiaIdFactory; +import org.nuiton.topia.persistence.TopiaNoResultException; +import org.nuiton.topia.persistence.TopiaNonUniqueResultException; +import org.nuiton.topia.persistence.TopiaPersistenceContext; +import org.nuiton.topia.persistence.TopiaQueryBuilderAddCriteriaOrRunQueryStep; +import org.nuiton.topia.persistence.TopiaQueryBuilderRunQueryStep; +import org.nuiton.topia.persistence.support.TopiaJpaSupport; +import org.nuiton.topia.persistence.support.TopiaListenableSupport; +import org.nuiton.topia.persistence.support.TopiaSqlSupport; +import org.nuiton.topia.persistence.event.TopiaEntityListener; +import org.nuiton.topia.persistence.event.TopiaEntityVetoable; +import org.nuiton.topia.persistence.internal.support.TopiaFiresSupport; +import org.nuiton.topia.persistence.util.TopiaUtil; +import org.nuiton.topia.persistence.pager.TopiaPagerBean; +import org.nuiton.util.PagerBeanUtil; + +import java.lang.reflect.InvocationTargetException; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Set; + +/** + * This class has the common methods usable for each Dao managed by Topia. It is not JPA implementation dependent, it + * only relies on {@link TopiaJpaSupport}. + * <p/> + * This class is directly extended by the GeneratedXyzTopiaDao which groups all the Xyz specific methods. + * <p/> + * Instances are created bt the model's specific {@link TopiaPersistenceContext}, which implements the + * {@link TopiaDaoSupplier} contract. + * + * @param <E> the managed entity type + * @author bpoussin <poussin@codelutin.com> + * @author Arnaud Thimel <thimel@codelutin.com> + * @author Tony CHEMIT <chemit@codelutin.com> + */ +public abstract class AbstractTopiaDao<E extends TopiaEntity> implements TopiaDao<E> { + + private static Log log = LogFactory.getLog(AbstractTopiaDao.class); + + /** + * Default batch size used to iterate on data. + * + * @since 2.6.14 + */ + protected int batchSize = 1000; + + protected TopiaJpaSupport topiaJpaSupport; + + protected TopiaSqlSupport topiaSqlSupport; + + protected TopiaListenableSupport topiaListenableSupport; + + protected TopiaIdFactory topiaIdFactory; + + protected TopiaFiresSupport topiaFiresSupport; + + protected TopiaDaoSupplier topiaDaoSupplier; + + public abstract TopiaEntityEnum getTopiaEntityEnum(); + + public abstract Class<E> getEntityClass(); + + /** + * When AbstractTopiaContext create the TopiaDAOHibernate, it must call this + * method just after. + */ + public void init( + TopiaJpaSupport topiaJpaSupport, + TopiaSqlSupport topiaSqlSupport, + TopiaListenableSupport topiaListenableSupport, + TopiaIdFactory topiaIdFactory, + TopiaFiresSupport topiaFiresSupport, + TopiaDaoSupplier topiaDaoSupplier) { + if (log.isDebugEnabled()) { + log.debug("init dao for " + getEntityClass()); + } + this.topiaJpaSupport = topiaJpaSupport; + this.topiaSqlSupport = topiaSqlSupport; + this.topiaListenableSupport = topiaListenableSupport; + this.topiaIdFactory = topiaIdFactory; + this.topiaFiresSupport = topiaFiresSupport; + this.topiaDaoSupplier = topiaDaoSupplier; + } + + public TopiaFiresSupport getTopiaFiresSupport() { + return topiaFiresSupport; + } + + @Override + public int getBatchSize() { + return batchSize; + } + + @Override + public void setBatchSize(int batchSize) { + this.batchSize = batchSize; + } + + protected String newFromClause() { + return newFromClause(null); + } + + protected String newFromClause(String alias) { + String hql = "from " + getTopiaEntityEnum().getImplementationFQN(); + if (StringUtils.isNotBlank(alias)) { + hql += " " + alias; + } + return hql; + } + + @Override + public E newInstance() { + if (log.isTraceEnabled()) { + log.trace("entityClass = " + getEntityClass()); + } + Class<E> implementation = (Class<E>) + getTopiaEntityEnum().getImplementation(); + try { + E newInstance = implementation.newInstance(); + return newInstance; + } catch (InstantiationException e) { + throw new TopiaException( + "Impossible de trouver ou d'instancier la classe " + + implementation); + } catch (IllegalAccessException e) { + throw new TopiaException( + "Impossible de trouver ou d'instancier la classe " + + implementation); + } + } + + @Override + public TopiaPagerBean newPager(int pageSize) { + TopiaPagerBean pager = newPager(newFromClause(), null, pageSize); + return pager; + } + + @Override + public TopiaPagerBean newPager(String hql, Map<String, Object> params, int pageSize) { + TopiaPagerBean pager = new TopiaPagerBean(); + + if (hqlContainsOrderBy(hql)) { + + // must remove the order by clause, otherwise some sql queries won't work. + hql = hql.substring(0, hql.toLowerCase().indexOf("order by")); + } + long count = count("SELECT COUNT(*) " + hql, params); + pager.setRecords(count); + pager.setPageSize(pageSize); + PagerBeanUtil.computeRecordIndexesAndPagesNumber(pager); + return pager; + } + + @Override + public void addTopiaEntityListener(TopiaEntityListener listener) { + topiaListenableSupport.addTopiaEntityListener(getEntityClass(), listener); + } + + @Override + public void addTopiaEntityVetoable(TopiaEntityVetoable vetoable) { + topiaListenableSupport.addTopiaEntityVetoable(getEntityClass(), vetoable); + } + + @Override + public void removeTopiaEntityListener(TopiaEntityListener listener) { + topiaListenableSupport.removeTopiaEntityListener(getEntityClass(), listener); + } + + @Override + public void removeTopiaEntityVetoable(TopiaEntityVetoable vetoable) { + topiaListenableSupport.removeTopiaEntityVetoable(getEntityClass(), vetoable); + } + + @Override + public E create(E entity) { + // first set topiaId + if (StringUtils.isBlank(entity.getTopiaId())) { + + // only set id if not already on + String topiaId = topiaIdFactory.newTopiaId(getEntityClass(), entity); + entity.setTopiaId(topiaId); + } + + if (entity instanceof TopiaEntityContextable) { + TopiaEntityContextable contextable = (TopiaEntityContextable) entity; + contextable.setTopiaDAOSupplier(this.topiaDaoSupplier); + } + + // save entity + topiaJpaSupport.save(entity); + topiaFiresSupport.warnOnCreateEntity(entity); + return entity; + } + + @Override + public E create(String propertyName, Object propertyValue, Object... otherPropertyNamesAndValues) { + Map<String, Object> properties = + TopiaUtil.convertPropertiesArrayToMap(propertyName, propertyValue, otherPropertyNamesAndValues); + E result = create(properties); + return result; + } + + @Override + public E create(Map<String, Object> properties) { + + E result = newInstance(); + + try { + for (Map.Entry<String, Object> e : properties.entrySet()) { + String propertyName = e.getKey(); + Object value = e.getValue(); + PropertyUtils.setProperty(result, propertyName, value); + } + } catch (IllegalAccessException eee) { + throw new IllegalArgumentException( + "Can't put properties on new Object", eee); + } catch (InvocationTargetException eee) { + throw new IllegalArgumentException( + "Can't put properties on new Object", eee); + } catch (NoSuchMethodException eee) { + throw new IllegalArgumentException( + "Can't put properties on new Object", eee); + } + + create(result); + + return result; + } + + @Override + public E create() { + E result = newInstance(); + create(result); + return result; + } + + @Override + public Iterable<E> createAll(Iterable<E> entities) { + for (E entity : entities) { + create(entity); + } + return entities; + } + + @Override + public E update(E entity) { + topiaJpaSupport.saveOrUpdate(entity); + topiaFiresSupport.warnOnUpdateEntity(entity); + return entity; + } + + @Override + public Iterable<E> updateAll(Iterable<E> entities) { + for (E entity : entities) { + update(entity); + } + return entities; + } + + @Override + public void delete(E entity) { + topiaJpaSupport.delete(entity); + entity.notifyDeleted(); + topiaFiresSupport.warnOnDeleteEntity(entity); + } + + @Override + public void deleteAll(Iterable<E> entities) { + for (E entity : entities) { + delete(entity); + } + } + + protected HqlAndParametersBuilder<E> newHqlAndParametersBuilder() { + HqlAndParametersBuilder<E> result = new HqlAndParametersBuilder<E>(getEntityClass()); + return result; + } + + protected HqlAndParametersBuilder<E> getHqlForProperties(String propertyName, + Object propertyValue, + Object... otherPropertyNamesAndValues) { + Map<String, Object> properties = + TopiaUtil.convertPropertiesArrayToMap(propertyName, propertyValue, otherPropertyNamesAndValues); + HqlAndParametersBuilder<E> result = getHqlForProperties(properties); + return result; + } + + protected HqlAndParametersBuilder<E> getHqlForNoConstraint() { + Map<String, Object> properties = Collections.emptyMap(); + HqlAndParametersBuilder<E> result = getHqlForProperties(properties); + return result; + } + + protected HqlAndParametersBuilder<E> getHqlForProperties(Map<String, Object> properties) { + HqlAndParametersBuilder<E> result = newHqlAndParametersBuilder(); + for (Map.Entry<String, Object> property : properties.entrySet()) { + result.addEquals(property.getKey(), property.getValue()); + } + return result; + } + + protected InnerTopiaQueryBuilderRunQueryStep<E> forHql(String hql) { + Map<String, Object> properties = Collections.emptyMap(); + InnerTopiaQueryBuilderRunQueryStep<E> result = forHql(hql, properties); + return result; + } + + protected InnerTopiaQueryBuilderRunQueryStep<E> forHql(String hql, Map<String, Object> hqlParameters) { + InnerTopiaQueryBuilderRunQueryStep<E> result = new InnerTopiaQueryBuilderRunQueryStep<E>(this, hql, hqlParameters); + return result; + } + + protected InnerTopiaQueryBuilderRunQueryStep<E> forHql(String hql, String parameterName, + Object parameterValue, + Object... otherParameterNamesAndValues) { + Map<String, Object> hqlParameters = + TopiaUtil.convertPropertiesArrayToMap(parameterName, parameterValue, otherParameterNamesAndValues); + InnerTopiaQueryBuilderRunQueryStep<E> result = forHql(hql, hqlParameters); + return result; + } + + @Override + public InnerTopiaQueryBuilderAddCriteriaOrRunQueryStep<E> forProperties(Map<String, Object> properties) { + HqlAndParametersBuilder<E> hqlAndParametersBuilder = getHqlForProperties(properties); + InnerTopiaQueryBuilderAddCriteriaOrRunQueryStep<E> result = new InnerTopiaQueryBuilderAddCriteriaOrRunQueryStep<E>(this, hqlAndParametersBuilder); + return result; + } + + @Override + public InnerTopiaQueryBuilderAddCriteriaOrRunQueryStep<E> forProperties(String propertyName, + Object propertyValue, + Object... otherPropertyNamesAndValues) { + HqlAndParametersBuilder<E> hqlAndParametersBuilder = getHqlForProperties(propertyName, propertyValue, otherPropertyNamesAndValues); + InnerTopiaQueryBuilderAddCriteriaOrRunQueryStep<E> result = new InnerTopiaQueryBuilderAddCriteriaOrRunQueryStep<E>(this, hqlAndParametersBuilder); + return result; + } + + @Override + public InnerTopiaQueryBuilderAddCriteriaOrRunQueryStep<E> newQueryBuilder() { + HqlAndParametersBuilder<E> hqlAndParametersBuilder = newHqlAndParametersBuilder(); + InnerTopiaQueryBuilderAddCriteriaOrRunQueryStep<E> result = new InnerTopiaQueryBuilderAddCriteriaOrRunQueryStep<E>(this, hqlAndParametersBuilder); + return result; + } + + @Override + public TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> forContains(String propertyName, Object propertyValue) { + TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> result = newQueryBuilder().addContains(propertyName, propertyValue); + return result; + } + + @Override + public TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> forEquals(String propertyName, Object propertyValue) { + TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> result = newQueryBuilder().addEquals(propertyName, propertyValue); + return result; + } + + @Override + public TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> forIn(String propertyName, Iterable<?> propertyValues) { + TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> result = newQueryBuilder().addIn(propertyName, propertyValues); + return result; + } + + protected boolean exists(String hql, Map<String, Object> hqlParameters) { + List<E> entities = topiaJpaSupport.find(hql, 0, 0, hqlParameters); + boolean result = !entities.isEmpty(); + return result; + } + + protected long count(String hql, Map<String, Object> hqlParameters) { + Preconditions.checkArgument(hql.toLowerCase().trim().startsWith("select count(")); + Long result = findUnique(hql, hqlParameters); + return result; + } + + protected <K> K findUnique(String hql, Map<String, Object> hqlParameters) throws TopiaNoResultException, TopiaNonUniqueResultException { + K result = findUniqueOrNull(hql, hqlParameters); + if (result == null) { + throw new TopiaNoResultException(hql, hqlParameters); + } + return result; + } + + protected <K> Optional<K> tryFindUnique(String hql, Map<String, Object> hqlParameters) throws TopiaNonUniqueResultException { + K uniqueOrNull = findUniqueOrNull(hql, hqlParameters); + Optional<K> result = Optional.fromNullable(uniqueOrNull); + return result; + } + + protected <K> K findUniqueOrNull(String hql, Map<String, Object> hqlParameters) throws TopiaNonUniqueResultException { + List<K> results = find(hql, hqlParameters, 0, 1); + // If there is more than 1 result, throw an exception + if (results.size() > 1) { + throw new TopiaNonUniqueResultException(hql, hqlParameters); + } + // otherwise return the first one, or null + K result = Iterables.getOnlyElement(results, null); + return result; + } + + protected <K> K findFirst(String hql, Map<String, Object> hqlParameters) throws QueryMissingOrderException { + K result = findFirstOrNull(hql, hqlParameters); + if (result == null) { + throw new TopiaNoResultException(hql, hqlParameters); + } + return result; + } + + protected <K> Optional<K> tryFindFirst(String hql, Map<String, Object> hqlParameters) throws QueryMissingOrderException { + K firstOrNull = findFirstOrNull(hql, hqlParameters); + Optional<K> result = Optional.fromNullable(firstOrNull); + return result; + } + + protected <K> K findFirstOrNull(String hql, Map<String, Object> hqlParameters) throws QueryMissingOrderException { + if (!hqlContainsOrderBy(hql)) { + throw new QueryMissingOrderException(hql, hqlParameters); + } + K result = findAnyOrNull(hql, hqlParameters); + return result; + } + + protected <K> K findAny(String hql, Map<String, Object> hqlParameters) throws TopiaNoResultException { + K result = findAnyOrNull(hql, hqlParameters); + if (result == null) { + throw new TopiaNoResultException(hql, hqlParameters); + } + return result; + } + + protected <K> Optional<K> tryFindAny(String hql, Map<String, Object> hqlParameters) { + K anyOrNull = findAnyOrNull(hql, hqlParameters); + Optional<K> result = Optional.fromNullable(anyOrNull); + return result; + } + + protected <K> K findAnyOrNull(String hql, Map<String, Object> hqlParameters) { + Preconditions.checkNotNull(hql); + Preconditions.checkNotNull(hqlParameters); + List<K> results = find(hql, hqlParameters, 0, 0); + K result = Iterables.getOnlyElement(results, null); + return result; + } + + protected <K> List<K> findAll(String hql, Map<String, Object> hqlParameters) { + Preconditions.checkNotNull(hql); + Preconditions.checkNotNull(hqlParameters); + List<K> result = topiaJpaSupport.findAll(hql, hqlParameters); + return result; + } + + protected <K> List<K> find(String hql, Map<String, Object> hqlParameters, int startIndex, int endIndex) { + Preconditions.checkNotNull(hql); + Preconditions.checkNotNull(hqlParameters); + List<K> result = topiaJpaSupport.find(hql, startIndex, endIndex, hqlParameters); + return result; + } + + public <K> List<K> find(String hql, Map<String, Object> hqlParameters, TopiaPagerBean pager) { + Preconditions.checkNotNull(hql); + Preconditions.checkNotNull(hqlParameters); + Preconditions.checkNotNull(pager); + + if (StringUtils.isNotBlank(pager.getSortColumn())) { + + // can't have a order by clause in hql query + Preconditions.checkState( + !hqlContainsOrderBy(hql), + "An 'order by' clause was already found in hql, can't use the order of the pager"); + + hql += " order by " + pager.getSortColumn(); + if (!pager.isSortAscendant()) { + hql += " desc"; + } + } + + List<K> result = topiaJpaSupport.find( + hql, + (int) pager.getRecordStartIndex(), + (int) pager.getRecordEndIndex() - 1, + hqlParameters); + + return result; + } + + protected <K> Iterable<K> findAllLazy(String hql, Map<String, Object> hqlParameters) { + + Iterable<K> result= findAllLazy(hql, hqlParameters, batchSize); + return result; + } + + protected <K> Iterable<K> findAllLazy(String hql, Map<String, Object> hqlParameters, int batchSize) { + + Preconditions.checkNotNull(hql); + Preconditions.checkNotNull(hqlParameters); + + final Iterator<K> iterator = new FindAllIterator<E, K>(this, + batchSize, + hql, + hqlParameters); + + Iterable<K> result = new Iterable<K>() { + @Override + public Iterator<K> iterator() { + return iterator; + } + }; + + return result; + } + + @Override + public TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> forTopiaIdEquals(String topiaId) { + Preconditions.checkArgument(StringUtils.isNotBlank(topiaId), "given topiaId is blank"); + TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> result = forEquals(TopiaEntity.PROPERTY_TOPIA_ID, topiaId); + return result; + } + + @Override + public TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> forTopiaIdIn(Iterable<String> topiaIds) { + Preconditions.checkNotNull(topiaIds, "given topiaIds is null"); + TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> result = forIn(TopiaEntity.PROPERTY_TOPIA_ID, (Iterable) topiaIds); + return result; + } + + @Override + public E findByTopiaId(String topiaId) throws TopiaNoResultException { + // AThimel 30/10/13 Not using findUnique to avoid querying several elements (cf. findUnique implementation) + E result = forTopiaIdEquals(topiaId).findAny(); + return result; + } + + @Override + public Optional<E> tryFindByTopiaId(String topiaId) { + Optional<E> result = forTopiaIdEquals(topiaId).tryFindAny(); + return result; + } + + @Override + public List<String> findAllIds() { + List<String> result = newQueryBuilder().findAllIds(); + return result; + } + + @Override + public List<E> findAll() { + List<E> result = newQueryBuilder().findAll(); + return result; + } + + @Override + public Iterable<E> findAllLazy() { + String hql = "from " + getTopiaEntityEnum().getImplementationFQN() + " order by id"; + Map<String, Object> hqlParameters = Collections.emptyMap(); + Iterable<E> result = findAllLazy(hql, hqlParameters); + return result; + } + + @Override + public Iterator<E> iterator() { + Iterator<E> result = findAllLazy().iterator(); + return result; + } + + @Override + public long count() { + long result = newQueryBuilder().count(); + return result; + } + + protected boolean hqlContainsOrderBy(String hql) { + return hql.toLowerCase().contains("order by"); + } + + protected boolean hqlContainsCount(String hql) { + return hql.toLowerCase().contains("count("); + } + +// /** +// * package locale method because this is hibernate specific method and +// * we don't want expose it. +// * +// * @return the meta-data of the entity +// * @throws org.nuiton.topia.persistence.TopiaException if any pb +// */ +// protected ClassMetadata getClassMetadata() { +// ClassMetadata meta = topiaHibernateSupport.getHibernateFactory().getClassMetadata(getEntityClass()); +// if (meta == null) { +// String implementationFQN = getTopiaEntityEnum().getImplementationFQN(); +// meta = topiaHibernateSupport.getHibernateFactory().getClassMetadata(implementationFQN); +// } +// return meta; +// } + + public static class FindAllIterator<E extends TopiaEntity, K> implements Iterator<K> { + + protected Iterator<K> data; + + protected final AbstractTopiaDao<E> dao; + + protected final String hql; + + protected final Map<String, Object> params; + + protected final TopiaPagerBean pager; + + public FindAllIterator(AbstractTopiaDao<E> dao, + int batchSize, + String hql, + Map<String, Object> params) { + + if (!dao.hqlContainsOrderBy(hql)) { + throw new QueryMissingOrderException(hql, params); + } + + this.dao = dao; + this.hql = hql; + this.params = params; + pager = dao.newPager(hql, params, batchSize); + + // empty iterator (will be changed at first next call) + data = Iterators.emptyIterator(); + } + + + public boolean hasNext() { + boolean result = data.hasNext() || // no more data + pager.getPageIndex() < pager.getPagesNumber(); + return result; + } + + + public K next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } + + if (!data.hasNext()) { + + // must load iterator + + // increments page index + pager.setPageIndex(pager.getPageIndex() + 1); + PagerBeanUtil.computeRecordIndexesAndPagesNumber(pager); + + // load new window of data + List<K> values = dao.find(hql, params, pager); + data = values.iterator(); + + } + + K next = data.next(); + return next; + } + + + public void remove() { + throw new UnsupportedOperationException( + "This iterator does not support remove operation."); + } + } + + public static class InnerTopiaQueryBuilderAddCriteriaOrRunQueryStep<E extends TopiaEntity> implements TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> { + + protected AbstractTopiaDao<E> topiaDAO; + + protected HqlAndParametersBuilder<E> hqlAndParametersBuilder; + + protected InnerTopiaQueryBuilderAddCriteriaOrRunQueryStep(AbstractTopiaDao<E> topiaDAO, HqlAndParametersBuilder<E> hqlAndParametersBuilder) { + this.topiaDAO = topiaDAO; + this.hqlAndParametersBuilder = hqlAndParametersBuilder; + } + + @Override + public InnerTopiaQueryBuilderRunQueryStep<E> setOrderByArguments(Set<String> orderByArguments) { + hqlAndParametersBuilder.setOrderByArguments(orderByArguments); + return getNextStep(); + } + + @Override + public InnerTopiaQueryBuilderRunQueryStep<E> setOrderByArguments(String... orderByArguments) { + hqlAndParametersBuilder.setOrderByArguments(orderByArguments); + return getNextStep(); + } + + @Override + public TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> addEquals(String property, Object value) { + hqlAndParametersBuilder.addEquals(property, value); + return this; + } + + @Override + public TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> addNotEquals(String property, Object value) { + hqlAndParametersBuilder.addNotEquals(property, value); + return this; + } + + @Override + public TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> addIn(String property, Iterable<?> values) { + hqlAndParametersBuilder.addIn(property, values); + return this; + } + + @Override + public TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> addNotIn(String property, Iterable<?> values) { + hqlAndParametersBuilder.addNotIn(property, values); + return this; + } + + @Override + public TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> addContains(String property, Object value) { + hqlAndParametersBuilder.addContains(property, value); + return this; + } + + @Override + public TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> addNotContains(String property, Object value) { + hqlAndParametersBuilder.addNotContains(property, value); + return this; + } + + @Override + public TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> addNull(String property) { + hqlAndParametersBuilder.addNull(property); + return this; + } + + @Override + public TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> addNotNull(String property) { + hqlAndParametersBuilder.addNotNull(property); + return this; + } + + @Override + public TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> addTopiaIdEquals(String property, String topiaId) { + hqlAndParametersBuilder.addTopiaIdEquals(property, topiaId); + return this; + } + + @Override + public TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> addTopiaIdIn(String property, Iterable<String> topiaIds) { + hqlAndParametersBuilder.addTopiaIdIn(property, topiaIds); + return this; + } + + @Override + public TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> addTopiaIdNotEquals(String property, String topiaId) { + hqlAndParametersBuilder.addTopiaIdNotEquals(property, topiaId); + return this; + } + + @Override + public TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> addTopiaIdNotIn(String property, Iterable<String> topiaIds) { + hqlAndParametersBuilder.addTopiaIdNotIn(property, topiaIds); + return this; + } + + // shortcuts to next step + + @Override + public boolean exists() { + return getNextStep().exists(); + } + + @Override + public E findAnyOrNull() { + return getNextStep().findAnyOrNull(); + } + + @Override + public E findUniqueOrNull() { + return getNextStep().findUniqueOrNull(); + } + + @Override + public E findAny() { + return getNextStep().findAny(); + } + + @Override + public E findUnique() { + return getNextStep().findUnique(); + } + + @Override + public E findFirst() { + return getNextStep().findFirst(); + } + + @Override + public E findFirstOrNull() { + return getNextStep().findFirstOrNull(); + } + + @Override + public Optional<E> tryFindAny() { + return getNextStep().tryFindAny(); + } + + @Override + public Optional<E> tryFindFirst() { + return getNextStep().tryFindFirst(); + } + + @Override + public Optional<E> tryFindUnique() { + return getNextStep().tryFindUnique(); + } + + @Override + public List<E> findAll() { + return getNextStep().findAll(); + } + + @Override + public List<E> find(int startIndex, int endIndex) { + return getNextStep().find(startIndex, endIndex); + } + + @Override + public List<E> find(TopiaPagerBean pager) { + return getNextStep().find(pager); + } + + @Override + public Iterable<E> findAllLazy() { + return getNextStep().findAllLazy(); + } + + @Override + public Iterable<E> findAllLazy(int batchSize) { + return getNextStep().findAllLazy(batchSize); + } + + @Override + public long count() { + return getNextStep().count(); + } + + @Override + public List<String> findIds(int startIndex, int endIndex) { + return getNextStep().findIds(startIndex, endIndex); + } + + @Override + public List<String> findIds(TopiaPagerBean pager) { + return getNextStep().findIds(pager); + } + + @Override + public List<String> findAllIds() { + return getNextStep().findAllIds(); + } + + protected InnerTopiaQueryBuilderRunQueryStep<E> getNextStep() { + String hql = hqlAndParametersBuilder.getHql(); + Map<String, Object> hqlParameters = hqlAndParametersBuilder.getHqlParameters(); + InnerTopiaQueryBuilderRunQueryStep<E> nextStep = new InnerTopiaQueryBuilderRunQueryStep<E>(topiaDAO, hql, hqlParameters); + return nextStep; + } + + } + + public static class InnerTopiaQueryBuilderRunQueryStep<E extends TopiaEntity> implements TopiaQueryBuilderRunQueryStep<E> { + + protected final String hql; + + protected final Map<String, Object> hqlParameters; + + protected final AbstractTopiaDao<E> topiaDAO; + + protected InnerTopiaQueryBuilderRunQueryStep(AbstractTopiaDao<E> topiaDAO, String hql, Map<String, Object> hqlParameters) { + this.hql = hql; + this.hqlParameters = hqlParameters; + this.topiaDAO = topiaDAO; + } + + @Override + public boolean exists() { + return topiaDAO.exists(hql, hqlParameters); + } + + @Override + public long count() { + String hqlWithSelectClause = "select count(topiaId) " + hql; + return topiaDAO.count(hqlWithSelectClause, hqlParameters); + } + + @Override + public E findUnique() throws TopiaNoResultException, TopiaNonUniqueResultException { + return topiaDAO.findUnique(hql, hqlParameters); + } + + @Override + public E findUniqueOrNull() throws TopiaNonUniqueResultException { + return topiaDAO.findUniqueOrNull(hql, hqlParameters); + } + + @Override + public Optional<E> tryFindUnique() throws TopiaNonUniqueResultException { + return topiaDAO.tryFindUnique(hql, hqlParameters); + } + + @Override + public E findFirst() throws QueryMissingOrderException, TopiaNoResultException { + return topiaDAO.findFirst(hql, hqlParameters); + } + + @Override + public E findFirstOrNull() throws QueryMissingOrderException { + return topiaDAO.findFirstOrNull(hql, hqlParameters); + } + + @Override + public Optional<E> tryFindFirst() throws QueryMissingOrderException { + return topiaDAO.tryFindFirst(hql, hqlParameters); + } + + @Override + public E findAny() throws TopiaNoResultException { + return topiaDAO.findAny(hql, hqlParameters); + } + + @Override + public E findAnyOrNull() { + return topiaDAO.findAnyOrNull(hql, hqlParameters); + } + + @Override + public Optional<E> tryFindAny() { + return topiaDAO.tryFindAny(hql, hqlParameters); + } + + @Override + public List<E> findAll() { + return topiaDAO.findAll(hql, hqlParameters); + } + + @Override + public Iterable<E> findAllLazy() { + return topiaDAO.findAllLazy(hql, hqlParameters); + } + + @Override + public Iterable<E> findAllLazy(int batchSize) { + return topiaDAO.findAllLazy(hql, hqlParameters, batchSize); + } + + @Override + public List<E> find(int startIndex, int endIndex) { + return topiaDAO.find(hql, hqlParameters, startIndex, endIndex); + } + + @Override + public List<E> find(TopiaPagerBean pager) { + return topiaDAO.find(hql, hqlParameters, pager); + } + + @Override + public List<String> findAllIds() { + String hqlWithSelectClause = "select topiaId " + hql; + return topiaDAO.findAll(hqlWithSelectClause, hqlParameters); + } + + @Override + public List<String> findIds(int startIndex, int endIndex) { + String hqlWithSelectClause = "select topiaId " + hql; + return topiaDAO.find(hqlWithSelectClause, hqlParameters, startIndex, endIndex); + } + + @Override + public List<String> findIds(TopiaPagerBean pager) { + String hqlWithSelectClause = "select topiaId " + hql; + return topiaDAO.find(hqlWithSelectClause, hqlParameters, pager); + } + } + +} Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/internal/AbstractTopiaPersistenceContext.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/internal/AbstractTopiaPersistenceContext.java 2013-12-20 16:07:29 UTC (rev 2954) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/internal/AbstractTopiaPersistenceContext.java 2013-12-20 16:19:35 UTC (rev 2955) @@ -41,8 +41,6 @@ import org.nuiton.topia.persistence.internal.support.HibernateTopiaReplicationSupport; import org.nuiton.topia.persistence.internal.support.HibernateTopiaSqlSupport; import org.nuiton.topia.persistence.internal.support.TopiaFiresSupport; -import org.nuiton.topia.persistence.AbstractTopiaDao; -import org.nuiton.topia.persistence.HibernateProvider; import org.nuiton.topia.persistence.TopiaDao; import org.nuiton.topia.persistence.TopiaEntity; import org.nuiton.topia.persistence.TopiaIdFactory; Copied: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/internal/DefaultTopiaIdFactory.java (from rev 2954, trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/DefaultTopiaIdFactory.java) =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/internal/DefaultTopiaIdFactory.java (rev 0) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/internal/DefaultTopiaIdFactory.java 2013-12-20 16:19:35 UTC (rev 2955) @@ -0,0 +1,75 @@ +package org.nuiton.topia.persistence.internal; + +/* + * #%L + * ToPIA :: Persistence + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2013 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ + +import org.apache.commons.lang3.StringUtils; +import org.nuiton.topia.persistence.TopiaEntity; +import org.nuiton.topia.persistence.TopiaException; +import org.nuiton.topia.persistence.TopiaIdFactory; + +import java.util.UUID; + +/** + * Default implementation of {@link TopiaIdFactory}. Generates an FQN followed + * by an random UUID. + * + * @author Brendan Le Ny <leny@codelutin.com> + * @since 3.0 + */ +public class DefaultTopiaIdFactory implements TopiaIdFactory { + + @Override + public <E extends TopiaEntity> String newTopiaId(Class<E> entityClass, TopiaEntity topiaEntity) { + if (!entityClass.isInterface()) { + throw new IllegalArgumentException( + "Only interface is permit to create id: " + entityClass); + } + String result = entityClass.getName() + getSeparator() + UUID.randomUUID().toString(); + return result; + } + + @Override + public <E extends TopiaEntity> Class<E> getClassName(String topiaId) { +// String className = Iterables.get(Splitter.on(getSeparator()).split(topiaId), 0); + String className = StringUtils.substringBefore(topiaId, getSeparator()); + try { + Class<E> entityClass = (Class<E>) Class.forName(className); + return entityClass; + } catch (ClassNotFoundException e) { + throw new TopiaException("can't find class for topiaId = '" + topiaId + "'", e); + } + } + + @Override + public String getSeparator() { + return "_"; + } + + @Override + public String getRandomPart(String topiaId) { + return StringUtils.substringBefore(topiaId, getSeparator()); + } + +} Copied: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/internal/HibernateProvider.java (from rev 2954, trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/HibernateProvider.java) =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/internal/HibernateProvider.java (rev 0) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/internal/HibernateProvider.java 2013-12-20 16:19:35 UTC (rev 2955) @@ -0,0 +1,262 @@ +package org.nuiton.topia.persistence.internal; + +/* + * #%L + * ToPIA :: Persistence + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2013 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ + +import java.io.File; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Properties; +import java.util.Set; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.hibernate.SessionFactory; +import org.hibernate.cfg.Configuration; +import org.hibernate.engine.spi.SessionFactoryImplementor; +import org.hibernate.event.service.spi.EventListenerRegistry; +import org.hibernate.event.spi.EventType; +import org.hibernate.service.ServiceRegistry; +import org.hibernate.service.ServiceRegistryBuilder; +import org.hibernate.service.jdbc.connections.spi.ConnectionProvider; +import org.hibernate.service.spi.ServiceRegistryImplementor; +import org.hibernate.service.spi.Stoppable; +import org.nuiton.topia.persistence.TopiaConfigurationConstants; +import org.nuiton.topia.persistence.TopiaNotFoundException; +import org.nuiton.topia.persistence.TopiaService; +import org.nuiton.topia.persistence.support.TopiaServiceSupport; +import org.nuiton.topia.persistence.internal.support.TopiaHibernateEventListener; +import org.nuiton.topia.persistence.util.TopiaUtil; + +import com.google.common.collect.Lists; + +/** + * @author Arnaud Thimel <thimel@codelutin.com> + */ +public class HibernateProvider { + + private static final Log log = LogFactory.getLog(HibernateProvider.class); + + protected SessionFactory hibernateSessionFactory; + protected Configuration hibernateConfiguration; + + protected Map<String, String> configuration; + protected TopiaServiceSupport topiaServiceSupport; + protected TopiaHibernateSessionRegistry sessionRegistry; + + /** + * List of persistent classes + */ + protected List<Class<?>> persistentClasses = Lists.newArrayList(); + + public HibernateProvider(Map<String, String> configuration, + TopiaServiceSupport topiaServiceSupport, + TopiaHibernateSessionRegistry sessionRegistry) { + this.configuration = configuration; + this.topiaServiceSupport = topiaServiceSupport; + this.sessionRegistry = sessionRegistry; + } + + protected String getProperty(String key) { + return getProperty(key, null); + } + + protected String getProperty(String key, String defaultValue) { + String result = defaultValue; + if (configuration.containsKey(key)) { + result = configuration.get(key); + } + + return result; + } + + public List<Class<?>> getPersistentClasses() { + if (persistentClasses.isEmpty()) { + // Force configuration load + getHibernateConfiguration(); + } + return persistentClasses; + } + + public Configuration getHibernateConfiguration() { + if (hibernateConfiguration == null) { + hibernateConfiguration = new Configuration(); + + // ajout des repertoires contenant les mappings hibernate + String[] dirs = getProperty( + TopiaConfigurationConstants.CONFIG_PERSISTENCE_DIRECTORIES, "").split(","); + for (String dir : dirs) { + dir = dir.trim(); + if (StringUtils.isNotEmpty(dir)) { + if (log.isDebugEnabled()) { + log.debug("Load persistence from dir : " + dir); + } + hibernateConfiguration.addDirectory(new File(dir)); + } + } + + // ajout des classes dites persistentes + Set<Class<?>> hibernatePersistanceClasses = new HashSet<Class<?>>(); + for (TopiaService service : topiaServiceSupport.getServices().values()) { + Class<?>[] classes = service.getPersistenceClasses(); + + // certains service n'ont pas de classe persistantes + if (classes != null) { + // sletellier 20110411 : http://www.nuiton.org/issues/show/1454 + hibernatePersistanceClasses.addAll(Arrays.asList(classes)); +// for (Class<?> clazz : classes) { +// hibernateConfiguration.addClass(clazz); +// } + } + } + + String listPersistenceClasses = getProperty( + TopiaConfigurationConstants.CONFIG_PERSISTENCE_CLASSES, ""); + + String[] classes = listPersistenceClasses.split(","); + for (String classname : classes) { + classname = classname.trim(); + if (StringUtils.isNotEmpty(classname)) { + if (log.isDebugEnabled()) { + log.debug("Load persistent class : " + classname); + } + + // XXX echatellier 20111007 ce qui est dommage ici, c'est + // la definition de cette classe ne sert a rien (apart security) + // car pour hibernate hibernateConfiguration.addClass(persistanceClass) + // il ne se sert pas de la classe en fait et fait seulement + // un classname.replace( '.', '/' ) + ".hbm.xml"; + // pour obtenir le mapping et la reinstancier ensuite + + Class<?> clazz; + try { + clazz = Class.forName(classname); + } catch (ClassNotFoundException eee) { + if (log.isDebugEnabled()) { + log.debug("Class " + classname + " not found"); + } + throw new TopiaNotFoundException( + String.format("Persistence class %1$s not found", + classname)); + } + persistentClasses.add(clazz); + + // sletellier 20110411 : http://www.nuiton.org/issues/show/1454 +// hibernateConfiguration.addClass(clazz); + hibernatePersistanceClasses.add(clazz); + } + } + + // sletellier 20110411 : http://www.nuiton.org/issues/show/1454 + // Add persistance classes in hibernate config + for (Class<?> persistanceClass : hibernatePersistanceClasses) { + hibernateConfiguration.addClass(persistanceClass); + } + + Properties prop = new Properties(); + prop.putAll(hibernateConfiguration.getProperties()); + prop.putAll(configuration); + + // Strange behavior, all properties are already loaded from + // constructor. Difficult to use this behavior, need to have + // TOPIA_PERSISTENCE_PROPERTIES_FILE in config. + Properties propertiesFromClasspath = + TopiaUtil.getProperties(getProperty(TopiaConfigurationConstants.CONFIG_PERSISTENCE_PROPERTIES_FILE)); + + if (!propertiesFromClasspath.isEmpty()) { + if (log.isDebugEnabled()) { + log.debug("Load properties from file : " + + propertiesFromClasspath); + } + prop.putAll(propertiesFromClasspath); + } + + hibernateConfiguration.setProperties(prop); + + // tchemit 2011-05-26 When using hibernate > 3.3, need to make sure all mappings are loaded (the one from directory files are not still done). + hibernateConfiguration.buildMappings(); + } + return hibernateConfiguration; + } + + public void close() { + if (hibernateSessionFactory != null) { + hibernateSessionFactory.close(); + // close connection provider if possible (http://nuiton.org/issues/2757) + SessionFactoryImplementor sessionFactoryImplementor = (SessionFactoryImplementor) hibernateSessionFactory; + ServiceRegistryImplementor serviceRegistry = sessionFactoryImplementor.getServiceRegistry(); + ConnectionProvider service = serviceRegistry.getService(ConnectionProvider.class); + + // TODO AThimel 18/12/13 Check this code compatibility with Hibernate 4.3.0.Final +// ConnectionProvider service = hibernateSessionFactory.getSessionFactoryOptions().getServiceRegistry().getService(ConnectionProvider.class); + if (service instanceof Stoppable) { + Stoppable stoppable = (Stoppable) service; + stoppable.stop(); + } + } + } + + public SessionFactory getSessionFactory() { + + if (hibernateSessionFactory == null) { + + // init service registry + Properties properties = getHibernateConfiguration().getProperties(); + ServiceRegistryBuilder builder = new ServiceRegistryBuilder().applySettings(properties); + ServiceRegistry serviceRegistry = builder.buildServiceRegistry(); + + hibernateSessionFactory = getHibernateConfiguration().buildSessionFactory(serviceRegistry); + + // TODO AThimel 18/12/13 Check this code compatibility with Hibernate 4.3.0.Final +// StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder(); +// Properties properties = getHibernateConfiguration().getProperties(); +// StandardServiceRegistry standardServiceRegistry = builder.applySettings(properties).build(); +// +// hibernateSessionFactory = getHibernateConfiguration().buildSessionFactory(standardServiceRegistry); + + // we can't reuse original serviceRegistry instance + // we must call getServiceRegistry on factory to get a working one + ServiceRegistry serviceRegistryInit = ((SessionFactoryImplementor) hibernateSessionFactory).getServiceRegistry(); + EventListenerRegistry eventListenerRegistry = serviceRegistryInit.getService(EventListenerRegistry.class); + + TopiaHibernateEventListener listener = new TopiaHibernateEventListener(sessionRegistry); + eventListenerRegistry.appendListeners(EventType.PRE_INSERT, listener); + eventListenerRegistry.appendListeners(EventType.PRE_LOAD, listener); + eventListenerRegistry.appendListeners(EventType.PRE_UPDATE, listener); + eventListenerRegistry.appendListeners(EventType.PRE_DELETE, listener); + eventListenerRegistry.appendListeners(EventType.POST_INSERT, listener); + eventListenerRegistry.appendListeners(EventType.POST_LOAD, listener); + eventListenerRegistry.appendListeners(EventType.POST_UPDATE, listener); + eventListenerRegistry.appendListeners(EventType.POST_DELETE, listener); + + // following listeners must be called before hibernate + eventListenerRegistry.prependListeners(EventType.SAVE_UPDATE, listener); + } + return hibernateSessionFactory; + } + +} Copied: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/internal/LegacyTopiaIdFactory.java (from rev 2954, trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/LegacyTopiaIdFactory.java) =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/internal/LegacyTopiaIdFactory.java (rev 0) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/internal/LegacyTopiaIdFactory.java 2013-12-20 16:19:35 UTC (rev 2955) @@ -0,0 +1,86 @@ +package org.nuiton.topia.persistence.internal; + +/* + * #%L + * ToPIA :: Persistence + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2013 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ + +import org.apache.commons.lang3.StringUtils; +import org.nuiton.topia.persistence.TopiaEntity; +import org.nuiton.topia.persistence.TopiaIdFactory; +import org.nuiton.topia.persistence.TopiaNotFoundException; + +/** + * Implements {@link TopiaIdFactory} with Topia 2.x and before ids. + * Suitable if you already have a database and your application need + * to generate ids like the old ones. + * + * @since 3.0 + */ +public class LegacyTopiaIdFactory implements TopiaIdFactory { + + @Override + public <E extends TopiaEntity> String newTopiaId(Class<E> entityClass, TopiaEntity topiaEntity) { + if (!entityClass.isInterface()) { + throw new IllegalArgumentException( + "Only interface is permit to create id: " + entityClass); + } + double random = Math.random(); + while (Double.toString(random).contains("E-")) { + random = Math.random(); + } + return entityClass.getName() + getSeparator() + System.currentTimeMillis() + '#' + random; + } + + /** + * Extrait la classe du topiaId. + * + * @param topiaId + * @return class + * @throws TopiaNotFoundException + */ + @Override + public <E extends TopiaEntity> Class<E> getClassName(String topiaId) { + String className = StringUtils.substringBefore(topiaId, getSeparator()); +// int i = topiaId.indexOf('#'); +// if (i > 0) { +// className = topiaId.substring(0, i); +// } + try { + Class result = Class.forName(className); + return result; + } catch (ClassNotFoundException eee) { + throw new TopiaNotFoundException("Can't find class for " + topiaId, + eee); + } + } + + @Override + public String getSeparator() { + return "#"; + } + + @Override + public String getRandomPart(String topiaId) { + return StringUtils.substringBefore(topiaId, getSeparator()); + } +} Modified: trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TopiaMigrationEngine.java =================================================================== --- trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TopiaMigrationEngine.java 2013-12-20 16:07:29 UTC (rev 2954) +++ trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TopiaMigrationEngine.java 2013-12-20 16:19:35 UTC (rev 2955) @@ -35,7 +35,7 @@ import org.nuiton.topia.persistence.internal.AbstractTopiaApplicationContext; import org.nuiton.topia.persistence.internal.AbstractTopiaPersistenceContext; import org.nuiton.topia.persistence.TopiaApplicationContext; -import org.nuiton.topia.persistence.HibernateProvider; +import org.nuiton.topia.persistence.internal.HibernateProvider; import org.nuiton.topia.persistence.TopiaException; import org.nuiton.topia.persistence.support.TopiaHibernateSupport; import org.nuiton.topia.persistence.TopiaNotFoundException; Modified: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityDaoTransformer.java =================================================================== --- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityDaoTransformer.java 2013-12-20 16:07:29 UTC (rev 2954) +++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityDaoTransformer.java 2013-12-20 16:19:35 UTC (rev 2955) @@ -48,7 +48,7 @@ import org.nuiton.eugene.models.object.ObjectModelOperation; import org.nuiton.topia.persistence.internal.support.HibernateTopiaJpaSupport; import org.nuiton.topia.persistence.support.TopiaHibernateSupport; -import org.nuiton.topia.persistence.AbstractTopiaDao; +import org.nuiton.topia.persistence.internal.AbstractTopiaDao; import org.nuiton.topia.persistence.TopiaEntity; import org.nuiton.topia.persistence.TopiaQueryBuilderAddCriteriaOrRunQueryStep; Modified: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/PersistenceContextTransformer.java =================================================================== --- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/PersistenceContextTransformer.java 2013-12-20 16:07:29 UTC (rev 2954) +++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/PersistenceContextTransformer.java 2013-12-20 16:19:35 UTC (rev 2955) @@ -35,7 +35,7 @@ import org.nuiton.eugene.models.object.ObjectModelOperation; import org.nuiton.topia.persistence.internal.AbstractTopiaPersistenceContext; import org.nuiton.topia.persistence.TopiaDaoSupplier; -import org.nuiton.topia.persistence.HibernateProvider; +import org.nuiton.topia.persistence.internal.HibernateProvider; import org.nuiton.topia.persistence.internal.TopiaHibernateSessionRegistry; import org.nuiton.topia.persistence.support.TopiaListenableSupport; import org.nuiton.topia.persistence.TopiaIdFactory; Modified: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaGeneratorUtil.java =================================================================== --- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaGeneratorUtil.java 2013-12-20 16:07:29 UTC (rev 2954) +++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaGeneratorUtil.java 2013-12-20 16:19:35 UTC (rev 2955) @@ -43,7 +43,7 @@ import org.nuiton.eugene.models.object.ObjectModelInterface; import org.nuiton.eugene.models.object.ObjectModelOperation; import org.nuiton.eugene.models.object.ObjectModelParameter; -import org.nuiton.topia.persistence.AbstractTopiaDao; +import org.nuiton.topia.persistence.internal.AbstractTopiaDao; import java.util.ArrayList; import java.util.Arrays; Modified: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaTagValues.java =================================================================== --- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaTagValues.java 2013-12-20 16:07:29 UTC (rev 2954) +++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaTagValues.java 2013-12-20 16:19:35 UTC (rev 2955) @@ -33,7 +33,7 @@ import org.nuiton.topia.persistence.internal.AbstractTopiaApplicationContext; import org.nuiton.topia.persistence.internal.AbstractTopiaPersistenceContext; import org.nuiton.topia.persistence.TopiaDaoSupplier; -import org.nuiton.topia.persistence.AbstractTopiaDao; +import org.nuiton.topia.persistence.internal.AbstractTopiaDao; import org.nuiton.topia.persistence.TopiaDao; import org.nuiton.topia.persistence.TopiaEntity; import org.nuiton.topia.persistence.TopiaEntityAbstract;
participants (1)
-
tchemit@users.nuiton.org