Topia-commits
Threads by month
- ----- 2026 -----
- June
- May
- April
- March
- February
- January
- ----- 2025 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2024 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2023 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2022 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2021 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2020 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2019 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2018 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2017 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2016 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2015 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2014 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2013 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2012 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2011 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2010 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2009 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2008 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2007 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2006 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2005 -----
- December
- November
- October
- September
- August
- July
- June
- May
- April
- March
- February
- January
- ----- 2004 -----
- December
- November
- October
- September
- August
- July
- June
- May
December 2013
- 6 participants
- 58 discussions
Author: tchemit
Date: 2013-12-25 18:12:05 +0100 (Wed, 25 Dec 2013)
New Revision: 2960
Url: http://nuiton.org/projects/topia/repository/revisions/2960
Log:
fixes #2990: Updates h2 to 1.3.174
fixes #2991: Updates nuiton-csv to 3.0-alpha-2
fixes #2992: updates nuiton-decorator to 3.0-alpha-2
fixes #2993: Updates nuiton-utils to 3.0-alpha-1
Modified:
trunk/pom.xml
Modified: trunk/pom.xml
===================================================================
--- trunk/pom.xml 2013-12-25 16:41:23 UTC (rev 2959)
+++ trunk/pom.xml 2013-12-25 17:12:05 UTC (rev 2960)
@@ -235,15 +235,15 @@
<!-- libs version -->
<eugeneVersion>2.7.3</eugeneVersion>
- <nuitonUtilsVersion>2.7</nuitonUtilsVersion>
- <nuitonCsvVersion>3.0-alpha-1</nuitonCsvVersion>
- <nuitonDecoratorVersion>3.0-alpha-1</nuitonDecoratorVersion>
+ <nuitonUtilsVersion>3.0-alpha-1</nuitonUtilsVersion>
+ <nuitonCsvVersion>3.0-alpha-2</nuitonCsvVersion>
+ <nuitonDecoratorVersion>3.0-alpha-2</nuitonDecoratorVersion>
<nuitonI18nVersion>2.5.2</nuitonI18nVersion>
<processorPluginVersion>1.3</processorPluginVersion>
<xmlrpcVersion>3.1.2</xmlrpcVersion>
<hibernateVersion>4.2.8.Final</hibernateVersion>
<sl4jVersion>1.7.5</sl4jVersion>
- <h2Version>1.3.172</h2Version>
+ <h2Version>1.3.174</h2Version>
<hamcrestVersion>1.3</hamcrestVersion>
</properties>
@@ -322,12 +322,6 @@
<scope>runtime</scope>
</dependency>
- <dependency>
- <groupId>commons-codec</groupId>
- <artifactId>commons-codec</artifactId>
- <version>1.8</version>
- </dependency>
-
<!-- hibernate-core only include api, need implementation,
binding with log4j will be used
-->
1
0
Author: tchemit
Date: 2013-12-25 17:41:23 +0100 (Wed, 25 Dec 2013)
New Revision: 2959
Url: http://nuiton.org/projects/topia/repository/revisions/2959
Log:
refs #2985: Updates mavenpom to 4.5
use new site API
Modified:
trunk/pom.xml
trunk/src/site/site_fr.xml
Modified: trunk/pom.xml
===================================================================
--- trunk/pom.xml 2013-12-20 17:34:59 UTC (rev 2958)
+++ trunk/pom.xml 2013-12-25 16:41:23 UTC (rev 2959)
@@ -29,7 +29,7 @@
<parent>
<groupId>org.nuiton</groupId>
<artifactId>mavenpom4redmineAndCentral</artifactId>
- <version>4.4</version>
+ <version>4.5-SNAPSHOT</version>
</parent>
<artifactId>topia</artifactId>
Modified: trunk/src/site/site_fr.xml
===================================================================
--- trunk/src/site/site_fr.xml 2013-12-20 17:34:59 UTC (rev 2958)
+++ trunk/src/site/site_fr.xml 2013-12-25 16:41:23 UTC (rev 2959)
@@ -27,7 +27,7 @@
<project name="ToPIA">
<bannerLeft>
- <!--<src alt="ToPIA">http://maven-site.nuiton.org/public/images/logos/topia-logo.png</src>-->
+ <!--<src alt="ToPIA">${mavenpomSiteCommonResourcesUrl}/images/logos/topia-logo.png</src>-->
<name>${project.name}</name>
<href>index.html</href>
</bannerLeft>
@@ -40,7 +40,7 @@
<skin>
<groupId>org.apache.maven.skins</groupId>
<artifactId>maven-fluido-skin</artifactId>
- <version>1.3.0</version>
+ <version>${fluidoSkinVersion}</version>
</skin>
<custom>
@@ -68,13 +68,13 @@
<logo href="http://docutils.sourceforge.net/rst.html"
name="ReStructuredText"
- img="http://maven-site.forge.codelutin.com/common/0.2/images/logos/restructuredt…"/>
+ img="${mavenpomSiteCommonResourcesUrl}/images/logos/restructuredtext-logo.png"/>
<logo href="http://maven-site.nuiton.org/jrst" name="JRst"
- img="http://maven-site.forge.codelutin.com/common/0.2/images/logos/jrst-logo.png"/>
+ img="${mavenpomSiteCommonResourcesUrl}/images/logos/jrst-logo.png"/>
<logo href="http://argouml.tigris.org/" name="ArgoUML"
- img="http://maven-site.forge.codelutin.com/common/0.2/images/logos/argouml-logo.…"/>
+ img="${mavenpomSiteCommonResourcesUrl}/images/logos/argouml-logo.png"/>
</poweredBy>
@@ -82,11 +82,11 @@
<head>
<script type="text/javascript"
- src="http://maven-site.forge.codelutin.com/common/0.2/js/mavenpom-site.js">
+ src="${mavenpomSiteCommonResourcesUrl}/js/mavenpom-site.js">
</script>
<link rel="stylesheet" type="text/css"
- href="http://maven-site.forge.codelutin.com/common/0.2/css/mavenpom-site.css"/>
+ href="${mavenpomSiteCommonResourcesUrl}/css/mavenpom-site.css"/>
</head>
<breadcrumbs>
1
0
Author: athimel
Date: 2013-12-20 18:34:59 +0100 (Fri, 20 Dec 2013)
New Revision: 2958
Url: http://nuiton.org/projects/topia/repository/revisions/2958
Log:
refs #2893 Document main classes renaming
Modified:
trunk/src/site/rst/migrate_to_3.0.rst
Modified: trunk/src/site/rst/migrate_to_3.0.rst
===================================================================
--- trunk/src/site/rst/migrate_to_3.0.rst 2013-12-20 16:39:11 UTC (rev 2957)
+++ trunk/src/site/rst/migrate_to_3.0.rst 2013-12-20 17:34:59 UTC (rev 2958)
@@ -248,5 +248,46 @@
Voir TopiaSqlQuery, TopiaSqlWork et TopiaSqlSupport.
+Refactoring des packages
+========================
+
+|MANDATORY|
+
+Un grand nombre de classes ont été déplacées. Voici les principaux renommages :
+
+::
+
+ org.nuiton.topia.TopiaException -> org.nuiton.topia.persistence.TopiaException
+ org.nuiton.topia.TopiaDaoSupplier -> org.nuiton.topia.persistence.TopiaDaoSupplier
+ org.nuiton.topia.TopiaJpaSupport -> org.nuiton.topia.persistence.support.TopiaJpaSupport
+ org.nuiton.topia.TopiaPersistenceContext -> org.nuiton.topia.persistence.TopiaPersistenceContext
+ org.nuiton.topia.TopiaNotFoundException -> org.nuiton.topia.persistence.TopiaNotFoundException
+ org.nuiton.topia.TopiaApplicationContextCache -> org.nuiton.topia.persistence.TopiaApplicationContextCache
+ org.nuiton.topia.TopiaTransaction -> org.nuiton.topia.persistence.TopiaTransaction
+ org.nuiton.topia.persistence.TopiaHibernateSessionRegistry -> org.nuiton.topia.persistence.internal.TopiaHibernateSessionRegistry
+ org.nuiton.topia.TopiaListenableSupport -> org.nuiton.topia.persistence.support.TopiaListenableSupport
+ org.nuiton.topia.persistence.HibernateProvider -> org.nuiton.topia.persistence.internal.HibernateProvider
+ org.nuiton.topia.TopiaContextFactory -> org.nuiton.topia.persistence.TopiaConfigurationConstants
+
+
+Le refactoring peut s'effectuer facilement en appliquant les commandes suivantes :
+
+::
+
+ grep -m 1 -nr 'org.nuiton.topia.TopiaException' . | awk -F ':' '{print $1}' | xargs sed -i -e 's/org.nuiton.topia.TopiaException/org.nuiton.topia.persistence.TopiaException/g'
+ grep -m 1 -nr 'org.nuiton.topia.TopiaDaoSupplier' . | awk -F ':' '{print $1}' | xargs sed -i -e 's/org.nuiton.topia.TopiaDaoSupplier/org.nuiton.topia.persistence.TopiaDaoSupplier/g'
+ grep -m 1 -nr 'org.nuiton.topia.TopiaJpaSupport' . | awk -F ':' '{print $1}' | xargs sed -i -e 's/org.nuiton.topia.TopiaJpaSupport/org.nuiton.topia.persistence.support.TopiaJpaSupport/g'
+ grep -m 1 -nr 'org.nuiton.topia.TopiaPersistenceContext' . | awk -F ':' '{print $1}' | xargs sed -i -e 's/org.nuiton.topia.TopiaPersistenceContext/org.nuiton.topia.persistence.TopiaPersistenceContext/g'
+ grep -m 1 -nr 'org.nuiton.topia.TopiaNotFoundException' . | awk -F ':' '{print $1}' | xargs sed -i -e 's/org.nuiton.topia.TopiaNotFoundException/org.nuiton.topia.persistence.TopiaNotFoundException/g'
+ grep -m 1 -nr 'org.nuiton.topia.TopiaApplicationContextCache' . | awk -F ':' '{print $1}' | xargs sed -i -e 's/org.nuiton.topia.TopiaApplicationContextCache/org.nuiton.topia.persistence.TopiaApplicationContextCache/g'
+ grep -m 1 -nr 'org.nuiton.topia.TopiaTransaction' . | awk -F ':' '{print $1}' | xargs sed -i -e 's/org.nuiton.topia.TopiaTransaction/org.nuiton.topia.persistence.TopiaTransaction/g'
+ grep -m 1 -nr 'org.nuiton.topia.persistence.TopiaHibernateSessionRegistry' . | awk -F ':' '{print $1}' | xargs sed -i -e 's/org.nuiton.topia.persistence.TopiaHibernateSessionRegistry/org.nuiton.topia.persistence.internal.TopiaHibernateSessionRegistry/g'
+ grep -m 1 -nr 'org.nuiton.topia.TopiaListenableSupport' . | awk -F ':' '{print $1}' | xargs sed -i -e 's/org.nuiton.topia.TopiaListenableSupport/org.nuiton.topia.persistence.support.TopiaListenableSupport/g'
+ grep -m 1 -nr 'org.nuiton.topia.persistence.HibernateProvider' . | awk -F ':' '{print $1}' | xargs sed -i -e 's/org.nuiton.topia.persistence.HibernateProvider/org.nuiton.topia.persistence.internal.HibernateProvider/g'
+ grep -m 1 -nr 'org.nuiton.topia.TopiaContextFactory' . | awk -F ':' '{print $1}' | xargs sed -i -e 's/org.nuiton.topia.TopiaContextFactory/org.nuiton.topia.persistence.TopiaConfigurationConstants/g'
+ grep -m 1 -nr 'TopiaContextFactory.CONFIG_' . | awk -F ':' '{print $1}' | xargs sed -i -e 's/TopiaContextFactory.CONFIG_/TopiaConfigurationConstants.CONFIG_/g'
+
+
+
.. |RECOMMENDED| image:: recommended.png
.. |MANDATORY| image:: mandatory.png
1
0
r2957 - trunk/topia-templates/src/main/java/org/nuiton/topia/templates
by bleny@users.nuiton.org 20 Dec '13
by bleny@users.nuiton.org 20 Dec '13
20 Dec '13
Author: bleny
Date: 2013-12-20 17:39:11 +0100 (Fri, 20 Dec 2013)
New Revision: 2957
Url: http://nuiton.org/projects/topia/repository/revisions/2957
Log:
fixes #2978 by adding isXXXNotEmpty and getXXXTopiaIds in generated
Modified:
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityTransformer.java
Modified: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityTransformer.java
===================================================================
--- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityTransformer.java 2013-12-20 16:27:35 UTC (rev 2956)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityTransformer.java 2013-12-20 16:39:11 UTC (rev 2957)
@@ -636,10 +636,10 @@
* @see #addMultipleRemoveOperation(ObjectModelAttribute)
* @see #addMultipleClearOperation(ObjectModelAttribute, String, String)
* @see #addMultipleGetOperation(ObjectModelAttribute, String)
- * @see #addMultipleGetTopiaIdOperation(ObjectModelAttribute)
+ * @see #addMultipleGetByTopiaIdOperation(ObjectModelAttribute)
* @see #addMultipleGetOperationFromEntity(ObjectModelAttribute)
* @see #addMultipleSizeOperation(ObjectModelAttribute)
- * @see #addMultipleIsEmptyOperation(ObjectModelAttribute)
+ * @see #addMultipleIsEmptyOperations(ObjectModelAttribute)
*/
protected void generatePropertyOperations(ObjectModelAttribute attribute) {
@@ -709,7 +709,11 @@
if (TopiaGeneratorUtil.isEntity(attribute, model)) {
// getXXXByTopiaId
- addMultipleGetTopiaIdOperation(attribute);
+ addMultipleGetByTopiaIdOperation(attribute);
+
+ // getXXXTopiaIds
+ addMultipleGetTopiaIdsOperation(attribute, collectionInterface, collectionImpl);
+
}
if (attribute.hasAssociationClass()) {
@@ -721,7 +725,7 @@
addMultipleSizeOperation(attribute);
// isXXXEmpty
- addMultipleIsEmptyOperation(attribute);
+ addMultipleIsEmptyOperations(attribute);
}
}
@@ -959,7 +963,7 @@
// Interface operation
ObjectModelOperation interfaceOperation =
- addOperation(outputInterface, getJavaBeanMethodName("remove" , attrName),
+ addOperation(outputInterface, getJavaBeanMethodName("remove", attrName),
void.class, ObjectModelJavaModifier.PACKAGE);
ObjectModelParameter param =
addParameter(interfaceOperation, attrType, attrName);
@@ -1100,7 +1104,7 @@
);
}
- protected void addMultipleGetTopiaIdOperation(ObjectModelAttribute attribute) {
+ protected void addMultipleGetByTopiaIdOperation(ObjectModelAttribute attribute) {
String attrName = getPropertyName(attribute);
String attrType = getPropertyType(attribute);
@@ -1130,6 +1134,41 @@
);
}
+ protected void addMultipleGetTopiaIdsOperation(ObjectModelAttribute attribute, String collectionInterface, String collectionImpl) {
+
+ String attrName = getPropertyName(attribute);
+ String attrType = getPropertyType(attribute);
+
+ String getterName = getJavaBeanMethodName("get" , attrName);
+
+ if (log.isDebugEnabled()) {
+ log.debug("Generate multiple 'getTopiaIds' operation for property : " + attrName +
+ " [" + attrType + "]");
+ }
+
+ // Interface operation
+ ObjectModelOperation interfaceOperation =
+ addOperation(outputInterface, getJavaBeanMethodName("get", attrName) + "TopiaIds",
+ collectionInterface + "<String>", ObjectModelJavaModifier.PACKAGE);
+
+ // Implementation
+ ObjectModelOperation implOperation =
+ createImplOperation(interfaceOperation);
+
+ setOperationBody(implOperation, ""
+/*{
+ <%=collectionInterface%><String> topiaIds = new <%=collectionImpl%><String>();
+ <%=collectionInterface%><<%=attrType%>> tmp = <%=getterName%>();
+ if (tmp != null) {
+ for (TopiaEntity topiaEntity : tmp) {
+ topiaIds.add(topiaEntity.getTopiaId());
+ }
+ }
+ return topiaIds;
+ }*/
+ );
+ }
+
protected void addMultipleGetOperationFromEntity(ObjectModelAttribute attribute) {
// reference to the real attribute name
@@ -1199,7 +1238,7 @@
);
}
- protected void addMultipleIsEmptyOperation(ObjectModelAttribute attribute) {
+ protected void addMultipleIsEmptyOperations(ObjectModelAttribute attribute) {
String attrName = getPropertyName(attribute);
@@ -1208,20 +1247,38 @@
}
String sizeMethodName = getJavaBeanMethodName("size", attrName);
- // Interface operation
- ObjectModelOperation interfaceOperation =
- addOperation(outputInterface, getJavaBeanMethodName("is", attrName)+ "Empty",
+
+ // isEmpty Interface operation
+ String isEmptyMethodName = getJavaBeanMethodName("is", attrName) + "Empty";
+
+ ObjectModelOperation isEmptyInterfaceOperation =
+ addOperation(outputInterface, isEmptyMethodName,
boolean.class, ObjectModelJavaModifier.PACKAGE);
// Implementation
- ObjectModelOperation implOperation = createImplOperation(interfaceOperation);
+ ObjectModelOperation isEmptyOperationImpl = createImplOperation(isEmptyInterfaceOperation);
- setOperationBody(implOperation, ""
+ setOperationBody(isEmptyOperationImpl, ""
/*{
int size = <%=sizeMethodName%>();
return size == 0;
}*/
);
+
+ // isNotEmpty Interface operation
+ ObjectModelOperation isNotEmptyInterfaceOperation =
+ addOperation(outputInterface, getJavaBeanMethodName("is", attrName)+ "NotEmpty",
+ boolean.class, ObjectModelJavaModifier.PACKAGE);
+
+ // Implementation
+ ObjectModelOperation isNotEmptyOperationImpl = createImplOperation(isNotEmptyInterfaceOperation);
+
+ setOperationBody(isNotEmptyOperationImpl, ""
+/*{
+ boolean empty = <%=isEmptyMethodName%>();
+ return ! empty;
+ }*/
+ );
}
// -------------------------------------------------------------------------
1
0
r2956 - in trunk/topia-it/src/test/java/org/nuiton/topia/persistence: . internal
by tchemit@users.nuiton.org 20 Dec '13
by tchemit@users.nuiton.org 20 Dec '13
20 Dec '13
Author: tchemit
Date: 2013-12-20 17:27:35 +0100 (Fri, 20 Dec 2013)
New Revision: 2956
Url: http://nuiton.org/projects/topia/repository/revisions/2956
Log:
refs #2893: Refactor packages (third pass)
Added:
trunk/topia-it/src/test/java/org/nuiton/topia/persistence/internal/
trunk/topia-it/src/test/java/org/nuiton/topia/persistence/internal/TopiaDaoTest.java
Removed:
trunk/topia-it/src/test/java/org/nuiton/topia/persistence/TopiaDaoTest.java
Deleted: trunk/topia-it/src/test/java/org/nuiton/topia/persistence/TopiaDaoTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/persistence/TopiaDaoTest.java 2013-12-20 16:19:35 UTC (rev 2955)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/persistence/TopiaDaoTest.java 2013-12-20 16:27:35 UTC (rev 2956)
@@ -1,204 +0,0 @@
-/*
- * #%L
- * ToPIA :: Persistence
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2004 - 2010 CodeLutin, Chatellier Eric
- * %%
- * 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%
- */
-
-package org.nuiton.topia.persistence;
-
-import java.util.List;
-import java.util.Map;
-
-import org.hamcrest.CoreMatchers;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.nuiton.topia.it.legacy.TopiaDatabase;
-import org.nuiton.topia.it.legacy.TopiaTestTopiaPersistenceContext;
-import org.nuiton.topia.it.legacy.test.entities.Person;
-import org.nuiton.topia.it.legacy.test.entities.PersonTopiaDao;
-
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-
-/**
- * Test on {@link TopiaDao}.
- * <p/>
- * Last update : $Date$
- * By : $Author$
- *
- * @author chatellier
- * @version $Revision$
- */
-public class TopiaDaoTest { // Should not be located in topia-it module
-
- @Rule
- public final TopiaDatabase db = new TopiaDatabase();
-
- protected TopiaTestTopiaPersistenceContext context;
-
- protected PersonTopiaDao dao;
-
- @Before
- public void setup() throws TopiaException {
-
- context = db.beginTransaction();
- dao = context.getPersonDao();
- }
-
- /**
- * Test de creer une entité et de verifier qu'elle est
- * présente dans la persistence au sein de la transaction.
- *
- * @throws Exception if any exception while test
- */
- @Test
- public void testCreateAndFindInTransaction() throws Exception {
-
- // appel 1 find all
- createPerson("toto");
- List<Person> allPerson = dao.findAll();
- Assert.assertEquals(1, allPerson.size());
- context.commit();
-
- // recherce la personne créée dans la même transaction
- Person person2 = createPerson("titi");
- allPerson = dao.findAll();
- Assert.assertEquals(2, allPerson.size());
- Assert.assertThat(allPerson, CoreMatchers.hasItem(person2));
-
- context.rollback();
-
- // meme test apres roolback
- Person person3 = createPerson("tata");
- allPerson = dao.findAll();
- Assert.assertEquals(2, allPerson.size());
- Assert.assertThat(allPerson, CoreMatchers.hasItem(person3));
-
- context.commit();
- }
-
- @Test
- public void findAllLazyByQuery() throws TopiaException {
-
- Assert.assertEquals(dao.count(), 0);
-
- createPersons(101);
-
- Map<String, Object> emptyArgs = Maps.newHashMap();
-
- dao.setBatchSize(100);
- Iterable<Person> allByLazy = dao.findAllLazy(
- "FROM " + dao.getTopiaEntityEnum().getImplementationFQN() + " ORDER BY id", emptyArgs);
-
- List<Person> actual = Lists.newArrayList();
-
- for (Person person : allByLazy) {
- actual.add(person);
- }
- Assert.assertEquals(dao.count(), actual.size());
-
- dao.setBatchSize(54);
- allByLazy = dao.findAllLazy(
- "FROM " + dao.getTopiaEntityEnum().getImplementationFQN() + " ORDER BY id", emptyArgs);
-
- actual = Lists.newArrayList();
-
- for (Person person : allByLazy) {
- actual.add(person);
- }
- Assert.assertEquals(dao.count(), actual.size());
-
- dao.setBatchSize(49);
- allByLazy = dao.findAllLazy(
- "FROM " + dao.getTopiaEntityEnum().getImplementationFQN() + " ORDER BY id", emptyArgs);
-
- actual = Lists.newArrayList();
-
- for (Person person : allByLazy) {
- actual.add(person);
- }
- Assert.assertEquals(dao.count(), actual.size());
-
- dao.setBatchSize(101);
- allByLazy = dao.findAllLazy(
- "FROM " + dao.getTopiaEntityEnum().getImplementationFQN() + " ORDER BY id", emptyArgs);
-
- actual = Lists.newArrayList();
-
- for (Person person : allByLazy) {
- actual.add(person);
- }
- Assert.assertEquals(dao.count(), actual.size());
-
- dao.setBatchSize(102);
- allByLazy = dao.findAllLazy(
- "FROM " + dao.getTopiaEntityEnum().getImplementationFQN() + " ORDER BY id", emptyArgs);
-
- actual = Lists.newArrayList();
-
- for (Person person : allByLazy) {
- actual.add(person);
- }
- Assert.assertEquals(dao.count(), actual.size());
- }
-
- @Test
- public void iterateOnTopiaDAO() throws TopiaException {
-
- createPersons(1999);
-
- List<Person> excepted = dao.findAll();
-
- List<Person> actual = Lists.newArrayList();
-
- for (Person person : dao) {
- Assert.assertThat(excepted, CoreMatchers.hasItem(person));
- actual.add(person);
- }
- Assert.assertEquals(excepted.size(), actual.size());
-
- dao.setBatchSize(54);
-
- actual = Lists.newArrayList();
-
- for (Person person : dao) {
- Assert.assertThat(excepted, CoreMatchers.hasItem(person));
- actual.add(person);
- }
- Assert.assertEquals(excepted.size(), actual.size());
-
- }
-
- protected void createPersons(int number) throws TopiaException {
- for (int i = 0; i < number; i++) {
- createPerson("toto" + i);
- }
-
- context.commit();
- }
-
- protected Person createPerson(String name) throws TopiaException {
- return dao.create(Person.PROPERTY_NAME, name);
- }
-}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/persistence/internal/TopiaDaoTest.java (from rev 2954, trunk/topia-it/src/test/java/org/nuiton/topia/persistence/TopiaDaoTest.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/persistence/internal/TopiaDaoTest.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/persistence/internal/TopiaDaoTest.java 2013-12-20 16:27:35 UTC (rev 2956)
@@ -0,0 +1,206 @@
+/*
+ * #%L
+ * ToPIA :: Persistence
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2004 - 2010 CodeLutin, Chatellier Eric
+ * %%
+ * 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%
+ */
+
+package org.nuiton.topia.persistence.internal;
+
+import java.util.List;
+import java.util.Map;
+
+import org.hamcrest.CoreMatchers;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.nuiton.topia.it.legacy.TopiaDatabase;
+import org.nuiton.topia.it.legacy.TopiaTestTopiaPersistenceContext;
+import org.nuiton.topia.it.legacy.test.entities.Person;
+import org.nuiton.topia.it.legacy.test.entities.PersonTopiaDao;
+
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import org.nuiton.topia.persistence.TopiaDao;
+import org.nuiton.topia.persistence.TopiaException;
+
+/**
+ * Test on {@link TopiaDao}.
+ * <p/>
+ * Last update : $Date$
+ * By : $Author$
+ *
+ * @author chatellier
+ * @version $Revision$
+ */
+public class TopiaDaoTest { // Should not be located in topia-it module
+
+ @Rule
+ public final TopiaDatabase db = new TopiaDatabase();
+
+ protected TopiaTestTopiaPersistenceContext context;
+
+ protected PersonTopiaDao dao;
+
+ @Before
+ public void setup() throws TopiaException {
+
+ context = db.beginTransaction();
+ dao = context.getPersonDao();
+ }
+
+ /**
+ * Test de creer une entité et de verifier qu'elle est
+ * présente dans la persistence au sein de la transaction.
+ *
+ * @throws Exception if any exception while test
+ */
+ @Test
+ public void testCreateAndFindInTransaction() throws Exception {
+
+ // appel 1 find all
+ createPerson("toto");
+ List<Person> allPerson = dao.findAll();
+ Assert.assertEquals(1, allPerson.size());
+ context.commit();
+
+ // recherce la personne créée dans la même transaction
+ Person person2 = createPerson("titi");
+ allPerson = dao.findAll();
+ Assert.assertEquals(2, allPerson.size());
+ Assert.assertThat(allPerson, CoreMatchers.hasItem(person2));
+
+ context.rollback();
+
+ // meme test apres roolback
+ Person person3 = createPerson("tata");
+ allPerson = dao.findAll();
+ Assert.assertEquals(2, allPerson.size());
+ Assert.assertThat(allPerson, CoreMatchers.hasItem(person3));
+
+ context.commit();
+ }
+
+ @Test
+ public void findAllLazyByQuery() throws TopiaException {
+
+ Assert.assertEquals(dao.count(), 0);
+
+ createPersons(101);
+
+ Map<String, Object> emptyArgs = Maps.newHashMap();
+
+ dao.setBatchSize(100);
+ Iterable<Person> allByLazy = dao.findAllLazy(
+ "FROM " + dao.getTopiaEntityEnum().getImplementationFQN() + " ORDER BY id", emptyArgs);
+
+ List<Person> actual = Lists.newArrayList();
+
+ for (Person person : allByLazy) {
+ actual.add(person);
+ }
+ Assert.assertEquals(dao.count(), actual.size());
+
+ dao.setBatchSize(54);
+ allByLazy = dao.findAllLazy(
+ "FROM " + dao.getTopiaEntityEnum().getImplementationFQN() + " ORDER BY id", emptyArgs);
+
+ actual = Lists.newArrayList();
+
+ for (Person person : allByLazy) {
+ actual.add(person);
+ }
+ Assert.assertEquals(dao.count(), actual.size());
+
+ dao.setBatchSize(49);
+ allByLazy = dao.findAllLazy(
+ "FROM " + dao.getTopiaEntityEnum().getImplementationFQN() + " ORDER BY id", emptyArgs);
+
+ actual = Lists.newArrayList();
+
+ for (Person person : allByLazy) {
+ actual.add(person);
+ }
+ Assert.assertEquals(dao.count(), actual.size());
+
+ dao.setBatchSize(101);
+ allByLazy = dao.findAllLazy(
+ "FROM " + dao.getTopiaEntityEnum().getImplementationFQN() + " ORDER BY id", emptyArgs);
+
+ actual = Lists.newArrayList();
+
+ for (Person person : allByLazy) {
+ actual.add(person);
+ }
+ Assert.assertEquals(dao.count(), actual.size());
+
+ dao.setBatchSize(102);
+ allByLazy = dao.findAllLazy(
+ "FROM " + dao.getTopiaEntityEnum().getImplementationFQN() + " ORDER BY id", emptyArgs);
+
+ actual = Lists.newArrayList();
+
+ for (Person person : allByLazy) {
+ actual.add(person);
+ }
+ Assert.assertEquals(dao.count(), actual.size());
+ }
+
+ @Test
+ public void iterateOnTopiaDAO() throws TopiaException {
+
+ createPersons(1999);
+
+ List<Person> excepted = dao.findAll();
+
+ List<Person> actual = Lists.newArrayList();
+
+ for (Person person : dao) {
+ Assert.assertThat(excepted, CoreMatchers.hasItem(person));
+ actual.add(person);
+ }
+ Assert.assertEquals(excepted.size(), actual.size());
+
+ dao.setBatchSize(54);
+
+ actual = Lists.newArrayList();
+
+ for (Person person : dao) {
+ Assert.assertThat(excepted, CoreMatchers.hasItem(person));
+ actual.add(person);
+ }
+ Assert.assertEquals(excepted.size(), actual.size());
+
+ }
+
+ protected void createPersons(int number) throws TopiaException {
+ for (int i = 0; i < number; i++) {
+ createPerson("toto" + i);
+ }
+
+ context.commit();
+ }
+
+ protected Person createPerson(String name) throws TopiaException {
+ return dao.create(Person.PROPERTY_NAME, name);
+ }
+}
1
0
20 Dec '13
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(a)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(a)codelutin.com>
- * @author Arnaud Thimel <thimel(a)codelutin.com>
- * @author Tony CHEMIT <chemit(a)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(a)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(a)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(a)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(a)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(a)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(a)codelutin.com>
+ * @author Arnaud Thimel <thimel(a)codelutin.com>
+ * @author Tony CHEMIT <chemit(a)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(a)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(a)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;
1
0
Author: tchemit
Date: 2013-12-20 17:07:29 +0100 (Fri, 20 Dec 2013)
New Revision: 2954
Url: http://nuiton.org/projects/topia/repository/revisions/2954
Log:
refs #2977: Extract csv api to a new topia-service-csv (move code from persistence module to service csv)
Added:
trunk/topia-service-csv/
trunk/topia-service-csv/LICENSE.txt
trunk/topia-service-csv/README.txt
trunk/topia-service-csv/changelog.txt
trunk/topia-service-csv/pom.xml
trunk/topia-service-csv/src/
trunk/topia-service-csv/src/main/
trunk/topia-service-csv/src/main/java/
trunk/topia-service-csv/src/main/java/org/
trunk/topia-service-csv/src/main/java/org/nuiton/
trunk/topia-service-csv/src/main/java/org/nuiton/topia/
trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/
trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/
trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/CsvProgressModel.java
trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/EntityCsvModel.java
trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/TopiaCsvCommons.java
trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/in/
trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/in/AbstractImportModel.java
trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/in/CsvFileImportResult.java
trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/in/CsvImportResult.java
trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/in/EntityAssociationImportModel.java
trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/in/ImportModelFactory.java
trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/in/ImportStrategy.java
trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/in/TopiaCsvImports.java
trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/in/package-info.java
trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/out/
trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/out/EntityAssociationExportModel.java
trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/out/ExportEntityVisitor.java
trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/out/ExportModelFactory.java
trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/out/PrepareDataForExport.java
trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/out/TopiaCsvExports.java
trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/out/package-info.java
trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/package-info.java
trunk/topia-service-csv/src/main/resources/
trunk/topia-service-csv/src/test/
trunk/topia-service-csv/src/test/java/
trunk/topia-service-csv/src/test/java/org/
trunk/topia-service-csv/src/test/java/org/nuiton/
trunk/topia-service-csv/src/test/java/org/nuiton/topia/
trunk/topia-service-csv/src/test/resources/
Removed:
trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/csv/
Modified:
trunk/pom.xml
trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/TopiaTestDaoSupplier.java
trunk/topia-persistence/pom.xml
trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaApplicationContext.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaConfigurationConstants.java
trunk/topia-service-migration/pom.xml
Modified: trunk/pom.xml
===================================================================
--- trunk/pom.xml 2013-12-20 16:05:54 UTC (rev 2953)
+++ trunk/pom.xml 2013-12-20 16:07:29 UTC (rev 2954)
@@ -207,6 +207,7 @@
<module>topia-it</module>
<module>topia-service-replication</module>
<module>topia-service-migration</module>
+ <module>topia-service-csv</module>
</modules>
<scm>
Modified: trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/TopiaTestDaoSupplier.java
===================================================================
--- trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/TopiaTestDaoSupplier.java 2013-12-20 16:05:54 UTC (rev 2953)
+++ trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/TopiaTestDaoSupplier.java 2013-12-20 16:07:29 UTC (rev 2954)
@@ -1,5 +1,29 @@
package org.nuiton.topia.it.legacy;
+/*
+ * #%L
+ * ToPIA :: IT
+ * $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%
+ */
+
/**
* Created on 12/20/13.
*
Property changes on: trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/TopiaTestDaoSupplier.java
___________________________________________________________________
Modified: svn:keywords
- Author Date Id Revision
+ Author Date Id Revision HeadURL
Modified: trunk/topia-persistence/pom.xml
===================================================================
--- trunk/topia-persistence/pom.xml 2013-12-20 16:05:54 UTC (rev 2953)
+++ trunk/topia-persistence/pom.xml 2013-12-20 16:07:29 UTC (rev 2954)
@@ -48,16 +48,6 @@
</dependency>
<dependency>
- <groupId>org.nuiton</groupId>
- <artifactId>nuiton-csv</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.nuiton</groupId>
- <artifactId>nuiton-decorator</artifactId>
- </dependency>
-
- <dependency>
<groupId>org.nuiton.i18n</groupId>
<artifactId>nuiton-i18n</artifactId>
<scope>test</scope>
@@ -84,11 +74,6 @@
</dependency>
<dependency>
- <groupId>commons-io</groupId>
- <artifactId>commons-io</artifactId>
- </dependency>
-
- <dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaApplicationContext.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaApplicationContext.java 2013-12-20 16:05:54 UTC (rev 2953)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaApplicationContext.java 2013-12-20 16:07:29 UTC (rev 2954)
@@ -1,5 +1,29 @@
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 com.google.common.collect.ImmutableMap;
import org.nuiton.topia.persistence.support.TopiaListenableSupport;
import org.nuiton.topia.persistence.support.TopiaServiceSupport;
Property changes on: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaApplicationContext.java
___________________________________________________________________
Modified: svn:keywords
- Author Date Id Revision
+ Author Date Id Revision HeadURL
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaConfigurationConstants.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaConfigurationConstants.java 2013-12-20 16:05:54 UTC (rev 2953)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaConfigurationConstants.java 2013-12-20 16:07:29 UTC (rev 2954)
@@ -1,5 +1,29 @@
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.hibernate.cfg.Environment;
/**
Property changes on: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaConfigurationConstants.java
___________________________________________________________________
Modified: svn:keywords
- Author Date Id Revision
+ Author Date Id Revision HeadURL
Property changes on: trunk/topia-service-csv
___________________________________________________________________
Added: svn:ignore
+ target
.idea
*.ipr
*.iws
*.iml
Added: trunk/topia-service-csv/LICENSE.txt
===================================================================
--- trunk/topia-service-csv/LICENSE.txt (rev 0)
+++ trunk/topia-service-csv/LICENSE.txt 2013-12-20 16:07:29 UTC (rev 2954)
@@ -0,0 +1,166 @@
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+
+ This version of the GNU Lesser General Public License incorporates
+the terms and conditions of version 3 of the GNU General Public
+License, supplemented by the additional permissions listed below.
+
+ 0. Additional Definitions.
+
+ As used herein, "this License" refers to version 3 of the GNU Lesser
+General Public License, and the "GNU GPL" refers to version 3 of the GNU
+General Public License.
+
+ "The Library" refers to a covered work governed by this License,
+other than an Application or a Combined Work as defined below.
+
+ An "Application" is any work that makes use of an interface provided
+by the Library, but which is not otherwise based on the Library.
+Defining a subclass of a class defined by the Library is deemed a mode
+of using an interface provided by the Library.
+
+ A "Combined Work" is a work produced by combining or linking an
+Application with the Library. The particular version of the Library
+with which the Combined Work was made is also called the "Linked
+Version".
+
+ The "Minimal Corresponding Source" for a Combined Work means the
+Corresponding Source for the Combined Work, excluding any source code
+for portions of the Combined Work that, considered in isolation, are
+based on the Application, and not on the Linked Version.
+
+ The "Corresponding Application Code" for a Combined Work means the
+object code and/or source code for the Application, including any data
+and utility programs needed for reproducing the Combined Work from the
+Application, but excluding the System Libraries of the Combined Work.
+
+ 1. Exception to Section 3 of the GNU GPL.
+
+ You may convey a covered work under sections 3 and 4 of this License
+without being bound by section 3 of the GNU GPL.
+
+ 2. Conveying Modified Versions.
+
+ If you modify a copy of the Library, and, in your modifications, a
+facility refers to a function or data to be supplied by an Application
+that uses the facility (other than as an argument passed when the
+facility is invoked), then you may convey a copy of the modified
+version:
+
+ a) under this License, provided that you make a good faith effort to
+ ensure that, in the event an Application does not supply the
+ function or data, the facility still operates, and performs
+ whatever part of its purpose remains meaningful, or
+
+ b) under the GNU GPL, with none of the additional permissions of
+ this License applicable to that copy.
+
+ 3. Object Code Incorporating Material from Library Header Files.
+
+ The object code form of an Application may incorporate material from
+a header file that is part of the Library. You may convey such object
+code under terms of your choice, provided that, if the incorporated
+material is not limited to numerical parameters, data structure
+layouts and accessors, or small macros, inline functions and templates
+(ten or fewer lines in length), you do both of the following:
+
+ a) Give prominent notice with each copy of the object code that the
+ Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the object code with a copy of the GNU GPL and this license
+ document.
+
+ 4. Combined Works.
+
+ You may convey a Combined Work under terms of your choice that,
+taken together, effectively do not restrict modification of the
+portions of the Library contained in the Combined Work and reverse
+engineering for debugging such modifications, if you also do each of
+the following:
+
+ a) Give prominent notice with each copy of the Combined Work that
+ the Library is used in it and that the Library and its use are
+ covered by this License.
+
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
+ document.
+
+ c) For a Combined Work that displays copyright notices during
+ execution, include the copyright notice for the Library among
+ these notices, as well as a reference directing the user to the
+ copies of the GNU GPL and this license document.
+
+ d) Do one of the following:
+
+ 0) Convey the Minimal Corresponding Source under the terms of this
+ License, and the Corresponding Application Code in a form
+ suitable for, and under terms that permit, the user to
+ recombine or relink the Application with a modified version of
+ the Linked Version to produce a modified Combined Work, in the
+ manner specified by section 6 of the GNU GPL for conveying
+ Corresponding Source.
+
+ 1) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (a) uses at run time
+ a copy of the Library already present on the user's computer
+ system, and (b) will operate properly with a modified version
+ of the Library that is interface-compatible with the Linked
+ Version.
+
+ e) Provide Installation Information, but only if you would otherwise
+ be required to provide such information under section 6 of the
+ GNU GPL, and only to the extent that such information is
+ necessary to install and execute a modified version of the
+ Combined Work produced by recombining or relinking the
+ Application with a modified version of the Linked Version. (If
+ you use option 4d0, the Installation Information must accompany
+ the Minimal Corresponding Source and Corresponding Application
+ Code. If you use option 4d1, you must provide the Installation
+ Information in the manner specified by section 6 of the GNU GPL
+ for conveying Corresponding Source.)
+
+ 5. Combined Libraries.
+
+ You may place library facilities that are a work based on the
+Library side by side in a single library together with other library
+facilities that are not Applications and are not covered by this
+License, and convey such a combined library under terms of your
+choice, if you do both of the following:
+
+ a) Accompany the combined library with a copy of the same work based
+ on the Library, uncombined with any other library facilities,
+ conveyed under the terms of this License.
+
+ b) Give prominent notice with the combined library that part of it
+ is a work based on the Library, and explaining where to find the
+ accompanying uncombined form of the same work.
+
+ 6. Revised Versions of the GNU Lesser General Public License.
+
+ The Free Software Foundation may publish revised and/or new versions
+of the GNU Lesser General Public License from time to time. Such new
+versions will be similar in spirit to the present version, but may
+differ in detail to address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Library as you received it specifies that a certain numbered version
+of the GNU Lesser General Public License "or any later version"
+applies to it, you have the option of following the terms and
+conditions either of that published version or of any later version
+published by the Free Software Foundation. If the Library as you
+received it does not specify a version number of the GNU Lesser
+General Public License, you may choose any version of the GNU Lesser
+General Public License ever published by the Free Software Foundation.
+
+ If the Library as you received it specifies that a proxy can decide
+whether future versions of the GNU Lesser General Public License shall
+apply, that proxy's public statement of acceptance of any version is
+permanent authorization for you to choose that version for the
+Library.
+
Property changes on: trunk/topia-service-csv/LICENSE.txt
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Added: trunk/topia-service-csv/README.txt
===================================================================
--- trunk/topia-service-csv/README.txt (rev 0)
+++ trunk/topia-service-csv/README.txt 2013-12-20 16:07:29 UTC (rev 2954)
@@ -0,0 +1,2 @@
+To deploy new version of pom: mvn deploy
+To install localy: mvn install
Property changes on: trunk/topia-service-csv/README.txt
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Added: trunk/topia-service-csv/changelog.txt
===================================================================
--- trunk/topia-service-csv/changelog.txt (rev 0)
+++ trunk/topia-service-csv/changelog.txt 2013-12-20 16:07:29 UTC (rev 2954)
@@ -0,0 +1,63 @@
+2.2.1 chemit 20090903
+
+ * [FIX #38] manual migration service does not work on windows OS
+ * [FEATURE #40] clean manual migration service
+ * [FEATURE #42] add i18n in migration service
+
+-- chemit -- Thu, 03 Sep 2009 18:51:54 +0200
+
+2.2.0
+ * integrate in ToPIA project as org.nuiton.topia:topia-service-migration
+ * introduce a simpler migration service ManualMigrationEngine
+ - do only manual sql migration (using ToPIA persistence api)
+ - use only one callback handler of type ManualMigrationCallback
+ - use a ToPIA TMSVersion entity in package org.nuiton.migration
+
+1.1.0
+ * migrate to nuiton
+
+1.0.3 chemit 20090511
+ * bump versions (lutinproject, lutinutil, topia, maven-license-switcher-plugin)
+ * use doxia-modules-jrst instead of maven-jrst-plugin
+ * improve download section on site
+
+1.0.2 chemit 20090220
+* 20090220 [chemit] - use lutinproject 3.4
+
+1.0.1 chemit 20081215
+* 20081215 [chemit] - new release for isis-fish :) follow release of topia
+
+1.0 chemit 20081210
+ * 20081205 [chemit] - improve poms, use lutinproject 3.2, migrate tests to JUnit4
+
+0.9.1
+ * [chatellier] Correction d'un bug de recherche de mapping sous windows (\)
+
+0.9
+ * <chemit> use lutinproject 3.0 + clean pom + use topia 2.0.27
+ * <poussin> modif dans service de migration pour permettre a l'app de
+ faire la migration via le callback
+
+0.8
+
+ * 20071120 [chatellier] update topia-service site
+ * 20071115 [chatellier] apply hibernate code style to open/close session and
+ transaction
+ * 20071115 [chatellier] refractoring separate specifique topia service
+ and real migration code
+ * 20071115 [chatellier] add schema existance detection support
+ and dont migrate if there is no table
+ * 20071111 [chatellier] add support for callback handler
+ * 20071111 [chatellier] use cascade to calculate dependencies order
+ * 20071109 [chatellier] change schema creation process to
+ correct duplicate foreign key creation
+ * 20071109 [chatellier] add inherit support to calculate dependancies
+
+0.6 ??? ???
+
+ * 20070426 [chatellier] use lutinutil.Resources.getUrls() to get mappings
+ * 20070426 [chatellier] change finder migration to use Class.forName()
+ * 20070420 [chatellier] remove the 'V' letter in old mapping directories name
+ * 20070420 [chatellier] add support to look for hibernate mapping in a tree
+ structure of directories
+ * 20070418 [chatellier] add migration service
\ No newline at end of file
Property changes on: trunk/topia-service-csv/changelog.txt
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Added: trunk/topia-service-csv/pom.xml
===================================================================
--- trunk/topia-service-csv/pom.xml (rev 0)
+++ trunk/topia-service-csv/pom.xml 2013-12-20 16:07:29 UTC (rev 2954)
@@ -0,0 +1,141 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ #%L
+ ToPIA :: Service Migration
+
+ $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%
+ -->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>org.nuiton</groupId>
+ <artifactId>topia</artifactId>
+ <version>3.0-SNAPSHOT</version>
+ </parent>
+
+ <groupId>org.nuiton.topia</groupId>
+ <artifactId>topia-service-csv</artifactId>
+ <name>ToPIA :: Service Csv</name>
+ <description>To import or export with csv format</description>
+
+ <properties>
+ <!-- Post Release configuration -->
+ <skipPostRelease>false</skipPostRelease>
+ </properties>
+
+ <dependencies>
+
+ <!-- Sibling dependencies -->
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>topia-persistence</artifactId>
+ <version>${project.version}</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>topia-junit</artifactId>
+ <version>${project.version}</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.nuiton</groupId>
+ <artifactId>nuiton-utils</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.nuiton</groupId>
+ <artifactId>nuiton-decorator</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.nuiton</groupId>
+ <artifactId>nuiton-csv</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-lang3</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>commons-collections</groupId>
+ <artifactId>commons-collections</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>commons-io</groupId>
+ <artifactId>commons-io</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>commons-logging</groupId>
+ <artifactId>commons-logging</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.hibernate</groupId>
+ <artifactId>hibernate-core</artifactId>
+ </dependency>
+
+ <!-- Depencies for test-->
+ <dependency>
+ <groupId>com.h2database</groupId>
+ <artifactId>h2</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-log4j12</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </dependency>
+
+ </dependencies>
+
+ <build>
+ <resources>
+
+ <resource>
+ <directory>${maven.src.dir}/main/resources</directory>
+ <includes>
+ <include>**/*.hbm.xml</include>
+ <include>**/*.properties</include>
+ </includes>
+ </resource>
+
+ </resources>
+ <plugins>
+
+ </plugins>
+ </build>
+
+</project>
Property changes on: trunk/topia-service-csv/pom.xml
___________________________________________________________________
Added: svn:mime-type
+ text/xml
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Copied: trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/CsvProgressModel.java (from rev 2939, trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/csv/CsvProgressModel.java)
===================================================================
--- trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/CsvProgressModel.java (rev 0)
+++ trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/CsvProgressModel.java 2013-12-20 16:07:29 UTC (rev 2954)
@@ -0,0 +1,46 @@
+package org.nuiton.topia.service.csv;
+
+/*
+ * #%L
+ * ToPIA :: Service Csv
+ * $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.Serializable;
+
+/**
+ * Csv progress model contract.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.6.14
+ */
+public interface CsvProgressModel extends Serializable {
+
+ long getNbSteps();
+
+ void setNbSteps(long nbSteps);
+
+ float getProgress();
+
+ void setProgress(float progress);
+
+ void incrementsProgress();
+}
Copied: trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/EntityCsvModel.java (from rev 2939, trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/csv/EntityCsvModel.java)
===================================================================
--- trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/EntityCsvModel.java (rev 0)
+++ trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/EntityCsvModel.java 2013-12-20 16:07:29 UTC (rev 2954)
@@ -0,0 +1,255 @@
+package org.nuiton.topia.service.csv;
+
+/*
+ * #%L
+ * ToPIA :: Service Csv
+ * $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 com.google.common.base.Function;
+import com.google.common.collect.Maps;
+import org.nuiton.topia.persistence.TopiaEntities;
+import org.nuiton.topia.persistence.TopiaEntity;
+import org.nuiton.topia.persistence.TopiaEntityEnum;
+import org.nuiton.topia.persistence.metadata.TableMeta;
+import org.nuiton.csv.ValueParserFormatter;
+import org.nuiton.csv.ext.AbstractImportExportModel;
+import org.nuiton.decorator.Decorator;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Date;
+import java.util.Map;
+
+/**
+ * A model to import / export entities into csv files.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 0.2
+ */
+public class EntityCsvModel<T extends TopiaEntityEnum, E extends TopiaEntity> extends AbstractImportExportModel<E> {
+
+ protected final TableMeta<T> tableMeta;
+
+ protected boolean useOrdinalForEnum;
+
+ public static <T extends TopiaEntityEnum, E extends TopiaEntity> EntityCsvModel<T, E> newModel(
+ char separator,
+ TableMeta<T> tableMeta) {
+ return new EntityCsvModel<T, E>(separator, tableMeta);
+ }
+
+ public static <T extends TopiaEntityEnum, E extends TopiaEntity> EntityCsvModel<T, E> newModel(
+ char separator,
+ TableMeta<T> tableMeta,
+ String idHeader) {
+ return new EntityCsvModel<T, E>(separator, tableMeta, idHeader);
+ }
+
+ @Override
+ public E newEmptyInstance() {
+ return (E) tableMeta.newEntity();
+ }
+
+ public void setUseOrdinalForEnum(boolean useOrdinalForEnum) {
+ this.useOrdinalForEnum = useOrdinalForEnum;
+ }
+
+ public void addForeignKeyForExport(String propertyName,
+ Class<TopiaEntity> entityType) {
+
+ Map<String, TopiaEntity> universe = Collections.emptyMap();
+
+ newColumnForExport(propertyName,
+ TopiaCsvCommons.newForeignKeyValue(entityType,
+ propertyName,
+ universe)
+ );
+ }
+
+ public <T> void addDecoratedForeignKeyForExport(String headerName,
+ String propertyName,
+ Decorator<T> decorator) {
+ modelBuilder.newColumnForExport(
+ headerName,
+ propertyName,
+ TopiaCsvCommons.newForeignKeyDecoratedValue(decorator));
+ }
+
+ public <E extends TopiaEntity> void addForeignKeyForImport(String headerName,
+ String propertyName,
+ Class<E> entityType,
+ Collection<E> entities,
+ Function<E, String> transform) {
+
+ Map<String, E> universe = Maps.uniqueIndex(entities, transform);
+
+ newMandatoryColumn(headerName,
+ propertyName,
+ TopiaCsvCommons.newForeignKeyValue(entityType,
+ propertyName,
+ universe)
+ );
+ }
+
+ public <E extends TopiaEntity> void addForeignKeyForAssociationForImport(String headerName,
+ String propertyName,
+ Class<E> entityType,
+ Collection<E> entities,
+ Function<E, String> transform) {
+
+ Map<String, E> universe = Maps.uniqueIndex(entities, transform);
+
+ newMandatoryColumn(
+ headerName,
+ propertyName,
+ TopiaCsvCommons.newForeignKeyValueAssociation(entityType,
+ propertyName,
+ universe)
+ );
+ }
+
+ public <E extends TopiaEntity> void addForeignKeyForImport(String propertyName,
+ Class<E> entityType,
+ Collection<E> entities) {
+
+ Map<String, E> universe = Maps.uniqueIndex(entities,
+ TopiaEntities.getTopiaIdFunction());
+
+ newMandatoryColumn(propertyName,
+ TopiaCsvCommons.newForeignKeyValue(entityType,
+ propertyName,
+ universe)
+ );
+ }
+
+ public <E extends TopiaEntity> void addForeignKeyForImport(String propertyName,
+ Class<E> entityType,
+ Map<String, E> universe) {
+
+ newMandatoryColumn(propertyName,
+ TopiaCsvCommons.newForeignKeyValue(entityType,
+ propertyName,
+ universe)
+ );
+ }
+ public void addDefaultColumn(String propertyName, Class<?> type) {
+ addDefaultColumn(propertyName, propertyName, type);
+ }
+
+ public void addDefaultColumn(String headerName,
+ String propertyName,
+ Class<?> type) {
+
+ if (Date.class.equals(type)) {
+ newColumnForImportExport(
+ headerName,
+ propertyName,
+ TopiaCsvCommons.DAY_TIME_SECOND_WITH_TIMESTAMP);
+ } else if (double.class.equals(type)) {
+ newColumnForImportExport(
+ headerName,
+ propertyName,
+ TopiaCsvCommons.DOUBLE_PRIMITIVE);
+ } else if (Double.class.equals(type)) {
+ newColumnForImportExport(
+ headerName,
+ propertyName,
+ TopiaCsvCommons.DOUBLE);
+ } else if (long.class.equals(type)) {
+ newColumnForImportExport(
+ headerName,
+ propertyName,
+ TopiaCsvCommons.PRIMITIVE_LONG);
+ } else if (Long.class.equals(type)) {
+ newColumnForImportExport(
+ headerName,
+ propertyName,
+ TopiaCsvCommons.LONG);
+ } else if (float.class.equals(type)) {
+ newColumnForImportExport(
+ headerName,
+ propertyName,
+ TopiaCsvCommons.PRIMITIVE_FLOAT);
+ } else if (Float.class.equals(type)) {
+ newColumnForImportExport(
+ headerName,
+ propertyName,
+ TopiaCsvCommons.FLOAT);
+ } else if (int.class.equals(type)) {
+ newColumnForImportExport(
+ headerName,
+ propertyName,
+ TopiaCsvCommons.PRIMITIVE_INTEGER);
+ } else if (Integer.class.equals(type)) {
+ newColumnForImportExport(
+ headerName,
+ propertyName,
+ TopiaCsvCommons.INTEGER);
+ } else if (boolean.class.equals(type)) {
+ newColumnForImportExport(
+ headerName,
+ propertyName,
+ TopiaCsvCommons.PRIMITIVE_BOOLEAN);
+ } else if (Boolean.class.equals(type)) {
+ newColumnForImportExport(
+ headerName,
+ propertyName,
+ TopiaCsvCommons.BOOLEAN);
+ } else if (String.class.equals(type)) {
+ newColumnForImportExport(
+ headerName,
+ propertyName);
+ } else if (type.isEnum()) {
+
+ Class<Enum> enumType = (Class<Enum>) type;
+ ValueParserFormatter<Enum> valueParserFormatter;
+ if (useOrdinalForEnum) {
+ valueParserFormatter =
+ TopiaCsvCommons.newEnumByOrdinalParserFormatter(enumType);
+ } else {
+ valueParserFormatter =
+ TopiaCsvCommons.newEnumByNameParserFormatter(enumType);
+ }
+
+ newColumnForImportExport(headerName,
+ propertyName,
+ valueParserFormatter);
+
+ } else {
+
+ throw new IllegalStateException(String.format(
+ "For header %s, property %s, no specific handler " +
+ "found for type %s", headerName, propertyName, type));
+ }
+ }
+
+ protected EntityCsvModel(char separator, TableMeta<T> tableMeta) {
+ super(separator);
+ this.tableMeta = tableMeta;
+ }
+
+ protected EntityCsvModel(char separator, TableMeta<T> tableMeta,
+ String idHeader) {
+ this(separator, tableMeta);
+ newColumnForImportExport(idHeader, TopiaEntity.PROPERTY_TOPIA_ID);
+ }
+}
\ No newline at end of file
Copied: trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/TopiaCsvCommons.java (from rev 2949, trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/csv/TopiaCsvCommons.java)
===================================================================
--- trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/TopiaCsvCommons.java (rev 0)
+++ trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/TopiaCsvCommons.java 2013-12-20 16:07:29 UTC (rev 2954)
@@ -0,0 +1,276 @@
+package org.nuiton.topia.service.csv;
+
+/*
+ * #%L
+ * ToPIA :: Service Csv
+ * $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 com.google.common.collect.Lists;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.nuiton.topia.persistence.TopiaException;
+import org.nuiton.topia.persistence.TopiaEntity;
+import org.nuiton.util.StringUtil;
+import org.nuiton.csv.Common;
+import org.nuiton.csv.ValueFormatter;
+import org.nuiton.csv.ValueParser;
+import org.nuiton.csv.ValueParserFormatter;
+import org.nuiton.decorator.Decorator;
+
+import java.sql.Timestamp;
+import java.text.ParseException;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Date;
+import java.util.Map;
+
+/**
+ * More useful method added to {@link Common}.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.6.12
+ */
+public class TopiaCsvCommons extends Common {
+
+ protected TopiaCsvCommons() {
+ // no instance of this helper
+ }
+
+ public static final ValueParserFormatter<Date> DAY_TIME_SECOND_WITH_TIMESTAMP =
+ new DateValue("dd/MM/yyyy HH:mm:ss") {
+
+ @Override
+ public Date parse(String value) throws ParseException {
+
+ Date parse = super.parse(value);
+ if (parse != null) {
+ parse = new Timestamp(parse.getTime());
+ }
+ return parse;
+ }
+ };
+
+ public static final ValueParserFormatter<Date> DAY_TIME_SECOND_MILI_WITH_TIMESTAMP =
+ new DateValue("dd/MM/yyyy HH:mm:ss.SSSS") {
+
+ @Override
+ public Date parse(String value) throws ParseException {
+
+ Date parse = super.parse(value);
+ if (parse != null) {
+ parse = new Timestamp(parse.getTime());
+ }
+ return parse;
+ }
+ };
+ public static final AssociationValueParser ASSOCIATION_VALUE_PARSER = new AssociationValueParser();
+
+ public static <E extends TopiaEntity> ForeignKeyValue<E> newForeignKeyValue(Class<E> type, String propertyName, Map<String, E> universe) {
+ return new ForeignKeyValue<E>(type, propertyName, universe);
+ }
+
+ public static <E extends TopiaEntity> ForeignKeyValueForAssociation<E> newForeignKeyValueAssociation(Class<E> type, String propertyName, Map<String, E> universe) {
+ return new ForeignKeyValueForAssociation<E>(type, propertyName, universe);
+ }
+
+ public static <E extends TopiaEntity> ValueFormatter<Collection<E>> newAssociationValueFormatter() {
+ return new AssociationValueParserFormatter<E>(null, null);
+ }
+
+ public static <E> ForeignKeyDecoratedValue<E> newForeignKeyDecoratedValue(Decorator<E> decorator) {
+ return new ForeignKeyDecoratedValue<E>(decorator);
+ }
+
+ /**
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.6.12
+ */
+ public static class AssociationValueParser implements ValueParser<String[]> {
+
+ @Override
+ public String[] parse(String value) throws ParseException {
+ String[] ids = value.split("\\|");
+ return ids;
+ }
+ }
+
+ /**
+ * @param <E>
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.6.12
+ */
+ public static class AssociationValueParserFormatter<E extends TopiaEntity> implements ValueParserFormatter<Collection<E>> {
+
+ protected final Class<E> entityType;
+
+ protected final Map<String, E> universe;
+
+ public AssociationValueParserFormatter(
+ Class<E> entityType,
+ Map<String, E> universe) {
+ this.entityType = entityType;
+ this.universe = universe;
+ }
+
+ @Override
+ public Collection<E> parse(String value) throws ParseException {
+ Collection<E> result = Lists.newArrayList();
+ if (StringUtils.isNotBlank(value)) {
+
+ String[] ids = value.split("\\|");
+ for (String id : ids) {
+ E association = universe.get(id);
+ association.setTopiaId(id);
+ result.add(association);
+ }
+ }
+ return result;
+ }
+
+ @Override
+ public String format(Collection<E> e) {
+
+ String value;
+ if (CollectionUtils.isEmpty(e)) {
+ value = "";
+ } else {
+ Collection<String> ids = Lists.newArrayList();
+ for (E e1 : e) {
+ ids.add(e1.getTopiaId());
+ }
+ value = StringUtil.join(ids, "|", true);
+ }
+ return value;
+ }
+ }
+
+ /**
+ * TODO
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.6.12
+ */
+ public static class ForeignKeyDecoratedValue<E> implements ValueFormatter<E> {
+
+ protected final Decorator<E> decorator;
+
+ public ForeignKeyDecoratedValue(Decorator<E> decorator) {
+ this.decorator = decorator;
+ }
+
+ @Override
+ public String format(E e) {
+ String value = "";
+ if (e != null) {
+ value = decorator.toString(e);
+ }
+ return value;
+ }
+ }
+
+ /**
+ * @param <E>
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.6.12
+ */
+ public static class ForeignKeyValue<E extends TopiaEntity> implements ValueParserFormatter<E> {
+
+ protected final String propertyName;
+
+ protected final Class<E> entityType;
+
+ protected final Map<String, E> universe;
+
+ public ForeignKeyValue(Class<E> entityType,
+ String propertyName,
+ Map<String, E> universe) {
+ this.entityType = entityType;
+ this.propertyName = propertyName;
+ this.universe = universe;
+ }
+
+
+ @Override
+ public E parse(String value) throws ParseException {
+ E result = null;
+ if (StringUtils.isNotBlank(value)) {
+
+ // get entity from universe
+ result = universe.get(value);
+
+ if (result == null) {
+
+ // can not find entity this is a big problem for us...
+ throw new TopiaException(
+ "Could not find entity of type " +
+ entityType.getSimpleName() + " with '" +
+ propertyName + "' = " + value);
+ }
+ }
+ return result;
+ }
+
+ @Override
+ public String format(E e) {
+ String value = "";
+ if (e != null) {
+ value = e.getTopiaId();
+ }
+ return value;
+ }
+ }
+
+ public static class ForeignKeyValueForAssociation<E extends TopiaEntity> implements ValueParser<Collection<E>> {
+
+ protected final String propertyName;
+
+ protected final Class<E> entityType;
+
+ protected final Map<String, E> universe;
+
+ public ForeignKeyValueForAssociation(Class<E> entityType,
+ String propertyName,
+ Map<String, E> universe) {
+ this.entityType = entityType;
+ this.propertyName = propertyName;
+ this.universe = universe;
+ }
+
+ @Override
+ public Collection<E> parse(String value) throws ParseException {
+ E result = null;
+ if (StringUtils.isNotBlank(value)) {
+
+ // get entity from universe
+ result = universe.get(value);
+
+ if (result == null) {
+
+ // can not find entity this is a big problem for us...
+ throw new TopiaException(
+ "Could not find entity with '" + propertyName + "' = " + value);
+ }
+ }
+ return Arrays.asList(result);
+ }
+ }
+}
Copied: trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/in/AbstractImportModel.java (from rev 2939, trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/csv/in/AbstractImportModel.java)
===================================================================
--- trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/in/AbstractImportModel.java (rev 0)
+++ trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/in/AbstractImportModel.java 2013-12-20 16:07:29 UTC (rev 2954)
@@ -0,0 +1,57 @@
+package org.nuiton.topia.service.csv.in;
+
+/*
+ * #%L
+ * ToPIA :: Service Csv
+ * $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.nuiton.topia.persistence.TopiaEntity;
+import org.nuiton.topia.service.csv.TopiaCsvCommons;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Abstract import model which add the useful methdo about importing foreign keys.
+ *
+ * @param <E> type of entity to import
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.6.12
+ */
+public abstract class AbstractImportModel<E> extends org.nuiton.csv.ext.AbstractImportModel<E> {
+
+ public AbstractImportModel(char separator) {
+ super(separator);
+ }
+
+ @Override
+ public void pushCsvHeaderNames(List<String> headerNames) {
+ }
+
+ public <E extends TopiaEntity> void newForeignKeyColumn(String headerName, String propertyName, Class<E> entityType, String foreignKeyName, Map<String, E> universe) {
+ newMandatoryColumn(headerName, propertyName, TopiaCsvCommons.newForeignKeyValue(entityType, foreignKeyName, universe));
+ }
+
+ public <E extends TopiaEntity> void newForeignKeyColumn(String propertyName, Class<E> entityType, String foreignKeyName, Map<String, E> universe) {
+ newMandatoryColumn(propertyName, propertyName, TopiaCsvCommons.newForeignKeyValue(entityType, foreignKeyName, universe));
+ }
+}
Copied: trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/in/CsvFileImportResult.java (from rev 2939, trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/csv/in/CsvFileImportResult.java)
===================================================================
--- trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/in/CsvFileImportResult.java (rev 0)
+++ trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/in/CsvFileImportResult.java 2013-12-20 16:07:29 UTC (rev 2954)
@@ -0,0 +1,112 @@
+package org.nuiton.topia.service.csv.in;
+
+/*
+ * #%L
+ * ToPIA :: Service Csv
+ * $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 com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+import org.nuiton.topia.persistence.TopiaEntityEnum;
+
+import java.io.Serializable;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * To keep result of the import of a file.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.6.12
+ */
+public class CsvFileImportResult<T extends TopiaEntityEnum> implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ /** Name of the csv file to import. */
+ protected final String importFileName;
+
+ /** type of entity to import csv datas. */
+ protected final Set<T> entityTypes;
+
+ /** Count of created entities. */
+ protected final Map<T, Integer> numberCreated;
+
+ /** Count of updated entities. */
+ protected final Map<T, Integer> numberUpdated;
+
+ public static <T extends TopiaEntityEnum> CsvFileImportResult<T> newResult(String importFileName, T... universe) {
+ CsvFileImportResult<T> result = new CsvFileImportResult<T>(
+ importFileName, universe
+ );
+ return result;
+ }
+
+ public CsvFileImportResult(String importFileName, T... universe) {
+ this.importFileName = importFileName;
+ entityTypes = Sets.newHashSet();
+ numberCreated = Maps.newHashMap();
+ numberUpdated = Maps.newHashMap();
+ for (T t : universe) {
+ numberCreated.put(t, 0);
+ numberUpdated.put(t, 0);
+ }
+ }
+
+ public Set<T> getEntityTypes() {
+ return ImmutableSet.copyOf(entityTypes);
+ }
+
+ public int getNumberCreated(T entityType) {
+ return getInteger(numberCreated, entityType);
+ }
+
+ public int getNumberUpdated(T entityType) {
+ return getInteger(numberUpdated, entityType);
+ }
+
+ public String getImportFileName() {
+ return importFileName;
+ }
+
+ public void incrementsNumberCreated(T entityType) {
+ increments(numberCreated, entityType);
+ }
+
+ public void incrementsNumberUpdated(T entityType) {
+ increments(numberUpdated, entityType);
+ }
+
+ protected int getInteger(Map<T, Integer> map, T entityType) {
+ Integer result = map.get(entityType);
+ return result;
+ }
+
+ protected void increments(Map<T, Integer> map, T entityType) {
+ Integer result = map.get(entityType);
+ if (result == 0) {
+ entityTypes.add(entityType);
+ }
+ map.put(entityType, ++result);
+ }
+}
Copied: trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/in/CsvImportResult.java (from rev 2939, trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/csv/in/CsvImportResult.java)
===================================================================
--- trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/in/CsvImportResult.java (rev 0)
+++ trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/in/CsvImportResult.java 2013-12-20 16:07:29 UTC (rev 2954)
@@ -0,0 +1,119 @@
+package org.nuiton.topia.service.csv.in;
+
+/*
+ * #%L
+ * ToPIA :: Service Csv
+ * $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.nuiton.topia.persistence.TopiaEntityEnum;
+import org.nuiton.topia.service.csv.CsvProgressModel;
+
+import java.io.Serializable;
+
+/**
+ * A simple csv result bean just to keep the number of created or
+ * updated entities.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 0.2
+ */
+public class CsvImportResult<T extends TopiaEntityEnum> implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ /** type of entity to import csv datas. */
+ protected final T entityType;
+
+ /** Name of the csv file to import. */
+ protected final String importFileName;
+
+ /** Flag to authorize to create entities not found in db. */
+ protected final boolean createIfNotFound;
+
+ /** Count of created entities. */
+ protected int numberCreated;
+
+ /** Count of updated entities. */
+ protected int numberUpdated;
+
+ protected final CsvProgressModel progressModel;
+
+ public static <T extends TopiaEntityEnum> CsvImportResult<T> newResult(T entityType,
+ String importFileName,
+ boolean createIfNotFound) {
+ CsvImportResult<T> result = newResult(entityType, importFileName,
+ createIfNotFound, null);
+ return result;
+ }
+
+ public static <T extends TopiaEntityEnum> CsvImportResult<T> newResult(T entityType,
+ String importFileName,
+ boolean createIfNotFound,
+ CsvProgressModel progressModel) {
+ CsvImportResult<T> result = new CsvImportResult<T>(entityType, importFileName,
+ createIfNotFound, progressModel);
+ return result;
+ }
+
+ protected CsvImportResult(T entityType,
+ String importFileName,
+ boolean createIfNotFound,
+ CsvProgressModel progressModel) {
+ this.entityType = entityType;
+ this.importFileName = importFileName;
+ this.createIfNotFound = createIfNotFound;
+ this.progressModel = progressModel;
+ }
+
+ public T getEntityType() {
+ return entityType;
+ }
+
+
+ public String getImportFileName() {
+ return importFileName;
+ }
+
+ public int getNumberCreated() {
+ return numberCreated;
+ }
+
+ public int getNumberUpdated() {
+ return numberUpdated;
+ }
+
+ public boolean isCreateIfNotFound() {
+ return createIfNotFound;
+ }
+
+ public void incrementsNumberCreated() {
+ numberCreated++;
+ }
+
+ public void incrementsNumberUpdated() {
+ numberUpdated++;
+ }
+
+ public CsvProgressModel getProgressModel() {
+ return progressModel;
+ }
+}
Copied: trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/in/EntityAssociationImportModel.java (from rev 2939, trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/csv/in/EntityAssociationImportModel.java)
===================================================================
--- trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/in/EntityAssociationImportModel.java (rev 0)
+++ trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/in/EntityAssociationImportModel.java 2013-12-20 16:07:29 UTC (rev 2954)
@@ -0,0 +1,76 @@
+package org.nuiton.topia.service.csv.in;
+
+/*
+ * #%L
+ * ToPIA :: Service Csv
+ * $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.nuiton.topia.persistence.TopiaEntity;
+import org.nuiton.topia.persistence.TopiaEntityEnum;
+import org.nuiton.topia.service.csv.TopiaCsvCommons;
+import org.nuiton.topia.persistence.metadata.AssociationMeta;
+import org.nuiton.csv.ImportModel;
+
+import java.util.Map;
+
+/**
+ * A model to import associations of entities from csv files.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.6.12
+ */
+public class EntityAssociationImportModel<T extends TopiaEntityEnum> extends AbstractImportModel<Map<String, Object>> {
+
+ protected final AssociationMeta meta;
+
+ public static <T extends TopiaEntityEnum> ImportModel<Map<String, Object>> newImportModel(char separator,
+ AssociationMeta<T> meta) {
+ EntityAssociationImportModel<T> model = new EntityAssociationImportModel<T>(
+ separator, meta);
+
+ // topiaId <-> topiaId
+ model.newMandatoryColumn(
+ TopiaEntity.PROPERTY_TOPIA_ID,
+ TopiaCsvCommons.<Map<String, Object>, String>newMapProperty(TopiaEntity.PROPERTY_TOPIA_ID)
+ );
+
+ // add association -> target
+ model.newMandatoryColumn(
+ meta.getName(),
+ TopiaCsvCommons.ASSOCIATION_VALUE_PARSER,
+ TopiaCsvCommons.<Map<String, Object>, String[]>newMapProperty("target")
+ );
+
+ return model;
+ }
+
+ @Override
+ public Map<String, Object> newEmptyInstance() {
+ return null;
+ }
+
+ public EntityAssociationImportModel(char separator, AssociationMeta<T> meta) {
+ super(separator);
+ this.meta = meta;
+ }
+
+}
Copied: trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/in/ImportModelFactory.java (from rev 2939, trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/csv/in/ImportModelFactory.java)
===================================================================
--- trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/in/ImportModelFactory.java (rev 0)
+++ trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/in/ImportModelFactory.java 2013-12-20 16:07:29 UTC (rev 2954)
@@ -0,0 +1,48 @@
+package org.nuiton.topia.service.csv.in;
+
+/*
+ * #%L
+ * ToPIA :: Service Csv
+ * $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.nuiton.topia.persistence.TopiaEntity;
+import org.nuiton.topia.persistence.TopiaEntityEnum;
+import org.nuiton.topia.persistence.metadata.AssociationMeta;
+import org.nuiton.topia.persistence.metadata.TableMeta;
+import org.nuiton.csv.ImportModel;
+
+import java.util.Map;
+
+/**
+ * To produce import model.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.6.12
+ */
+public interface ImportModelFactory<T extends TopiaEntityEnum> {
+
+ <E extends TopiaEntity> ImportModel<E> buildForImport(TableMeta<T> meta);
+
+ ImportModel<Map<String, Object>> buildForImport(AssociationMeta<T> meta);
+
+ boolean isNMAssociationMeta(AssociationMeta<T> meta);
+}
Copied: trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/in/ImportStrategy.java (from rev 2949, trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/csv/in/ImportStrategy.java)
===================================================================
--- trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/in/ImportStrategy.java (rev 0)
+++ trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/in/ImportStrategy.java 2013-12-20 16:07:29 UTC (rev 2954)
@@ -0,0 +1,90 @@
+package org.nuiton.topia.service.csv.in;
+
+/*
+ * #%L
+ * ToPIA :: Service Csv
+ * $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.nuiton.topia.persistence.TopiaException;
+import org.nuiton.topia.persistence.TopiaEntity;
+import org.nuiton.topia.persistence.TopiaEntityEnum;
+import org.nuiton.topia.persistence.metadata.AssociationMeta;
+import org.nuiton.topia.persistence.metadata.TableMeta;
+import org.nuiton.csv.Import;
+import org.nuiton.csv.ImportToMap;
+
+import java.io.Reader;
+
+/**
+ * Strategy to import some stuff.
+ * <p/>
+ * Implements it and then you can use it with helper methods
+ * {@link TopiaCsvImports#importTable(Reader, ImportStrategy, TableMeta, CsvImportResult)},
+ * {@link TopiaCsvImports#importAssociation(Reader, ImportStrategy, AssociationMeta, CsvImportResult)}.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.6.12
+ */
+public interface ImportStrategy<T extends TopiaEntityEnum> {
+
+ /** @return the model factory (will be used to produce the model to import). */
+ ImportModelFactory<T> getModelFactory();
+
+ /**
+ * Import a table given a {@code importer} with an optional csv result.
+ *
+ * @param meta type of table to import
+ * @param importer the csv importer
+ * @param csvResult optional object where to put csv import result
+ * @throws TopiaException if any db problem
+ */
+ <E extends TopiaEntity> void importTable(TableMeta<T> meta, Import<E> importer,
+ CsvImportResult<T> csvResult) throws TopiaException;
+
+ /**
+ * Import a table given a {@code importer} with an optional csv result,
+ * and return them.
+ *
+ * @param meta type of table to import
+ * @param importer the csv importer
+ * @param csvResult optional object where to put csv import result
+ * @return imported entities
+ * @throws TopiaException if any db problem
+ * @since 2.6.14
+ */
+ <E extends TopiaEntity> Iterable<E> importTableAndReturnThem(TableMeta<T> meta, Import<E> importer,
+ CsvImportResult<T> csvResult) throws TopiaException;
+
+ /**
+ * Import a association given a {@code importer} with an optional csv result.
+ *
+ * @param meta type of association to import
+ * @param importer the csv importer
+ * @param csvResult optional object where to put csv import result
+ * @throws TopiaException if any db problem
+ */
+ void importAssociation(AssociationMeta<T> meta,
+ ImportToMap importer,
+ CsvImportResult<T> csvResult) throws TopiaException;
+
+
+}
Copied: trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/in/TopiaCsvImports.java (from rev 2949, trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/csv/in/TopiaCsvImports.java)
===================================================================
--- trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/in/TopiaCsvImports.java (rev 0)
+++ trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/in/TopiaCsvImports.java 2013-12-20 16:07:29 UTC (rev 2954)
@@ -0,0 +1,591 @@
+package org.nuiton.topia.service.csv.in;
+
+/*
+ * #%L
+ * ToPIA :: Service Csv
+ * $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 com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.csv.Import;
+import org.nuiton.csv.ImportModel;
+import org.nuiton.csv.ImportToMap;
+import org.nuiton.topia.persistence.TopiaDao;
+import org.nuiton.topia.persistence.TopiaEntity;
+import org.nuiton.topia.persistence.TopiaEntityEnum;
+import org.nuiton.topia.persistence.TopiaException;
+import org.nuiton.topia.persistence.metadata.AssociationMeta;
+import org.nuiton.topia.persistence.metadata.MetaFilenameAware;
+import org.nuiton.topia.persistence.metadata.TableMeta;
+import org.nuiton.topia.persistence.support.TopiaHibernateSupport;
+import org.nuiton.topia.persistence.support.TopiaSqlSupport;
+import org.nuiton.topia.persistence.util.TopiaEntityHelper;
+import org.nuiton.topia.service.csv.CsvProgressModel;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.Reader;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+/**
+ * Helper for csv imports.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.6.12
+ */
+public class TopiaCsvImports {
+
+ /** Logger. */
+ private static final Log log = LogFactory.getLog(TopiaCsvImports.class);
+
+ protected static final String UPDATE_ASSOCIATION =
+ "UPDATE %s SET %s = '%%s' WHERE topiaId ='%%s';";
+
+ protected static final String INSERT_ASSOCIATION =
+ "INSERT INTO %s (%s,%s) VALUES('%%s','%%s');";
+
+ protected TopiaCsvImports() {
+ // no instance of this helper
+ }
+
+ /**
+ * Discover all files that can be imported (as a table or an association) from a zipfile.
+ *
+ * @param entryPrefix prefix where to find files in the zip
+ * @param possibleMetas list of possible meta to be imported
+ * @param zipFile zip file where to seek for csv files to import
+ * @param missingEntries to fill missing files
+ * @param <T> type of topia entity enum
+ * @param <M> type of data to import (table or association)
+ * @return the map of found files indexed by his meta
+ */
+ public static <T extends TopiaEntityEnum, M extends MetaFilenameAware<T>> Map<M, ZipEntry> discoverEntries(
+ String entryPrefix,
+ Iterable<M> possibleMetas,
+ ZipFile zipFile,
+ List<String> missingEntries) {
+
+ Map<M, ZipEntry> result = Maps.newLinkedHashMap();
+
+ // check that all mandatories
+ for (M entry : possibleMetas) {
+ String filename = entry.getFilename();
+ ZipEntry zipEntry = zipFile.getEntry(entryPrefix + filename);
+
+ if (zipEntry == null) {
+ missingEntries.add(filename);
+ } else {
+ result.put(entry, zipEntry);
+ }
+ }
+ return result;
+ }
+
+ /**
+ * Discover all files that can be imported (as a table or an association) from a directory.
+ *
+ * @param possibleMetas list of possible meta to be imported
+ * @param directory directory where to seek for csv files to import
+ * @param missingEntries to fill missing files
+ * @param <T> type of topia entity enum
+ * @param <M> type of data to import (table or association)
+ * @return the map of found files indexed by his meta
+ */
+ public static <T extends TopiaEntityEnum, M extends MetaFilenameAware<T>> Map<M, File> discoverEntries(
+ Iterable<M> possibleMetas,
+ File directory,
+ List<String> missingEntries) {
+
+ Map<M, File> result = Maps.newLinkedHashMap();
+
+ // check that all mandatories
+ for (M entry : possibleMetas) {
+ String filename = entry.getFilename();
+ File zipEntry = new File(directory, filename);
+
+ if (zipEntry.exists()) {
+ result.put(entry, zipEntry);
+ } else {
+ missingEntries.add(filename);
+ }
+ }
+ return result;
+ }
+
+ /**
+ * To import a table (given by his {@code meta}) from a reader and a strategy.
+ * <p/>
+ * Result of import can be stored in an optional csv result.
+ *
+ * @param reader where to read csv data
+ * @param importStrategy import strategy used to store csv data
+ * @param meta meta of the data
+ * @param csvResult optional csv result
+ * @param <T> type of entity enum
+ * @param <E> type of data
+ * @throws TopiaException if any db problem while storing datas
+ * @throws IOException if any pb while reading csv data
+ * @see ImportStrategy#importTable(TableMeta, Import, CsvImportResult)
+ */
+ public static <T extends TopiaEntityEnum, E extends TopiaEntity> void importTable(Reader reader,
+ ImportStrategy<T> importStrategy,
+ TableMeta<T> meta,
+ CsvImportResult<T> csvResult) throws TopiaException, IOException {
+
+
+ if (log.isInfoEnabled()) {
+ log.info("Will import " + meta);
+ }
+
+ ImportModel<E> model = importStrategy.getModelFactory().buildForImport(meta);
+ Import<E> importer = Import.newImport(model, reader);
+ try {
+ importStrategy.importTable(meta, importer, csvResult);
+ } finally {
+ importer.close();
+ }
+ }
+
+ /**
+ * To import a table (given by his {@code meta}) from a reader and a strategy.
+ * <p/>
+ * Result of import can be stored in an optional csv result.
+ *
+ * @param reader where to read csv data
+ * @param importStrategy import strategy used to store csv data
+ * @param meta meta of the data
+ * @param csvResult optional csv result
+ * @param <T> type of entity enum
+ * @param <E> type of data
+ * @throws TopiaException if any db problem while storing datas
+ * @throws IOException if any pb while reading csv data
+ * @see ImportStrategy#importTable(TableMeta, Import, CsvImportResult)
+ */
+ public static <T extends TopiaEntityEnum, E extends TopiaEntity> Iterable<E> importTableAndReturn(Reader reader,
+ ImportStrategy<T> importStrategy,
+ TableMeta<T> meta,
+ CsvImportResult<T> csvResult) throws TopiaException, IOException {
+
+
+ if (log.isInfoEnabled()) {
+ log.info("Will import " + meta);
+ }
+
+ ImportModel<E> model = importStrategy.getModelFactory().buildForImport(meta);
+ Import<E> importer = Import.newImport(model, reader);
+ try {
+ return importStrategy.importTableAndReturnThem(meta, importer, csvResult);
+ } finally {
+ importer.close();
+ }
+ }
+
+ /**
+ * To import a association (given by his {@code meta}) from a reader and a strategy.
+ * <p/>
+ * Result of import can be stored in an optional csv result.
+ *
+ * @param reader where to read csv data
+ * @param importStrategy import strategy used to store csv data
+ * @param meta meta of the data
+ * @param csvResult optional csv result
+ * @param <T> type of entity enum
+ * @throws TopiaException if any db problem while storing datas
+ * @throws IOException if any pb while reading csv data
+ * @see ImportStrategy#importAssociation(AssociationMeta, ImportToMap, CsvImportResult)
+ */
+ public static <T extends TopiaEntityEnum> void importAssociation(Reader reader,
+ ImportStrategy<T> importStrategy,
+ AssociationMeta<T> meta,
+ CsvImportResult<T> csvResult) throws IOException, TopiaException {
+
+ if (log.isInfoEnabled()) {
+ log.info("Will import " + meta);
+ }
+
+ // load a association input
+ ImportModelFactory<T> modelFactory = importStrategy.getModelFactory();
+ ImportModel<Map<String, Object>> model =
+ modelFactory.buildForImport(meta);
+ ImportToMap importer = ImportToMap.newImportToMap(model, reader, false);
+
+ try {
+ importStrategy.importAssociation(meta, importer, csvResult);
+
+ } finally {
+ importer.close();
+ }
+ }
+
+ public static <T extends TopiaEntityEnum, E extends TopiaEntity> void importAllEntities(TopiaDao<E> dao,
+ TableMeta<T> meta,
+ Import<E> importer,
+ CsvImportResult<T> csvResult) throws TopiaException {
+
+ CsvProgressModel progressModel = csvResult == null ? null :
+ csvResult.getProgressModel();
+ for (E entity : importer) {
+
+ Map<String, Object> properties = meta.prepareCreate(
+ entity, entity.getTopiaId());
+ E entityToSave = dao.create(properties);
+
+ meta.copy(entity, entityToSave);
+
+ if (csvResult != null) {
+ csvResult.incrementsNumberUpdated();
+ if (progressModel != null) {
+ progressModel.incrementsProgress();
+ }
+ }
+ }
+ }
+
+ public static <T extends TopiaEntityEnum, E extends TopiaEntity> void importAllEntities(TopiaDao<E> dao,
+ TableMeta<T> meta,
+ Import<E> importer,
+ CsvImportResult<T> csvResult,
+ int nbRowBuffer) throws TopiaException {
+
+ TopiaHibernateSupport hibernateSupport = null; // FIXME AThimel 23/11/13 Get an hibernate support instance
+
+ CsvProgressModel progressModel = csvResult == null ? null :
+ csvResult.getProgressModel();
+
+ int compt = 0;
+ for (E entity : importer) {
+
+ Map<String, Object> properties = meta.prepareCreate(
+ entity, entity.getTopiaId());
+ E entityToSave = dao.create(properties);
+
+ meta.copy(entity, entityToSave);
+
+ if (csvResult != null) {
+ csvResult.incrementsNumberUpdated();
+ if (progressModel != null) {
+ progressModel.incrementsProgress();
+ }
+ }
+ compt++;
+ if (compt % nbRowBuffer == 0) {
+ // flush it
+ hibernateSupport.getHibernateSession().flush();
+ }
+ }
+ }
+
+ public static <T extends TopiaEntityEnum, E extends TopiaEntity> Iterable<E> importAllEntitiesAndReturnThem(TopiaDao<E> dao,
+ TableMeta<T> meta,
+ Import<E> importer,
+ CsvImportResult<T> csvResult) throws TopiaException {
+
+ CsvProgressModel progressModel = csvResult == null ? null :
+ csvResult.getProgressModel();
+ List<E> result = Lists.newArrayList();
+ for (E entity : importer) {
+
+ Map<String, Object> properties = meta.prepareCreate(
+ entity, entity.getTopiaId());
+ E entityToSave = dao.create(properties);
+
+ meta.copy(entity, entityToSave);
+
+ if (csvResult != null) {
+ csvResult.incrementsNumberUpdated();
+ if (progressModel != null) {
+ progressModel.incrementsProgress();
+ }
+ }
+
+ result.add(entityToSave);
+ }
+ return result;
+ }
+
+ public static <T extends TopiaEntityEnum, E extends TopiaEntity> void importNotExistingEntities(TopiaDao<E> dao,
+ TableMeta<T> meta,
+ Map<String, TopiaEntity> universe,
+ Import<E> importer,
+ CsvImportResult<T> csvResult) throws TopiaException {
+
+ CsvProgressModel progressModel = csvResult == null ? null :
+ csvResult.getProgressModel();
+ for (E entity : importer) {
+
+ String topiaId = entity.getTopiaId();
+
+ Map<String, Object> properties = meta.prepareCreate(entity, null);
+ E existingEntity = dao.forProperties(properties).findAnyOrNull();
+ if (existingEntity == null) {
+
+ // new entity to create
+ E entityToSave = dao.create(properties);
+ String newTopiaId = entityToSave.getTopiaId();
+ Date topiaCreateDate = entityToSave.getTopiaCreateDate();
+ meta.copy(entity, entityToSave);
+ entityToSave.setTopiaId(newTopiaId);
+ entityToSave.setTopiaCreateDate(topiaCreateDate);
+
+ if (log.isInfoEnabled()) {
+ log.info(String.format("Create entity [%s becomes %s] with naturalId %s", topiaId, newTopiaId, properties));
+ }
+ universe.put(topiaId, entityToSave);
+
+ if (csvResult != null) {
+ csvResult.incrementsNumberCreated();
+ if (progressModel != null) {
+ progressModel.incrementsProgress();
+ }
+ }
+ } else {
+ // existing entity, nothing to create
+ // just add a ref into universe to make translation possible by foreign keys
+
+ if (log.isDebugEnabled()) {
+ log.debug(String.format("Existing entity [%s] with naturalId %s, do not create anything", topiaId, properties));
+ }
+
+ universe.put(topiaId, existingEntity);
+ }
+ }
+ }
+
+ public static <T extends TopiaEntityEnum> void importAssociation(TopiaSqlSupport sqlSupport, AssociationMeta<T> meta,
+ ImportToMap importer,
+ CsvImportResult<T> csvResult,
+ int nbRowBuffer) throws TopiaException {
+
+ CsvProgressModel progressModel = csvResult == null ? null :
+ csvResult.getProgressModel();
+ T source = meta.getSource();
+ T target = meta.getTarget();
+
+ StringBuilder builder = new StringBuilder();
+
+ String targetTableName = target.getContract().getSimpleName();
+ String sourceTableName = source.getContract().getSimpleName();
+ String table = targetTableName;
+
+ String updateString = String.format(UPDATE_ASSOCIATION, table, sourceTableName);
+
+ if (log.isDebugEnabled()) {
+ log.debug("Will apply " + updateString);
+ }
+ int compt = 0;
+ for (Map<String, Object> row : importer) {
+ String topiaId = (String) row.get(TopiaEntity.PROPERTY_TOPIA_ID);
+ String[] associations = (String[]) row.get("target");
+ for (String association : associations) {
+ if (StringUtils.isNotEmpty(association)) {
+ builder.append(String.format(updateString, topiaId, association)).append('\n');
+ compt++;
+ if (compt % nbRowBuffer == 0) {
+ // flush it
+ sqlSupport.executeSql(builder.toString());
+ builder = new StringBuilder();
+ }
+ }
+ }
+ if (csvResult != null) {
+ csvResult.incrementsNumberUpdated();
+ if (progressModel != null) {
+ progressModel.incrementsProgress();
+ }
+ }
+ }
+ if (builder.length() > 0) {
+ sqlSupport.executeSql(builder.toString());
+ }
+ }
+
+ public static <T extends TopiaEntityEnum> void importNMAssociation(TopiaSqlSupport sqlSupport,
+ AssociationMeta<T> meta,
+ ImportToMap importer,
+ CsvImportResult<T> csvResult,
+ int nbRowBuffer) throws TopiaException {
+
+ CsvProgressModel progressModel = csvResult == null ? null :
+ csvResult.getProgressModel();
+ T source = meta.getSource();
+ T target = meta.getTarget();
+
+ StringBuilder builder = new StringBuilder();
+
+
+ String targetTableName = target.getContract().getSimpleName();
+ String sourceTableName = source.getContract().getSimpleName();
+
+ // relation *-*
+ String table = TopiaEntityHelper.getNormalizedAssociationTableName(
+ sourceTableName, targetTableName);
+
+ String updateString = String.format(INSERT_ASSOCIATION, table, sourceTableName, targetTableName);
+
+ if (log.isDebugEnabled()) {
+ log.debug("Will apply " + updateString);
+ }
+ int compt = 0;
+ for (Map<String, Object> row : importer) {
+ String topiaId = (String) row.get(TopiaEntity.PROPERTY_TOPIA_ID);
+ String[] associations = (String[]) row.get("target");
+ for (String association : associations) {
+ if (StringUtils.isNotEmpty(association)) {
+ builder.append(String.format(updateString, topiaId, association)).append('\n');
+ compt++;
+ if (compt % nbRowBuffer == 0) {
+ // flush it
+ sqlSupport.executeSql(builder.toString());
+ builder = new StringBuilder();
+ }
+ }
+ }
+ if (csvResult != null) {
+ csvResult.incrementsNumberUpdated();
+ if (progressModel != null) {
+ progressModel.incrementsProgress();
+ }
+ }
+ }
+ if (builder.length() > 0) {
+ sqlSupport.executeSql(builder.toString());
+ }
+ }
+
+ public static <T extends TopiaEntityEnum> void importNMAssociation(TopiaSqlSupport sqlSupport,
+ AssociationMeta<T> meta,
+ Map<String, TopiaEntity> universe,
+ ImportToMap importer,
+ CsvImportResult<T> csvResult,
+ int nbRowBuffer) throws TopiaException {
+
+ CsvProgressModel progressModel = csvResult == null ? null :
+ csvResult.getProgressModel();
+ T source = meta.getSource();
+ T target = meta.getTarget();
+
+ StringBuilder builder = new StringBuilder();
+
+
+ String targetTableName = target.getContract().getSimpleName();
+ String sourceTableName = source.getContract().getSimpleName();
+
+ // relation *-*
+ String table = TopiaEntityHelper.getNormalizedAssociationTableName(
+ sourceTableName, targetTableName);
+
+ String updateString = String.format(INSERT_ASSOCIATION, table, sourceTableName, targetTableName);
+
+ if (log.isDebugEnabled()) {
+ log.debug("Will apply " + updateString);
+ }
+ int compt = 0;
+ for (Map<String, Object> row : importer) {
+ String topiaId = (String) row.get(TopiaEntity.PROPERTY_TOPIA_ID);
+ String[] associations = (String[]) row.get("target");
+ for (String association : associations) {
+ if (StringUtils.isNotEmpty(association)) {
+ TopiaEntity targetEntity = universe.get(association);
+ Preconditions.checkNotNull(targetEntity, "Could not find target entity from id: " + association);
+ builder.append(String.format(updateString, topiaId, targetEntity.getTopiaId())).append('\n');
+ compt++;
+ if (compt % nbRowBuffer == 0) {
+ // flush it
+ sqlSupport.executeSql(builder.toString());
+ builder = new StringBuilder();
+ }
+ }
+ }
+ if (csvResult != null) {
+ csvResult.incrementsNumberUpdated();
+ if (progressModel != null) {
+ progressModel.incrementsProgress();
+ }
+ }
+ }
+ if (builder.length() > 0) {
+ sqlSupport.executeSql(builder.toString());
+ }
+ }
+
+ public static <T extends TopiaEntityEnum> void importAssociation(TopiaSqlSupport sqlSupport,
+ AssociationMeta<T> meta,
+ Map<String, TopiaEntity> universe,
+ ImportToMap importer,
+ CsvImportResult<T> csvResult,
+ int nbRowBuffer) throws TopiaException {
+
+ CsvProgressModel progressModel = csvResult == null ? null :
+ csvResult.getProgressModel();
+
+ T source = meta.getSource();
+ T target = meta.getTarget();
+
+ StringBuilder builder = new StringBuilder();
+
+ String targetTableName = target.getContract().getSimpleName();
+ String sourceTableName = source.getContract().getSimpleName();
+ String table = targetTableName;
+
+ String updateString = String.format(UPDATE_ASSOCIATION, table, sourceTableName);
+
+ if (log.isDebugEnabled()) {
+ log.debug("Will apply " + updateString);
+ }
+ int compt = 0;
+ for (Map<String, Object> row : importer) {
+ String topiaId = (String) row.get(TopiaEntity.PROPERTY_TOPIA_ID);
+ String[] associations = (String[]) row.get("target");
+ for (String association : associations) {
+ if (StringUtils.isNotEmpty(association)) {
+
+ TopiaEntity targetEntity = universe.get(association);
+ Preconditions.checkNotNull(targetEntity, "Could not find target entity from id: " + association);
+ builder.append(String.format(updateString, topiaId, targetEntity.getTopiaId())).append('\n');
+ compt++;
+ if (compt % nbRowBuffer == 0) {
+ // flush it
+ sqlSupport.executeSql(builder.toString());
+ builder = new StringBuilder();
+ }
+ }
+ }
+ if (csvResult != null) {
+ csvResult.incrementsNumberUpdated();
+ if (progressModel != null) {
+ progressModel.incrementsProgress();
+ }
+ }
+ }
+ if (builder.length() > 0) {
+ sqlSupport.executeSql(builder.toString());
+ }
+ }
+}
Copied: trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/in/package-info.java (from rev 2939, trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/csv/in/package-info.java)
===================================================================
--- trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/in/package-info.java (rev 0)
+++ trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/in/package-info.java 2013-12-20 16:07:29 UTC (rev 2954)
@@ -0,0 +1,31 @@
+/**
+ * Package for csv import of entities.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.6.12
+ */
+package org.nuiton.topia.service.csv.in;
+
+/*
+ * #%L
+ * ToPIA :: Service Csv
+ * $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%
+ */
Copied: trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/out/EntityAssociationExportModel.java (from rev 2939, trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/csv/out/EntityAssociationExportModel.java)
===================================================================
--- trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/out/EntityAssociationExportModel.java (rev 0)
+++ trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/out/EntityAssociationExportModel.java 2013-12-20 16:07:29 UTC (rev 2954)
@@ -0,0 +1,65 @@
+package org.nuiton.topia.service.csv.out;
+
+/*
+ * #%L
+ * ToPIA :: Service Csv
+ * $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.nuiton.csv.ExportModel;
+import org.nuiton.csv.ext.AbstractExportModel;
+import org.nuiton.topia.persistence.TopiaEntity;
+import org.nuiton.topia.persistence.TopiaEntityEnum;
+import org.nuiton.topia.persistence.metadata.AssociationMeta;
+import org.nuiton.topia.service.csv.TopiaCsvCommons;
+
+/**
+ * A model to export associations of entities into csv files.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.6.12
+ */
+public class EntityAssociationExportModel<T extends TopiaEntityEnum, E extends TopiaEntity> extends AbstractExportModel<E> {
+
+ protected final AssociationMeta meta;
+
+ public static <T extends TopiaEntityEnum, E extends TopiaEntity> ExportModel<E> newExportModel(char separator,
+ AssociationMeta<T> meta
+ ) {
+ EntityAssociationExportModel<T, E> model = new EntityAssociationExportModel<T, E>(
+ separator,
+ meta);
+
+ // topiaId <-> topiaId
+ model.newColumnForExport(TopiaEntity.PROPERTY_TOPIA_ID);
+
+ model.newColumnForExport(
+ meta.getName(),
+ TopiaCsvCommons.newAssociationValueFormatter()
+ );
+ return model;
+ }
+
+ EntityAssociationExportModel(char separator, AssociationMeta<T> meta) {
+ super(separator);
+ this.meta = meta;
+ }
+}
Copied: trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/out/ExportEntityVisitor.java (from rev 2949, trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/csv/out/ExportEntityVisitor.java)
===================================================================
--- trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/out/ExportEntityVisitor.java (rev 0)
+++ trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/out/ExportEntityVisitor.java 2013-12-20 16:07:29 UTC (rev 2954)
@@ -0,0 +1,212 @@
+package org.nuiton.topia.service.csv.out;
+
+/*
+ * #%L
+ * ToPIA :: Service Csv
+ * $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 com.google.common.base.Preconditions;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.topia.persistence.TopiaException;
+import org.nuiton.topia.persistence.EntityVisitor;
+import org.nuiton.topia.persistence.TopiaEntity;
+import org.nuiton.topia.persistence.TopiaEntityEnum;
+import org.nuiton.topia.persistence.TopiaPersistenceHelper;
+import org.nuiton.util.TimeLog;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.util.Collection;
+import java.util.Map;
+
+/**
+ * Entity visitor to export data to csv files.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.6.12
+ */
+public class ExportEntityVisitor<T extends TopiaEntityEnum> implements EntityVisitor, Closeable {
+
+ /** Logger. */
+ private static final Log log = LogFactory.getLog(ExportEntityVisitor.class);
+
+ public static final TimeLog TIME_LOG =
+ new TimeLog(ExportEntityVisitor.class);
+
+ /** Export for simple entity. */
+ protected final Map<T, TopiaCsvExports.EntityExportContext<T>> entityExporters;
+
+ protected final TopiaPersistenceHelper<T> persistenceHelper;
+
+ public static <T extends TopiaEntityEnum> ExportEntityVisitor<T> newVisitor(
+ TopiaPersistenceHelper<T> persistenceHelper,
+ Map<T, TopiaCsvExports.EntityExportContext<T>> entityExporters) {
+ return new ExportEntityVisitor<T>(
+ persistenceHelper,
+ entityExporters
+ );
+ }
+
+ public ExportEntityVisitor(TopiaPersistenceHelper<T> persistenceHelper,
+ Map<T, TopiaCsvExports.EntityExportContext<T>> entityExporters) {
+ this.persistenceHelper = persistenceHelper;
+ this.entityExporters = entityExporters;
+ }
+
+ public <E extends TopiaEntity> void export(Iterable<E> entities) {
+ for (E entity : entities) {
+ export(entity);
+ }
+ }
+
+ public void export(TopiaEntity entity) {
+ Preconditions.checkNotNull(entity);
+ long s1 = TimeLog.getTime();
+ try {
+ entity.accept(this);
+ } catch (TopiaException e) {
+ throw new TopiaException(
+ "Could not export entity " + entity.getTopiaId(), e);
+ } finally {
+ TIME_LOG.log(s1, "export::" + entity.getTopiaId());
+ }
+ }
+
+ @Override
+ public void start(TopiaEntity entity) {
+ String topiaId = entity.getTopiaId();
+ try {
+ if (log.isDebugEnabled()) {
+ log.debug("Starts export of entity " + topiaId);
+ }
+ TopiaCsvExports.EntityExportContext entityExporter =
+ getEntityContext(entity.getClass());
+ Preconditions.checkNotNull(entityExporter);
+ entityExporter.write(entity);
+ } catch (Exception e) {
+ throw new TopiaException(
+ "Could not export entity " + entity, e);
+ } finally {
+ if (log.isDebugEnabled()) {
+ log.debug("Ends export of entity " + topiaId);
+ }
+ }
+ }
+
+ @Override
+ public void end(TopiaEntity entity) {
+ try {
+ if (log.isDebugEnabled()) {
+ log.debug("Starts export of association of entity " +
+ entity.getTopiaId());
+ }
+ TopiaCsvExports.EntityExportContext entityExporter =
+ getEntityContext(entity.getClass());
+ Preconditions.checkNotNull(entityExporter);
+ entityExporter.writeAssociations(entity);
+ } catch (Exception e) {
+ throw new TopiaException(
+ "Could not export associations of entity " + entity, e);
+ } finally {
+ if (log.isDebugEnabled()) {
+ log.debug("Ends export of association of entity " +
+ entity.getTopiaId());
+ }
+ }
+ }
+
+
+ @Override
+ public void visit(TopiaEntity entity, String propertyName,
+ Class<?> type, Object value) {
+ }
+
+ @Override
+ public void visit(TopiaEntity entity,
+ String propertyName,
+ Class<?> collectionType,
+ Class<?> type,
+ Object value) {
+
+ if (TopiaEntity.class.isAssignableFrom(type) &&
+ getEntityContext((Class<? extends TopiaEntity>) type) != null) {
+ Collection<?> cValue = (Collection<?>) value;
+
+ if (CollectionUtils.isNotEmpty(cValue)) {
+
+ visitEntityCollection(entity,
+ propertyName,
+ collectionType,
+ type,
+ cValue);
+ }
+ }
+ }
+
+ protected void visitEntityCollection(TopiaEntity entity,
+ String propertyName,
+ Class<?> collectionType,
+ Class<?> type,
+ Collection<?> cValue) {
+ for (Object currentValue : cValue) {
+ try {
+ ((TopiaEntity) currentValue).accept(this);
+ } catch (TopiaException e) {
+ if (log.isErrorEnabled()) {
+ log.error("Can not visit entity " + currentValue, e);
+ }
+ }
+ }
+ }
+
+ @Override
+ public void visit(TopiaEntity entity,
+ String propertyName,
+ Class<?> collectionType, Class<?> type,
+ int index,
+ Object value) {
+
+ // nothing to do
+ }
+
+ @Override
+ public void close() throws IOException {
+
+ // use at the end of visit (or later)
+
+ for (TopiaCsvExports.EntityExportContext<T> exportContext : entityExporters.values()) {
+ exportContext.close();
+ }
+ }
+
+ @Override
+ public void clear() {
+ // prefer use the close api
+ }
+
+ protected TopiaCsvExports.EntityExportContext getEntityContext(Class<? extends TopiaEntity> entityType) {
+ T entityEnum = persistenceHelper.getEntityEnum(entityType);
+ return entityEnum == null ? null : entityExporters.get(entityEnum);
+ }
+}
Copied: trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/out/ExportModelFactory.java (from rev 2939, trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/csv/out/ExportModelFactory.java)
===================================================================
--- trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/out/ExportModelFactory.java (rev 0)
+++ trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/out/ExportModelFactory.java 2013-12-20 16:07:29 UTC (rev 2954)
@@ -0,0 +1,44 @@
+package org.nuiton.topia.service.csv.out;
+
+/*
+ * #%L
+ * ToPIA :: Service Csv
+ * $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.nuiton.topia.persistence.TopiaEntity;
+import org.nuiton.topia.persistence.TopiaEntityEnum;
+import org.nuiton.topia.persistence.metadata.AssociationMeta;
+import org.nuiton.topia.persistence.metadata.TableMeta;
+import org.nuiton.csv.ExportModel;
+
+/**
+* To produce export model.
+*
+* @author tchemit <chemit(a)codelutin.com>
+* @since 2.6.12
+*/
+public interface ExportModelFactory<T extends TopiaEntityEnum> {
+
+ <E extends TopiaEntity> ExportModel<E> buildForExport(TableMeta<T> meta);
+
+ <E extends TopiaEntity> ExportModel<E> buildForExport(AssociationMeta<T> associationMeta);
+}
Copied: trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/out/PrepareDataForExport.java (from rev 2939, trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/csv/out/PrepareDataForExport.java)
===================================================================
--- trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/out/PrepareDataForExport.java (rev 0)
+++ trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/out/PrepareDataForExport.java 2013-12-20 16:07:29 UTC (rev 2954)
@@ -0,0 +1,43 @@
+package org.nuiton.topia.service.csv.out;
+
+/*
+ * #%L
+ * ToPIA :: Service Csv
+ * $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.nuiton.topia.persistence.TopiaEntity;
+import org.nuiton.topia.persistence.TopiaEntityEnum;
+import org.nuiton.topia.persistence.metadata.AssociationMeta;
+import org.nuiton.topia.persistence.metadata.TableMeta;
+
+/**
+ * Prepare data to export.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.6.12
+ */
+public interface PrepareDataForExport<T extends TopiaEntityEnum> {
+
+ <E extends TopiaEntity> Iterable<E> prepareData(TableMeta<T> tableMeta);
+
+ <E extends TopiaEntity> Iterable<E> prepareData(AssociationMeta<T> associationMeta);
+}
Copied: trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/out/TopiaCsvExports.java (from rev 2949, trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/csv/out/TopiaCsvExports.java)
===================================================================
--- trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/out/TopiaCsvExports.java (rev 0)
+++ trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/out/TopiaCsvExports.java 2013-12-20 16:07:29 UTC (rev 2954)
@@ -0,0 +1,407 @@
+package org.nuiton.topia.service.csv.out;
+
+/*
+ * #%L
+ * ToPIA :: Service Csv
+ * $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 com.google.common.base.Charsets;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Multimap;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.io.IOUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.topia.persistence.TopiaException;
+import org.nuiton.topia.persistence.TopiaEntity;
+import org.nuiton.topia.persistence.TopiaEntityEnum;
+import org.nuiton.topia.persistence.metadata.AssociationMeta;
+import org.nuiton.topia.persistence.metadata.MetaFilenameAware;
+import org.nuiton.topia.persistence.metadata.Metadatas;
+import org.nuiton.topia.persistence.metadata.TableMeta;
+import org.nuiton.util.TimeLog;
+import org.nuiton.csv.Export;
+import org.nuiton.csv.ExportModel;
+import org.nuiton.csv.ext.RepeatableExport;
+
+import java.io.Closeable;
+import java.io.File;
+import java.io.IOException;
+import java.io.Writer;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Helper for csv exports.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.6.12
+ */
+public class TopiaCsvExports {
+
+ /** Logger. */
+ private static final Log log = LogFactory.getLog(TopiaCsvExports.class);
+
+
+ public static final TimeLog TIME_LOG = new TimeLog(TopiaCsvExports.class);
+
+
+ protected TopiaCsvExports() {
+ // no instance of this helper
+ }
+
+ public static <T extends TopiaEntityEnum> String exportData(TableMeta<T> tableMeta,
+ ExportModelFactory<T> modelFactory,
+ PrepareDataForExport<T> prepareDataForExport) {
+
+
+ long s1 = TimeLog.getTime();
+ Export<TopiaEntity> export = prepareExport(tableMeta, modelFactory, prepareDataForExport);
+ TIME_LOG.log(s1, "exportData::prepareExport");
+ long s2 = TimeLog.getTime();
+ String result;
+ try {
+ result = export.toString(Charsets.UTF_8);
+ } catch (Exception eee) {
+ throw new TopiaException("Can not export datas", eee);
+ }
+ TIME_LOG.log(s2, "exportData::exportToString");
+ return result;
+ }
+
+ public static <T extends TopiaEntityEnum> void exportData(TableMeta<T> tableMeta,
+ ExportModelFactory<T> modelFactory,
+ PrepareDataForExport<T> prepareDataForExport,
+ File file) {
+
+ if (log.isInfoEnabled()) {
+ log.info("Export table " + tableMeta + " to " + file);
+ }
+ long s1 = TimeLog.getTime();
+ Export<TopiaEntity> export = prepareExport(tableMeta, modelFactory, prepareDataForExport);
+ TIME_LOG.log(s1, "exportDatas::prepareExport");
+ long s2 = TimeLog.getTime();
+ try {
+ export.write(file, Charsets.UTF_8);
+ } catch (Exception eee) {
+ throw new TopiaException("Can not export datas", eee);
+ }
+ TIME_LOG.log(s2, "exportData::exportToFile");
+ }
+
+ public static <T extends TopiaEntityEnum> void exportData(AssociationMeta<T> associationMeta,
+ ExportModelFactory<T> modelFactory,
+ PrepareDataForExport<T> prepareDataForExport,
+ File file) {
+
+ if (log.isInfoEnabled()) {
+ log.info("Export association " + associationMeta + " to " + file);
+ }
+ long s1 = TimeLog.getTime();
+
+ Export<TopiaEntity> export = prepareExport(associationMeta, modelFactory, prepareDataForExport);
+ TIME_LOG.log(s1, "exportData::prepareExport");
+
+ long s2 = TimeLog.getTime();
+ try {
+ export.write(file, Charsets.UTF_8);
+ } catch (Exception eee) {
+ throw new TopiaException("Can not export datas", eee);
+ }
+ TIME_LOG.log(s2, "exportData::exportToFile");
+ }
+
+ public static <T extends TopiaEntityEnum, E extends TopiaEntity> Export<E> prepareExport(TableMeta<T> tableMeta,
+ ExportModelFactory<T> modelFactory,
+ PrepareDataForExport<T> prepareDataForExport) {
+
+ Iterable<E> datas = prepareDataForExport.prepareData(tableMeta);
+ ExportModel<E> model = modelFactory.buildForExport(tableMeta);
+ return Export.newExport(model, datas);
+ }
+
+ public static <T extends TopiaEntityEnum, E extends TopiaEntity> Export<E> prepareExport(AssociationMeta<T> associationMeta,
+ ExportModelFactory<T> modelFactory,
+ PrepareDataForExport<T> prepareDataForExport) {
+
+ Iterable<E> datas = prepareDataForExport.prepareData(associationMeta);
+ ExportModel<E> model = modelFactory.buildForExport(associationMeta);
+ return Export.newExport(model, datas);
+ }
+
+ public static <T extends TopiaEntityEnum> Map<T, EntityExportContext<T>> createReplicateEntityVisitorContexts(ExportModelFactory<T> modelFactory,
+ MetaFilenameAware<T>[] entityMetas,
+ Multimap<T, MetaFilenameAware<T>> associations,
+ File container) {
+
+ Preconditions.checkNotNull(modelFactory);
+ Preconditions.checkNotNull(entityMetas);
+ Preconditions.checkNotNull(associations);
+ Preconditions.checkNotNull(container);
+
+ Map<T, EntityExportContext<T>> contexts = Maps.newHashMap();
+
+ for (MetaFilenameAware<T> entityMeta : entityMetas) {
+ TableMeta<T> meta = (TableMeta<T>) entityMeta;
+
+ ExportModel<TopiaEntity> model = modelFactory.buildForExport(meta);
+
+ EntityExportContext<T> exportContext = EntityExportContext.newExportContext(
+ model,
+ meta,
+ container);
+
+ T source = meta.getSource();
+
+ contexts.put(source, exportContext);
+
+ for (MetaFilenameAware<T> metaFilenameAware : associations.get(source)) {
+ AssociationMeta<T> associationMeta =
+ (AssociationMeta<T>) metaFilenameAware;
+
+ ExportModel<TopiaEntity> associationModel =
+ modelFactory.buildForExport(associationMeta);
+ exportContext.addAssociationExportContext(associationMeta,
+ associationModel,
+ container);
+ }
+ }
+ return contexts;
+ }
+
+
+ public static <T extends TopiaEntityEnum> Map<T, EntityExportContext<T>> createReplicateEntityVisitorContexts(ExportModelFactory<T> modelFactory,
+ Iterable<TableMeta<T>> entityMetas,
+ Iterable<AssociationMeta<T>> associationMetas,
+ File container) {
+
+ Preconditions.checkNotNull(modelFactory);
+ Preconditions.checkNotNull(entityMetas);
+ Preconditions.checkNotNull(associationMetas);
+ Preconditions.checkNotNull(container);
+
+ Multimap<T, AssociationMeta<T>> associations = Metadatas.split(associationMetas);
+ Map<T, EntityExportContext<T>> contexts = Maps.newHashMap();
+
+ for (TableMeta<T> meta : entityMetas) {
+
+ ExportModel<TopiaEntity> model = modelFactory.buildForExport(meta);
+
+ EntityExportContext<T> exportContext = EntityExportContext.newExportContext(
+ model,
+ meta,
+ container);
+
+ T source = meta.getSource();
+
+ contexts.put(source, exportContext);
+
+ for (AssociationMeta<T> associationMeta : associations.get(source)) {
+
+ ExportModel<TopiaEntity> associationModel =
+ modelFactory.buildForExport(associationMeta);
+ exportContext.addAssociationExportContext(associationMeta,
+ associationModel,
+ container);
+ }
+ }
+ return contexts;
+ }
+
+ /**
+ * to export entity as csv files.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.6.12
+ */
+ public static class EntityExportContext<T extends TopiaEntityEnum> implements Closeable {
+
+ /** meta to export. */
+ protected final TableMeta<T> meta;
+
+ /** Exporter object. */
+ protected final RepeatableExport export;
+
+ /** Where to export datas. */
+ protected final Writer writer;
+
+ /**
+ * Unique list to store data to export. (will be shared with
+ * association export contexts.)
+ */
+ private final List<TopiaEntity> data;
+
+ /** Association export context for this type of entity. */
+ protected final Collection<AssociationExportContext<T>> associationExportContexts;
+
+ protected final File entryFile;
+
+ public static <T extends TopiaEntityEnum> EntityExportContext<T> newExportContext(
+ ExportModel<TopiaEntity> model,
+ TableMeta<T> meta,
+ File container) {
+ return new EntityExportContext<T>(model, meta, container);
+ }
+
+ protected EntityExportContext(ExportModel<TopiaEntity> model,
+ TableMeta<T> meta,
+ File container) {
+ Preconditions.checkNotNull(model);
+ Preconditions.checkNotNull(meta);
+ Preconditions.checkNotNull(container);
+
+ this.meta = meta;
+ data = Lists.newArrayList();
+ export = RepeatableExport.newExport(model, data, true);
+ entryFile = meta.newFile(container);
+ if (log.isDebugEnabled()) {
+ log.debug("Creates EntityExportContext::" + meta + " - " +
+ entryFile.getName());
+ }
+ writer = meta.newWriter(container);
+ associationExportContexts = Lists.newArrayList();
+ }
+
+ public void addAssociationExportContext(AssociationMeta<T> meta,
+ ExportModel<TopiaEntity> model,
+ File container) {
+ associationExportContexts.add(
+ new AssociationExportContext<T>(model,
+ meta,
+ container,
+ data)
+ );
+ }
+
+ @Override
+ public void close() throws IOException {
+
+ try {
+ if (export.isHeaderWritten()) {
+
+ if (log.isInfoEnabled()) {
+ log.info("Export table " + meta + " to " + entryFile);
+ }
+ writer.flush();
+ } else {
+ // this file was not used, delete it
+ FileUtils.deleteQuietly(entryFile);
+ }
+ } finally {
+ IOUtils.closeQuietly(writer);
+ for (AssociationExportContext<T> c : associationExportContexts) {
+ c.close();
+ }
+ }
+ }
+
+ public void write(TopiaEntity data) throws Exception {
+ this.data.add(data);
+ try {
+ export.write(writer);
+ } finally {
+ this.data.clear();
+ }
+ }
+
+ public void writeAssociations(TopiaEntity data) throws Exception {
+ this.data.add(data);
+ try {
+ for (AssociationExportContext<T> c : associationExportContexts) {
+ AssociationMeta<T> cMeta = c.meta;
+ boolean emptyChild = cMeta.isChildEmpty(data);
+ if (!emptyChild) {
+ c.write();
+ }
+ }
+ } finally {
+ this.data.clear();
+ }
+ }
+ }
+
+ /**
+ * To export associations as csv files.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.6.12
+ */
+ public static class AssociationExportContext<T extends TopiaEntityEnum> implements Closeable {
+
+ /** association meta to export. */
+ protected final AssociationMeta<T> meta;
+
+ /** Exporter object. */
+ protected final RepeatableExport export;
+
+ /** Where to export datas. */
+ protected final Writer writer;
+
+ protected final File entryFile;
+
+ protected AssociationExportContext(ExportModel<TopiaEntity> model,
+ AssociationMeta<T> meta,
+ File container,
+ List<TopiaEntity> data) {
+ Preconditions.checkNotNull(model);
+ Preconditions.checkNotNull(meta);
+ Preconditions.checkNotNull(container);
+ Preconditions.checkNotNull(data);
+ this.meta = meta;
+
+ export = RepeatableExport.newExport(model, data, true);
+
+ entryFile = meta.newFile(container);
+ if (log.isDebugEnabled()) {
+ log.debug("Creates AssociationExportContext::" + meta +
+ " - " + entryFile.getName());
+ }
+ writer = meta.newWriter(container);
+ }
+
+ @Override
+ public void close() throws IOException {
+ try {
+ if (export.isHeaderWritten()) {
+
+ if (log.isInfoEnabled()) {
+ log.info("Export association " + meta + " to " + entryFile);
+ }
+ writer.flush();
+ } else {
+
+ // this file was not used, delete it
+ FileUtils.deleteQuietly(entryFile);
+ }
+ } finally {
+ IOUtils.closeQuietly(writer);
+ }
+ }
+
+ public void write() throws Exception {
+ export.write(writer);
+ }
+ }
+}
Copied: trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/out/package-info.java (from rev 2939, trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/csv/out/package-info.java)
===================================================================
--- trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/out/package-info.java (rev 0)
+++ trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/out/package-info.java 2013-12-20 16:07:29 UTC (rev 2954)
@@ -0,0 +1,31 @@
+/**
+ * Package for csv export of entities.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.6.12
+ */
+package org.nuiton.topia.service.csv.out;
+
+/*
+ * #%L
+ * ToPIA :: Service Csv
+ * $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%
+ */
Copied: trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/package-info.java (from rev 2939, trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/csv/package-info.java)
===================================================================
--- trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/package-info.java (rev 0)
+++ trunk/topia-service-csv/src/main/java/org/nuiton/topia/service/csv/package-info.java 2013-12-20 16:07:29 UTC (rev 2954)
@@ -0,0 +1,31 @@
+/**
+ * Base package for csv import and export of entities.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.6.12
+ */
+package org.nuiton.topia.service.csv;
+
+/*
+ * #%L
+ * ToPIA :: Service Csv
+ * $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%
+ */
Modified: trunk/topia-service-migration/pom.xml
===================================================================
--- trunk/topia-service-migration/pom.xml 2013-12-20 16:05:54 UTC (rev 2953)
+++ trunk/topia-service-migration/pom.xml 2013-12-20 16:07:29 UTC (rev 2954)
@@ -38,11 +38,6 @@
<name>ToPIA :: Service Migration</name>
<description>Hibernate based migration service</description>
- <properties>
- <!-- Post Release configuration -->
- <skipPostRelease>false</skipPostRelease>
- </properties>
-
<dependencies>
<!-- Sibling dependencies -->
1
0
Author: tchemit
Date: 2013-12-20 17:05:54 +0100 (Fri, 20 Dec 2013)
New Revision: 2953
Url: http://nuiton.org/projects/topia/repository/revisions/2953
Log:
remove site from modules
Removed:
trunk/topia-persistence/src/site/
1
0
r2952 - in trunk: topia-service-migration/src topia-service-replication/src
by tchemit@users.nuiton.org 20 Dec '13
by tchemit@users.nuiton.org 20 Dec '13
20 Dec '13
Author: tchemit
Date: 2013-12-20 17:05:33 +0100 (Fri, 20 Dec 2013)
New Revision: 2952
Url: http://nuiton.org/projects/topia/repository/revisions/2952
Log:
remove site from modules
Removed:
trunk/topia-service-migration/src/site/
trunk/topia-service-replication/src/site/
1
0
Author: tchemit
Date: 2013-12-20 17:04:59 +0100 (Fri, 20 Dec 2013)
New Revision: 2951
Url: http://nuiton.org/projects/topia/repository/revisions/2951
Log:
remove from svn topia-service-security
Removed:
trunk/topia-service-security/
1
0