Topia-commits
Threads by month
- ----- 2026 -----
- August
- July
- 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
November 2013
- 7 participants
- 43 discussions
Author: echatellier
Date: 2013-11-28 10:41:24 +0100 (Thu, 28 Nov 2013)
New Revision: 2904
Url: http://nuiton.org/projects/topia/repository/revisions/2904
Log:
fixes #2950: Update hibernate to 4.2.7.SP1
Modified:
trunk/pom.xml
Modified: trunk/pom.xml
===================================================================
--- trunk/pom.xml 2013-11-28 08:43:39 UTC (rev 2903)
+++ trunk/pom.xml 2013-11-28 09:41:24 UTC (rev 2904)
@@ -6,7 +6,7 @@
$Id$
$HeadURL$
%%
- Copyright (C) 2004 - 2010 CodeLutin
+ Copyright (C) 2004 - 2013 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
@@ -240,7 +240,7 @@
<nuitonI18nVersion>2.5.2</nuitonI18nVersion>
<processorPluginVersion>1.3</processorPluginVersion>
<xmlrpcVersion>3.1.2</xmlrpcVersion>
- <hibernateVersion>4.2.3.Final</hibernateVersion>
+ <hibernateVersion>4.2.7.SP1</hibernateVersion>
<sl4jVersion>1.7.5</sl4jVersion>
<h2Version>1.3.172</h2Version>
<hamcrestVersion>1.3</hamcrestVersion>
1
0
r2903 - trunk/topia-templates/src/main/java/org/nuiton/topia/templates
by sbavencoff@users.nuiton.org Nov. 28, 2013
by sbavencoff@users.nuiton.org Nov. 28, 2013
Nov. 28, 2013
Author: sbavencoff
Date: 2013-11-28 09:43:39 +0100 (Thu, 28 Nov 2013)
New Revision: 2903
Url: http://nuiton.org/projects/topia/repository/revisions/2903
Log:
refs #2923 : change call deprecated functions
Modified:
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityDaoTransformer.java
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-11-28 08:42:15 UTC (rev 2902)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityDaoTransformer.java 2013-11-28 08:43:39 UTC (rev 2903)
@@ -768,9 +768,9 @@
String methodName;
if (TopiaGeneratorUtil.isNMultiplicity(attr)) {
- methodName = getJavaBeanMethodName("findAllContains", attrName);
+ methodName = getJavaBeanMethodName("for", attrName , "Contains");
} else {
- methodName = getJavaBeanMethodName("findAllBy", attrName);
+ methodName = getJavaBeanMethodName("for", attrName, "Equals");
}
String daoName = TopiaGeneratorUtil.getConcreteDaoName(usageClass);
@@ -779,9 +779,9 @@
buffer.append(""
/*{
if (type == <%=usageSimpleType%>.class) {
- <%=daoName%> dao = (<%=daoName%>)
- topiaDaoSupplier.getDao(<%=usageSimpleType%>.class);
- tmp = dao.<%=methodName%>(entity);
+ <%=daoName%> dao =
+ topiaDaoSupplier.getDao(<%=usageSimpleType%>.class, <%=daoName%>.class);
+ tmp = dao.<%=methodName%>(entity).findAll();
result.addAll(tmp);
}
}*/
1
0
r2902 - trunk/topia-persistence/src/main/java/org/nuiton/topia/framework
by athimel@users.nuiton.org Nov. 28, 2013
by athimel@users.nuiton.org Nov. 28, 2013
Nov. 28, 2013
Author: athimel
Date: 2013-11-28 09:42:15 +0100 (Thu, 28 Nov 2013)
New Revision: 2902
Url: http://nuiton.org/projects/topia/repository/revisions/2902
Log:
Syntax
Modified:
trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaHibernateEventListener.java
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaHibernateEventListener.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaHibernateEventListener.java 2013-11-28 08:39:47 UTC (rev 2901)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaHibernateEventListener.java 2013-11-28 08:42:15 UTC (rev 2902)
@@ -131,7 +131,8 @@
public void onPostInsert(PostInsertEvent event) {
TopiaPersistenceContext context = getContext(event);
if (context != null && event.getEntity() instanceof TopiaEntity) {
- context.getTopiaFiresSupport().fireOnPostCreate(context, (TopiaEntity) event.getEntity(), event.getState());
+ TopiaEntity entity = (TopiaEntity) event.getEntity();
+ context.getTopiaFiresSupport().fireOnPostCreate(context, entity, event.getState());
}
}
@@ -142,7 +143,8 @@
TopiaPersistenceContext context = getContext(event);
if (context != null && event.getEntity() instanceof TopiaEntity) {
// try {
- context.getTopiaFiresSupport().fireOnPreLoad(context, (TopiaEntity) event.getEntity(), event.getState());
+ TopiaEntity entity = (TopiaEntity) event.getEntity();
+ context.getTopiaFiresSupport().fireOnPreLoad(context, entity, event.getState());
//TODO (thimel 20071213) On commente pour le moment @see(TopiaDAOHibernate#filterElements)
// } catch (TopiaVetoException tve) {
// //On ne fait pas de remontee d'exception
@@ -157,7 +159,7 @@
if (context != null && event.getEntity() instanceof TopiaEntity) {
attachContext(event.getEntity(), context);
TopiaEntity entity = (TopiaEntity) event.getEntity();
- context.getTopiaFiresSupport().fireOnPostLoad(context, (TopiaEntity) event.getEntity(), new Object[]{});
+ context.getTopiaFiresSupport().fireOnPostLoad(context, entity, new Object[]{});
}
}
@@ -167,7 +169,8 @@
public boolean onPreUpdate(PreUpdateEvent event) {
TopiaPersistenceContext context = getContext(event);
if (context != null && event.getEntity() instanceof TopiaEntity) {
- context.getTopiaFiresSupport().fireOnPreUpdate(context, (TopiaEntity) event.getEntity(), event.getOldState());
+ TopiaEntity entity = (TopiaEntity) event.getEntity();
+ context.getTopiaFiresSupport().fireOnPreUpdate(context, entity, event.getOldState());
}
return false;
}
@@ -176,7 +179,8 @@
public void onPostUpdate(PostUpdateEvent event) {
TopiaPersistenceContext context = getContext(event);
if (context != null && event.getEntity() instanceof TopiaEntity) {
- context.getTopiaFiresSupport().fireOnPostUpdate(context, (TopiaEntity) event.getEntity(), event.getState());
+ TopiaEntity entity = (TopiaEntity) event.getEntity();
+ context.getTopiaFiresSupport().fireOnPostUpdate(context, entity, event.getState());
}
// FIXME indexation
// if (!(entity instanceof NotIndexable) && context.isIndexEnabled()) {
@@ -190,7 +194,8 @@
public boolean onPreDelete(PreDeleteEvent event) {
TopiaPersistenceContext context = getContext(event);
if (context != null && event.getEntity() instanceof TopiaEntity) {
- context.getTopiaFiresSupport().fireOnPreDelete(context, (TopiaEntity) event.getEntity(), event.getDeletedState());
+ TopiaEntity entity = (TopiaEntity) event.getEntity();
+ context.getTopiaFiresSupport().fireOnPreDelete(context, entity, event.getDeletedState());
}
return false;
}
@@ -199,7 +204,8 @@
public void onPostDelete(PostDeleteEvent event) {
TopiaPersistenceContext context = getContext(event);
if (context != null && event.getEntity() instanceof TopiaEntity) {
- context.getTopiaFiresSupport().fireOnPostDelete(context, (TopiaEntity) event.getEntity(), event.getDeletedState());
+ TopiaEntity entity = (TopiaEntity) event.getEntity();
+ context.getTopiaFiresSupport().fireOnPostDelete(context, entity, event.getDeletedState());
}
// FIXME indexation
// if (!(entity instanceof NotIndexable) && context.isIndexEnabled()) {
1
0
r2901 - in trunk: topia-it/src/test/java/org/nuiton/topia/it/legacy topia-persistence/src/main/java/org/nuiton/topia topia-service-replication/src/test/java/org/nuiton/topia/replication
by athimel@users.nuiton.org Nov. 28, 2013
by athimel@users.nuiton.org Nov. 28, 2013
Nov. 28, 2013
Author: athimel
Date: 2013-11-28 09:39:47 +0100 (Thu, 28 Nov 2013)
New Revision: 2901
Url: http://nuiton.org/projects/topia/repository/revisions/2901
Log:
refs #2923 Extract the cache functionnality from TopiaContextFactory. New class is TopiaApplicationContextCache
Added:
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaApplicationContextCacheTest.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaApplicationContextCache.java
Removed:
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaContextFactoryTest.java
Modified:
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TestHelper.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaContextFactory.java
trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationOperationTest.java
trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplAllTest.java
trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplTest.java
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TestHelper.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TestHelper.java 2013-11-28 00:43:28 UTC (rev 2900)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TestHelper.java 2013-11-28 08:39:47 UTC (rev 2901)
@@ -30,6 +30,7 @@
import org.hibernate.cfg.Environment;
import org.junit.Ignore;
import org.nuiton.topia.AbstractTopiaApplicationContext;
+import org.nuiton.topia.TopiaApplicationContextCache;
import org.nuiton.topia.TopiaContextFactory;
import org.nuiton.topia.TopiaNotFoundException;
import org.nuiton.util.FileUtil;
@@ -117,7 +118,7 @@
testDirectory,
dbPropertiesPath,
dbname);
- return TopiaContextFactory.getContext(configuration, CREATE_TOPIA_TEST_CONTEXT);
+ return TopiaApplicationContextCache.getContext(configuration, CREATE_TOPIA_TEST_CONTEXT);
}
public static Properties initTopiaContextConfiguration(File testDirectory,
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaApplicationContextCacheTest.java (from rev 2899, trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaContextFactoryTest.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaApplicationContextCacheTest.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaApplicationContextCacheTest.java 2013-11-28 08:39:47 UTC (rev 2901)
@@ -0,0 +1,205 @@
+/*
+ * #%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%
+ */
+package org.nuiton.topia.it.legacy;
+
+import org.apache.commons.lang3.reflect.FieldUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.nuiton.topia.AbstractTopiaApplicationContext;
+import org.nuiton.topia.TopiaApplicationContextCache;
+import org.nuiton.topia.junit.ConfigurationHelper;
+
+import java.io.File;
+import java.io.IOException;
+import java.lang.reflect.Field;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+
+import com.google.common.base.Function;
+
+/**
+ * Created: 8 mai 2010
+ *
+ * @author fdesbois <fdesbois(a)codelutin.com>
+ * @version $Id$
+ */
+public class TopiaApplicationContextCacheTest {
+
+ private static final Log log =
+ LogFactory.getLog(TopiaApplicationContextCacheTest.class);
+
+ protected static final Function<Properties,AbstractTopiaApplicationContext> CREATE_TOPIA_TEST_CONTEXT = new Function<Properties, AbstractTopiaApplicationContext>() {
+ @Override
+ public AbstractTopiaApplicationContext apply(Properties input) {
+ return new TopiaTestTopiaApplicationContext(input);
+ }
+ };
+
+ protected static Map<Properties, AbstractTopiaApplicationContext> contextCache;
+
+ protected static File testBasedir;
+
+ protected Properties properties;
+
+ @BeforeClass
+ public static void init() throws IOException, IllegalAccessException {
+
+ testBasedir = ConfigurationHelper.getTestSpecificDirectory(TopiaApplicationContextCacheTest.class, "dummy");
+ Field field = FieldUtils.getField(TopiaApplicationContextCache.class, "contextCache", true);
+ contextCache = (Map<Properties, AbstractTopiaApplicationContext>) field.get(null);
+ }
+
+ @Before
+ public void setUp() throws Exception {
+ properties = new Properties();
+ properties.setProperty("prop1", "value1");
+ properties.setProperty("prop2", "value2");
+ contextCache.clear();
+ }
+
+ @Test
+ public void testGetRegisteredContextUrls() throws Exception {
+ log.debug("## testGetRegisteredContextUrls");
+
+ /** PREPARE DATA **/
+ String databaseName = "h2data-testGetContextByProperties";
+ File dbDirectory = new File(testBasedir, databaseName);
+ String url = "jdbc:h2:file:" + dbDirectory;
+ properties.setProperty("hibernate.connection.url", url);
+
+ TopiaTestTopiaApplicationContext test = new TopiaTestTopiaApplicationContext(properties);
+ contextCache.put(properties, test);
+
+ /** EXEC METHOD **/
+ List<String> result = TopiaApplicationContextCache.getRegisteredContextUrls();
+ Assert.assertEquals(1, result.size());
+ Assert.assertEquals(url, result.get(0));
+ }
+
+ @Test
+ public void testRemoveContext() throws Exception {
+ log.debug("## testRemoveContext");
+
+ /** PREPARE DATA **/
+ TopiaTestTopiaApplicationContext test = new TopiaTestTopiaApplicationContext(properties);
+ contextCache.put(properties, test);
+
+ /** EXEC METHOD **/
+ TopiaApplicationContextCache.removeContext(test);
+ Assert.assertEquals(0, contextCache.size());
+ }
+
+ //@Test
+
+ public void testGetContext() throws Exception {
+ // TODO-fdesbois-20100508 : only used TopiaUtil.getProperties, need tests for this method
+ }
+
+ @Test
+ public void testGetContextByProperties() throws Exception {
+ log.debug("## testGetContextByProperties");
+
+ /** PREPARE DATA **/
+ Properties propertiesParent = new Properties(properties);
+ propertiesParent.setProperty("prop3", "value3");
+
+ Properties propertiesAll = new Properties();
+ propertiesAll.setProperty("prop1", "value1");
+ propertiesAll.setProperty("prop2", "value2");
+ propertiesAll.setProperty("prop3", "value3");
+
+ /** EXEC METHOD **/
+
+ log.info("test 0 : add null properties");
+ try {
+ TopiaApplicationContextCache.getContext(null, CREATE_TOPIA_TEST_CONTEXT);
+ } catch (Exception eee) {
+ Assert.assertEquals(NullPointerException.class, eee.getClass());
+ }
+
+ log.info("test 1 : add new properties, will instantiate a new" +
+ " TopiaContext");
+ AbstractTopiaApplicationContext test1 = TopiaApplicationContextCache.getContext(propertiesParent, CREATE_TOPIA_TEST_CONTEXT);
+ Assert.assertNotNull(test1);
+ Assert.assertEquals(1, contextCache.size());
+
+ log.info("test 2 : with same properties, will retrieve existing" +
+ " TopiaContext");
+ AbstractTopiaApplicationContext test2 = TopiaApplicationContextCache.getContext(propertiesParent, CREATE_TOPIA_TEST_CONTEXT);
+ Assert.assertEquals(test1, test2);
+ Assert.assertEquals(1, contextCache.size());
+
+ log.info("test 3 : use other properties, will instantiate a different" +
+ "TopiaContext");
+ AbstractTopiaApplicationContext test3 = TopiaApplicationContextCache.getContext(properties, CREATE_TOPIA_TEST_CONTEXT);
+ log.debug("cache size : " + contextCache.size());
+ log.debug("result : " + test1);
+ log.debug("result3 : " + test3);
+ Assert.assertNotSame(test1, test3);
+ Assert.assertEquals(2, contextCache.size());
+
+ log.info("test 4 : use other properties but equivalent to existing " +
+ "TopiaContext");
+ // Test flating of properties
+ AbstractTopiaApplicationContext test4 = TopiaApplicationContextCache.getContext(propertiesAll, CREATE_TOPIA_TEST_CONTEXT);
+ Assert.assertEquals(test1, test4);
+ Assert.assertEquals(2, contextCache.size());
+
+ log.info("test5a : reinstantiate new TopiaContext after one is closed.");
+ // TEST
+ // Strange behavior the closed flag of context stay true if
+ // hibernateFactory is not loaded from real properties
+// test1.closeContext();
+// Assert.assertTrue(test1.isClosed());
+
+ // Add properties for Hibernate to have real opened topiaContext
+ String databaseName = "h2data-testGetContextByPropertie";
+ File f = new File(testBasedir, databaseName);
+
+ properties.setProperty("hibernate.connection.username", "sa");
+ properties.setProperty("hibernate.connection.password", "");
+ properties.setProperty("hibernate.connection.driver_class", "org.h2.Driver");
+ properties.setProperty("hibernate.connection.url",
+ "jdbc:h2:file:" + f.getAbsolutePath());
+
+
+ AbstractTopiaApplicationContext test5 = TopiaApplicationContextCache.getContext(properties, CREATE_TOPIA_TEST_CONTEXT);
+ Assert.assertNotSame(test1, test5);
+ Assert.assertEquals(3, contextCache.size());
+
+ log.info("test5b : beginTransaction to properly close the context");
+ test5.newPersistenceContext();
+ test5.closeContext();
+
+ AbstractTopiaApplicationContext test5b = TopiaApplicationContextCache.getContext(properties, CREATE_TOPIA_TEST_CONTEXT);
+ Assert.assertNotSame(test5, test5b);
+ Assert.assertEquals(3, contextCache.size());
+ }
+}
Deleted: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaContextFactoryTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaContextFactoryTest.java 2013-11-28 00:43:28 UTC (rev 2900)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaContextFactoryTest.java 2013-11-28 08:39:47 UTC (rev 2901)
@@ -1,205 +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%
- */
-package org.nuiton.topia.it.legacy;
-
-import org.apache.commons.lang3.reflect.FieldUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.nuiton.topia.AbstractTopiaApplicationContext;
-import org.nuiton.topia.TopiaContextFactory;
-import org.nuiton.topia.junit.ConfigurationHelper;
-
-import java.io.File;
-import java.io.IOException;
-import java.lang.reflect.Field;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-
-import com.google.common.base.Function;
-
-/**
- * Created: 8 mai 2010
- *
- * @author fdesbois <fdesbois(a)codelutin.com>
- * @version $Id$
- */
-public class TopiaContextFactoryTest {
-
- private static final Log log =
- LogFactory.getLog(TopiaContextFactoryTest.class);
-
- protected static final Function<Properties,AbstractTopiaApplicationContext> CREATE_TOPIA_TEST_CONTEXT = new Function<Properties, AbstractTopiaApplicationContext>() {
- @Override
- public AbstractTopiaApplicationContext apply(Properties input) {
- return new TopiaTestTopiaApplicationContext(input);
- }
- };
-
- protected static Map<Properties, AbstractTopiaApplicationContext> contextCache;
-
- protected static File testBasedir;
-
- protected Properties properties;
-
- @BeforeClass
- public static void init() throws IOException, IllegalAccessException {
-
- testBasedir = ConfigurationHelper.getTestSpecificDirectory(TopiaContextFactoryTest.class, "dummy");
- Field field = FieldUtils.getField(TopiaContextFactory.class, "contextCache", true);
- contextCache = (Map<Properties, AbstractTopiaApplicationContext>) field.get(null);
- }
-
- @Before
- public void setUp() throws Exception {
- properties = new Properties();
- properties.setProperty("prop1", "value1");
- properties.setProperty("prop2", "value2");
- contextCache.clear();
- }
-
- @Test
- public void testGetContextOpened() throws Exception {
- log.debug("## testGetContextOpened");
-
- /** PREPARE DATA **/
- String databaseName = "h2data-testGetContextByProperties";
- File dbDirectory = new File(testBasedir, databaseName);
- String url = "jdbc:h2:file:" + dbDirectory;
- properties.setProperty("hibernate.connection.url", url);
-
- TopiaTestTopiaApplicationContext test = new TopiaTestTopiaApplicationContext(properties);
- contextCache.put(properties, test);
-
- /** EXEC METHOD **/
- List<String> result = TopiaContextFactory.getContextOpened();
- Assert.assertEquals(1, result.size());
- Assert.assertEquals(url, result.get(0));
- }
-
- @Test
- public void testRemoveContext() throws Exception {
- log.debug("## testRemoveContext");
-
- /** PREPARE DATA **/
- TopiaTestTopiaApplicationContext test = new TopiaTestTopiaApplicationContext(properties);
- contextCache.put(properties, test);
-
- /** EXEC METHOD **/
- TopiaContextFactory.removeContext(test);
- Assert.assertEquals(0, contextCache.size());
- }
-
- //@Test
-
- public void testGetContext() throws Exception {
- // TODO-fdesbois-20100508 : only used TopiaUtil.getProperties, need tests for this method
- }
-
- @Test
- public void testGetContextByProperties() throws Exception {
- log.debug("## testGetContextByProperties");
-
- /** PREPARE DATA **/
- Properties propertiesParent = new Properties(properties);
- propertiesParent.setProperty("prop3", "value3");
-
- Properties propertiesAll = new Properties();
- propertiesAll.setProperty("prop1", "value1");
- propertiesAll.setProperty("prop2", "value2");
- propertiesAll.setProperty("prop3", "value3");
-
- /** EXEC METHOD **/
-
- log.info("test 0 : add null properties");
- try {
- TopiaContextFactory.getContext(null, CREATE_TOPIA_TEST_CONTEXT);
- } catch (Exception eee) {
- Assert.assertEquals(NullPointerException.class, eee.getClass());
- }
-
- log.info("test 1 : add new properties, will instantiate a new" +
- " TopiaContext");
- AbstractTopiaApplicationContext test1 = TopiaContextFactory.getContext(propertiesParent, CREATE_TOPIA_TEST_CONTEXT);
- Assert.assertNotNull(test1);
- Assert.assertEquals(1, contextCache.size());
-
- log.info("test 2 : with same properties, will retrieve existing" +
- " TopiaContext");
- AbstractTopiaApplicationContext test2 = TopiaContextFactory.getContext(propertiesParent, CREATE_TOPIA_TEST_CONTEXT);
- Assert.assertEquals(test1, test2);
- Assert.assertEquals(1, contextCache.size());
-
- log.info("test 3 : use other properties, will instantiate a different" +
- "TopiaContext");
- AbstractTopiaApplicationContext test3 = TopiaContextFactory.getContext(properties, CREATE_TOPIA_TEST_CONTEXT);
- log.debug("cache size : " + contextCache.size());
- log.debug("result : " + test1);
- log.debug("result3 : " + test3);
- Assert.assertNotSame(test1, test3);
- Assert.assertEquals(2, contextCache.size());
-
- log.info("test 4 : use other properties but equivalent to existing " +
- "TopiaContext");
- // Test flating of properties
- AbstractTopiaApplicationContext test4 = TopiaContextFactory.getContext(propertiesAll, CREATE_TOPIA_TEST_CONTEXT);
- Assert.assertEquals(test1, test4);
- Assert.assertEquals(2, contextCache.size());
-
- log.info("test5a : reinstantiate new TopiaContext after one is closed.");
- // TEST
- // Strange behavior the closed flag of context stay true if
- // hibernateFactory is not loaded from real properties
-// test1.closeContext();
-// Assert.assertTrue(test1.isClosed());
-
- // Add properties for Hibernate to have real opened topiaContext
- String databaseName = "h2data-testGetContextByPropertie";
- File f = new File(testBasedir, databaseName);
-
- properties.setProperty("hibernate.connection.username", "sa");
- properties.setProperty("hibernate.connection.password", "");
- properties.setProperty("hibernate.connection.driver_class", "org.h2.Driver");
- properties.setProperty("hibernate.connection.url",
- "jdbc:h2:file:" + f.getAbsolutePath());
-
-
- AbstractTopiaApplicationContext test5 = TopiaContextFactory.getContext(properties, CREATE_TOPIA_TEST_CONTEXT);
- Assert.assertNotSame(test1, test5);
- Assert.assertEquals(3, contextCache.size());
-
- log.info("test5b : beginTransaction to properly close the context");
- test5.newPersistenceContext();
- test5.closeContext();
-
- AbstractTopiaApplicationContext test5b = TopiaContextFactory.getContext(properties, CREATE_TOPIA_TEST_CONTEXT);
- Assert.assertNotSame(test5, test5b);
- Assert.assertEquals(3, contextCache.size());
- }
-}
Added: trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaApplicationContextCache.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaApplicationContextCache.java (rev 0)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaApplicationContextCache.java 2013-11-28 08:39:47 UTC (rev 2901)
@@ -0,0 +1,133 @@
+package org.nuiton.topia;
+
+/*
+ * #%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.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+
+import org.apache.commons.collections.map.AbstractReferenceMap;
+import org.apache.commons.collections.map.ReferenceMap;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import com.google.common.base.Function;
+import com.google.common.collect.Lists;
+
+/**
+ * This class will provide a TopiaApplicationContext cache. Its usage is not necessary, contexts can be directly created
+ * outside of this cache, then the cache will not contain any reference to the created ApplicationContexts.
+ * <p/>
+ * This class is 'inspired' from the TopiaContextFactory of ToPIA 2.x
+ *
+ * @author Arnaud Thimel <thimel(a)codelutin.com>
+ * @since 3.0
+ */
+public class TopiaApplicationContextCache {
+
+ private static final Log log = LogFactory.getLog(TopiaApplicationContextCache.class);
+
+ /**
+ * Cache that contains all some already registered caches
+ */
+ protected static Map<Properties, AbstractTopiaApplicationContext> contextCache =
+ new ReferenceMap(AbstractReferenceMap.HARD,
+ AbstractReferenceMap.SOFT);
+
+ /**
+ * Static method that can provide an ApplicationContext. If the found context is closed, or if it does not exist, a
+ * new one is created using the given Function<Properties, C>.
+ *
+ * @param <C> the type of TopiaApplicationContext you expect
+ * @param config the configuration of the context
+ * @param createContextFunction the function that will be in charge of the context creation. It might not be used
+ * inside the method if the context is found and still opened
+ * @return an opened instance of XyzTopiaApplicationContext
+ * @throws TopiaNotFoundException if any pb
+ */
+ public static <C extends AbstractTopiaApplicationContext> C getContext(
+ Properties config, Function<Properties, C> createContextFunction)
+ throws TopiaNotFoundException {
+ // Put all properties from a hierarchy in the current properties object.
+ // Resolve problem with hibernate which used iterator to get properties
+ // and so only values from the current properties object and not all
+ // hierarchy
+ Properties cloned = new Properties();
+ for (String key : config.stringPropertyNames()) {
+ cloned.setProperty(key, config.getProperty(key));
+ }
+ C result = (C) contextCache.get(cloned);
+ if (result == null || result.isClosed()) {
+ if (createContextFunction == null) {
+ throw new TopiaException(
+ "Function<Properties, AbstractTopiaApplicationContext> is required to create context");
+ } else {
+ result = createContextFunction.apply(cloned);
+ }
+ if (log.isDebugEnabled()) {
+ log.debug("New context created : " + result);
+ }
+ contextCache.put(cloned, result);
+ } else if (log.isDebugEnabled()) {
+ log.debug("Context found : " + result);
+ }
+ return result;
+ }
+
+ /**
+ * Method to get the list of contexts in memory (each context is identified by its URL).
+ * <p/>
+ * To be used for debugging purpose only.
+ *
+ * @return a list of contexts URLs
+ */
+ public static List<String> getRegisteredContextUrls() {
+ List<String> result = Lists.newArrayList();
+ for (Properties e : contextCache.keySet()) {
+ result.add(e.getProperty(TopiaContextFactory.CONFIG_URL));
+ }
+ return result;
+ }
+
+ /**
+ * Remove the given TopiaApplicationContext from the registered ones
+ *
+ * @param context the context instance to remove
+ */
+ public static void removeContext(AbstractTopiaApplicationContext context) {
+
+ Iterator<AbstractTopiaApplicationContext> it = contextCache.values().iterator();
+
+ while (it.hasNext()) {
+ AbstractTopiaApplicationContext curr = it.next();
+ if (curr == context) {
+ it.remove();
+ break;
+ }
+ }
+ }
+
+}
Property changes on: trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaApplicationContextCache.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaContextFactory.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaContextFactory.java 2013-11-28 00:43:28 UTC (rev 2900)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaContextFactory.java 2013-11-28 08:39:47 UTC (rev 2901)
@@ -58,11 +58,6 @@
private static final String DEFAULT_CONFIG_PROPERTIES =
"TopiaContextImpl.properties";
- /** Cache contenant tous les contexts deja créé. */
- protected static Map<Properties, AbstractTopiaApplicationContext> contextCache =
- new ReferenceMap(AbstractReferenceMap.HARD,
- AbstractReferenceMap.SOFT);
-
public final static String CONFIG_DEFAULT_SCHEMA = Environment.DEFAULT_SCHEMA;
public final static String CONFIG_USER = Environment.USER;
@@ -111,103 +106,4 @@
public final static String CONFIG_PERSISTENCE_TOPIA_ID_FACTORY_CLASS_NAME =
"topia.persistence.topiaIdFactoryClassName";
- /**
- * Permet de connaitre la liste des contexts encore en memoire, utile pour
- * du debuggage.
- *
- * @return la liste des urls de connexion
- */
- public static List<String> getContextOpened() {
- List<String> result = new ArrayList<String>();
- for (Properties e : contextCache.keySet()) {
- // Useless test : will never happened that e.getValue() is null,
- // not allowed for {@link AbstractReferenceMap#SOFT}.
-// if (e.getValue() != null) {
- result.add(e.getProperty(CONFIG_URL));
-// }
- }
- return result;
- }
-
- /**
- * Used when TopiaContext root is closed
- *
- * @param context closed
- */
- public static void removeContext(AbstractTopiaApplicationContext context) {
-// Properties key = null;
-// for (Entry<Properties, AbstractTopiaContext> e : contextCache.entrySet()) {
-// if (e.getValue() == context) {
-// key = e.getKey();
-// break;
-// }
-// }
-// if (key != null) {
-// contextCache.remove(key);
-// }
-
- // Replaced by more powerful algorithm using iterator to remove context
-
- Iterator<AbstractTopiaApplicationContext> it = contextCache.values().iterator();
-
- while (it.hasNext()) {
- AbstractTopiaApplicationContext curr = it.next();
- if (curr == context) {
- it.remove();
- break;
- }
- }
- }
-
- /**
- * Utilise par defaut le fichier de propriete AbstractTopiaContext.properties
- *
- * @return the context using the default configuration file
- * @throws TopiaNotFoundException Si le fichier de configuration par defaut
- * n'est pas retrouvé.
- */
- public static AbstractTopiaApplicationContext getContext() throws TopiaNotFoundException {
- Properties config = TopiaUtil.getProperties(DEFAULT_CONFIG_PROPERTIES);
- AbstractTopiaApplicationContext result = getContext(config, null);
- return result;
- }
-
- /**
- * Methode static permettant de recuperer un context. Si on donne plusieurs
- * fois le meme objet config, on obtient la meme instance de
- * AbstractTopiaContext. Si le context qui devrait etre retourné est ferme,
- * alors un nouveau est creer et retourné.
- *
- * @param config the configuration of the context
- * @return Un TopiaContext ouvert
- * @throws TopiaNotFoundException if any pb
- */
- public static <C extends AbstractTopiaApplicationContext> C getContext(
- Properties config, Function<Properties, C> createContextFunction)
- throws TopiaNotFoundException {
- // Put all properties from a hierarchy in the current properties object.
- // Resolve problem with hibernate which used iterator to get properties
- // and so only values from the current properties object and not all
- // hierarchy
- Properties cloned = new Properties();
- for (String key : config.stringPropertyNames()) {
- cloned.setProperty(key, config.getProperty(key));
- }
- C result = (C)contextCache.get(cloned);
- if (result == null || result.isClosed()) {
- if (createContextFunction == null) {
- throw new TopiaException("Function<Properties, AbstractTopiaApplicationContext> is needed to create context");
- } else {
- result = createContextFunction.apply(cloned);
- }
- if (log.isDebugEnabled()) {
- log.debug("instantiate new topiaContext : " + result);
- }
- contextCache.put(cloned, result);
- } else if (log.isDebugEnabled()) {
- log.debug("topiaContext found : " + result);
- }
- return result;
- }
-
}
Modified: trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationOperationTest.java
===================================================================
--- trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationOperationTest.java 2013-11-28 00:43:28 UTC (rev 2900)
+++ trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationOperationTest.java 2013-11-28 08:39:47 UTC (rev 2901)
@@ -33,7 +33,7 @@
import org.junit.BeforeClass;
import org.junit.Test;
import org.nuiton.topia.AbstractTopiaApplicationContext;
-import org.nuiton.topia.TopiaContextFactory;
+import org.nuiton.topia.TopiaApplicationContextCache;
import org.nuiton.topia.TopiaPersistenceContext;
import org.nuiton.topia.it.TopiaConfigurationHelper;
import org.nuiton.topia.it.legacy.TopiaTestEntityEnum;
@@ -285,7 +285,7 @@
Properties config = getH2Properties(name);
- sourceContext = TopiaContextFactory.getContext(config, CREATE_TOPIA_TEST_APPLICATION_CONTEXT);
+ sourceContext = TopiaApplicationContextCache.getContext(config, CREATE_TOPIA_TEST_APPLICATION_CONTEXT);
TopiaPersistenceContext tx = sourceContext.newPersistenceContext();
Modified: trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplAllTest.java
===================================================================
--- trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplAllTest.java 2013-11-28 00:43:28 UTC (rev 2900)
+++ trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplAllTest.java 2013-11-28 08:39:47 UTC (rev 2901)
@@ -33,7 +33,7 @@
import org.junit.BeforeClass;
import org.junit.Test;
import org.nuiton.topia.AbstractTopiaApplicationContext;
-import org.nuiton.topia.TopiaContextFactory;
+import org.nuiton.topia.TopiaApplicationContextCache;
import org.nuiton.topia.TopiaException;
import org.nuiton.topia.TopiaPersistenceContext;
import org.nuiton.topia.it.TopiaConfigurationHelper;
@@ -232,7 +232,7 @@
Properties config = getH2Properties(name);
- sourceContext = TopiaContextFactory.getContext(config, CREATE_TOPIA_TEST_APPLICATION_CONTEXT);
+ sourceContext = TopiaApplicationContextCache.getContext(config, CREATE_TOPIA_TEST_APPLICATION_CONTEXT);
TopiaPersistenceContext tx = sourceContext.newPersistenceContext();
@@ -259,7 +259,7 @@
Properties config = getH2Properties(name);
- return TopiaContextFactory.getContext(config, CREATE_TOPIA_TEST_APPLICATION_CONTEXT);
+ return TopiaApplicationContextCache.getContext(config, CREATE_TOPIA_TEST_APPLICATION_CONTEXT);
}
@Override
Modified: trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplTest.java
===================================================================
--- trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplTest.java 2013-11-28 00:43:28 UTC (rev 2900)
+++ trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplTest.java 2013-11-28 08:39:47 UTC (rev 2901)
@@ -33,7 +33,7 @@
import org.junit.BeforeClass;
import org.junit.Test;
import org.nuiton.topia.AbstractTopiaApplicationContext;
-import org.nuiton.topia.TopiaContextFactory;
+import org.nuiton.topia.TopiaApplicationContextCache;
import org.nuiton.topia.TopiaException;
import org.nuiton.topia.TopiaPersistenceContext;
import org.nuiton.topia.it.TopiaConfigurationHelper;
@@ -391,7 +391,7 @@
Properties config = getH2Properties(name);
- sourceContext = TopiaContextFactory.getContext(config, CREATE_TOPIA_TEST_APPLICATION_CONTEXT);
+ sourceContext = TopiaApplicationContextCache.getContext(config, CREATE_TOPIA_TEST_APPLICATION_CONTEXT);
TopiaPersistenceContext tx = sourceContext.newPersistenceContext();
@@ -420,7 +420,7 @@
Properties config = getH2Properties(name);
- return TopiaContextFactory.getContext(config, CREATE_TOPIA_TEST_APPLICATION_CONTEXT);
+ return TopiaApplicationContextCache.getContext(config, CREATE_TOPIA_TEST_APPLICATION_CONTEXT);
}
@Override
1
0
r2900 - in trunk/topia-persistence/src/main/java/org/nuiton/topia: . persistence/util
by athimel@users.nuiton.org Nov. 28, 2013
by athimel@users.nuiton.org Nov. 28, 2013
Nov. 28, 2013
Author: athimel
Date: 2013-11-28 01:43:28 +0100 (Thu, 28 Nov 2013)
New Revision: 2900
Url: http://nuiton.org/projects/topia/repository/revisions/2900
Log:
fixes #2923 Fix the latests impacts of deprecated code removal
Modified:
trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaApplicationContext.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaPersistenceContext.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/HibernateTopiaSqlSupport.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaVetoException.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/DBMapping.java
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaApplicationContext.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaApplicationContext.java 2013-11-27 18:18:10 UTC (rev 2899)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaApplicationContext.java 2013-11-28 00:43:28 UTC (rev 2900)
@@ -119,7 +119,7 @@
persistenceContexts.add(persistenceContext);
}
- // TODO AThimel 25/11/13 I don't like it to be public, but necessary for services. Review it
+ // FIXME AThimel 25/11/13 I don't like it to be public, but necessary for services. Review it
public HibernateProvider getHibernateProvider() {
if (hibernateProvider == null) {
hibernateProvider = new HibernateProvider(configuration, topiaServiceSupport, sessionRegistry);
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaPersistenceContext.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaPersistenceContext.java 2013-11-27 18:18:10 UTC (rev 2899)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaPersistenceContext.java 2013-11-28 00:43:28 UTC (rev 2900)
@@ -131,6 +131,28 @@
this.sqlSupport = new HibernateTopiaSqlSupport(hibernateSupport);
}
+ protected TopiaFiresSupport getFiresSupport() {
+ return firesSupport;
+ }
+
+ public TopiaHibernateSupport getHibernateSupport() {
+ return hibernateSupport;
+ }
+
+ public TopiaSqlSupport getSqlSupport() {
+ return sqlSupport;
+ }
+
+ @Override
+ public TopiaIdFactory getTopiaIdFactory() {
+ return topiaIdFactory;
+ }
+
+ @Override
+ public TopiaFiresSupport getTopiaFiresSupport() {
+ return firesSupport;
+ }
+
/**
* This subclass of TopiaHibernateSupport is made to be used only internally within this persistence context. This
* class only acts as an information container (as a structure does).
@@ -215,14 +237,6 @@
}
}
- protected TopiaFiresSupport getFiresSupport() {
- return firesSupport;
- }
-
- public TopiaHibernateSupport getHibernateSupport() {
- return hibernateSupport;
- }
-
@Override
public <E extends TopiaEntity> E findByTopiaId(String topiaId) {
checkClosed();
@@ -245,16 +259,6 @@
}
@Override
- public TopiaIdFactory getTopiaIdFactory() {
- return topiaIdFactory;
- }
-
- @Override
- public TopiaFiresSupport getTopiaFiresSupport() {
- return firesSupport;
- }
-
- @Override
public <E extends TopiaEntity> TopiaDao<E> getDao(Class<E> entityClass) {
Preconditions.checkArgument(entityClass != null, "The method 'getDao' requires a non null 'entityClass' parameter");
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/HibernateTopiaSqlSupport.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/HibernateTopiaSqlSupport.java 2013-11-27 18:18:10 UTC (rev 2899)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/HibernateTopiaSqlSupport.java 2013-11-28 00:43:28 UTC (rev 2900)
@@ -45,10 +45,11 @@
this.hibernateSupport = hibernateSupport;
}
- public static class SQLWork implements Work {
- private final String script;
+ public static class HibernateSqlWork implements Work {
- public SQLWork(String script) {
+ protected final String script;
+
+ public HibernateSqlWork(String script) {
this.script = script;
}
@@ -63,12 +64,11 @@
}
}
- // FIXME AThimel 22/11/2013 WTF name ?
- public static class TopiaSQLWorkWork implements Work {
+ public static class HibernateTopiaSqlWork implements Work {
- final TopiaSqlWork work;
+ protected final TopiaSqlWork work;
- public TopiaSQLWorkWork(TopiaSqlWork work) {
+ public HibernateTopiaSqlWork(TopiaSqlWork work) {
this.work = work;
}
@@ -78,15 +78,15 @@
}
}
- public static class TopiaSqlQueryWork<O> implements Work {
+ public static class HibernateTopiaSqlQueryWork<O> implements Work {
- final TopiaSqlQuery<O> query;
+ protected final TopiaSqlQuery<O> query;
- final boolean multipleResult;
+ protected final boolean multipleResult;
- final List<O> result = new ArrayList<O>();
+ protected final List<O> result = new ArrayList<O>();
- public TopiaSqlQueryWork(TopiaSqlQuery<O> query, boolean multipleResult) {
+ public HibernateTopiaSqlQueryWork(TopiaSqlQuery<O> query, boolean multipleResult) {
this.query = query;
this.multipleResult = multipleResult;
}
@@ -129,7 +129,7 @@
@Override
public void executeSql(String sqlScript) {
- SQLWork work = new SQLWork(sqlScript);
+ HibernateSqlWork work = new HibernateSqlWork(sqlScript);
try {
hibernateSupport.getHibernateSession().doWork(work);
} catch (HibernateException e) {
@@ -139,7 +139,7 @@
@Override
public void doSqlWork(TopiaSqlWork sqlWork) {
- TopiaSQLWorkWork work = new TopiaSQLWorkWork(sqlWork);
+ HibernateTopiaSqlWork work = new HibernateTopiaSqlWork(sqlWork);
try {
hibernateSupport.getHibernateSession().doWork(work);
} catch (HibernateException e) {
@@ -150,7 +150,7 @@
@Override
public <O> O findSingleResult(final TopiaSqlQuery<O> query) throws TopiaException {
- TopiaSqlQueryWork<O> work = new TopiaSqlQueryWork<O>(query, false);
+ HibernateTopiaSqlQueryWork<O> work = new HibernateTopiaSqlQueryWork<O>(query, false);
hibernateSupport.getHibernateSession().doWork(work);
final List<O> result = work.getResult();
return result.isEmpty() ? null : result.get(0);
@@ -159,7 +159,7 @@
@Override
public <O> List<O> findMultipleResult(final TopiaSqlQuery<O> query) throws TopiaException {
- TopiaSqlQueryWork<O> work = new TopiaSqlQueryWork<O>(query, true);
+ HibernateTopiaSqlQueryWork<O> work = new HibernateTopiaSqlQueryWork<O>(query, true);
hibernateSupport.getHibernateSession().doWork(work);
final List<O> result = work.getResult();
return result;
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaVetoException.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaVetoException.java 2013-11-27 18:18:10 UTC (rev 2899)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaVetoException.java 2013-11-28 00:43:28 UTC (rev 2900)
@@ -33,10 +33,8 @@
* @author poussin <poussin(a)codelutin.com>
* @version $Id$
*/
-// TODO AThimel 03/08/13 Extends TopiaException ?
-public class TopiaVetoException extends RuntimeException {
+public class TopiaVetoException extends TopiaException {
- /** Version UID */
private static final long serialVersionUID = 6809613247516488399L;
/**
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/DBMapping.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/DBMapping.java 2013-11-27 18:18:10 UTC (rev 2899)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/DBMapping.java 2013-11-28 00:43:28 UTC (rev 2900)
@@ -29,6 +29,7 @@
import org.apache.commons.logging.LogFactory;
import org.hibernate.exception.SQLGrammarException;
import org.nuiton.topia.AbstractTopiaApplicationContext;
+import org.nuiton.topia.AbstractTopiaPersistenceContext;
import org.nuiton.topia.TopiaException;
import org.nuiton.topia.TopiaPersistenceContext;
import org.nuiton.topia.TopiaSqlQuery;
@@ -122,7 +123,7 @@
}
String firstSequenceKey = sequences.keySet().iterator().next();
TopiaPersistenceContext newContext = ctxt.newPersistenceContext();
- TopiaSqlSupport sqlSupport = null; // TODO AThimel 23/11/13 Get an instance of TopiaSqlSupprt
+ TopiaSqlSupport sqlSupport = ((AbstractTopiaPersistenceContext)newContext).getSqlSupport();
boolean exists = existSequence(firstSequenceKey, sqlSupport);
if (!exists) {
1
0
r2899 - in trunk: topia-persistence/src/main/java/org/nuiton/topia topia-persistence/src/main/java/org/nuiton/topia/persistence topia-templates/src/main/java/org/nuiton/topia/templates
by athimel@users.nuiton.org Nov. 27, 2013
by athimel@users.nuiton.org Nov. 27, 2013
Nov. 27, 2013
Author: athimel
Date: 2013-11-27 19:18:10 +0100 (Wed, 27 Nov 2013)
New Revision: 2899
Url: http://nuiton.org/projects/topia/repository/revisions/2899
Log:
fixes #2925 AbstractTopiaDao is not dependent anymore of the JPA implementation choosen
Modified:
trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaPersistenceContext.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/HibernateTopiaJpaSupport.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaJpaSupport.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/AbstractTopiaDao.java
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityDaoTransformer.java
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaPersistenceContext.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaPersistenceContext.java 2013-11-27 17:13:23 UTC (rev 2898)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaPersistenceContext.java 2013-11-27 18:18:10 UTC (rev 2899)
@@ -301,7 +301,7 @@
if (dao instanceof AbstractTopiaDao) {
AbstractTopiaDao abstractTopiaDao = (AbstractTopiaDao) dao;
- abstractTopiaDao.init(hibernateSupport, jpaSupport, sqlSupport, listenableSupport, topiaIdFactory, firesSupport, this);
+ abstractTopiaDao.init(jpaSupport, sqlSupport, listenableSupport, topiaIdFactory, firesSupport, this);
}
daoCache.put(entityClass, dao);
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/HibernateTopiaJpaSupport.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/HibernateTopiaJpaSupport.java 2013-11-27 17:13:23 UTC (rev 2898)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/HibernateTopiaJpaSupport.java 2013-11-27 18:18:10 UTC (rev 2899)
@@ -58,7 +58,7 @@
* <p/>
* The normal usage is to says yes (that's why the default value is
* {@code true}), in that case whebn doing queries (says in method
- * {@link #findAll(String, Object...)} or {@link #find(String, int, int, Object...)})
+ * {@link #findAll(String, Map<String, Object>)} or {@link #find(String, int, int, Map<String, Object>)})
* it will use the flush mode {@link FlushMode#AUTO}).
* <p/>
* But sometimes, when doing a lot of queries (for some imports for example),
@@ -74,6 +74,10 @@
this.firesSupport = firesSupport;
}
+ public TopiaHibernateSupport getHibernateSupport() {
+ return hibernateSupport;
+ }
+
@Override
public void setUseFlushMode(boolean useFlushMode) {
this.useFlushMode = useFlushMode;
@@ -180,4 +184,40 @@
}
}
+ @Override
+ public void save(Object object) {
+ try {
+ hibernateSupport.getHibernateSession().save(object);
+ } catch (HibernateException eee) {
+ throw new TopiaException("Unable to 'save' instance", eee);
+ }
+ }
+
+ @Override
+ public void update(Object object) {
+ try {
+ hibernateSupport.getHibernateSession().update(object);
+ } catch (HibernateException eee) {
+ throw new TopiaException("Unable to 'update' instance", eee);
+ }
+ }
+
+ @Override
+ public void saveOrUpdate(Object object) {
+ try {
+ hibernateSupport.getHibernateSession().saveOrUpdate(object);
+ } catch (HibernateException eee) {
+ throw new TopiaException("Unable to 'saveOrUpdate' instance", eee);
+ }
+ }
+
+ @Override
+ public void delete(Object object) {
+ try {
+ hibernateSupport.getHibernateSession().delete(object);
+ } catch (HibernateException eee) {
+ throw new TopiaException("Unable to 'delete' instance", eee);
+ }
+ }
+
} // HibernateTopiaJpaSupport
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaJpaSupport.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaJpaSupport.java 2013-11-27 17:13:23 UTC (rev 2898)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaJpaSupport.java 2013-11-27 18:18:10 UTC (rev 2899)
@@ -33,7 +33,6 @@
* @author Arnaud Thimel <thimel(a)codelutin.com>
* @since 3.0
*/
-// TODO AThimel 02/08/13 I think we need another name
public interface TopiaJpaSupport {
/**
@@ -103,6 +102,45 @@
* @param useFlushMode the new value to set
* @since 2.5
*/
- void setUseFlushMode(boolean useFlushMode); // XXX AThimel 27/09/13 Maybe this method has to be renamed
+ void setUseFlushMode(boolean useFlushMode);
+ /**
+ * Persist the given transient instance, first assigning a generated identifier. This method is JPA implementation
+ * independent.
+ * <p/>
+ * This method is "inspired" of the Hibernate's Session#save method.
+ *
+ * @param object a transient instance of a persistent class
+ */
+ void save(Object object);
+
+ /**
+ * Update the persistent instance with the identifier of the given detached instance.
+ * <p/>
+ * This method is "inspired" of the Hibernate's Session#update method.
+ *
+ * @param object a detached instance containing updated state
+ */
+ void update(Object object);
+
+ /**
+ * Either {@link #save(Object)} or {@link #update(Object)} the given instance.
+ * <p/>
+ * This method is "inspired" of the Hibernate's Session#saveOrUpdate method.
+ *
+ * @param object a transient or detached instance containing new or updated state
+ * @see #save(java.lang.Object)
+ * @see #update(Object object)
+ */
+ void saveOrUpdate(Object object);
+
+ /**
+ * Remove a persistent instance.
+ * <p/>
+ * This method is "inspired" of the Hibernate's Session#delete method.
+ *
+ * @param object the instance to be removed
+ */
+ void delete(Object object);
+
}
Modified: 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-11-27 17:13:23 UTC (rev 2898)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/AbstractTopiaDao.java 2013-11-27 18:18:10 UTC (rev 2899)
@@ -45,12 +45,9 @@
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.hibernate.HibernateException;
-import org.hibernate.metadata.ClassMetadata;
import org.nuiton.topia.QueryMissingOrderException;
import org.nuiton.topia.TopiaDaoSupplier;
import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.TopiaHibernateSupport;
import org.nuiton.topia.TopiaJpaSupport;
import org.nuiton.topia.TopiaListenableSupport;
import org.nuiton.topia.TopiaNoResultException;
@@ -72,21 +69,20 @@
import java.util.Set;
/**
- * Cette classe permet d'avoir un ensemble de méthode implantée de façon
- * standard et plus spécifiquement pour Hibernate.
+ * 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/>
- * Certains accès à Hibernate sont tout de même fait ici, car on a pris le choix
- * de se baser entièrement sur hibernate pour la persistence, et il est ainsi
- * possible d'accèder au meta information hibernate sur les classes lorque l'on
- * en a besoin.
+ * 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 org.nuiton.topia.TopiaPersistenceContext}, which implements the
+ * {@link TopiaDaoSupplier} contract.
*
- * @param <E> le type de l'entite
+ * @param <E> the managed entity type
* @author bpoussin <poussin(a)codelutin.com>
- * @version $Id$
+ * @author Arnaud Thimel <thimel(a)codelutin.com>
*/
public abstract class AbstractTopiaDao<E extends TopiaEntity> implements TopiaDao<E> {
- /** to use log facility, just put in your code: log.info(\"...\"); */
private static Log log = LogFactory.getLog(AbstractTopiaDao.class);
/**
@@ -96,9 +92,6 @@
*/
protected int batchSize = 1000;
- @Deprecated // Should not be used here, cf http://nuiton.org/issues/2925
- protected TopiaHibernateSupport topiaHibernateSupport;
-
protected TopiaJpaSupport topiaJpaSupport;
protected TopiaSqlSupport topiaSqlSupport;
@@ -120,7 +113,6 @@
* method just after.
*/
public void init(
- TopiaHibernateSupport topiaHibernateSupport,
TopiaJpaSupport topiaJpaSupport,
TopiaSqlSupport topiaSqlSupport,
TopiaListenableSupport topiaListenableSupport,
@@ -130,7 +122,6 @@
if (log.isDebugEnabled()) {
log.debug("init dao for " + getEntityClass());
}
- this.topiaHibernateSupport = topiaHibernateSupport;
this.topiaJpaSupport = topiaJpaSupport;
this.topiaSqlSupport = topiaSqlSupport;
this.topiaListenableSupport = topiaListenableSupport;
@@ -204,27 +195,23 @@
@Override
public E create(E entity) {
- try {
- // first set topiaId
- if (StringUtils.isBlank(entity.getTopiaId())) {
+ // first set topiaId
+ if (StringUtils.isBlank(entity.getTopiaId())) {
- // only set id if not already on
- String topiaId = topiaIdFactory.newTopiaId(getEntityClass(), entity);
- entity.setTopiaId(topiaId);
- }
+ // 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
- topiaHibernateSupport.getHibernateSession().save(entity);
- topiaFiresSupport.warnOnCreateEntity(entity);
- return entity;
- } catch (HibernateException eee) {
- throw new TopiaException(eee);
+ if (entity instanceof TopiaEntityContextable) {
+ TopiaEntityContextable contextable = (TopiaEntityContextable) entity;
+ contextable.setTopiaDAOSupplier(this.topiaDaoSupplier);
}
+
+ // save entity
+ topiaJpaSupport.save(entity);
+ topiaFiresSupport.warnOnCreateEntity(entity);
+ return entity;
}
@Override
@@ -279,13 +266,9 @@
@Override
public E update(E entity) {
- try {
- topiaHibernateSupport.getHibernateSession().saveOrUpdate(entity);
- topiaFiresSupport.warnOnUpdateEntity(entity);
- return entity;
- } catch (HibernateException eee) {
- throw new TopiaException(eee);
- }
+ topiaJpaSupport.saveOrUpdate(entity);
+ topiaFiresSupport.warnOnUpdateEntity(entity);
+ return entity;
}
@Override
@@ -298,13 +281,9 @@
@Override
public void delete(E entity) {
- try {
- topiaHibernateSupport.getHibernateSession().delete(entity);
- entity.notifyDeleted();
- topiaFiresSupport.warnOnDeleteEntity(entity);
- } catch (HibernateException eee) {
- throw new TopiaException(eee);
- }
+ topiaJpaSupport.delete(entity);
+ entity.notifyDeleted();
+ topiaFiresSupport.warnOnDeleteEntity(entity);
}
@Override
@@ -672,22 +651,21 @@
return result;
}
- /**
- * 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.TopiaException if any pb
- */
- protected ClassMetadata getClassMetadata() {
- ClassMetadata meta = topiaHibernateSupport.getHibernateFactory()
- .getClassMetadata(getEntityClass());
- if (meta == null) {
- meta = topiaHibernateSupport.getHibernateFactory().getClassMetadata(
- getTopiaEntityEnum().getImplementationFQN());
- }
- return meta;
- }
+// /**
+// * 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.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, R> implements Iterator<R> {
@@ -1032,14 +1010,12 @@
@Override
public List<String> findAllIds() {
- // XXX brendan 30/09/13 does this truely work ?
String hqlWithSelectClause = "select topiaId " + hql;
return topiaDAO.findAll(hqlWithSelectClause, hqlParameters, String.class);
}
@Override
public List<String> findIds(int startIndex, int endIndex) {
- // XXX brendan 30/09/13 does this truely work ?
String hqlWithSelectClause = "select topiaId " + hql;
return topiaDAO.find(hqlWithSelectClause, hqlParameters, String.class, startIndex, endIndex);
}
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-11-27 17:13:23 UTC (rev 2898)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityDaoTransformer.java 2013-11-27 18:18:10 UTC (rev 2899)
@@ -33,6 +33,7 @@
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.hibernate.Session;
import org.nuiton.eugene.GeneratorUtil;
import org.nuiton.eugene.java.JavaGeneratorUtil;
import org.nuiton.eugene.java.ObjectModelTransformerToJava;
@@ -45,7 +46,8 @@
import org.nuiton.eugene.models.object.ObjectModelInterface;
import org.nuiton.eugene.models.object.ObjectModelJavaModifier;
import org.nuiton.eugene.models.object.ObjectModelOperation;
-import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.HibernateTopiaJpaSupport;
+import org.nuiton.topia.TopiaHibernateSupport;
import org.nuiton.topia.persistence.TopiaEntity;
import org.nuiton.topia.persistence.TopiaQueryBuilderAddCriteriaOrRunQueryStep;
@@ -417,7 +419,6 @@
addImport(daoAbstractClass, Set.class);
}
addImport(daoAbstractClass, List.class);
- addImport(daoAbstractClass, TopiaException.class);
addImport(daoAbstractClass, TopiaQueryBuilderAddCriteriaOrRunQueryStep.class);
ObjectModelOperation op;
@@ -495,6 +496,8 @@
PROP_DEFAULT_PACKAGE) + '.' + modelName +
"DAOHelper.getImplementationClass";
+ boolean hibernateSupportGenerated = false;
+
for (ObjectModelAttribute attr : clazz.getAttributes()) {
String attrType = GeneratorUtil.getSimpleName(attr.getType());
@@ -559,16 +562,31 @@
// System.out.println("Query : " + query);
// List<<%=attrType%>> list = dao.findAllByQuery(query);
+ if (!hibernateSupportGenerated) {
+ hibernateSupportGenerated = true;
+ addImport(result, TopiaHibernateSupport.class);
+ addImport(result, HibernateTopiaJpaSupport.class);
+ addImport(result, Session.class);
+ body.append(""
+/*{
+ TopiaHibernateSupport hibernateSupport = ((HibernateTopiaJpaSupport) topiaJpaSupport).getHibernateSupport();
+ Session hibernateSession = hibernateSupport.getHibernateSession();
+}*/
+ );
+ }
+
String removeName = getJavaBeanMethodName("remove", reverseAttrName);
body.append(""
/*{
{
- List<<%=attrType%>> list = topiaHibernateSupport.getHibernateSession().createSQLQuery(
- "SELECT main.topiaid " +
- "from <%=attrClassifierDBName%> main, <%=attrJoinTableName%> secondary " +
- "where main.topiaid=secondary.<%=attrDBName%>" +
- " and secondary.<%=attrReverseDBName%>='" + entity.getTopiaId() + "'")
- .addEntity("main", <%=entityEnumName%>.<%=attrType%>.getImplementation()).list();
+ String sql = "SELECT main.topiaid " +
+ " FROM <%=attrClassifierDBName%> main, <%=attrJoinTableName%> secondary " +
+ " WHERE main.topiaid=secondary.<%=attrDBName%> " +
+ " AND secondary.<%=attrReverseDBName%>='" + entity.getTopiaId() + "'";
+ List<<%=attrType%>> list = hibernateSession
+ .createSQLQuery(sql)
+ .addEntity("main", <%=entityEnumName%>.<%=attrType%>.getImplementation())
+ .list();
for (<%=attrType%> item : list) {
item.<%=removeName%>(entity);
1
0
r2898 - trunk/topia-templates/src/main/java/org/nuiton/topia/templates
by athimel@users.nuiton.org Nov. 27, 2013
by athimel@users.nuiton.org Nov. 27, 2013
Nov. 27, 2013
Author: athimel
Date: 2013-11-27 18:13:23 +0100 (Wed, 27 Nov 2013)
New Revision: 2898
Url: http://nuiton.org/projects/topia/repository/revisions/2898
Log:
Let PersistenceContextTransformer delegate to XyzEntityEnum as much as possible
Modified:
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityEnumTransformer.java
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/PersistenceContextTransformer.java
Modified: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityEnumTransformer.java
===================================================================
--- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityEnumTransformer.java 2013-11-27 11:11:51 UTC (rev 2897)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityEnumTransformer.java 2013-11-27 17:13:23 UTC (rev 2898)
@@ -90,7 +90,9 @@
}
entityEnum = createEnumeration(entityEnumName, packageName);
addImport(entityEnum, TopiaEntity.class);
- addImport(entityEnum, EntityOperatorStore.class);
+ if (generateOperator) {
+ addImport(entityEnum, EntityOperatorStore.class);
+ }
addImport(entityEnum, Arrays.class);
addImport(entityEnum, ArrayUtils.class);
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-11-27 11:11:51 UTC (rev 2897)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/PersistenceContextTransformer.java 2013-11-27 17:13:23 UTC (rev 2898)
@@ -42,7 +42,6 @@
import org.nuiton.topia.persistence.util.EntityOperator;
import org.nuiton.topia.persistence.util.EntityOperatorStore;
-import java.lang.reflect.Array;
import java.util.List;
/**
@@ -131,15 +130,11 @@
//
// }
-// addImport(output, TopiaDAO.class);
addImport(output, TopiaEntity.class);
-// addImport(output, TopiaContext.class);
- addImport(output, Array.class);
- addImport(output, Array.class);
if (generateOperator) {
addImport(output, EntityOperator.class);
- addImport(output, EntityOperatorStore.class);
+// addImport(output, EntityOperatorStore.class);
}
// add public constructor
@@ -194,23 +189,20 @@
}
- // getContractClass method
- op = addOperation(output, "getContractClass", "<T extends TopiaEntity> Class<T>", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
- addParameter(op, "Class<T>", "klass");
+ // getContracts method
+ op = addOperation(output, "getContracts", entityEnumName + "[]", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
setOperationBody(op, ""
/*{
- <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass);
- return (Class<T>) constant.getContract();
+ return <%=entityEnumName%>.getContracts();
}*/
);
- // getImplementationClass method
- op = addOperation(output, "getImplementationClass", "<T extends TopiaEntity> Class<T>", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
+ // getContractClass method
+ op = addOperation(output, "getContractClass", "<T extends TopiaEntity> Class<T>", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
addParameter(op, "Class<T>", "klass");
setOperationBody(op, ""
/*{
- <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass);
- return (Class<T>) constant.getImplementation();
+ return <%=entityEnumName%>.getContractClass(klass);
}*/
);
@@ -218,33 +210,32 @@
op = addOperation(output, "getContractClasses", "Class<? extends TopiaEntity>[]", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
setOperationBody(op, ""
/*{
- <%=entityEnumName%>[] values = <%=entityEnumName%>.values();
- Class<? extends TopiaEntity>[] result = (Class<? extends TopiaEntity>[]) Array.newInstance(Class.class, values.length);
- for (int i = 0; i < values.length; i++) {
- result[i] = values[i].getContract();
- }
- return result;
+ return <%=entityEnumName%>.getContractClasses();
}*/
);
+ // getImplementationClass method
+ op = addOperation(output, "getImplementationClass", "<T extends TopiaEntity> Class<T>", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
+ addParameter(op, "Class<T>", "klass");
+ setOperationBody(op, ""
+/*{
+ return <%=entityEnumName%>.getImplementationClass(klass);
+ }*/
+ );
+
// getImplementationClasses method
op = addOperation(output, "getImplementationClasses", "Class<? extends TopiaEntity>[]", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
setOperationBody(op, ""
/*{
- <%=entityEnumName%>[] values = <%=entityEnumName%>.values();
- Class<? extends TopiaEntity>[] result = (Class<? extends TopiaEntity>[]) Array.newInstance(Class.class, values.length);
- for (int i = 0; i < values.length; i++) {
- result[i] = values[i].getImplementation();
- }
- return result;
+ return <%=entityEnumName%>.getImplementationClasses();
}*/
);
- // getContracts method
- op = addOperation(output, "getContracts", entityEnumName + "[]", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
+ // getImplementationClassesAsString method
+ op = addOperation(output, "getImplementationClassesAsString", "String", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
setOperationBody(op, ""
/*{
- return <%=entityEnumName%>.values();
+ return <%=entityEnumName%>.getImplementationClassesAsString();
}*/
);
@@ -254,8 +245,7 @@
addParameter(op, "Class<T>", "klass");
setOperationBody(op, ""
/*{
- <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass);
- return EntityOperatorStore.getOperator(constant);
+ return <%=entityEnumName%>.getOperator(klass);
}*/
);
}
1
0
Nov. 27, 2013
Author: athimel
Date: 2013-11-27 12:11:51 +0100 (Wed, 27 Nov 2013)
New Revision: 2897
Url: http://nuiton.org/projects/topia/repository/revisions/2897
Log:
Introduce TopiaHibernateSessionRegistry in order to make possible to get the PersistenceContext from Hibernate's events
(this will be reused for Topia's event firing)
Move some internal classes to o.n.t.persistence
Added:
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/CascadeSaveTest.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/HibernateProvider.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaHibernateSessionRegistry.java
Removed:
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/beangen/
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/
trunk/topia-persistence/src/main/java/org/nuiton/topia/HibernateProvider.java
Modified:
trunk/topia-junit/src/main/java/org/nuiton/topia/junit/AbstractDatabaseResource.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaApplicationContext.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaPersistenceContext.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaHibernateEventListener.java
trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TopiaMigrationEngine.java
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/ApplicationContextTransformer.java
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/PersistenceContextTransformer.java
Added: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/CascadeSaveTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/CascadeSaveTest.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/CascadeSaveTest.java 2013-11-27 11:11:51 UTC (rev 2897)
@@ -0,0 +1,64 @@
+package org.nuiton.topia.it.legacy.topiatest;
+
+/*
+ * #%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%
+ */
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.it.legacy.TopiaDatabase;
+import org.nuiton.topia.it.legacy.TopiaTestTopiaPersistenceContext;
+
+/**
+ * @author Arnaud Thimel <thimel(a)codelutin.com>
+ */
+public class CascadeSaveTest {
+
+ @Rule
+ public final TopiaDatabase db = new TopiaDatabase();
+
+ /**
+ * The following test will fail if no topiaId is injected on cascade save. This will test code within this method :
+ * org.nuiton.topia.framework.TopiaHibernateEventListener#onSaveOrUpdate(org.hibernate.event.spi.SaveOrUpdateEvent)
+ *
+ * @throws TopiaException
+ */
+ @Test
+ public void testSaveCascade() {
+
+ TopiaTestTopiaPersistenceContext persistenceContext = db.beginTransaction();
+
+ CompanyTopiaDao companyDao = persistenceContext.getCompanyDao();
+ DepartmentTopiaDao departmentDao = persistenceContext.getDepartmentDao();
+ Company company = companyDao.newInstance();
+ company.setName("Toto corp.");
+ Department department = departmentDao.newInstance();
+ department.setName("Jokes");
+ company.addDepartment(department);
+
+ companyDao.create(company);
+
+ }
+
+}
Property changes on: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/CascadeSaveTest.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
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-11-27 07:38:49 UTC (rev 2896)
+++ trunk/topia-junit/src/main/java/org/nuiton/topia/junit/AbstractDatabaseResource.java 2013-11-27 11:11:51 UTC (rev 2897)
@@ -31,7 +31,7 @@
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.nuiton.topia.AbstractTopiaApplicationContext;
-import org.nuiton.topia.HibernateProvider;
+import org.nuiton.topia.persistence.HibernateProvider;
import org.nuiton.topia.TopiaContextFactory;
import org.nuiton.topia.TopiaException;
import org.nuiton.topia.TopiaPersistenceContext;
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaApplicationContext.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaApplicationContext.java 2013-11-27 07:38:49 UTC (rev 2896)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaApplicationContext.java 2013-11-27 11:11:51 UTC (rev 2897)
@@ -44,7 +44,9 @@
import org.nuiton.topia.framework.TopiaService;
import org.nuiton.topia.framework.TopiaUtil;
import org.nuiton.topia.persistence.DefaultTopiaIdFactory;
+import org.nuiton.topia.persistence.HibernateProvider;
import org.nuiton.topia.persistence.TopiaEntity;
+import org.nuiton.topia.persistence.TopiaHibernateSessionRegistry;
import org.nuiton.topia.persistence.TopiaIdFactory;
import java.beans.PropertyChangeListener;
@@ -77,6 +79,8 @@
protected HibernateProvider hibernateProvider;
+ protected TopiaHibernateSessionRegistry sessionRegistry = new TopiaHibernateSessionRegistry();
+
protected boolean closed = false;
protected Set<TopiaPersistenceContext> persistenceContexts = Collections.newSetFromMap(
@@ -118,7 +122,7 @@
// TODO AThimel 25/11/13 I don't like it to be public, but necessary for services. Review it
public HibernateProvider getHibernateProvider() {
if (hibernateProvider == null) {
- hibernateProvider = new HibernateProvider(configuration, topiaServiceSupport);
+ hibernateProvider = new HibernateProvider(configuration, topiaServiceSupport, sessionRegistry);
}
return hibernateProvider;
}
@@ -158,6 +162,10 @@
return topiaIdFactory;
}
+ public TopiaHibernateSessionRegistry getSessionRegistry() {
+ return sessionRegistry;
+ }
+
@Override
public void addTopiaEntityListener(TopiaEntityListener listener) {
topiaFiresSupport.addTopiaEntityListener(listener);
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaPersistenceContext.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaPersistenceContext.java 2013-11-27 07:38:49 UTC (rev 2896)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaPersistenceContext.java 2013-11-27 11:11:51 UTC (rev 2897)
@@ -36,8 +36,10 @@
import org.hibernate.cfg.Configuration;
import org.nuiton.topia.framework.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.TopiaHibernateSessionRegistry;
import org.nuiton.topia.persistence.TopiaIdFactory;
import java.lang.reflect.InvocationTargetException;
@@ -70,6 +72,11 @@
*/
protected TopiaIdFactory topiaIdFactory;
+ /**
+ * The shared instance of TopiaHibernateSessionRegistry
+ */
+ protected TopiaHibernateSessionRegistry sessionRegistry;
+
// TODO AThimel 27/09/13 Javadoc
protected TopiaFiresSupport firesSupport;
@@ -105,10 +112,12 @@
*/
public AbstractTopiaPersistenceContext(HibernateProvider hibernateProvider,
TopiaListenableSupport listenableSupport,
- TopiaIdFactory topiaIdFactory) {
+ TopiaIdFactory topiaIdFactory,
+ TopiaHibernateSessionRegistry sessionRegistry) {
this.listenableSupport = listenableSupport;
this.topiaIdFactory = topiaIdFactory;
+ this.sessionRegistry = sessionRegistry;
this.firesSupport = new TopiaFiresSupport();
// Hibernate support can be created using the given hibernateProvider
@@ -170,6 +179,8 @@
// tchemit 2010-12-06 propagates the value of the flag
// result.useFlushMode = useFlushMode;
+ sessionRegistry.register(result, this);
+
// 20060926 poussin ajouter pour voir si ca regle les problemes de
// deadlock h2. Conclusion, il faut bien ouvrir une transaction
// maintenant, sinon lorsque l'on fait des acces a la base, une
@@ -183,6 +194,7 @@
// et declancher une exception
try {
result.close();
+ sessionRegistry.unregister(result);
} catch (HibernateException e1) {
if (log.isErrorEnabled()) {
log.error("Could not close hibernate session", e1);
@@ -314,9 +326,9 @@
Session hibernateSession = hibernateSupport.getHibernateSession();
- Transaction tx = hibernateSession.getTransaction();
+ Transaction transaction = hibernateSession.getTransaction();
hibernateSession.flush();
- tx.commit();
+ transaction.commit();
getFiresSupport().fireOnPostCommit(this);
// TopiaContextImplementor parent = getParentContext();
@@ -343,17 +355,21 @@
try {
Session hibernateSession = hibernateSupport.getHibernateSession();
- Transaction tx = hibernateSession.getTransaction();
+ Transaction transaction = hibernateSession.getTransaction();
hibernateSession.clear();
- tx.rollback();
+ transaction.rollback();
hibernateSession.close();
+ sessionRegistry.unregister(hibernateSession);
+
// it's very important to change the session after rollback
// otherwise there are many error during next Entity's modification
hibernateSession = hibernateSupport.getHibernateFactory().openSession();
hibernateSupport.setHibernateSession(hibernateSession);
hibernateSession.setFlushMode(FlushMode.MANUAL);
+ sessionRegistry.register(hibernateSession, this);
+
hibernateSession.beginTransaction();
getFiresSupport().fireOnPostRollback(this);
@@ -374,7 +390,10 @@
closed = true;
// Now close the current Hibernate session
- hibernateSupport.getHibernateSession().close();
+ Session hibernateSession = hibernateSupport.getHibernateSession();
+ hibernateSession.close();
+
+ sessionRegistry.unregister(hibernateSession);
}
@Override
Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/HibernateProvider.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/HibernateProvider.java 2013-11-27 07:38:49 UTC (rev 2896)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/HibernateProvider.java 2013-11-27 11:11:51 UTC (rev 2897)
@@ -1,241 +0,0 @@
-package org.nuiton.topia;
-
-/*
- * #%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.Stoppable;
-import org.nuiton.topia.framework.TopiaHibernateEventListener;
-import org.nuiton.topia.framework.TopiaService;
-import org.nuiton.topia.framework.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;
-
- /**
- * List of persistent classes
- */
- protected List<Class<?>> persistentClasses = Lists.newArrayList();
-
- public HibernateProvider(Map<String, String> configuration, TopiaServiceSupport topiaServiceSupport) {
- this.configuration = configuration;
- this.topiaServiceSupport = topiaServiceSupport;
- }
-
- 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(
- TopiaContextFactory.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(
- TopiaContextFactory.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(TopiaContextFactory.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)
- ConnectionProvider service = ((SessionFactoryImplementor) hibernateSessionFactory).getServiceRegistry().getService(ConnectionProvider.class);
- if (service instanceof Stoppable) {
- Stoppable stoppable = (Stoppable) service;
- stoppable.stop();
- }
- }
- }
-
- public SessionFactory getSessionFactory() {
-
- if (hibernateSessionFactory == null) {
-
- // init service registry
- ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(
- getHibernateConfiguration().getProperties()).buildServiceRegistry();
-
- hibernateSessionFactory = getHibernateConfiguration().buildSessionFactory(serviceRegistry);
-
- // 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);
-// TopiaFiresSupport.TopiaHibernateEvent listener = new TopiaFiresSupport.TopiaHibernateEvent(this);
- TopiaHibernateEventListener listener = new TopiaHibernateEventListener(null); // FIXME AThimel 11/10/13 Give a correct instance
- 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;
- }
-
-}
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaHibernateEventListener.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaHibernateEventListener.java 2013-11-27 07:38:49 UTC (rev 2896)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaHibernateEventListener.java 2013-11-27 11:11:51 UTC (rev 2897)
@@ -28,7 +28,8 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
-import org.hibernate.Session;
+import org.hibernate.event.spi.AbstractEvent;
+import org.hibernate.event.spi.EventSource;
import org.hibernate.event.spi.PostDeleteEvent;
import org.hibernate.event.spi.PostDeleteEventListener;
import org.hibernate.event.spi.PostInsertEvent;
@@ -47,14 +48,15 @@
import org.hibernate.event.spi.PreUpdateEventListener;
import org.hibernate.event.spi.SaveOrUpdateEvent;
import org.hibernate.event.spi.SaveOrUpdateEventListener;
-import org.nuiton.topia.AbstractTopiaApplicationContext;
import org.nuiton.topia.TopiaDaoSupplier;
import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.persistence.TopiaHibernateSessionRegistry;
import org.nuiton.topia.TopiaPersistenceContext;
-import org.nuiton.topia.persistence.AbstractTopiaDao;
import org.nuiton.topia.persistence.TopiaEntity;
import org.nuiton.topia.persistence.TopiaEntityContextable;
+import com.google.common.base.Preconditions;
+
/**
* @author Arnaud Thimel <thimel(a)codelutin.com>
*/
@@ -66,55 +68,22 @@
private static final long serialVersionUID = -9206039888626756924L;
- protected AbstractTopiaApplicationContext rootContext;
+ protected TopiaHibernateSessionRegistry registry;
- public TopiaHibernateEventListener(AbstractTopiaApplicationContext rootContext) {
- this.rootContext = rootContext;
+ public TopiaHibernateEventListener(TopiaHibernateSessionRegistry registry) {
+ Preconditions.checkArgument(registry != null);
+ this.registry = registry;
}
/**
- * Recherche le context utilisant la session hibernate passe en
- * parametre
+ * Look for the TopiaPersistenceContext based on the given Hibernate session
*
- * @param parent le context parent
- * @param hibernate la session hibernate que doit utiliser le
- * TopiaContext pour etre retourne
- * @return le TopiaContext utilisant cette session hibernate ou null si
- * aucun TopiaContext n'utilise cette session.
+ * @param event the Hibernate event that contains the Session to use
+ * @return the TopiaPersistenceContext using this Session, or null if not found
*/
- protected TopiaPersistenceContext getContext(
- AbstractTopiaApplicationContext parent, Session hibernate) {
- TopiaPersistenceContext result = null;
- // FIXME AThimel 23/11/13 Find a way to implement it
-
-// // FD-20100421 : Ano #546 : no need to copy childContext, the
-// // {@link #getChildContext()} provides a thread-safe copy to iterate
-// // on it.
-//// Set<TopiaContextImplementor> contextChilds = new HashSet<TopiaContextImplementor>(parent.getChildContext());
-// if (parent != null) { // TODO AThimel 11/10/13 It should never be null, fix it
-// for (TopiaPersistenceContext context : parent.getChildContext()) {
-//
-// // by sletellier 24/09/09 : Fix concurent acces error
-// // ArrayList<TopiaContextImplementor> children = new ArrayList(parent.getChildContext());
-// // for (TopiaContextImplementor context : children) {
-// try {
-// if (context.getHibernate() == hibernate) {
-// result = context;
-// } else {
-// // TODO: poussin 20090706 on pourrait ameliorer en ne faisant pas un parcours recursif, en utilisant la liste children (sans doute a transformer en stack)
-// result = getContext(context, hibernate);
-// }
-// if (result != null) {
-// break;
-// }
-// } catch (TopiaException eee) {
-// if (log.isWarnEnabled()) {
-// log.warn("Error durant la recherche d'un context pour"
-// + " lancer un event", eee);
-// }
-// }
-// }
-// }
+ protected TopiaPersistenceContext getContext(AbstractEvent event) {
+ EventSource session = event.getSession();
+ TopiaPersistenceContext result = registry.getPersistenceContext(session);
return result;
}
@@ -140,10 +109,10 @@
@Override
public boolean onPreInsert(PreInsertEvent event) {
- TopiaPersistenceContext context = getContext(rootContext, event.getSession());
+ TopiaPersistenceContext context = getContext(event);
if (context != null && event.getEntity() instanceof TopiaEntity) {
TopiaEntity entity = (TopiaEntity) event.getEntity();
-
+
context.getTopiaFiresSupport().fireOnPreCreate(context, entity, event.getState());
// when using composition, hibernate will persist entities by him self
@@ -160,7 +129,7 @@
@Override
public void onPostInsert(PostInsertEvent event) {
- TopiaPersistenceContext context = getContext(rootContext, event.getSession());
+ TopiaPersistenceContext context = getContext(event);
if (context != null && event.getEntity() instanceof TopiaEntity) {
context.getTopiaFiresSupport().fireOnPostCreate(context, (TopiaEntity) event.getEntity(), event.getState());
}
@@ -170,7 +139,7 @@
@Override
public void onPreLoad(PreLoadEvent event) {
- TopiaPersistenceContext context = getContext(rootContext, event.getSession());
+ TopiaPersistenceContext context = getContext(event);
if (context != null && event.getEntity() instanceof TopiaEntity) {
// try {
context.getTopiaFiresSupport().fireOnPreLoad(context, (TopiaEntity) event.getEntity(), event.getState());
@@ -184,7 +153,7 @@
@Override
public void onPostLoad(PostLoadEvent event) {
- TopiaPersistenceContext context = getContext(rootContext, event.getSession());
+ TopiaPersistenceContext context = getContext(event);
if (context != null && event.getEntity() instanceof TopiaEntity) {
attachContext(event.getEntity(), context);
TopiaEntity entity = (TopiaEntity) event.getEntity();
@@ -196,7 +165,7 @@
@Override
public boolean onPreUpdate(PreUpdateEvent event) {
- TopiaPersistenceContext context = getContext(rootContext, event.getSession());
+ TopiaPersistenceContext context = getContext(event);
if (context != null && event.getEntity() instanceof TopiaEntity) {
context.getTopiaFiresSupport().fireOnPreUpdate(context, (TopiaEntity) event.getEntity(), event.getOldState());
}
@@ -205,7 +174,7 @@
@Override
public void onPostUpdate(PostUpdateEvent event) {
- TopiaPersistenceContext context = getContext(rootContext, event.getSession());
+ TopiaPersistenceContext context = getContext(event);
if (context != null && event.getEntity() instanceof TopiaEntity) {
context.getTopiaFiresSupport().fireOnPostUpdate(context, (TopiaEntity) event.getEntity(), event.getState());
}
@@ -219,7 +188,7 @@
@Override
public boolean onPreDelete(PreDeleteEvent event) {
- TopiaPersistenceContext context = getContext(rootContext, event.getSession());
+ TopiaPersistenceContext context = getContext(event);
if (context != null && event.getEntity() instanceof TopiaEntity) {
context.getTopiaFiresSupport().fireOnPreDelete(context, (TopiaEntity) event.getEntity(), event.getDeletedState());
}
@@ -228,7 +197,7 @@
@Override
public void onPostDelete(PostDeleteEvent event) {
- TopiaPersistenceContext context = getContext(rootContext, event.getSession());
+ TopiaPersistenceContext context = getContext(event);
if (context != null && event.getEntity() instanceof TopiaEntity) {
context.getTopiaFiresSupport().fireOnPostDelete(context, (TopiaEntity) event.getEntity(), event.getDeletedState());
}
@@ -241,12 +210,13 @@
@Override
public void onSaveOrUpdate(SaveOrUpdateEvent event) throws HibernateException {
try {
- // this event is called when hibernate try to persist entities
- // using cascade (save)
- TopiaPersistenceContext context = getContext(rootContext, event.getSession());
+ // this event is called when hibernate try to persist entities using cascade (save)
+ TopiaPersistenceContext context = getContext(event);
// warning, event.getEntity() return null here :(
+
if (event.getObject() instanceof TopiaEntity) {
TopiaEntity entity = (TopiaEntity) event.getObject();
+
if (StringUtils.isBlank(entity.getTopiaId())) {
if (log.isDebugEnabled()) {
log.debug("Adding topiaId into entity " + entity.getClass());
Copied: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/HibernateProvider.java (from rev 2895, trunk/topia-persistence/src/main/java/org/nuiton/topia/HibernateProvider.java)
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/HibernateProvider.java (rev 0)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/HibernateProvider.java 2013-11-27 11:11:51 UTC (rev 2897)
@@ -0,0 +1,248 @@
+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.Stoppable;
+import org.nuiton.topia.TopiaContextFactory;
+import org.nuiton.topia.TopiaNotFoundException;
+import org.nuiton.topia.TopiaServiceSupport;
+import org.nuiton.topia.framework.TopiaHibernateEventListener;
+import org.nuiton.topia.framework.TopiaService;
+import org.nuiton.topia.framework.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(
+ TopiaContextFactory.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(
+ TopiaContextFactory.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(TopiaContextFactory.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)
+ ConnectionProvider service = ((SessionFactoryImplementor) hibernateSessionFactory).getServiceRegistry().getService(ConnectionProvider.class);
+ if (service instanceof Stoppable) {
+ Stoppable stoppable = (Stoppable) service;
+ stoppable.stop();
+ }
+ }
+ }
+
+ public SessionFactory getSessionFactory() {
+
+ if (hibernateSessionFactory == null) {
+
+ // init service registry
+ ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(
+ getHibernateConfiguration().getProperties()).buildServiceRegistry();
+
+ hibernateSessionFactory = getHibernateConfiguration().buildSessionFactory(serviceRegistry);
+
+ // 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;
+ }
+
+}
Added: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaHibernateSessionRegistry.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaHibernateSessionRegistry.java (rev 0)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaHibernateSessionRegistry.java 2013-11-27 11:11:51 UTC (rev 2897)
@@ -0,0 +1,95 @@
+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.lang.ref.WeakReference;
+import java.util.WeakHashMap;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.hibernate.Session;
+import org.nuiton.topia.TopiaPersistenceContext;
+
+import com.google.common.base.Preconditions;
+
+/**
+ * Class used to keep an association between an Hibernate Session and a TopiaPersistenceContext
+ *
+ * @author Arnaud Thimel <thimel(a)codelutin.com>
+ * @since 3.0
+ */
+public class TopiaHibernateSessionRegistry {
+
+ private static final Log log = LogFactory.getLog(TopiaHibernateSessionRegistry.class);
+
+ protected WeakHashMap<Session, WeakReference<TopiaPersistenceContext>> registry =
+ new WeakHashMap<Session, WeakReference<TopiaPersistenceContext>>();
+
+ /**
+ * Register the Session<->TopiaPersistenceContext couple
+ *
+ * @param session the currently used Session
+ * @param persistenceContext the current TopiaPersistenceContext using this Session
+ */
+ public void register(Session session, TopiaPersistenceContext persistenceContext) {
+ if (log.isDebugEnabled()) {
+ log.debug("New Session<->TopiaPersistenceContext registration");
+ }
+ Preconditions.checkArgument(session != null);
+ Preconditions.checkArgument(persistenceContext != null);
+ WeakReference<TopiaPersistenceContext> reference = new WeakReference<TopiaPersistenceContext>(persistenceContext);
+ registry.put(session, reference);
+ }
+
+ /**
+ * Look for the TopiaPersistenceContext based on the given Hibernate session
+ *
+ * @param session the Hibernate Session to use
+ * @return the TopiaPersistenceContext using this Session, or null if not found
+ */
+ public TopiaPersistenceContext getPersistenceContext(Session session) {
+ Preconditions.checkArgument(session != null);
+ WeakReference<TopiaPersistenceContext> reference = registry.get(session);
+ TopiaPersistenceContext result = reference.get();
+ if (log.isDebugEnabled()) {
+ log.debug("Get TopiaPersistenceContext from Session : " + (result == null ? "Not found" : "HIT !"));
+ }
+ return result;
+ }
+
+ /**
+ * Removes the Session<->TopiaPersistenceContext association from the registry
+ *
+ * @param session the Hibernate Session to remove
+ */
+ public void unregister(Session session) {
+ Preconditions.checkArgument(session != null);
+ WeakReference<TopiaPersistenceContext> reference = registry.remove(session);
+ if (log.isDebugEnabled()) {
+ log.debug("Remove TopiaPersistenceContext from Session : " + (reference != null));
+ }
+ }
+
+}
Property changes on: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaHibernateSessionRegistry.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
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-11-27 07:38:49 UTC (rev 2896)
+++ trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TopiaMigrationEngine.java 2013-11-27 11:11:51 UTC (rev 2897)
@@ -34,7 +34,7 @@
import org.hibernate.cfg.Configuration;
import org.nuiton.topia.AbstractTopiaApplicationContext;
import org.nuiton.topia.AbstractTopiaPersistenceContext;
-import org.nuiton.topia.HibernateProvider;
+import org.nuiton.topia.persistence.HibernateProvider;
import org.nuiton.topia.TopiaException;
import org.nuiton.topia.TopiaHibernateSupport;
import org.nuiton.topia.TopiaNotFoundException;
Modified: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/ApplicationContextTransformer.java
===================================================================
--- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/ApplicationContextTransformer.java 2013-11-27 07:38:49 UTC (rev 2896)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/ApplicationContextTransformer.java 2013-11-27 11:11:51 UTC (rev 2897)
@@ -167,7 +167,7 @@
setOperationBody(op, ""
/*{
<%=persistenceContextConcreteName%> newContext = new <%=persistenceContextConcreteName%>(
- getHibernateProvider(), getTopiaListenableSupport(), getTopiaIdFactory());
+ getHibernateProvider(), getTopiaListenableSupport(), getTopiaIdFactory(), getSessionRegistry());
registerPersistenceContext(newContext);
return newContext;
}*/
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-11-27 07:38:49 UTC (rev 2896)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/PersistenceContextTransformer.java 2013-11-27 11:11:51 UTC (rev 2897)
@@ -34,7 +34,8 @@
import org.nuiton.eugene.models.object.ObjectModelJavaModifier;
import org.nuiton.eugene.models.object.ObjectModelOperation;
import org.nuiton.topia.AbstractTopiaPersistenceContext;
-import org.nuiton.topia.HibernateProvider;
+import org.nuiton.topia.persistence.HibernateProvider;
+import org.nuiton.topia.persistence.TopiaHibernateSessionRegistry;
import org.nuiton.topia.TopiaListenableSupport;
import org.nuiton.topia.persistence.TopiaEntity;
import org.nuiton.topia.persistence.TopiaIdFactory;
@@ -148,9 +149,10 @@
addParameter(constructor, HibernateProvider.class, "hibernateProvider");
addParameter(constructor, TopiaListenableSupport.class, "listenableSupport");
addParameter(constructor, TopiaIdFactory.class, "topiaIdFactory");
+ addParameter(constructor, TopiaHibernateSessionRegistry.class, "sessionRegistry");
setOperationBody(constructor, ""
/*{
- super(hibernateProvider, listenableSupport, topiaIdFactory);
+ super(hibernateProvider, listenableSupport, topiaIdFactory, sessionRegistry);
}*/
);
@@ -274,9 +276,10 @@
addParameter(constructor, HibernateProvider.class, "hibernateProvider");
addParameter(constructor, TopiaListenableSupport.class, "listenableSupport");
addParameter(constructor, TopiaIdFactory.class, "topiaIdFactory");
+ addParameter(constructor, TopiaHibernateSessionRegistry.class, "sessionRegistry");
setOperationBody(constructor, ""
/*{
- super(hibernateProvider, listenableSupport, topiaIdFactory);
+ super(hibernateProvider, listenableSupport, topiaIdFactory, sessionRegistry);
}*/
);
1
0
r2896 - in trunk: topia-it/src/test/java/org/nuiton/topia/it/legacy topia-persistence/src/main/java/org/nuiton/topia
by athimel@users.nuiton.org Nov. 27, 2013
by athimel@users.nuiton.org Nov. 27, 2013
Nov. 27, 2013
Author: athimel
Date: 2013-11-27 08:38:49 +0100 (Wed, 27 Nov 2013)
New Revision: 2896
Url: http://nuiton.org/projects/topia/repository/revisions/2896
Log:
refs #2923 Remove deprecated code from TopiaJpaSupport
Modified:
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaJpaSupportTest.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/HibernateTopiaJpaSupport.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaJpaSupport.java
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaJpaSupportTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaJpaSupportTest.java 2013-11-26 17:19:25 UTC (rev 2895)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaJpaSupportTest.java 2013-11-27 07:38:49 UTC (rev 2896)
@@ -40,7 +40,10 @@
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
+import java.util.Map;
+import com.google.common.collect.Maps;
+
/**
* Tests the TopiaContext#find|findAll|findUnique methods
*
@@ -105,17 +108,24 @@
String query = "from " + Personne.class.getName() +
" where " + Personne.PROPERTY_GENDER + "=:g";
- List females = jpaSupport.findAll(query, "g", Gender.FEMALE);
+ Map<String, Object> args = Maps.newHashMap();
+ args.put("g", Gender.FEMALE);
+ List females = jpaSupport.findAll(query, args);
Assert.assertEquals(2, females.size());
- List males = jpaSupport.findAll(query, "g", Gender.MALE);
+ args = Maps.newHashMap();
+ args.put("g", Gender.MALE);
+ List males = jpaSupport.findAll(query, args);
Assert.assertEquals(1, males.size());
- List all = jpaSupport.findAll("from " + Personne.class.getName());
+ args = Maps.newHashMap();
+ List all = jpaSupport.findAll("from " + Personne.class.getName(), args);
Assert.assertEquals(3, all.size());
+ args = Maps.newHashMap();
+ args.put("pax", "nobody");
List none = jpaSupport.findAll("from " + Personne.class.getName() +
- " where " + Personne.PROPERTY_NAME + "=:pax", "pax", "nobody");
+ " where " + Personne.PROPERTY_NAME + "=:pax", args);
Assert.assertEquals(0, none.size());
}
@@ -126,14 +136,17 @@
String query = "from " + Personne.class.getName() +
" where " + Personne.PROPERTY_GENDER + "=:g";
- List females = jpaSupport.find(query, 0, 100, "g", Gender.FEMALE);
+
+ Map<String, Object> args = Maps.newHashMap();
+ args.put("g", Gender.FEMALE);
+ List females = jpaSupport.find(query, 0, 100, args);
Assert.assertEquals(2, females.size());
- females = jpaSupport.find(query, 0, 0, "g", Gender.FEMALE);
+ females = jpaSupport.find(query, 0, 0, args);
Assert.assertEquals(1, females.size());
Personne charlotte = (Personne) females.get(0);
- females = jpaSupport.find(query, 1, 1, "g", Gender.FEMALE);
+ females = jpaSupport.find(query, 1, 1, args);
Assert.assertEquals(1, females.size());
Personne hortense = (Personne) females.get(0);
@@ -151,11 +164,15 @@
String query = "from " + Personne.class.getName() +
" where " + Personne.PROPERTY_GENDER + "=:g";
- Object male = jpaSupport.findUnique(query, "g", Gender.MALE);
+ Map<String, Object> args = Maps.newHashMap();
+ args.put("g", Gender.MALE);
+ Object male = jpaSupport.findUnique(query, args);
Assert.assertNotNull(male);
+ args = Maps.newHashMap();
+ args.put("pax", "nobody");
Object none = jpaSupport.findUnique("from " + Personne.class.getName() +
- " where " + Personne.PROPERTY_NAME + "=:pax", "pax", "nobody");
+ " where " + Personne.PROPERTY_NAME + "=:pax", args);
Assert.assertNull(none);
}
@@ -166,7 +183,9 @@
String query = "from " + Personne.class.getName() +
" where " + Personne.PROPERTY_GENDER + "=:g";
- Object female = jpaSupport.findUnique(query, "g", Gender.FEMALE);
+ Map<String, Object> args = Maps.newHashMap();
+ args.put("g", Gender.FEMALE);
+ Object female = jpaSupport.findUnique(query, args);
Assert.assertNotNull(female);
}
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/HibernateTopiaJpaSupport.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/HibernateTopiaJpaSupport.java 2013-11-26 17:19:25 UTC (rev 2895)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/HibernateTopiaJpaSupport.java 2013-11-27 07:38:49 UTC (rev 2896)
@@ -180,32 +180,4 @@
}
}
- @Override
- public <T> List<T> findAll(String jpaql, Object... propertyNamesAndValues) {
- Map<String, Object> parameters = TopiaUtil.convertPropertiesArrayToMap(propertyNamesAndValues);
- List<T> result = findAll(jpaql, parameters);
- return result;
- }
-
- @Override
- public <T> List<T> find(String jpaql, int startIndex, int endIndex, Object... propertyNamesAndValues) {
- Map<String, Object> parameters = TopiaUtil.convertPropertiesArrayToMap(propertyNamesAndValues);
- List<T> result = find(jpaql, startIndex, endIndex, parameters);
- return result;
- }
-
- @Override
- public <T> T findUnique(String jpaql, Object... propertyNamesAndValues) {
- Map<String, Object> parameters = TopiaUtil.convertPropertiesArrayToMap(propertyNamesAndValues);
- T result = findUnique(jpaql, parameters);
- return result;
- }
-
- @Override
- public int execute(String jpaql, Object... propertyNamesAndValues) {
- Map<String, Object> parameters = TopiaUtil.convertPropertiesArrayToMap(propertyNamesAndValues);
- int result = execute(jpaql, parameters);
- return result;
- }
-
} // HibernateTopiaJpaSupport
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaJpaSupport.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaJpaSupport.java 2013-11-26 17:19:25 UTC (rev 2895)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaJpaSupport.java 2013-11-27 07:38:49 UTC (rev 2896)
@@ -50,22 +50,6 @@
Map<String, Object> parameters);
/**
- * Allow to do some JPA-QL query
- * <p/>
- * WARNING : Depending on the registered service, this method may not
- * support something else than queries on TopiaEntity
- *
- * @param jpaql the JPA-QL query
- * @param propertyNamesAndValues the query parameters. Arguments are key-value paired :
- * [propertyName;value;propertyName;value;...]
- * @return The result list
- * @deprecated prefer using {@link #findAll(String, java.util.Map)}
- */
- @Deprecated
- <T> List<T> findAll(String jpaql,
- Object... propertyNamesAndValues);
-
- /**
* Allow to do some JPA-QL query using the given bounds.
* <p/>
* No lower bound : <code>startIndex</code> = 0.<br/>
@@ -74,9 +58,9 @@
* WARNING : Depending on the registered service, this method may not
* support something else than queries on TopiaEntity
*
- * @param jpaql the JPA-QL query
- * @param startIndex first index of entity to return
- * @param endIndex last index of entity to return
+ * @param jpaql the JPA-QL query
+ * @param startIndex first index of entity to return
+ * @param endIndex last index of entity to return
* @param parameters a map which keys are the attribute names and values are the attributes expected values
* @return The result list
*/
@@ -86,29 +70,6 @@
Map<String, Object> parameters);
/**
- * Allow to do some JPA-QL query using the given bounds.
- * <p/>
- * No lower bound : <code>startIndex</code> = 0.<br/>
- * No upper bound : <code>endIndex</code> = -1.
- * <p/>
- * WARNING : Depending on the registered service, this method may not
- * support something else than queries on TopiaEntity
- *
- * @param jpaql the JPA-QL query
- * @param startIndex first index of entity to return
- * @param endIndex last index of entity to return
- * @param propertyNamesAndValues the query parameters. Arguments are key-value paired :
- * [propertyName;value;propertyName;value;...]
- * @return The result list
- * @deprecated prefer using {@link #find(String, int, int, java.util.Map)}
- */
- @Deprecated
- <T> List<T> find(String jpaql,
- int startIndex,
- int endIndex,
- Object... propertyNamesAndValues);
-
- /**
* Allow to do some JPA-QL query and return an unique result. If nothing if
* found by the query, will return null. If more than one result is found,
* will throw an exception.
@@ -116,7 +77,7 @@
* WARNING : Depending on the registered service, this method may not
* support something else than queries on TopiaEntity
*
- * @param jpaql the JPA-QL query
+ * @param jpaql the JPA-QL query
* @param parameters a map which keys are the attribute names and values are the attributes expected values
* @return The result instance or null
*/
@@ -124,27 +85,9 @@
Map<String, Object> parameters);
/**
- * Allow to do some JPA-QL query and return an unique result. If nothing if
- * found by the query, will return null. If more than one result is found,
- * will throw an exception.
- * <p/>
- * WARNING : Depending on the registered service, this method may not
- * support something else than queries on TopiaEntity
- *
- * @param jpaql the JPA-QL query
- * @param propertyNamesAndValues the query parameters. Arguments are key-value paired :
- * [propertyName;value;propertyName;value;...]
- * @return The result instance or null
- * @deprecated prefer using {@link #findUnique(String, java.util.Map)}
- */
- @Deprecated
- <T> T findUnique(String jpaql,
- Object... propertyNamesAndValues);
-
- /**
* Execute JPA-QL operation on data (Update, Delete).
*
- * @param jpaql the JPA-QL query
+ * @param jpaql the JPA-QL query
* @param parameters a map which keys are the attribute names and values are the attributes expected values
* @return The number of entities updated or deleted.
*/
@@ -152,19 +95,6 @@
Map<String, Object> parameters);
/**
- * Execute JPA-QL operation on data (Update, Delete).
- *
- * @param jpaql the JPA-QL query
- * @param propertyNamesAndValues the query parameters. Arguments are key-value paired :
- * [propertyName;value;propertyName;value;...]
- * @return The number of entities updated or deleted.
- * @deprecated prefer using {@link #execute(String, java.util.Map)}
- */
- @Deprecated
- int execute(String jpaql,
- Object... propertyNamesAndValues);
-
- /**
* Tells to the context if it has to use a flush mode before each query.
* <p/>
* By default, we use a flush mode, but in some case it costs to much doing
1
0
r2895 - in trunk: src/site/rst topia-persistence/src/main/java/org/nuiton/topia topia-persistence/src/main/java/org/nuiton/topia/persistence
by athimel@users.nuiton.org Nov. 26, 2013
by athimel@users.nuiton.org Nov. 26, 2013
Nov. 26, 2013
Author: athimel
Date: 2013-11-26 18:19:25 +0100 (Tue, 26 Nov 2013)
New Revision: 2895
Url: http://nuiton.org/projects/topia/repository/revisions/2895
Log:
refs #2923 TopiaContextFactory is adapted
refs #299 Documentation on migration
Modified:
trunk/src/site/rst/migrate_to_3.0.rst
trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaContextFactory.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/AbstractTopiaDao.java
Modified: trunk/src/site/rst/migrate_to_3.0.rst
===================================================================
--- trunk/src/site/rst/migrate_to_3.0.rst 2013-11-26 15:51:34 UTC (rev 2894)
+++ trunk/src/site/rst/migrate_to_3.0.rst 2013-11-26 17:19:25 UTC (rev 2895)
@@ -40,10 +40,32 @@
* Hibernate >= 4.2.1.Final
+Configuration du plugin Maven
+=============================
+
+|MANDATORY|
+
+Les templates sont contenus dans un modules à part, il faut désormais utiliser
+cette dépendance dans le plugin eugene.
+
+::
+
+ <dependency>
+ <groupId>org.nuiton.topia</groupId>
+ <artifactId>topia-templates</artifactId>
+ <version>3.0</version>
+ </dependency>
+
+De plus les templates ont changé de package, le nouveau package est le suivant :
+
+::
+
+ org.nuiton.topia.templates
+
+
Code déprécié
=============
-
La migration vers ToPIA 3.0 voit un certain nombre de classes et attributs dépréciés.
Gérer les impacts n'est pas *nécessaire* pour passer à ToPIA 3.0, mais c'est fortement recommandé. En effet, ce code
@@ -144,7 +166,7 @@
|RECOMMENDED|
Si vous utilisiez explicitement le Transformer de DAO dans la configuration de votre plugin Eugene, il faut maintenant
-changer le nouveau Transformer : org.nuiton.topia.generator.EntityDaoTransformer
+changer le nouveau Transformer : org.nuiton.topia.templates.EntityDaoTransformer
Exemple de configuration :
@@ -161,7 +183,7 @@
<inputs>classpath:model:/:myProject.objectmodel</inputs>
<defaultPackage>org.project.entities</defaultPackage>
<templates>
- org.nuiton.topia.generator.EntityDaoTransformer
+ org.nuiton.topia.templates.EntityDaoTransformer
</templates>
</configuration>
<goals>
@@ -220,26 +242,6 @@
méthodes les remplacer. S'il n'y pas de documentation, il faut remplacer le code appellant par le corps de la méthode dépréciée
(fonctionnalité « inline » dans l'IDE).
-Utilisation des templates de générations
-----------------------------------------
-
-Les templates sont contenues dans un modules à part, il faut désormais utiliser
-cette dépendance dans le plugin eugene.
-
-::
-
- <dependency>
- <groupId>org.nuiton.topia</groupId>
- <artifactId>topia-templates</artifactId>
- <version>3.0</version>
- </dependency>
-
-De plus les templates ont changé de paquetage, le nouveau paquetage est le suivant :
-
-::
-
- org.nuiton.topia.templates
-
Amélioration du code sql
------------------------
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaContextFactory.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaContextFactory.java 2013-11-26 15:51:34 UTC (rev 2894)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaContextFactory.java 2013-11-26 17:19:25 UTC (rev 2895)
@@ -182,8 +182,8 @@
* @return Un TopiaContext ouvert
* @throws TopiaNotFoundException if any pb
*/
- public static AbstractTopiaApplicationContext getContext(
- Properties config, Function<Properties, AbstractTopiaApplicationContext> createContextFunction)
+ public static <C extends AbstractTopiaApplicationContext> C getContext(
+ Properties config, Function<Properties, C> createContextFunction)
throws TopiaNotFoundException {
// Put all properties from a hierarchy in the current properties object.
// Resolve problem with hibernate which used iterator to get properties
@@ -193,7 +193,7 @@
for (String key : config.stringPropertyNames()) {
cloned.setProperty(key, config.getProperty(key));
}
- AbstractTopiaApplicationContext result = contextCache.get(cloned);
+ C result = (C)contextCache.get(cloned);
if (result == null || result.isClosed()) {
if (createContextFunction == null) {
throw new TopiaException("Function<Properties, AbstractTopiaApplicationContext> is needed to create context");
Modified: 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-11-26 15:51:34 UTC (rev 2894)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/AbstractTopiaDao.java 2013-11-26 17:19:25 UTC (rev 2895)
@@ -475,7 +475,7 @@
}
protected <R> R findUniqueOrNull(String hql, Map<String, Object> hqlParameters, Class<R> type) throws TopiaNonUniqueResultException {
- List<R> results = findAll(hql, hqlParameters, type, 0, 1);
+ List<R> results = find(hql, hqlParameters, type, 0, 1);
// If there is more than 1 result, throw an exception
if (results.size() > 1) {
throw new TopiaNonUniqueResultException(hql, hqlParameters);
@@ -524,7 +524,7 @@
protected <R> R findAnyOrNull(String hql, Map<String, Object> hqlParameters, Class<R> type) {
Preconditions.checkNotNull(hql);
Preconditions.checkNotNull(hqlParameters);
- List<R> results = findAll(hql, hqlParameters, type, 0, 0);
+ List<R> results = find(hql, hqlParameters, type, 0, 0);
R result = Iterables.getOnlyElement(results, null);
return result;
}
@@ -536,15 +536,15 @@
return result;
}
- protected List<E> findAll(String hql, Map<String, Object> hqlParameters, int startIndex, int endIndex) {
+ protected List<E> find(String hql, Map<String, Object> hqlParameters, int startIndex, int endIndex) {
Preconditions.checkNotNull(hql);
Preconditions.checkNotNull(hqlParameters);
List<E> result = topiaJpaSupport.find(hql, startIndex, endIndex, hqlParameters);
return result;
}
- protected List<E> findAll(String hql, Map<String, Object> hqlParameters, TopiaPagerBean pager) {
- List<E> result = findAll(hql, hqlParameters, getEntityClass(), pager);
+ protected List<E> find(String hql, Map<String, Object> hqlParameters, TopiaPagerBean pager) {
+ List<E> result = find(hql, hqlParameters, getEntityClass(), pager);
return result;
}
@@ -556,7 +556,7 @@
return result;
}
- protected <R> List<R> findAll(String hql, Map<String, Object> hqlParameters, Class<R> type, int startIndex, int endIndex) {
+ protected <R> List<R> find(String hql, Map<String, Object> hqlParameters, Class<R> type, int startIndex, int endIndex) {
Preconditions.checkNotNull(hql);
Preconditions.checkNotNull(hqlParameters);
Preconditions.checkNotNull(type);
@@ -564,7 +564,7 @@
return result;
}
- protected <R> List<R> findAll(String hql, Map<String, Object> hqlParameters, Class<R> type, TopiaPagerBean pager) {
+ protected <R> List<R> find(String hql, Map<String, Object> hqlParameters, Class<R> type, TopiaPagerBean pager) {
Preconditions.checkNotNull(hql);
Preconditions.checkNotNull(hqlParameters);
Preconditions.checkNotNull(type);
@@ -753,7 +753,7 @@
PagerBeanUtil.computeRecordIndexesAndPagesNumber(pager);
// load new window of data
- data = dao.findAll(hql, params, type, pager).iterator();
+ data = dao.find(hql, params, type, pager).iterator();
}
@@ -1027,7 +1027,7 @@
@Override
public List<E> find(int startIndex, int endIndex) {
- return topiaDAO.findAll(hql, hqlParameters, startIndex, endIndex);
+ return topiaDAO.find(hql, hqlParameters, startIndex, endIndex);
}
@Override
@@ -1041,7 +1041,7 @@
public List<String> findIds(int startIndex, int endIndex) {
// XXX brendan 30/09/13 does this truely work ?
String hqlWithSelectClause = "select topiaId " + hql;
- return topiaDAO.findAll(hqlWithSelectClause, hqlParameters, String.class, startIndex, endIndex);
+ return topiaDAO.find(hqlWithSelectClause, hqlParameters, String.class, startIndex, endIndex);
}
}
1
0
r2894 - in trunk: topia-persistence/src/main/java/org/nuiton/topia topia-templates/src/main/java/org/nuiton/topia/templates
by athimel@users.nuiton.org Nov. 26, 2013
by athimel@users.nuiton.org Nov. 26, 2013
Nov. 26, 2013
Author: athimel
Date: 2013-11-26 16:51:34 +0100 (Tue, 26 Nov 2013)
New Revision: 2894
Url: http://nuiton.org/projects/topia/repository/revisions/2894
Log:
SVN properties and file headers
Modified:
trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaSqlWork.java
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityEnumTransformer.java
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaSqlWork.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaSqlWork.java 2013-11-26 15:51:16 UTC (rev 2893)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaSqlWork.java 2013-11-26 15:51:34 UTC (rev 2894)
@@ -1,5 +1,29 @@
package org.nuiton.topia;
+/*
+ * #%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.sql.Connection;
import java.sql.SQLException;
Property changes on: trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaSqlWork.java
___________________________________________________________________
Modified: svn:keywords
- Author Date Id Revision
+ Author Date Id Revision HeadURL
Modified: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityEnumTransformer.java
===================================================================
--- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityEnumTransformer.java 2013-11-26 15:51:16 UTC (rev 2893)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityEnumTransformer.java 2013-11-26 15:51:34 UTC (rev 2894)
@@ -3,8 +3,8 @@
/*
* #%L
* ToPIA :: Templates
- * $Id: ApplicationContextTransformer.java 2885 2013-11-22 20:03:11Z tchemit $
- * $HeadURL: http://svn.nuiton.org/svn/topia/trunk/topia-templates/src/main/java/org/nui… $
+ * $Id$
+ * $HeadURL$
* %%
* Copyright (C) 2004 - 2013 CodeLutin
* %%
Property changes on: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityEnumTransformer.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
1
0
Nov. 26, 2013
Author: athimel
Date: 2013-11-26 16:51:16 +0100 (Tue, 26 Nov 2013)
New Revision: 2893
Url: http://nuiton.org/projects/topia/repository/revisions/2893
Log:
refs #2923 Remove DAOHelperTransformer from TopiaMetaTransformer
Added:
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityEnumTransformer.java
Modified:
trunk/topia-it/src/main/java/org/nuiton/topia/it/TopiaConfigurationHelper.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TestHelper.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaDatabase.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaConnectionProviderTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextReplicateTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/generator/TopiaTestCase.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/NaturalIdTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/CollectorTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/EntityOperatorTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityBinderTest.java
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/TopiaEntityRefTesterTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/ano1882/DAOAbstractTransformerTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/EnumTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/DeleteEntityTest.java
trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationOperationTest.java
trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplAllTest.java
trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplTest.java
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/ApplicationContextTransformer.java
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/BinderHelperTransformer.java
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/DAOHelperTransformer.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/TopiaMetaTransformer.java
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaTagValues.java
Modified: trunk/topia-it/src/main/java/org/nuiton/topia/it/TopiaConfigurationHelper.java
===================================================================
--- trunk/topia-it/src/main/java/org/nuiton/topia/it/TopiaConfigurationHelper.java 2013-11-25 15:28:01 UTC (rev 2892)
+++ trunk/topia-it/src/main/java/org/nuiton/topia/it/TopiaConfigurationHelper.java 2013-11-26 15:51:16 UTC (rev 2893)
@@ -27,10 +27,8 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.cfg.Environment;
-import org.nuiton.topia.AbstractTopiaApplicationContext;
import org.nuiton.topia.TopiaContextFactory;
-import org.nuiton.topia.TopiaNotFoundException;
-import org.nuiton.topia.it.legacy.TopiaTestDAOHelper;
+import org.nuiton.topia.it.legacy.TopiaTestEntityEnum;
import org.nuiton.topia.junit.ConfigurationHelper;
import java.io.File;
@@ -106,7 +104,7 @@
configuration.load(stream);
configuration.setProperty(
TopiaContextFactory.CONFIG_PERSISTENCE_CLASSES,
- TopiaTestDAOHelper.getImplementationClassesAsString());
+ TopiaTestEntityEnum.getImplementationClassesAsString());
return configuration;
}
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TestHelper.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TestHelper.java 2013-11-25 15:28:01 UTC (rev 2892)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TestHelper.java 2013-11-26 15:51:16 UTC (rev 2893)
@@ -150,7 +150,7 @@
configuration.load(stream);
configuration.setProperty(
TopiaContextFactory.CONFIG_PERSISTENCE_CLASSES,
- TopiaTestDAOHelper.getImplementationClassesAsString());
+ TopiaTestEntityEnum.getImplementationClassesAsString());
return configuration;
}
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaDatabase.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaDatabase.java 2013-11-25 15:28:01 UTC (rev 2892)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaDatabase.java 2013-11-26 15:51:16 UTC (rev 2893)
@@ -72,7 +72,7 @@
@Override
protected String getImplementationClassesAsString() {
- return TopiaTestDAOHelper.getImplementationClassesAsString();
+ return TopiaTestEntityEnum.getImplementationClassesAsString();
}
}
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaConnectionProviderTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaConnectionProviderTest.java 2013-11-25 15:28:01 UTC (rev 2892)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaConnectionProviderTest.java 2013-11-26 15:51:16 UTC (rev 2893)
@@ -24,23 +24,22 @@
*/
package org.nuiton.topia.it.legacy.framework;
+import java.io.File;
+import java.util.Locale;
+import java.util.Properties;
+
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.nuiton.topia.TopiaContextFactory;
import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.it.legacy.TopiaTestDAOHelper;
-import org.nuiton.topia.it.legacy.TopiaTestTopiaPersistenceContext;
import org.nuiton.topia.framework.TopiaConnectionProvider;
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 org.nuiton.topia.it.legacy.topiatest.Personne;
-import java.io.File;
-import java.util.Locale;
-import java.util.Properties;
-
import static org.junit.Assert.assertNotNull;
/**
@@ -126,7 +125,7 @@
TopiaTestTopiaPersistenceContext transaction = db.beginTransaction();
try {
- PersonTopiaDao dao = TopiaTestDAOHelper.getPersonTopiaDao(transaction);
+ PersonTopiaDao dao = transaction.getPersonDao();
Person personne = dao.create(Personne.PROPERTY_NAME, "Jack Bauer");
transaction.commit();
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextReplicateTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextReplicateTest.java 2013-11-25 15:28:01 UTC (rev 2892)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextReplicateTest.java 2013-11-26 15:51:16 UTC (rev 2893)
@@ -32,7 +32,6 @@
import org.junit.Test;
import org.nuiton.topia.TopiaContextFactory;
import org.nuiton.topia.it.legacy.TopiaDatabase;
-import org.nuiton.topia.it.legacy.TopiaTestDAOHelper;
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;
@@ -98,8 +97,8 @@
Pet petSource, petTarget;
txSource = dbSource.beginTransaction();
- daoSource = TopiaTestDAOHelper.getPersonTopiaDao(txSource);
- petDAOSource = TopiaTestDAOHelper.getPetTopiaDao(txSource);
+ daoSource = txSource.getPersonDao();
+ petDAOSource = txSource.getPetDao();
personSource = daoSource.create(Person.PROPERTY_FIRSTNAME, " firstName",
Person.PROPERTY_NAME, " name"
@@ -114,7 +113,7 @@
txSource.commit();
- daoSource = TopiaTestDAOHelper.getPersonTopiaDao(txSource);
+ daoSource = txSource.getPersonDao();
personSource = daoSource.findByTopiaId(personSource.getTopiaId());
Assert.assertNotNull(personSource);
@@ -131,8 +130,8 @@
txTarget.commit();
- daoTarget = TopiaTestDAOHelper.getPersonTopiaDao(txTarget);
- petDAOTarget = TopiaTestDAOHelper.getPetTopiaDao(txTarget);
+ daoTarget = txTarget.getPersonDao();
+ petDAOTarget = txTarget.getPetDao();
personTarget = daoTarget.findByTopiaId(personSource.getTopiaId());
Assert.assertNotNull(personTarget);
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/generator/TopiaTestCase.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/generator/TopiaTestCase.java 2013-11-25 15:28:01 UTC (rev 2892)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/generator/TopiaTestCase.java 2013-11-26 15:51:16 UTC (rev 2893)
@@ -32,7 +32,6 @@
import org.junit.Test;
import org.nuiton.topia.TopiaException;
import org.nuiton.topia.it.legacy.TopiaDatabase;
-import org.nuiton.topia.it.legacy.TopiaTestDAOHelper;
import org.nuiton.topia.it.legacy.TopiaTestTopiaPersistenceContext;
import org.nuiton.topia.it.legacy.topiatest.Company;
import org.nuiton.topia.it.legacy.topiatest.CompanyTopiaDao;
@@ -154,7 +153,7 @@
newContext = db.beginTransaction();
- companyDAO = TopiaTestDAOHelper.getCompanyTopiaDao(newContext);
+ companyDAO = newContext.getCompanyDao();
company = companyDAO.findByTopiaId(company.getTopiaId());
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/NaturalIdTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/NaturalIdTest.java 2013-11-25 15:28:01 UTC (rev 2892)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/NaturalIdTest.java 2013-11-26 15:51:16 UTC (rev 2893)
@@ -33,7 +33,7 @@
import org.junit.Test;
import org.nuiton.topia.it.legacy.TopiaDatabase;
import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.it.legacy.TopiaTestDAOHelper;
+import org.nuiton.topia.it.legacy.TopiaTestEntityEnum;
import org.nuiton.topia.it.legacy.TopiaTestTopiaPersistenceContext;
import org.nuiton.topia.it.legacy.topiatest.NaturalizedEntity;
import org.nuiton.topia.it.legacy.topiatest.NaturalizedEntityTopiaDao;
@@ -169,8 +169,8 @@
public void testNaturalIdAreGeneralized() throws Exception {
// test that natural ids are generalized
- String[] generalizedNaturalizedNaturalIds = TopiaTestDAOHelper.TopiaTestEntityEnum.GeneralizedNaturalizedEntity.getNaturalIds();
- String[] naturalizedNaturalIds = TopiaTestDAOHelper.TopiaTestEntityEnum.NaturalizedEntity.getNaturalIds();
+ String[] generalizedNaturalizedNaturalIds = TopiaTestEntityEnum.GeneralizedNaturalizedEntity.getNaturalIds();
+ String[] naturalizedNaturalIds = TopiaTestEntityEnum.NaturalizedEntity.getNaturalIds();
Assert.assertArrayEquals(generalizedNaturalizedNaturalIds, naturalizedNaturalIds);
}
@@ -178,8 +178,8 @@
public void testNotNullsAreGeneralized() throws Exception {
// test that not nulls are generalized
- String[] generalizedNaturalizedNotNulls = TopiaTestDAOHelper.TopiaTestEntityEnum.GeneralizedNaturalizedEntity.getNotNulls();
- String[] naturalizedNotNulls = TopiaTestDAOHelper.TopiaTestEntityEnum.NaturalizedEntity.getNotNulls();
+ String[] generalizedNaturalizedNotNulls = TopiaTestEntityEnum.GeneralizedNaturalizedEntity.getNotNulls();
+ String[] naturalizedNotNulls = TopiaTestEntityEnum.NaturalizedEntity.getNotNulls();
Assert.assertArrayEquals(generalizedNaturalizedNotNulls, naturalizedNotNulls);
}
}
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/CollectorTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/CollectorTest.java 2013-11-25 15:28:01 UTC (rev 2892)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/CollectorTest.java 2013-11-26 15:51:16 UTC (rev 2893)
@@ -32,7 +32,7 @@
import org.junit.BeforeClass;
import org.junit.Test;
import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.it.legacy.TopiaTestDAOHelper;
+import org.nuiton.topia.it.legacy.TopiaTestEntityEnum;
import org.nuiton.topia.persistence.TopiaEntity;
import org.nuiton.topia.persistence.TopiaEntityEnum;
import org.nuiton.topia.it.legacy.topiatest.Company;
@@ -45,15 +45,13 @@
/** @author tchemit <chemit(a)codelutin.com> */
public class CollectorTest {
-
private static Log log = LogFactory.getLog(CollectorTest.class);
-
static TopiaEntityEnum[] contracts;
@BeforeClass
public static void setUpClass() throws Exception {
- contracts = TopiaTestDAOHelper.getContracts();
+ contracts = TopiaTestEntityEnum.getContracts();
}
@AfterClass
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/EntityOperatorTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/EntityOperatorTest.java 2013-11-25 15:28:01 UTC (rev 2892)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/EntityOperatorTest.java 2013-11-26 15:51:16 UTC (rev 2893)
@@ -30,7 +30,7 @@
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
-import org.nuiton.topia.it.legacy.TopiaTestDAOHelper;
+import org.nuiton.topia.it.legacy.TopiaTestEntityEnum;
import org.nuiton.topia.it.legacy.topiatest.Company;
import org.nuiton.topia.it.legacy.topiatest.CompanyImpl;
import org.nuiton.topia.it.legacy.topiatest.Department;
@@ -73,10 +73,10 @@
@BeforeClass
public static void setUpClass() throws Exception {
- operationC = TopiaTestDAOHelper.getOperator(Company.class);
- operationE = TopiaTestDAOHelper.getOperator(Employe.class);
- operationP = TopiaTestDAOHelper.getOperator(Personne.class);
- operationD = TopiaTestDAOHelper.getOperator(Department.class);
+ operationC = TopiaTestEntityEnum.getOperator(Company.class);
+ operationE = TopiaTestEntityEnum.getOperator(Employe.class);
+ operationP = TopiaTestEntityEnum.getOperator(Personne.class);
+ operationD = TopiaTestEntityEnum.getOperator(Department.class);
}
@AfterClass
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityBinderTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityBinderTest.java 2013-11-25 15:28:01 UTC (rev 2892)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityBinderTest.java 2013-11-26 15:51:16 UTC (rev 2893)
@@ -30,7 +30,7 @@
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
-import org.nuiton.topia.it.legacy.TopiaTestDAOHelper;
+import org.nuiton.topia.it.legacy.TopiaTestEntityEnum;
import org.nuiton.topia.persistence.TopiaEntity;
import org.nuiton.topia.persistence.TopiaEntityEnum;
import org.nuiton.topia.it.legacy.topiatest.Company;
@@ -44,7 +44,7 @@
@BeforeClass
public static void setUpClass() throws Exception {
- contracts = TopiaTestDAOHelper.getContracts();
+ contracts = TopiaTestEntityEnum.getContracts();
}
public static class CompanyDTO {
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-11-25 15:28:01 UTC (rev 2892)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityHelperTest.java 2013-11-26 15:51:16 UTC (rev 2893)
@@ -30,7 +30,7 @@
import org.junit.BeforeClass;
import org.junit.Test;
import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.it.legacy.TopiaTestDAOHelper;
+import org.nuiton.topia.it.legacy.TopiaTestEntityEnum;
import org.nuiton.topia.persistence.DefaultTopiaIdFactory;
import org.nuiton.topia.persistence.TopiaEntity;
import org.nuiton.topia.persistence.TopiaEntityEnum;
@@ -75,7 +75,7 @@
@BeforeClass
public static void setUpClass() throws Exception {
- contracts = TopiaTestDAOHelper.getContracts();
+ contracts = TopiaTestEntityEnum.getContracts();
}
@AfterClass
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityRefTesterTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityRefTesterTest.java 2013-11-25 15:28:01 UTC (rev 2892)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityRefTesterTest.java 2013-11-26 15:51:16 UTC (rev 2893)
@@ -28,7 +28,7 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
-import org.nuiton.topia.it.legacy.TopiaTestDAOHelper.TopiaTestEntityEnum;
+import org.nuiton.topia.it.legacy.TopiaTestEntityEnum;
import org.nuiton.topia.it.legacy.test.entities.Person;
import org.nuiton.topia.it.legacy.test.entities.Pet;
import org.nuiton.topia.it.legacy.test.entities.Race;
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/ano1882/DAOAbstractTransformerTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/ano1882/DAOAbstractTransformerTest.java 2013-11-25 15:28:01 UTC (rev 2892)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/ano1882/DAOAbstractTransformerTest.java 2013-11-26 15:51:16 UTC (rev 2893)
@@ -29,7 +29,6 @@
import org.junit.Rule;
import org.junit.Test;
import org.nuiton.topia.it.legacy.TopiaDatabase;
-import org.nuiton.topia.it.legacy.TopiaTestDAOHelper;
import org.nuiton.topia.it.legacy.TopiaTestTopiaPersistenceContext;
public class DAOAbstractTransformerTest {
@@ -41,8 +40,8 @@
public void testAno1882() throws Exception {
TopiaTestTopiaPersistenceContext transaction = db.beginTransaction();
- FrenchCompanyTopiaDao dao = TopiaTestDAOHelper.getFrenchCompanyTopiaDao(transaction);
- SIRETTopiaDao siretDAO = TopiaTestDAOHelper.getSIRETTopiaDao(transaction);
+ FrenchCompanyTopiaDao dao = transaction.getFrenchCompanyDao();
+ SIRETTopiaDao siretDAO = transaction.getSIRETDao();
SIRET siret = siretDAO.create();
FrenchCompany entity =
dao.create(
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/EnumTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/EnumTest.java 2013-11-25 15:28:01 UTC (rev 2892)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/EnumTest.java 2013-11-26 15:51:16 UTC (rev 2893)
@@ -29,7 +29,6 @@
import org.junit.Test;
import org.nuiton.topia.it.legacy.TopiaDatabase;
import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.it.legacy.TopiaTestDAOHelper;
import org.nuiton.topia.it.legacy.TopiaTestTopiaPersistenceContext;
/**
@@ -53,7 +52,7 @@
public void storeEntityWithEnumValue() throws TopiaException {
TopiaTestTopiaPersistenceContext transaction = db.beginTransaction();
- PersonneTopiaDao dao = TopiaTestDAOHelper.getPersonneTopiaDao(transaction);
+ PersonneTopiaDao dao = transaction.getPersonneDao();
Personne personne = new PersonneImpl();
personne.setGender(Gender.FEMALE);
personne.setOtherGender(Gender.MALE);
@@ -63,7 +62,7 @@
transaction.closeContext();
transaction = db.beginTransaction();
- dao = TopiaTestDAOHelper.getPersonneTopiaDao(transaction);
+ dao = transaction.getPersonneDao();
dao.findByTopiaId(topiaId);
Assert.assertEquals(Gender.FEMALE, personne.getGender());
Assert.assertEquals(Gender.MALE, personne.getOtherGender());
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/DeleteEntityTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/DeleteEntityTest.java 2013-11-25 15:28:01 UTC (rev 2892)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/DeleteEntityTest.java 2013-11-26 15:51:16 UTC (rev 2893)
@@ -45,7 +45,6 @@
import org.junit.Test;
import org.nuiton.topia.TopiaException;
import org.nuiton.topia.it.legacy.TopiaDatabase;
-import org.nuiton.topia.it.legacy.TopiaTestDAOHelper;
import org.nuiton.topia.it.legacy.TopiaTestTopiaPersistenceContext;
import org.nuiton.topia.it.legacy.topiatest.Gender;
import org.nuiton.topia.it.legacy.topiatest.Personne;
@@ -84,7 +83,7 @@
TopiaTestTopiaPersistenceContext transaction = db.beginTransaction();
log.debug("DAO : PersonneDAO");
- PersonneTopiaDao dao = TopiaTestDAOHelper.getPersonneTopiaDao(transaction);
+ PersonneTopiaDao dao = transaction.getPersonneDao();
log.debug("CREATE PERSONNE : Bob Marley");
Personne personne = dao.create(Personne.PROPERTY_NAME, "Bob Marley");
@@ -108,7 +107,7 @@
log.debug("ENTITY PERSONNE SAVED !");
log.debug("DAO parent (abstract) : PartyDAO");
- Party2TopiaDao dao2 = TopiaTestDAOHelper.getParty2TopiaDao(transaction);
+ Party2TopiaDao dao2 = transaction.getParty2Dao();
log.debug("DELETE PERSONNE with PartyDAO");
dao2.delete(personne2);
@@ -134,7 +133,7 @@
TopiaTestTopiaPersistenceContext transaction = db.beginTransaction();
- PersonneTopiaDao dao = TopiaTestDAOHelper.getPersonneTopiaDao(transaction);
+ PersonneTopiaDao dao = transaction.getPersonneDao();
log.debug("CREATE PERSONNE : Bob Marley");
Personne personne = dao.create(Personne.PROPERTY_NAME, "Bob Marley");
@@ -143,7 +142,7 @@
assertNotNull(idPersonne);
log.debug("ENTITY PERSONNE SAVED !");
- Contact2TopiaDao contactDAO = TopiaTestDAOHelper.getContact2TopiaDao(transaction);
+ Contact2TopiaDao contactDAO = transaction.getContact2Dao();
log.debug("CREATE CONTACT : jaja(a)codelutin.com");
Contact2 contact = contactDAO.create(Contact2.PROPERTY_CONTACT_VALUE, "jaja(a)codelutin.com");
@@ -185,7 +184,7 @@
TopiaTestTopiaPersistenceContext transaction = db.beginTransaction();
- PersonneTopiaDao dao = TopiaTestDAOHelper.getPersonneTopiaDao(transaction);
+ PersonneTopiaDao dao = transaction.getPersonneDao();
Personne person = dao.newInstance();
Assert.assertNull(person.getTopiaId());
Modified: trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationOperationTest.java
===================================================================
--- trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationOperationTest.java 2013-11-25 15:28:01 UTC (rev 2892)
+++ trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationOperationTest.java 2013-11-26 15:51:16 UTC (rev 2893)
@@ -36,7 +36,7 @@
import org.nuiton.topia.TopiaContextFactory;
import org.nuiton.topia.TopiaPersistenceContext;
import org.nuiton.topia.it.TopiaConfigurationHelper;
-import org.nuiton.topia.it.legacy.TopiaTestDAOHelper.TopiaTestEntityEnum;
+import org.nuiton.topia.it.legacy.TopiaTestEntityEnum;
import org.nuiton.topia.it.legacy.test.entities.Person;
import org.nuiton.topia.it.legacy.test.entities.PersonImpl;
import org.nuiton.topia.it.legacy.test.entities.Pet;
Modified: trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplAllTest.java
===================================================================
--- trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplAllTest.java 2013-11-25 15:28:01 UTC (rev 2892)
+++ trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplAllTest.java 2013-11-26 15:51:16 UTC (rev 2893)
@@ -37,6 +37,7 @@
import org.nuiton.topia.TopiaException;
import org.nuiton.topia.TopiaPersistenceContext;
import org.nuiton.topia.it.TopiaConfigurationHelper;
+import org.nuiton.topia.it.legacy.TopiaTestEntityEnum;
import org.nuiton.topia.it.legacy.test.entities.Person;
import org.nuiton.topia.it.legacy.test.entities.PersonImpl;
import org.nuiton.topia.it.legacy.test.entities.Pet;
@@ -50,8 +51,6 @@
import java.io.IOException;
import java.util.Properties;
-import static org.nuiton.topia.it.legacy.TopiaTestDAOHelper.TopiaTestEntityEnum;
-
/**
* TopiaReplicationServiceImplTest on model TopiaTest
* <p/>
Modified: trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplTest.java
===================================================================
--- trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplTest.java 2013-11-25 15:28:01 UTC (rev 2892)
+++ trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplTest.java 2013-11-26 15:51:16 UTC (rev 2893)
@@ -37,6 +37,7 @@
import org.nuiton.topia.TopiaException;
import org.nuiton.topia.TopiaPersistenceContext;
import org.nuiton.topia.it.TopiaConfigurationHelper;
+import org.nuiton.topia.it.legacy.TopiaTestEntityEnum;
import org.nuiton.topia.it.legacy.test.entities.Person;
import org.nuiton.topia.it.legacy.test.entities.PersonImpl;
import org.nuiton.topia.it.legacy.test.entities.Pet;
@@ -56,8 +57,6 @@
import java.io.IOException;
import java.util.Properties;
-import static org.nuiton.topia.it.legacy.TopiaTestDAOHelper.TopiaTestEntityEnum;
-
/**
* TopiaReplicationServiceImplTest on model TopiaTest
* <p/>
Modified: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/ApplicationContextTransformer.java
===================================================================
--- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/ApplicationContextTransformer.java 2013-11-25 15:28:01 UTC (rev 2892)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/ApplicationContextTransformer.java 2013-11-26 15:51:16 UTC (rev 2893)
@@ -120,15 +120,15 @@
boolean generateOperator =
TopiaGeneratorUtil.shouldGenerateOperatorForDAOHelper(model);
- boolean generateStandaloneEnum =
- TopiaGeneratorUtil.shouldGenerateStandaloneEnumForDAOHelper(model);
+// boolean generateStandaloneEnum =
+// TopiaGeneratorUtil.shouldGenerateStandaloneEnumForDAOHelper(model);
+//
+// if (!generateStandaloneEnum) {
+//
+// addImport(output, packageName + "." + daoHelperClazzName + "." + entityEnumName);
+//
+// }
- if (!generateStandaloneEnum) {
-
- addImport(output, packageName + "." + daoHelperClazzName + "." + entityEnumName);
-
- }
-
addImport(output, TopiaEntity.class);
addImport(output, Array.class);
addImport(output, Array.class);
Modified: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/BinderHelperTransformer.java
===================================================================
--- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/BinderHelperTransformer.java 2013-11-25 15:28:01 UTC (rev 2892)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/BinderHelperTransformer.java 2013-11-26 15:51:16 UTC (rev 2893)
@@ -77,15 +77,18 @@
String binderHelperClazzName = modelName + "BinderHelper";
String daoHelperClazzName = modelName + "DAOHelper";
+ String entityEnumName = TopiaGeneratorUtil.getEntityEnumName(model);
+ String entityEnumPackage = packageName + "." + entityEnumName;
+
resultClass = createClass(binderHelperClazzName, packageName);
setSuperClass(resultClass, BinderFactory.class);
-
addImport(resultClass, TopiaEntityBinder.class);
addImport(resultClass, TopiaEntityHelper.class);
addImport(resultClass, TopiaEntity.class);
addImport(resultClass, BinderModelBuilder.class);
+ addImport(resultClass, entityEnumPackage);
ObjectModelOperation op;
@@ -153,10 +156,10 @@
addParameter(op, "boolean", "tech");
setOperationBody(op, ""
/*{
- Class<E> entityClass = (Class<E>) TopiaEntityHelper.getContractClass(<%=daoHelperClazzName%>.getContracts(), target.getClass());
+ Class<E> entityClass = (Class<E>) TopiaEntityHelper.getContractClass(<%=entityEnumName%>.values(), target.getClass());
TopiaEntityBinder<E> binder = getTopiaBinder(entityClass, contextName);
if (binder == null) {
- throw new NullPointerException("could not find a simple topia binder of type : " + target.getClass());
+ throw new NullPointerException("Could not find a simple topia binder of type : " + target.getClass());
}
binder.load(source, target, tech);
}*/
@@ -172,10 +175,10 @@
addParameter(op, "boolean", "tech");
setOperationBody(op, ""
/*{
- Class<E> entityClass = (Class<E>) TopiaEntityHelper.getContractClass(<%=daoHelperClazzName%>.getContracts(), target.getClass());
+ Class<E> entityClass = (Class<E>) TopiaEntityHelper.getContractClass(<%=entityEnumName%>.values(), target.getClass());
TopiaEntityBinder<E> binder = getSimpleTopiaBinder(entityClass);
if (binder == null) {
- throw new NullPointerException("could not find a simple topia binder of type : " + target.getClass());
+ throw new NullPointerException("Could not find a simple topia binder of type : " + target.getClass());
}
binder.load(source, target, tech);
}*/
Modified: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/DAOHelperTransformer.java
===================================================================
--- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/DAOHelperTransformer.java 2013-11-25 15:28:01 UTC (rev 2892)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/DAOHelperTransformer.java 2013-11-26 15:51:16 UTC (rev 2893)
@@ -62,6 +62,7 @@
* @version $Id$
* @since 2.3.0
* @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.templates.DAOHelperTransformer"
+ * @deprecated Will be removed before 3.0
*/
public class DAOHelperTransformer extends ObjectModelTransformerToJava {
@@ -82,15 +83,15 @@
boolean generateOperator =
TopiaGeneratorUtil.shouldGenerateOperatorForDAOHelper(model);
- boolean generateStandaloneEnum =
- TopiaGeneratorUtil.shouldGenerateStandaloneEnumForDAOHelper(model);
+// boolean generateStandaloneEnum =
+// TopiaGeneratorUtil.shouldGenerateStandaloneEnumForDAOHelper(model);
ObjectModelClass daoHelper = createClass(daoHelperClazzName,
packageName);
ObjectModelEnumeration entityEnum;
- if (generateStandaloneEnum) {
+// if (generateStandaloneEnum) {
if (log.isDebugEnabled()) {
log.debug("Will generate standalone " + entityEnumName +
" in package " + packageName);
@@ -101,17 +102,17 @@
addImport(entityEnum, Arrays.class);
addImport(entityEnum, ArrayUtils.class);
- } else {
- entityEnum = (ObjectModelEnumerationImpl)
- addInnerClassifier(daoHelper,
- ObjectModelType.OBJECT_MODEL_ENUMERATION,
- entityEnumName
- );
- addImport(daoHelper, TopiaEntityEnum.class);
- addImport(daoHelper, EntityOperatorStore.class);
- addImport(daoHelper, Arrays.class);
- addImport(daoHelper, ArrayUtils.class);
- }
+// } else {
+// entityEnum = (ObjectModelEnumerationImpl)
+// addInnerClassifier(daoHelper,
+// ObjectModelType.OBJECT_MODEL_ENUMERATION,
+// entityEnumName
+// );
+// addImport(daoHelper, TopiaEntityEnum.class);
+// addImport(daoHelper, EntityOperatorStore.class);
+// addImport(daoHelper, Arrays.class);
+// addImport(daoHelper, ArrayUtils.class);
+// }
// generate DAOHelper
createDAOHelper(model,
@@ -127,7 +128,6 @@
daoHelperClazzName,
entityEnumName,
generateOperator,
- generateStandaloneEnum,
classes
);
}
@@ -306,7 +306,6 @@
String daoHelperClazzName,
String entityEnumName,
boolean generateOperator,
- boolean generateStandaloneEnum,
List<ObjectModelClass> classes) {
ObjectModelAttributeImpl attr;
@@ -346,9 +345,9 @@
}
addLiteral(entityEnum, clazzName + '(' + params.toString() + ')');
- if (generateStandaloneEnum) {
+// if (generateStandaloneEnum) {
addImport(entityEnum, clazz);
- }
+// }
}
attr = (ObjectModelAttributeImpl) addAttribute(entityEnum, "contract", "Class<? extends TopiaEntity>");
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-11-25 15:28:01 UTC (rev 2892)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityDaoTransformer.java 2013-11-26 15:51:16 UTC (rev 2893)
@@ -104,8 +104,6 @@
@Override
public void transformFromModel(ObjectModel model) {
- boolean generateStandaloneEnum =
- TopiaGeneratorUtil.shouldGenerateStandaloneEnumForDAOHelper(model);
String modelName = model.getName();
entityEnumName = modelName + "EntityEnum";
@@ -113,12 +111,7 @@
String packageName =
getOutputProperties().getProperty(PROP_DEFAULT_PACKAGE);
- if (generateStandaloneEnum) {
- entityEnumPackage = packageName + "." + entityEnumName;
- } else {
- String daoHelperClazzName = modelName + "DAOHelper";
- entityEnumPackage = packageName + "." + daoHelperClazzName + "." + entityEnumName;
- }
+ entityEnumPackage = packageName + "." + entityEnumName;
usages = TopiaGeneratorUtil.searchDirectUsages(model);
@@ -575,7 +568,7 @@
"from <%=attrClassifierDBName%> main, <%=attrJoinTableName%> secondary " +
"where main.topiaid=secondary.<%=attrDBName%>" +
" and secondary.<%=attrReverseDBName%>='" + entity.getTopiaId() + "'")
- .addEntity("main", <%=providerFQN%>(<%=attrType%>.class)).list();
+ .addEntity("main", <%=entityEnumName%>.<%=attrType%>.getImplementation()).list();
for (<%=attrType%> item : list) {
item.<%=removeName%>(entity);
Added: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityEnumTransformer.java
===================================================================
--- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityEnumTransformer.java (rev 0)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityEnumTransformer.java 2013-11-26 15:51:16 UTC (rev 2893)
@@ -0,0 +1,401 @@
+package org.nuiton.topia.templates;
+
+/*
+ * #%L
+ * ToPIA :: Templates
+ * $Id: ApplicationContextTransformer.java 2885 2013-11-22 20:03:11Z tchemit $
+ * $HeadURL: http://svn.nuiton.org/svn/topia/trunk/topia-templates/src/main/java/org/nui… $
+ * %%
+ * 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%
+ */
+
+/*{generator option: parentheses = false}*/
+
+/*{generator option: writeString = +}*/
+
+import java.lang.reflect.Array;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.commons.lang3.ArrayUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.eugene.java.ObjectModelTransformerToJava;
+import org.nuiton.eugene.models.object.ObjectModel;
+import org.nuiton.eugene.models.object.ObjectModelAttribute;
+import org.nuiton.eugene.models.object.ObjectModelClass;
+import org.nuiton.eugene.models.object.ObjectModelEnumeration;
+import org.nuiton.eugene.models.object.ObjectModelJavaModifier;
+import org.nuiton.eugene.models.object.ObjectModelOperation;
+import org.nuiton.eugene.models.object.xml.ObjectModelAttributeImpl;
+import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.persistence.TopiaEntity;
+import org.nuiton.topia.persistence.TopiaEntityEnum;
+import org.nuiton.topia.persistence.util.EntityOperator;
+import org.nuiton.topia.persistence.util.EntityOperatorStore;
+
+/**
+ * Will generate XyzEntityEnum (where Xyz = Model name)
+ *
+ * @author Arnaud Thimel <thimel(a)codelutin.com>
+ * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.templates.EntityEnumTransformer"
+ * @since 3.0
+ */
+public class EntityEnumTransformer extends ObjectModelTransformerToJava {
+
+ private static final Log log = LogFactory.getLog(EntityEnumTransformer.class);
+
+ @Override
+ public void transformFromModel(ObjectModel input) {
+
+ String packageName = TopiaGeneratorUtil.getApplicationContextPackage(this, model);
+
+ String entityEnumName = TopiaGeneratorUtil.getEntityEnumName(model);
+
+ boolean generateOperator =
+ TopiaGeneratorUtil.shouldGenerateOperatorForDAOHelper(model);
+
+ generateEntityEnum(packageName, entityEnumName, generateOperator);
+
+ }
+
+ protected void generateEntityEnum(String packageName,
+ String entityEnumName,
+ boolean generateOperator) {
+
+ List<ObjectModelClass> classes =
+ TopiaGeneratorUtil.getEntityClasses(model, true);
+
+ ObjectModelEnumeration entityEnum;
+
+ if (log.isDebugEnabled()) {
+ log.debug("Will generate standalone " + entityEnumName +
+ " in package " + packageName);
+ }
+ entityEnum = createEnumeration(entityEnumName, packageName);
+ addImport(entityEnum, TopiaEntity.class);
+ addImport(entityEnum, EntityOperatorStore.class);
+ addImport(entityEnum, Arrays.class);
+ addImport(entityEnum, ArrayUtils.class);
+
+ // generate TopiaEntityEnum
+ createEntityEnum(entityEnum,
+ entityEnumName,
+ generateOperator,
+ classes
+ );
+ }
+
+ protected void createEntityEnum(ObjectModelEnumeration entityEnum,
+ String entityEnumName,
+ boolean generateOperator,
+ List<ObjectModelClass> classes) {
+
+ ObjectModelAttributeImpl attr;
+ ObjectModelOperation op;
+
+ addInterface(entityEnum, TopiaEntityEnum.class);
+
+ addImport(entityEnum, Array.class);
+ if (generateOperator) {
+ addImport(entityEnum, EntityOperator.class);
+ }
+
+ for (ObjectModelClass clazz : classes) {
+ String clazzName = clazz.getName();
+
+ boolean withNatural = false;
+ boolean withNotNull = false;
+ StringBuilder naturalIdsParams = new StringBuilder();
+ StringBuilder notNullParams = new StringBuilder();
+
+ Set<ObjectModelAttribute> naturalIdsAttributes = TopiaGeneratorUtil.getNaturalIdAttributes(clazz);
+ for (ObjectModelAttribute attribute: naturalIdsAttributes) {
+ withNatural = true;
+ // attribut metier
+ naturalIdsParams.append(", \"").append(attribute.getName()).append("\"");
+ }
+ Set<ObjectModelAttribute> notNullIdsAttributes = TopiaGeneratorUtil.getNotNullAttributes(clazz);
+ for (ObjectModelAttribute attribute : notNullIdsAttributes) {
+ withNotNull = true;
+ // attribut not-null
+ notNullParams.append(", \"").append(attribute.getName()).append("\"");
+ }
+
+ StringBuilder params = new StringBuilder(clazzName + ".class");
+ if (withNotNull) {
+ params.append(", new String[]{" + notNullParams.substring(2) + "}");
+ } else {
+ params.append(", ArrayUtils.EMPTY_STRING_ARRAY");
+ }
+ if (withNatural) {
+ params.append(", ").append(naturalIdsParams.substring(2));
+ }
+ addLiteral(entityEnum, clazzName + '(' + params.toString() + ')');
+
+ addImport(entityEnum, clazz);
+ }
+
+ attr = (ObjectModelAttributeImpl) addAttribute(entityEnum, "contract", "Class<? extends TopiaEntity>");
+ attr.setDocumentation("The contract of the entity.");
+
+ attr = (ObjectModelAttributeImpl) addAttribute(entityEnum, "implementationFQN", "String");
+ attr.setDocumentation("The fully qualified name of the implementation of the entity.");
+
+ attr = (ObjectModelAttributeImpl) addAttribute(entityEnum, "implementation", "Class<? extends TopiaEntity>");
+ attr.setDocumentation("The implementation class of the entity (will be lazy computed at runtime).");
+
+ attr = (ObjectModelAttributeImpl) addAttribute(entityEnum, "naturalIds", "String[]");
+ attr.setDocumentation("The array of property involved in the natural key of the entity.");
+
+ attr = (ObjectModelAttributeImpl) addAttribute(entityEnum, "notNulls", "String[]");
+ attr.setDocumentation("The array of not null properties of the entity.");
+
+ // constructor
+ op = addConstructor(entityEnum, ObjectModelJavaModifier.PACKAGE);
+ addParameter(op,"Class<? extends TopiaEntity>","contract");
+ addParameter(op,"String[]","notNulls");
+ addParameter(op,"String ...","naturalIds");
+ setOperationBody(op, ""
+/*{
+ this.contract = contract;
+ this.notNulls = Arrays.copyOf(notNulls, notNulls.length);
+ this.naturalIds = naturalIds;
+ implementationFQN = contract.getName() + "Impl";
+ }*/
+ );
+
+ // getContract method
+ op = addOperation(entityEnum, "getContract", "Class<? extends TopiaEntity>", ObjectModelJavaModifier.PUBLIC);
+ addAnnotation(entityEnum,op,Override.class);
+ setOperationBody(op, ""
+/*{
+ return contract;
+ }*/
+ );
+
+ // getNaturalIds method
+ op = addOperation(entityEnum, "getNaturalIds", "String[]", ObjectModelJavaModifier.PUBLIC);
+ addAnnotation(entityEnum,op,Override.class);
+ setOperationBody(op, ""
+/*{
+ return naturalIds;
+ }*/
+ );
+
+ // isUseNaturalIds method
+ op = addOperation(entityEnum, "isUseNaturalIds", "boolean", ObjectModelJavaModifier.PUBLIC);
+ addAnnotation(entityEnum,op,Override.class);
+ setOperationBody(op, ""
+/*{
+ return naturalIds.length > 0;
+ }*/
+ );
+
+ // getNotNulls method
+ op = addOperation(entityEnum, "getNotNulls", "String[]", ObjectModelJavaModifier.PUBLIC);
+ addAnnotation(entityEnum,op,Override.class);
+ setOperationBody(op, ""
+/*{
+ return notNulls;
+ }*/
+ );
+
+ // isUseNotNulls method
+ op = addOperation(entityEnum, "isUseNotNulls", "boolean", ObjectModelJavaModifier.PUBLIC);
+ addAnnotation(entityEnum,op,Override.class);
+ setOperationBody(op, ""
+/*{
+ return notNulls.length > 0;
+ }*/
+ );
+
+ // getImplementationFQN method
+ op = addOperation(entityEnum, "getImplementationFQN","String",ObjectModelJavaModifier.PUBLIC);
+ addAnnotation(entityEnum, op, Override.class);
+ setOperationBody(op, ""
+/*{
+ return implementationFQN;
+ }*/
+ );
+
+ // setImplementationFQN method
+ op = addOperation(entityEnum, "setImplementationFQN","void",ObjectModelJavaModifier.PUBLIC);
+ addAnnotation(entityEnum,op,Override.class);
+ addParameter(op,"String","implementationFQN");
+ if (generateOperator) {
+ setOperationBody(op, ""
+/*{
+ this.implementationFQN = implementationFQN;
+ implementation = null;
+ // reinit the operators store
+ EntityOperatorStore.clear();
+ }*/
+ );
+ } else {
+ setOperationBody(op, ""
+/*{
+ this.implementationFQN = implementationFQN;
+ this.implementation = null;
+ }*/
+ );
+ }
+
+ // accept method
+ op = addOperation(entityEnum, "accept","boolean",ObjectModelJavaModifier.PUBLIC);
+ addAnnotation(entityEnum,op,Override.class);
+ addParameter(op,"Class<? extends TopiaEntity>","klass");
+ setOperationBody(op, ""
+/*{
+ <%=entityEnumName%> constant = valueOf(klass);
+ boolean result = constant.getContract() == contract;
+ return result;
+ }*/
+ );
+
+ // getImplementation method
+ op = addOperation(entityEnum, "getImplementation","Class<? extends TopiaEntity>",ObjectModelJavaModifier.PUBLIC);
+ addAnnotation(entityEnum,op,Override.class);
+ addImport(entityEnum, TopiaException.class);
+ setOperationBody(op, ""
+/*{
+ if (implementation == null) {
+ try {
+ implementation = (Class<? extends TopiaEntity>) Class.forName(implementationFQN);
+ } catch (ClassNotFoundException e) {
+ throw new TopiaException("could not find class " + implementationFQN, e);
+ }
+ }
+ return implementation;
+ }*/
+ );
+
+ // valueOf method
+ op = addOperation(entityEnum, "valueOf", entityEnumName, ObjectModelJavaModifier.PUBLIC,ObjectModelJavaModifier.STATIC);
+ addParameter(op,"TopiaEntity", "entity");
+ setOperationBody(op, ""
+/*{
+ return valueOf(entity.getClass());
+ }*/
+ );
+
+ // valueOf method
+ op = addOperation(entityEnum, "valueOf", entityEnumName, ObjectModelJavaModifier.PUBLIC,ObjectModelJavaModifier.STATIC);
+ addParameter(op,"Class<?>", "klass");
+ setOperationBody(op, ""
+/*{
+ if (klass.isInterface()) {
+ return valueOf(klass.getSimpleName());
+ }
+ for (<%=entityEnumName%> entityEnum : <%=entityEnumName%>.values()) {
+ if (entityEnum.getContract().isAssignableFrom(klass)) {
+ //todo check it works for inheritance
+ return entityEnum;
+ }
+ }
+ throw new IllegalArgumentException("no entity defined for the class " + klass + " in : " + Arrays.toString(<%=entityEnumName%>.values()));
+ }*/
+ );
+
+ // getContracts method
+ op = addOperation(entityEnum, "getContracts", entityEnumName + "[]", ObjectModelJavaModifier.PUBLIC,ObjectModelJavaModifier.STATIC);
+ setOperationBody(op, ""
+/*{
+ <%=entityEnumName%>[] result = values();
+ return result;
+ }*/
+ );
+
+ // getContractClass method
+ op = addOperation(entityEnum, "getContractClass", "<T extends TopiaEntity> Class<T>", ObjectModelJavaModifier.PUBLIC,ObjectModelJavaModifier.STATIC);
+ addParameter(op,"Class<T>", "klass");
+ setOperationBody(op, ""
+/*{
+ <%=entityEnumName%> constant = valueOf(klass);
+ Class<T> result = (Class<T>) constant.getContract();
+ return result;
+ }*/
+ );
+
+ // getContractClasses method
+ op = addOperation(entityEnum, "getContractClasses", "Class<? extends TopiaEntity>[]", ObjectModelJavaModifier.PUBLIC,ObjectModelJavaModifier.STATIC);
+ setOperationBody(op, ""
+/*{
+ <%=entityEnumName%>[] values = values();
+ Class<? extends TopiaEntity>[] result = (Class<? extends TopiaEntity>[]) Array.newInstance(Class.class, values.length);
+ for (int i = 0; i < values.length; i++) {
+ result[i] = values[i].getContract();
+ }
+ return result;
+ }*/
+ );
+
+ // getContractClasses method
+ op = addOperation(entityEnum, "getImplementationClass", "<T extends TopiaEntity> Class<T>", ObjectModelJavaModifier.PUBLIC,ObjectModelJavaModifier.STATIC);
+ addParameter(op,"Class<T>", "klass");
+ setOperationBody(op, ""
+/*{
+ <%=entityEnumName%> constant = valueOf(klass);
+ Class<T> result = (Class<T>) constant.getImplementation();
+ return result;
+ }*/
+ );
+
+ // getImplementationClasses method
+ op = addOperation(entityEnum, "getImplementationClasses", "Class<? extends TopiaEntity>[]", ObjectModelJavaModifier.PUBLIC,ObjectModelJavaModifier.STATIC);
+ setOperationBody(op, ""
+/*{
+ <%=entityEnumName%>[] values = values();
+ Class<? extends TopiaEntity>[] result = (Class<? extends TopiaEntity>[]) Array.newInstance(Class.class, values.length);
+ for (int i = 0; i < values.length; i++) {
+ result[i] = values[i].getImplementation();
+ }
+ return result;
+ }*/
+ );
+
+ // getImplementationClassesAsString method
+ op = addOperation(entityEnum, "getImplementationClassesAsString", "String", ObjectModelJavaModifier.PUBLIC,ObjectModelJavaModifier.STATIC);
+ setOperationBody(op, ""
+/*{
+ StringBuilder buffer = new StringBuilder();
+ for (Class<? extends TopiaEntity> aClass : getImplementationClasses()) {
+ buffer.append(',').append(aClass.getName());
+ }
+ String result = buffer.substring(1);
+ return result;
+ }*/
+ );
+
+ if (generateOperator) {
+ // getOperator method
+ op = addOperation(entityEnum, "getOperator", "<T extends TopiaEntity> EntityOperator<T>", ObjectModelJavaModifier.PUBLIC,ObjectModelJavaModifier.STATIC);
+ addParameter(op,"Class<T>", "klass");
+ setOperationBody(op, ""
+/*{
+ <%=entityEnumName%> constant = valueOf(klass);
+ EntityOperator<T> result = EntityOperatorStore.getOperator(constant);
+ return result;
+ }*/
+ );
+ }
+
+ }
+
+}
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-11-25 15:28:01 UTC (rev 2892)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/PersistenceContextTransformer.java 2013-11-26 15:51:16 UTC (rev 2893)
@@ -113,7 +113,7 @@
String modelName = model.getName();
String daoHelperClazzName = modelName + "DAOHelper";
- String entityEnumName = modelName + "EntityEnum";
+ String entityEnumName = TopiaGeneratorUtil.getEntityEnumName(model);
List<ObjectModelClass> entityClasses =
TopiaGeneratorUtil.getEntityClasses(model, true);
@@ -121,15 +121,15 @@
boolean generateOperator =
TopiaGeneratorUtil.shouldGenerateOperatorForDAOHelper(model);
- boolean generateStandaloneEnum =
- TopiaGeneratorUtil.shouldGenerateStandaloneEnumForDAOHelper(model);
+// boolean generateStandaloneEnum =
+// TopiaGeneratorUtil.shouldGenerateStandaloneEnumForDAOHelper(model);
- if (!generateStandaloneEnum) {
+// if (!generateStandaloneEnum) {
+//
+// addImport(output, packageName + "." + entityEnumName);
+//
+// }
- addImport(output, packageName + "." + daoHelperClazzName + "." + entityEnumName);
-
- }
-
// addImport(output, TopiaDAO.class);
addImport(output, TopiaEntity.class);
// addImport(output, TopiaContext.class);
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-11-25 15:28:01 UTC (rev 2892)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaGeneratorUtil.java 2013-11-26 15:51:16 UTC (rev 2893)
@@ -181,6 +181,10 @@
return model.getName() + "PersistenceContext";
}
+ public static String getEntityEnumName(ObjectModel model) {
+ return model.getName() + "EntityEnum";
+ }
+
public static String getEntityAbstractName(ObjectModelClass input) {
return "AbstractTopia" + input.getName();
}
@@ -320,22 +324,6 @@
}
/**
- * Cherche si le tagvalue {@link TopiaTagValues#TAG_GENERATE_OPERATOR_FOR_DAO_HELPER} a été
- * activé dans le model.
- *
- * @param model le modele utilisé
- * @return {@code true} si le tag value trouvé dans le modèle, {@code false}
- * sinon.
- * @since 2.5
- */
- public static boolean shouldGenerateStandaloneEnumForDAOHelper(ObjectModel model) {
- String tagValue = getGenerateStandaloneEnumForDAOHelperTagValue(model);
- boolean generate = StringUtils.isNotEmpty(tagValue) &&
- Boolean.valueOf(tagValue);
- return generate;
- }
-
- /**
* Cherche et renvoie la liste des attributs constituant la clef metier
* d'une classe.
*
@@ -1599,20 +1587,6 @@
return value;
}
- /**
- * Obtain the value of the {@link TopiaTagValues#TAG_GENERATE_STANDALONE_ENUM_FOR_DAO_HELPER}
- * tag value on the given model.
- *
- * @param model model to seek
- * @return the none empty value of the found tag value or {@code null} if not found nor empty.
- * @see TopiaTagValues#TAG_GENERATE_STANDALONE_ENUM_FOR_DAO_HELPER
- * @since 2.5
- */
- public static String getGenerateStandaloneEnumForDAOHelperTagValue(ObjectModel model) {
- String value = findTagValue(TopiaTagValues.TAG_GENERATE_STANDALONE_ENUM_FOR_DAO_HELPER, null, model);
- return value;
- }
-
/* Obtain the value of the {@link TopiaTagValues#TAG_GENERATE_OPERATOR_FOR_DAO_HELPER}
* tag value on the given model.
*
Modified: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaMetaTransformer.java
===================================================================
--- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaMetaTransformer.java 2013-11-25 15:28:01 UTC (rev 2892)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaMetaTransformer.java 2013-11-26 15:51:16 UTC (rev 2893)
@@ -67,8 +67,9 @@
// DAOTransformer.class,
// DAOImplTransformer.class,
// DAOAbstractTransformer.class,
- DAOHelperTransformer.class,
- EntityHibernateMappingGenerator.class
+// DAOHelperTransformer.class,
+ EntityHibernateMappingGenerator.class,
+ EntityEnumTransformer.class
);
}
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-11-25 15:28:01 UTC (rev 2892)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaTagValues.java 2013-11-26 15:51:16 UTC (rev 2893)
@@ -31,7 +31,6 @@
import org.nuiton.eugene.models.object.ObjectModelClassifier;
import org.nuiton.eugene.models.object.ObjectModelElement;
import org.nuiton.topia.persistence.TopiaEntityContextable;
-import org.nuiton.topia.persistence.TopiaEntityEnum;
import static org.nuiton.eugene.ModelPropertiesUtil.TagValueDefinition;
@@ -306,20 +305,6 @@
String TAG_GENERATE_OPERATOR_FOR_DAO_HELPER = "generateOperatorForDAOHelper";
/**
- * Tag pour spécifier si on doit générer le {@link TopiaEntityEnum} en tant qu'inner classe
- * du dao helper ou pas.
- * <p/>
- * <b>Note:</b> Par défaut, on génère en tant qu'inner classe.
- *
- * @see TopiaGeneratorUtil#getGenerateStandaloneEnumForDAOHelperTagValue(ObjectModel)
- * @see TopiaGeneratorUtil#shouldGenerateStandaloneEnumForDAOHelper(ObjectModel)
- * @since 2.5
- */
- @TagValueDefinition(target = {ObjectModel.class},
- documentation = "To generate a standalon EntityEnum outside the DAOHelper")
- String TAG_GENERATE_STANDALONE_ENUM_FOR_DAO_HELPER = "generateStandaloneEnumForDAOHelper";
-
- /**
* Tag pour spécifier le type d'une propriété dans le mapping hibernate.
*
* @see TopiaGeneratorUtil#getTypeTagValue(ObjectModelAttribute)
1
0
Nov. 25, 2013
Author: athimel
Date: 2013-11-25 16:28:01 +0100 (Mon, 25 Nov 2013)
New Revision: 2892
Url: http://nuiton.org/projects/topia/repository/revisions/2892
Log:
refs #2923 Remove deprecated classes (TopiaContext, TopiaContextImplementor, TopiaDAO, TopiaId, LegacyTopiaDao, ...
Added:
trunk/topia-it/src/test/java/org/nuiton/topia/persistence/
trunk/topia-it/src/test/java/org/nuiton/topia/persistence/TopiaDaoTest.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/TopiaH2Util.java
Removed:
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextImplTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/TopiaDAOTest.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaContext.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/event/TopiaContextListener.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/AbstractTopiaContext.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaContextImplementor.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/LegacyTopiaDao.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaDAO.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaDAOImpl.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaId.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/Creator.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/Deletor.java
Modified:
trunk/topia-it/src/main/java/org/nuiton/topia/it/TopiaConfigurationHelper.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TestHelper.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaContextFactoryTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaConnectionProviderTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextReplicateTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/generator/TopiaTestCase.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/NaturalIdTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/ano1882/DAOAbstractTransformerTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/EnumTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/DeleteEntityTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/FakeService.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/TestService.java
trunk/topia-persistence/src/it/ANOMALIE-1640/src/test/java/org/nuiton/topia/testabstract/TopiaAbstractTest.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaApplicationContext.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaPersistenceContext.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/HibernateTopiaSqlSupport.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaContextFactory.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaDaoSupplier.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaPersistenceContext.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaReplicationDestination.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaServiceSupportImpl.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaSqlSupport.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/event/TopiaContextAdapter.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/event/TopiaContextEvent.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/event/TopiaEntitiesEvent.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/event/TopiaEntityEvent.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/event/TopiaTransactionEvent.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/event/TopiaTransactionListener.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaFiresSupport.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaHibernateEventListener.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaService.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaTransactionAware.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaUtil.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/AbstractTopiaDao.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaEntityContextable.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaPersistenceHelper.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/csv/in/TopiaCsvImports.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/DBMapping.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/TopiaEntityHelper.java
trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/AbstractTopiaMigrationCallback.java
trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TopiaMigrationCallbackByClass.java
trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TopiaMigrationCallbackByClassNG.java
trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TopiaMigrationCallbackByMethod.java
trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TopiaMigrationEngine.java
trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/mappings/TMSVersionDAO.java
trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/TopiaReplicationContext.java
trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/TopiaReplicationModelBuilder.java
trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/TopiaReplicationOperation.java
trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/TopiaReplicationOperationUndoable.java
trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/TopiaReplicationService.java
trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/TopiaReplicationServiceImpl.java
trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/operation/AttachLink.java
trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/operation/DettachAssociation.java
trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/operation/Duplicate.java
trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/operation/LoadLink.java
trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/AbstractTopiaReplicationServiceTest.java
trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationOperationTest.java
trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplAllTest.java
trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplTest.java
trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/operation/FakeOperation.java
trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/operation/UncreatableOperation.java
trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/operation/UnregistredOperation.java
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/DAOHelperTransformer.java
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityDaoTransformer.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/topia-it/src/main/java/org/nuiton/topia/it/TopiaConfigurationHelper.java
===================================================================
--- trunk/topia-it/src/main/java/org/nuiton/topia/it/TopiaConfigurationHelper.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-it/src/main/java/org/nuiton/topia/it/TopiaConfigurationHelper.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -27,7 +27,7 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.cfg.Environment;
-import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.AbstractTopiaApplicationContext;
import org.nuiton.topia.TopiaContextFactory;
import org.nuiton.topia.TopiaNotFoundException;
import org.nuiton.topia.it.legacy.TopiaTestDAOHelper;
@@ -51,31 +51,31 @@
public static final String DEFAULT_CONFIGURATION_LOCATION = "/TopiaContextImpl.properties";
- public static TopiaContext initTopiaContext(File testDirectory,
- String dbname)
- throws IOException, TopiaNotFoundException {
+// public static AbstractTopiaApplicationContext initTopiaContext(File testDirectory,
+// String dbname)
+// throws IOException, TopiaNotFoundException {
+//
+//
+// AbstractTopiaApplicationContext topiaContext = initTopiaContext(
+// testDirectory,
+// DEFAULT_CONFIGURATION_LOCATION,
+// dbname
+// );
+// return topiaContext;
+// }
+//
+// public static AbstractTopiaApplicationContext initTopiaContext(File testDirectory,
+// String dbPropertiesPath,
+// String dbname)
+// throws IOException, TopiaNotFoundException {
+//
+// Properties configuration = initTopiaContextConfiguration(
+// testDirectory,
+// dbPropertiesPath,
+// dbname);
+// return TopiaContextFactory.getContext(configuration);
+// }
-
- TopiaContext topiaContext = initTopiaContext(
- testDirectory,
- DEFAULT_CONFIGURATION_LOCATION,
- dbname
- );
- return topiaContext;
- }
-
- public static TopiaContext initTopiaContext(File testDirectory,
- String dbPropertiesPath,
- String dbname)
- throws IOException, TopiaNotFoundException {
-
- Properties configuration = initTopiaContextConfiguration(
- testDirectory,
- dbPropertiesPath,
- dbname);
- return TopiaContextFactory.getContext(configuration);
- }
-
public static Properties initTopiaContextConfiguration(File testDirectory,
String dbPropertiesPath,
String dbname)
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TestHelper.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TestHelper.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TestHelper.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -29,7 +29,7 @@
import org.apache.commons.logging.LogFactory;
import org.hibernate.cfg.Environment;
import org.junit.Ignore;
-import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.AbstractTopiaApplicationContext;
import org.nuiton.topia.TopiaContextFactory;
import org.nuiton.topia.TopiaNotFoundException;
import org.nuiton.util.FileUtil;
@@ -39,6 +39,8 @@
import java.io.InputStream;
import java.util.Properties;
+import com.google.common.base.Function;
+
/**
* Helper for all topia tests.
*
@@ -86,12 +88,19 @@
return result;
}
- public static TopiaContext initTopiaContext(File testDirectory,
+ protected static final Function<Properties,AbstractTopiaApplicationContext> CREATE_TOPIA_TEST_CONTEXT = new Function<Properties, AbstractTopiaApplicationContext>() {
+ @Override
+ public AbstractTopiaApplicationContext apply(Properties input) {
+ return new TopiaTestTopiaApplicationContext(input);
+ }
+ };
+
+ public static AbstractTopiaApplicationContext initTopiaContext(File testDirectory,
String dbname)
throws IOException, TopiaNotFoundException {
- TopiaContext topiaContext = initTopiaContext(
+ AbstractTopiaApplicationContext topiaContext = initTopiaContext(
testDirectory,
DEFAULT_CONFIGURATION_LOCATION,
dbname
@@ -99,7 +108,7 @@
return topiaContext;
}
- public static TopiaContext initTopiaContext(File testDirectory,
+ public static AbstractTopiaApplicationContext initTopiaContext(File testDirectory,
String dbPropertiesPath,
String dbname)
throws IOException, TopiaNotFoundException {
@@ -108,7 +117,7 @@
testDirectory,
dbPropertiesPath,
dbname);
- return TopiaContextFactory.getContext(configuration);
+ return TopiaContextFactory.getContext(configuration, CREATE_TOPIA_TEST_CONTEXT);
}
public static Properties initTopiaContextConfiguration(File testDirectory,
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaContextFactoryTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaContextFactoryTest.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaContextFactoryTest.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -31,9 +31,8 @@
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
-import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.AbstractTopiaApplicationContext;
import org.nuiton.topia.TopiaContextFactory;
-import org.nuiton.topia.framework.AbstractTopiaContext;
import org.nuiton.topia.junit.ConfigurationHelper;
import java.io.File;
@@ -43,6 +42,8 @@
import java.util.Map;
import java.util.Properties;
+import com.google.common.base.Function;
+
/**
* Created: 8 mai 2010
*
@@ -54,8 +55,15 @@
private static final Log log =
LogFactory.getLog(TopiaContextFactoryTest.class);
- protected static Map<Properties, TopiaContext> contextCache;
+ protected static final Function<Properties,AbstractTopiaApplicationContext> CREATE_TOPIA_TEST_CONTEXT = new Function<Properties, AbstractTopiaApplicationContext>() {
+ @Override
+ public AbstractTopiaApplicationContext apply(Properties input) {
+ return new TopiaTestTopiaApplicationContext(input);
+ }
+ };
+ protected static Map<Properties, AbstractTopiaApplicationContext> contextCache;
+
protected static File testBasedir;
protected Properties properties;
@@ -65,7 +73,7 @@
testBasedir = ConfigurationHelper.getTestSpecificDirectory(TopiaContextFactoryTest.class, "dummy");
Field field = FieldUtils.getField(TopiaContextFactory.class, "contextCache", true);
- contextCache = (Map<Properties, TopiaContext>) field.get(null);
+ contextCache = (Map<Properties, AbstractTopiaApplicationContext>) field.get(null);
}
@Before
@@ -81,12 +89,12 @@
log.debug("## testGetContextOpened");
/** PREPARE DATA **/
- String databaseName = "h2data-testGetContextByPropertie";
+ String databaseName = "h2data-testGetContextByProperties";
File dbDirectory = new File(testBasedir, databaseName);
String url = "jdbc:h2:file:" + dbDirectory;
properties.setProperty("hibernate.connection.url", url);
- AbstractTopiaContext test = new AbstractTopiaContext(properties);
+ TopiaTestTopiaApplicationContext test = new TopiaTestTopiaApplicationContext(properties);
contextCache.put(properties, test);
/** EXEC METHOD **/
@@ -100,7 +108,7 @@
log.debug("## testRemoveContext");
/** PREPARE DATA **/
- AbstractTopiaContext test = new AbstractTopiaContext(properties);
+ TopiaTestTopiaApplicationContext test = new TopiaTestTopiaApplicationContext(properties);
contextCache.put(properties, test);
/** EXEC METHOD **/
@@ -131,26 +139,26 @@
log.info("test 0 : add null properties");
try {
- TopiaContextFactory.getContext(null);
+ TopiaContextFactory.getContext(null, CREATE_TOPIA_TEST_CONTEXT);
} catch (Exception eee) {
Assert.assertEquals(NullPointerException.class, eee.getClass());
}
log.info("test 1 : add new properties, will instantiate a new" +
" TopiaContext");
- TopiaContext test1 = TopiaContextFactory.getContext(propertiesParent);
+ AbstractTopiaApplicationContext test1 = TopiaContextFactory.getContext(propertiesParent, CREATE_TOPIA_TEST_CONTEXT);
Assert.assertNotNull(test1);
Assert.assertEquals(1, contextCache.size());
log.info("test 2 : with same properties, will retrieve existing" +
" TopiaContext");
- TopiaContext test2 = TopiaContextFactory.getContext(propertiesParent);
+ AbstractTopiaApplicationContext test2 = TopiaContextFactory.getContext(propertiesParent, CREATE_TOPIA_TEST_CONTEXT);
Assert.assertEquals(test1, test2);
Assert.assertEquals(1, contextCache.size());
log.info("test 3 : use other properties, will instantiate a different" +
"TopiaContext");
- TopiaContext test3 = TopiaContextFactory.getContext(properties);
+ AbstractTopiaApplicationContext test3 = TopiaContextFactory.getContext(properties, CREATE_TOPIA_TEST_CONTEXT);
log.debug("cache size : " + contextCache.size());
log.debug("result : " + test1);
log.debug("result3 : " + test3);
@@ -160,7 +168,7 @@
log.info("test 4 : use other properties but equivalent to existing " +
"TopiaContext");
// Test flating of properties
- TopiaContext test4 = TopiaContextFactory.getContext(propertiesAll);
+ AbstractTopiaApplicationContext test4 = TopiaContextFactory.getContext(propertiesAll, CREATE_TOPIA_TEST_CONTEXT);
Assert.assertEquals(test1, test4);
Assert.assertEquals(2, contextCache.size());
@@ -182,17 +190,16 @@
"jdbc:h2:file:" + f.getAbsolutePath());
- TopiaContext test5 = TopiaContextFactory.getContext(properties);
+ AbstractTopiaApplicationContext test5 = TopiaContextFactory.getContext(properties, CREATE_TOPIA_TEST_CONTEXT);
Assert.assertNotSame(test1, test5);
Assert.assertEquals(3, contextCache.size());
log.info("test5b : beginTransaction to properly close the context");
- test5.beginTransaction();
-
+ test5.newPersistenceContext();
test5.closeContext();
- TopiaContext result = TopiaContextFactory.getContext(properties);
- Assert.assertNotSame(test5, result);
+ AbstractTopiaApplicationContext test5b = TopiaContextFactory.getContext(properties, CREATE_TOPIA_TEST_CONTEXT);
+ Assert.assertNotSame(test5, test5b);
Assert.assertEquals(3, contextCache.size());
}
}
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaConnectionProviderTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaConnectionProviderTest.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaConnectionProviderTest.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -34,7 +34,7 @@
import org.nuiton.topia.framework.TopiaConnectionProvider;
import org.nuiton.topia.it.legacy.TopiaDatabase;
import org.nuiton.topia.it.legacy.test.entities.Person;
-import org.nuiton.topia.it.legacy.test.entities.PersonDAO;
+import org.nuiton.topia.it.legacy.test.entities.PersonTopiaDao;
import org.nuiton.topia.it.legacy.topiatest.Personne;
import java.io.File;
@@ -126,7 +126,7 @@
TopiaTestTopiaPersistenceContext transaction = db.beginTransaction();
try {
- PersonDAO dao = TopiaTestDAOHelper.getPersonDAO(transaction);
+ PersonTopiaDao dao = TopiaTestDAOHelper.getPersonTopiaDao(transaction);
Person personne = dao.create(Personne.PROPERTY_NAME, "Jack Bauer");
transaction.commit();
Deleted: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextImplTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextImplTest.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextImplTest.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -1,574 +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%
- */
-package org.nuiton.topia.it.legacy.framework;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.nuiton.topia.TopiaNotFoundException;
-import org.nuiton.topia.framework.AbstractTopiaContext;
-import org.nuiton.topia.framework.TopiaContextImplementor;
-import org.nuiton.topia.framework.TopiaService;
-import org.nuiton.topia.it.legacy.topiatest.service.FakeService;
-import org.nuiton.topia.it.legacy.topiatest.service.TestService;
-import org.nuiton.topia.junit.ConfigurationHelper;
-
-import java.io.File;
-import java.util.Map;
-import java.util.Properties;
-
-/**
- * Created: 10 mai 2010
- *
- * @author fdesbois <fdesbois(a)codelutin.com>
- * @version $Id$
- */
-public class TopiaContextImplTest {
-
- class MyAbstractTopiaContext extends AbstractTopiaContext {
-
- MyAbstractTopiaContext(TopiaContextImplementor parentContext) {
- super(parentContext);
- }
-
- MyAbstractTopiaContext(Properties config) throws TopiaNotFoundException {
- super(config);
- }
-
- MyAbstractTopiaContext() {
- }
-
- @Override
- protected Map<String, TopiaService> loadServices(Properties config) {
- return super.loadServices(config);
- }
-
- @Override
- protected boolean serviceEnabled(String name) {
- return super.serviceEnabled(name);
- }
-
- @Override
- protected TopiaService getService(String name) {
- return super.getService(name);
- }
- }
-
- private static final Log log =
- LogFactory.getLog(TopiaContextImplTest.class);
-
- protected Properties properties = new Properties();
-
- static File testBasedir;
-
- @BeforeClass
- public static void setUpClass() throws Exception {
-
- testBasedir = ConfigurationHelper.getTestSpecificDirectory(TopiaContextImplTest.class, "dummy");
- }
-
- @Before
- public void setUp() throws Exception {
- properties.clear();
- }
-
- @After
- public void tearDown() throws Exception {
- }
-
- @Test
- public void testLoadServices() throws Exception {
- if (log.isDebugEnabled()) {
- log.debug("## testLoadServices");
- }
-
- /** PREPARE DATA **/
- properties.setProperty("topia.service.test",
- TestService.class.getName());
-
- MyAbstractTopiaContext context = new MyAbstractTopiaContext();
-
- /** EXEC METHOD **/
- if (log.isInfoEnabled()) {
- log.info("test 1 : load a simple TestService from properties");
- }
- Map<String, TopiaService> results = context.loadServices(properties);
- Assert.assertEquals(1, results.size());
- Assert.assertTrue(results.containsKey("test"));
- TopiaService service = results.get("test");
- Assert.assertEquals(TestService.class, service.getClass());
-
- if (log.isInfoEnabled()) {
- log.info("test 2 : load with wrong key : will display a WARN");
- }
- properties.clear();
-
- properties.setProperty("topia.service.fake",
- TestService.class.getName());
-
- results = context.loadServices(properties);
- Assert.assertEquals(0, results.size());
- Assert.assertFalse(results.containsKey("fake"));
-
- if (log.isInfoEnabled()) {
- log.info("test 3 : load with fake service name : will display an ERROR");
- }
- properties.clear();
-
- properties.setProperty("topia.service.test", "FAKE");
-
- results = context.loadServices(properties);
- Assert.assertEquals(0, results.size());
- Assert.assertFalse(results.containsKey("test"));
- }
-
- @Test
- public void testGetServices() throws Exception {
- if (log.isDebugEnabled()) {
- log.debug("## testGetServices");
- }
-
- /** PREPARE DATA **/
- properties.setProperty("topia.service.test",
- TestService.class.getName());
-
- // Calling the constructor with properties will load the services
- AbstractTopiaContext context = new AbstractTopiaContext(properties);
-
- // Instantiate a child context and set its parent
- MyAbstractTopiaContext child = new MyAbstractTopiaContext(context);
-
- /** EXEC METHOD **/
- if (log.isInfoEnabled()) {
- log.info("test 1 : with child context");
- }
- Map<String, TopiaService> test1 = child.getServices();
- Assert.assertEquals(1, test1.size());
- Assert.assertTrue(test1.containsKey("test"));
-
- if (log.isInfoEnabled()) {
- log.info("test 2 : test serviceEnabled method");
- }
- boolean test2 = child.serviceEnabled("test");
- Assert.assertTrue(test2);
-
- if (log.isInfoEnabled()) {
- log.info("test 3 : test getService method");
- }
- TopiaService test3 = child.getService("test");
- Assert.assertEquals(TestService.class, test3.getClass());
-
- if (log.isInfoEnabled()) {
- log.info("test 4 : test serviceEnabled from class TestService");
- }
- boolean test4 = child.serviceEnabled(TestService.class);
- Assert.assertTrue(test4);
-
- if (log.isInfoEnabled()) {
- log.info("test 5 : test getService from class TestService");
- }
- TestService test5 = child.getService(TestService.class);
- Assert.assertNotNull(test5);
-
- if (log.isInfoEnabled()) {
- log.info("test 6 : test serviceEnabled error with class FakeService");
- }
- // FakeService doesn't contains property SERVICE_NAME used by
- // serviceEnabled method
- // Even it's properly loaded the serviceEnabled method will return false
- properties.clear();
- properties.setProperty("topia.service.fake",
- FakeService.class.getName());
- AbstractTopiaContext otherContext = new AbstractTopiaContext(properties);
-
- boolean test6 = otherContext.serviceEnabled(FakeService.class);
- Assert.assertFalse(test6);
-
- if (log.isInfoEnabled()) {
- log.info("test 7 : test getService with error TopiaNotFoundException" +
- " : service not loaded");
- }
- // TestService is not loaded in otherContext
- try {
- TestService test7 = otherContext.getService(TestService.class);
- Assert.fail();
- } catch (TopiaNotFoundException eee) {
- //log.error(eee.getClass().getSimpleName() + " : " + eee.getMessage());
- //Assert.assertEquals(TopiaNotFoundException.class, eee.getClass());
- } catch (Exception e) {
- Assert.fail();
- }
- }
-
-// @Test
-// public void testContextHierarchy() throws Exception {
-// if (log.isDebugEnabled()) {
-// log.debug("## testContextHierarchy");
-// }
-//
-// /** PREPARE DATA **/
-// MyAbstractTopiaContext context = new MyAbstractTopiaContext(properties);
-//
-// /** EXEC METHODS **/
-// if (log.isInfoEnabled()) {
-// log.info("test 1 : constructor with parent context");
-// }
-// AbstractTopiaContext test1 = new AbstractTopiaContext(context);
-// Assert.assertEquals(context, test1.parentContext);
-//
-// if (log.isInfoEnabled()) {
-// log.info("test 2 : addChildContext");
-// }
-// AbstractTopiaContext test2 = new AbstractTopiaContext(properties);
-// AbstractTopiaContext child2 = new AbstractTopiaContext();
-// test2.addChildContext(child2);
-// Assert.assertEquals(1, test2.childContext.size());
-//
-// if (log.isInfoEnabled()) {
-// log.info("test 3 : removeChildContext");
-// }
-// AbstractTopiaContext test3 = new AbstractTopiaContext(properties);
-// AbstractTopiaContext child3 = new AbstractTopiaContext(test3);
-// test3.childContext.add(child3);
-// test3.removeChildContext(child3);
-// Assert.assertEquals(0, test3.childContext.size());
-//
-// // No remove if context is closed
-// test3.childContext.add(child3);
-// test3.closed = true;
-// test3.removeChildContext(child3);
-// Assert.assertEquals(1, test3.childContext.size());
-//
-// if (log.isInfoEnabled()) {
-// log.info("test 4 : getRootContext");
-// }
-// TopiaContextImplementor test4 = child3.getRootContext();
-// Assert.assertEquals(test3, test4);
-//
-// // Note : existing test is already done for concurrency problem on
-// // getChildContext(). Go to : http://www.nuiton.org/repositories/browse/sandbox/testTopiaPostgresError/tr…
-// }
-//
-// @Test
-// public void testCreateSchema() throws Exception {
-// }
-//
-// @Test
-// public void testShowCreateSchema() throws Exception {
-// }
-//
-// @Test
-// public void testUpdateSchema() throws Exception {
-// }
-//
-// @Test
-// public void testGetHibernate() throws Exception {
-// }
-//
-
-// @Test
-// public void testGetHibernateFactory() throws Exception {
-// if (log.isDebugEnabled()) {
-// log.debug("## testGetHibernateFactory");
-// }
-//
-// /** PREPARE DATA **/
-// AbstractTopiaContext context = new AbstractTopiaContext();
-// context.services = new HashMap<String, TopiaService>();
-//
-// String basedir = System.getenv("basedir");
-// if (basedir == null) {
-//
-// // says basedir is where we start tests.
-// basedir = new File("").getAbsolutePath();
-// }
-//
-// if (log.isDebugEnabled()) {
-// log.debug("baseDir : " + basedir);
-// }
-// File persistenceDir = new File(basedir,
-// "target" + File.separator +
-// "test-classes" + File.separator +
-// "org" + File.separator +
-// "nuiton" + File.separator +
-// "topiatest" + File.separator +
-// "persistence");
-// if (log.isDebugEnabled()) {
-// log.debug("persistenceDir : " + persistenceDir);
-// }
-// File resourcesDir = new File(basedir,
-// "target" + File.separator +
-// "test-classes");
-//
-// /** EXEC METHOD **/
-// if (log.isInfoEnabled()) {
-// log.info("test 1 : load mappings from directory");
-// }
-//
-// properties.setProperty(TopiaContextFactory.CONFIG_PERSISTENCE_DIRECTORIES,
-// persistenceDir.getAbsolutePath());
-// context.config = properties;
-//
-// Configuration test1 = context.getHibernateConfiguration();
-// PersistentClass persistentClass =
-// test1.getClassMapping(Entity1Impl.class.getName());
-// Assert.assertNotNull(persistentClass);
-// Assert.assertEquals(Entity1.class, persistentClass.getProxyInterface());
-//
-//// for (Iterator<RootClass> it = test1.getClassMappings(); it.hasNext();) {
-//// RootClass o = it.next();
-//// log.debug("entity : " + o.getEntityName());
-//// }
-//
-// if (log.isInfoEnabled()) {
-// log.info("test 2 : load mappings for all entities");
-// }
-// //reset from previous test
-// context = new AbstractTopiaContext();
-// context.services = new HashMap<String, TopiaService>();
-// properties.clear();
-//
-// // use property TOPIA_PERSISTENCE_CLASSES
-// properties.setProperty(TopiaContextFactory.CONFIG_PERSISTENCE_CLASSES,
-// Entity1Impl.class.getName());
-// context.config = properties;
-//
-// Configuration test2 = context.getHibernateConfiguration();
-// persistentClass = test2.getClassMapping(Entity1Impl.class.getName());
-// Assert.assertNotNull(persistentClass);
-// Assert.assertEquals(Entity1.class, persistentClass.getProxyInterface());
-//
-// if (log.isInfoEnabled()) {
-// log.info("test 3 : add properties from file");
-// }
-// //reset from previous test
-// context = new AbstractTopiaContext();
-// context.services = new HashMap<String, TopiaService>();
-// properties.clear();
-//
-// // use property TOPIA_PERSISTENCE_PROPERTIES_FILE to add default
-// // properties from file
-// properties.setProperty(TopiaContextFactory.CONFIG_PERSISTENCE_PROPERTIES_FILE,
-// resourcesDir + File.separator + "TopiaContextImpl.properties");
-// context.config = properties;
-//
-// Configuration test3 = context.getHibernateConfiguration();
-// Assert.assertEquals(
-// test3.getProperty("hibernate.connection.driver_class"),
-// Driver.class.getName());
-//
-// // Note : maybe add a test to load classes from services
-// }
-
-// @Test
-// public void replicateEntity() throws Exception {
-//
-// Properties configSource = TestHelper.initTopiaContextConfiguration(
-// testBasedir,
-// "/TopiaContextImpl.properties",
-// "replicateSource");
-//
-// Properties configTarget = TestHelper.initTopiaContextConfiguration(
-// testBasedir,
-// "/TopiaContextImpl.properties",
-// "replicateTarget");
-//
-//
-// TopiaContext contextSource = null;
-// TopiaContext contextTarget = null;
-//
-// try {
-// contextSource = TopiaContextFactory.getContext(configSource);
-// contextTarget = TopiaContextFactory.getContext(configTarget);
-//
-// TopiaContext txSource;
-// TopiaContext txTarget;
-// PersonDAO daoSource, daoTarget;
-// PetDAO petDAOSource, petDAOTarget;
-// Person personSource, personTarget;
-// Pet petSource, petTarget;
-//
-// txSource = contextSource.beginTransaction();
-// daoSource = TopiaTestDAOHelper.getPersonDAO(txSource);
-// petDAOSource = TopiaTestDAOHelper.getPetDAO(txSource);
-//
-// personSource = daoSource.create(Person.PROPERTY_FIRSTNAME, " firstName",
-// Person.PROPERTY_NAME, " name"
-// );
-//
-// petSource = petDAOSource.create(Pet.PROPERTY_NAME, "name",
-// Pet.PROPERTY_TYPE, "type",
-// Pet.PROPERTY_PERSON, personSource
-// );
-//
-// personSource.addPet(petSource);
-//
-// txSource.commit();
-//
-// daoSource = TopiaTestDAOHelper.getPersonDAO(txSource);
-//
-// personSource = daoSource.findByTopiaId(personSource.getTopiaId());
-// Assert.assertNotNull(personSource);
-//
-// petSource = petDAOSource.findByTopiaId(petSource.getTopiaId());
-// Assert.assertNotNull(petSource);
-// Assert.assertEquals(1, personSource.sizePet());
-// Assert.assertEquals(petSource, personSource.getPet().iterator().next());
-//
-// txTarget = contextTarget.beginTransaction();
-//
-// txSource.replicateEntity(txTarget, petSource);
-// txSource.replicateEntity(txTarget, personSource);
-//
-// txTarget.commit();
-//
-// daoTarget = TopiaTestDAOHelper.getPersonDAO(txTarget);
-// petDAOTarget = TopiaTestDAOHelper.getPetDAO(txTarget);
-//
-// personTarget = daoTarget.findByTopiaId(personSource.getTopiaId());
-// Assert.assertNotNull(personTarget);
-// Assert.assertEquals(personSource, personTarget);
-// Assert.assertEquals(1, personTarget.sizePet());
-//
-// petTarget = petDAOTarget.findByTopiaId(petSource.getTopiaId());
-// Assert.assertNotNull(petTarget);
-// Assert.assertEquals(petSource, petTarget);
-//
-// Assert.assertEquals(petTarget, personTarget.getPet().iterator().next());
-//
-//
-// } finally {
-// closeDb(contextSource);
-// closeDb(contextTarget);
-// }
-//
-// }
-//
-// protected static void closeDb(TopiaContext contextSource) {
-// if (contextSource != null && !contextSource.isClosed())
-// try {
-// contextSource.clear(false);
-// } catch (TopiaException e) {
-// if (log.isErrorEnabled()) {
-// log.error("Could not close db " + contextSource, e);
-// }
-// }
-// }
-
-
-//
-// @Test
-// public void testGetHibernateConfiguration() throws Exception {
-// }
-//
-// @Test
-// public void testGetDAO() throws Exception {
-// }
-//
-// @Test
-// public void testBeginTransaction() throws Exception {
-// }
-//
-// @Test
-// public void testCommitTransaction() throws Exception {
-// }
-//
-// @Test
-// public void testRollbackTransaction() throws Exception {
-// }
-//
-// @Test
-// public void testCloseContext() throws Exception {
-// }
-//
-// @Test
-// public void testIsClosed() throws Exception {
-// }
-//
-// @Test
-// public void testFindByTopiaId() throws Exception {
-// }
-//
-// @Test
-// public void testFind() throws Exception {
-// }
-//
-// @Test
-// public void testFind2() throws Exception {
-// }
-//
-// @Test
-// public void testExecute() throws Exception {
-// }
-//
-// @Test
-// public void testAdd() throws Exception {
-// }
-//
-// @Test
-// public void testImportXML() throws Exception {
-// }
-//
-// @Test
-// public void testExportXML() throws Exception {
-// }
-//
-//
-// @Test
-// public void testReplicateEntity() throws Exception {
-// }
-//
-// @Test
-// public void testReplicateEntities() throws Exception {
-// }
-//
-// @Test
-// public void testGetFiresSupport() throws Exception {
-// }
-//
-// @Test
-// public void testBackup() throws Exception {
-// }
-//
-// @Test
-// public void testRestore() throws Exception {
-// }
-//
-// @Test
-// public void testClear() throws Exception {
-// }
-//
-// @Test
-// public void testGetPersistenceClasses() throws Exception {
-// }
-//
-// @Test
-// public void testIsSchemaExist() throws Exception {
-// }
-}
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextReplicateTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextReplicateTest.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextReplicateTest.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -24,6 +24,9 @@
*/
package org.nuiton.topia.it.legacy.framework;
+import java.io.File;
+import java.util.Properties;
+
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
@@ -32,13 +35,10 @@
import org.nuiton.topia.it.legacy.TopiaTestDAOHelper;
import org.nuiton.topia.it.legacy.TopiaTestTopiaPersistenceContext;
import org.nuiton.topia.it.legacy.test.entities.Person;
-import org.nuiton.topia.it.legacy.test.entities.PersonDAO;
+import org.nuiton.topia.it.legacy.test.entities.PersonTopiaDao;
import org.nuiton.topia.it.legacy.test.entities.Pet;
-import org.nuiton.topia.it.legacy.test.entities.PetDAO;
+import org.nuiton.topia.it.legacy.test.entities.PetTopiaDao;
-import java.io.File;
-import java.util.Properties;
-
/**
* To test replication sugin TopiaContext.
*
@@ -92,14 +92,14 @@
TopiaTestTopiaPersistenceContext txSource;
TopiaTestTopiaPersistenceContext txTarget;
- PersonDAO daoSource, daoTarget;
- PetDAO petDAOSource, petDAOTarget;
+ PersonTopiaDao daoSource, daoTarget;
+ PetTopiaDao petDAOSource, petDAOTarget;
Person personSource, personTarget;
Pet petSource, petTarget;
txSource = dbSource.beginTransaction();
- daoSource = TopiaTestDAOHelper.getPersonDAO(txSource);
- petDAOSource = TopiaTestDAOHelper.getPetDAO(txSource);
+ daoSource = TopiaTestDAOHelper.getPersonTopiaDao(txSource);
+ petDAOSource = TopiaTestDAOHelper.getPetTopiaDao(txSource);
personSource = daoSource.create(Person.PROPERTY_FIRSTNAME, " firstName",
Person.PROPERTY_NAME, " name"
@@ -114,7 +114,7 @@
txSource.commit();
- daoSource = TopiaTestDAOHelper.getPersonDAO(txSource);
+ daoSource = TopiaTestDAOHelper.getPersonTopiaDao(txSource);
personSource = daoSource.findByTopiaId(personSource.getTopiaId());
Assert.assertNotNull(personSource);
@@ -131,8 +131,8 @@
txTarget.commit();
- daoTarget = TopiaTestDAOHelper.getPersonDAO(txTarget);
- petDAOTarget = TopiaTestDAOHelper.getPetDAO(txTarget);
+ daoTarget = TopiaTestDAOHelper.getPersonTopiaDao(txTarget);
+ petDAOTarget = TopiaTestDAOHelper.getPetTopiaDao(txTarget);
personTarget = daoTarget.findByTopiaId(personSource.getTopiaId());
Assert.assertNotNull(personTarget);
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/generator/TopiaTestCase.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/generator/TopiaTestCase.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/generator/TopiaTestCase.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -30,14 +30,14 @@
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
+import org.nuiton.topia.TopiaException;
import org.nuiton.topia.it.legacy.TopiaDatabase;
-import org.nuiton.topia.TopiaException;
import org.nuiton.topia.it.legacy.TopiaTestDAOHelper;
import org.nuiton.topia.it.legacy.TopiaTestTopiaPersistenceContext;
import org.nuiton.topia.it.legacy.topiatest.Company;
-import org.nuiton.topia.it.legacy.topiatest.CompanyDAO;
+import org.nuiton.topia.it.legacy.topiatest.CompanyTopiaDao;
import org.nuiton.topia.it.legacy.topiatest.Department;
-import org.nuiton.topia.it.legacy.topiatest.DepartmentDAO;
+import org.nuiton.topia.it.legacy.topiatest.DepartmentTopiaDao;
/**
* TopiaTestCase.
@@ -123,8 +123,8 @@
// try {
TopiaTestTopiaPersistenceContext newContext = db.beginTransaction();
- CompanyDAO companyDAO = newContext.getCompanyDao();
- DepartmentDAO departmentDAO = newContext.getDepartmentDao();
+ CompanyTopiaDao companyDAO = newContext.getCompanyDao();
+ DepartmentTopiaDao departmentDAO = newContext.getDepartmentDao();
Company company = companyDAO.create();
company.setName("Ma société");
@@ -154,7 +154,7 @@
newContext = db.beginTransaction();
- companyDAO = TopiaTestDAOHelper.getCompanyDAO(newContext);
+ companyDAO = TopiaTestDAOHelper.getCompanyTopiaDao(newContext);
company = companyDAO.findByTopiaId(company.getTopiaId());
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/NaturalIdTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/NaturalIdTest.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/NaturalIdTest.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -36,7 +36,7 @@
import org.nuiton.topia.it.legacy.TopiaTestDAOHelper;
import org.nuiton.topia.it.legacy.TopiaTestTopiaPersistenceContext;
import org.nuiton.topia.it.legacy.topiatest.NaturalizedEntity;
-import org.nuiton.topia.it.legacy.topiatest.NaturalizedEntityDAO;
+import org.nuiton.topia.it.legacy.topiatest.NaturalizedEntityTopiaDao;
/**
* NaturalIdTest
@@ -61,7 +61,7 @@
log.debug("Test naturalId : create succesfull");
TopiaTestTopiaPersistenceContext persistenceContext = db.beginTransaction();
- NaturalizedEntityDAO dao =
+ NaturalizedEntityTopiaDao dao =
persistenceContext.getNaturalizedEntityDao();
// No exception will be thrown with the two properties
@@ -82,7 +82,7 @@
log.debug("Test naturalId : create failed");
TopiaTestTopiaPersistenceContext persistenceContext = db.beginTransaction();
- NaturalizedEntityDAO dao =
+ NaturalizedEntityTopiaDao dao =
persistenceContext.getNaturalizedEntityDao();
// Exception will be throw
@@ -108,7 +108,7 @@
TopiaTestTopiaPersistenceContext persistenceContext = db.beginTransaction();
- NaturalizedEntityDAO dao =
+ NaturalizedEntityTopiaDao dao =
persistenceContext.getNaturalizedEntityDao();
NaturalizedEntity entity =
@@ -131,7 +131,7 @@
TopiaTestTopiaPersistenceContext persistenceContext = db.beginTransaction();
- NaturalizedEntityDAO dao =
+ NaturalizedEntityTopiaDao dao =
persistenceContext.getNaturalizedEntityDao();
NaturalizedEntity entity =
@@ -149,7 +149,7 @@
TopiaTestTopiaPersistenceContext persistenceContext = db.beginTransaction();
- NaturalizedEntityDAO dao =
+ NaturalizedEntityTopiaDao dao =
persistenceContext.getNaturalizedEntityDao();
dao.createByNaturalId(5, "str");
Deleted: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/TopiaDAOTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/TopiaDAOTest.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/TopiaDAOTest.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -1,202 +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.it.legacy.persistence;
-
-import java.util.List;
-
-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.TopiaException;
-import org.nuiton.topia.it.legacy.TopiaTestTopiaPersistenceContext;
-import org.nuiton.topia.it.legacy.test.entities.Person;
-import org.nuiton.topia.it.legacy.test.entities.PersonDAO;
-
-import com.google.common.collect.Lists;
-import org.nuiton.topia.persistence.TopiaDAO;
-
-/**
- * Test on {@link TopiaDAO}.
- * <p/>
- * Last update : $Date$
- * By : $Author$
- *
- * @author chatellier
- * @version $Revision$
- */
-public class TopiaDAOTest {
-
- @Rule
- public final TopiaDatabase db = new TopiaDatabase();
-
- protected TopiaTestTopiaPersistenceContext context;
-
- protected PersonDAO 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);
-
- Iterable<Person> allByLazy = dao.findAllLazyByQuery(
- 100,
- "FROM " + dao.getTopiaEntityEnum().getImplementationFQN() + " ORDER BY id");
-
- List<Person> actual = Lists.newArrayList();
-
- for (Person person : allByLazy) {
- actual.add(person);
- }
- Assert.assertEquals(dao.count(), actual.size());
-
- allByLazy = dao.findAllLazyByQuery(
- 54,
- "FROM " + dao.getTopiaEntityEnum().getImplementationFQN() + " ORDER BY id");
-
- actual = Lists.newArrayList();
-
- for (Person person : allByLazy) {
- actual.add(person);
- }
- Assert.assertEquals(dao.count(), actual.size());
-
- allByLazy = dao.findAllLazyByQuery(
- 49,
- "FROM " + dao.getTopiaEntityEnum().getImplementationFQN() + " ORDER BY id");
-
- actual = Lists.newArrayList();
-
- for (Person person : allByLazy) {
- actual.add(person);
- }
- Assert.assertEquals(dao.count(), actual.size());
-
- allByLazy = dao.findAllLazyByQuery(
- 101,
- "FROM " + dao.getTopiaEntityEnum().getImplementationFQN() + " ORDER BY id");
-
- actual = Lists.newArrayList();
-
- for (Person person : allByLazy) {
- actual.add(person);
- }
- Assert.assertEquals(dao.count(), actual.size());
-
- allByLazy = dao.findAllLazyByQuery(
- 102,
- "FROM " + dao.getTopiaEntityEnum().getImplementationFQN() + " ORDER BY id");
-
- 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);
- }
-}
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/ano1882/DAOAbstractTransformerTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/ano1882/DAOAbstractTransformerTest.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/ano1882/DAOAbstractTransformerTest.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -24,14 +24,14 @@
*/
package org.nuiton.topia.it.legacy.test.ano1882;
+import java.util.Arrays;
+
import org.junit.Rule;
import org.junit.Test;
import org.nuiton.topia.it.legacy.TopiaDatabase;
import org.nuiton.topia.it.legacy.TopiaTestDAOHelper;
import org.nuiton.topia.it.legacy.TopiaTestTopiaPersistenceContext;
-import java.util.Arrays;
-
public class DAOAbstractTransformerTest {
@Rule
@@ -41,8 +41,8 @@
public void testAno1882() throws Exception {
TopiaTestTopiaPersistenceContext transaction = db.beginTransaction();
- FrenchCompanyDAO dao = TopiaTestDAOHelper.getFrenchCompanyDAO(transaction);
- SIRETDAO siretDAO = TopiaTestDAOHelper.getSIRETDAO(transaction);
+ FrenchCompanyTopiaDao dao = TopiaTestDAOHelper.getFrenchCompanyTopiaDao(transaction);
+ SIRETTopiaDao siretDAO = TopiaTestDAOHelper.getSIRETTopiaDao(transaction);
SIRET siret = siretDAO.create();
FrenchCompany entity =
dao.create(
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/EnumTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/EnumTest.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/EnumTest.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -53,7 +53,7 @@
public void storeEntityWithEnumValue() throws TopiaException {
TopiaTestTopiaPersistenceContext transaction = db.beginTransaction();
- PersonneDAO dao = TopiaTestDAOHelper.getPersonneDAO(transaction);
+ PersonneTopiaDao dao = TopiaTestDAOHelper.getPersonneTopiaDao(transaction);
Personne personne = new PersonneImpl();
personne.setGender(Gender.FEMALE);
personne.setOtherGender(Gender.MALE);
@@ -63,7 +63,7 @@
transaction.closeContext();
transaction = db.beginTransaction();
- dao = TopiaTestDAOHelper.getPersonneDAO(transaction);
+ dao = TopiaTestDAOHelper.getPersonneTopiaDao(transaction);
dao.findByTopiaId(topiaId);
Assert.assertEquals(Gender.FEMALE, personne.getGender());
Assert.assertEquals(Gender.MALE, personne.getOtherGender());
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/DeleteEntityTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/DeleteEntityTest.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/DeleteEntityTest.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -43,13 +43,13 @@
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
+import org.nuiton.topia.TopiaException;
import org.nuiton.topia.it.legacy.TopiaDatabase;
-import org.nuiton.topia.TopiaException;
import org.nuiton.topia.it.legacy.TopiaTestDAOHelper;
import org.nuiton.topia.it.legacy.TopiaTestTopiaPersistenceContext;
import org.nuiton.topia.it.legacy.topiatest.Gender;
import org.nuiton.topia.it.legacy.topiatest.Personne;
-import org.nuiton.topia.it.legacy.topiatest.PersonneDAO;
+import org.nuiton.topia.it.legacy.topiatest.PersonneTopiaDao;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
@@ -84,7 +84,7 @@
TopiaTestTopiaPersistenceContext transaction = db.beginTransaction();
log.debug("DAO : PersonneDAO");
- PersonneDAO dao = TopiaTestDAOHelper.getPersonneDAO(transaction);
+ PersonneTopiaDao dao = TopiaTestDAOHelper.getPersonneTopiaDao(transaction);
log.debug("CREATE PERSONNE : Bob Marley");
Personne personne = dao.create(Personne.PROPERTY_NAME, "Bob Marley");
@@ -108,7 +108,7 @@
log.debug("ENTITY PERSONNE SAVED !");
log.debug("DAO parent (abstract) : PartyDAO");
- Party2DAO dao2 = TopiaTestDAOHelper.getParty2DAO(transaction);
+ Party2TopiaDao dao2 = TopiaTestDAOHelper.getParty2TopiaDao(transaction);
log.debug("DELETE PERSONNE with PartyDAO");
dao2.delete(personne2);
@@ -134,7 +134,7 @@
TopiaTestTopiaPersistenceContext transaction = db.beginTransaction();
- PersonneDAO dao = TopiaTestDAOHelper.getPersonneDAO(transaction);
+ PersonneTopiaDao dao = TopiaTestDAOHelper.getPersonneTopiaDao(transaction);
log.debug("CREATE PERSONNE : Bob Marley");
Personne personne = dao.create(Personne.PROPERTY_NAME, "Bob Marley");
@@ -143,7 +143,7 @@
assertNotNull(idPersonne);
log.debug("ENTITY PERSONNE SAVED !");
- Contact2DAO contactDAO = TopiaTestDAOHelper.getContact2DAO(transaction);
+ Contact2TopiaDao contactDAO = TopiaTestDAOHelper.getContact2TopiaDao(transaction);
log.debug("CREATE CONTACT : jaja(a)codelutin.com");
Contact2 contact = contactDAO.create(Contact2.PROPERTY_CONTACT_VALUE, "jaja(a)codelutin.com");
@@ -185,7 +185,7 @@
TopiaTestTopiaPersistenceContext transaction = db.beginTransaction();
- PersonneDAO dao = TopiaTestDAOHelper.getPersonneDAO(transaction);
+ PersonneTopiaDao dao = TopiaTestDAOHelper.getPersonneTopiaDao(transaction);
Personne person = dao.newInstance();
Assert.assertNull(person.getTopiaId());
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/FakeService.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/FakeService.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/FakeService.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -24,9 +24,8 @@
*/
package org.nuiton.topia.it.legacy.topiatest.service;
-import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.AbstractTopiaApplicationContext;
import org.nuiton.topia.framework.TopiaService;
-import org.nuiton.topia.it.legacy.framework.TopiaContextImplTest;
/**
* FakeService which implements {@link TopiaService} to test existing service
@@ -52,12 +51,12 @@
}
@Override
- public boolean preInit(TopiaContext context) {
+ public boolean preInit(AbstractTopiaApplicationContext context) {
return true;
}
@Override
- public boolean postInit(TopiaContext context) {
+ public boolean postInit(AbstractTopiaApplicationContext context) {
return true;
}
}
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/TestService.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/TestService.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/TestService.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -25,8 +25,7 @@
package org.nuiton.topia.it.legacy.topiatest.service;
import org.junit.Ignore;
-import org.nuiton.topia.TopiaContext;
-import org.nuiton.topia.it.legacy.framework.TopiaContextImplTest;
+import org.nuiton.topia.AbstractTopiaApplicationContext;
import org.nuiton.topia.framework.TopiaService;
/**
@@ -55,12 +54,12 @@
}
@Override
- public boolean preInit(TopiaContext context) {
+ public boolean preInit(AbstractTopiaApplicationContext context) {
return true;
}
@Override
- public boolean postInit(TopiaContext context) {
+ public boolean postInit(AbstractTopiaApplicationContext context) {
return true;
}
}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/persistence/TopiaDaoTest.java (from rev 2891, trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/TopiaDAOTest.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/persistence/TopiaDaoTest.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/persistence/TopiaDaoTest.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -0,0 +1,205 @@
+/*
+ * #%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.TopiaException;
+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);
+ }
+}
Modified: trunk/topia-persistence/src/it/ANOMALIE-1640/src/test/java/org/nuiton/topia/testabstract/TopiaAbstractTest.java
===================================================================
--- trunk/topia-persistence/src/it/ANOMALIE-1640/src/test/java/org/nuiton/topia/testabstract/TopiaAbstractTest.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-persistence/src/it/ANOMALIE-1640/src/test/java/org/nuiton/topia/testabstract/TopiaAbstractTest.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -25,7 +25,6 @@
package org.nuiton.topia.testabstract;
import org.junit.Test;
-import org.nuiton.topia.TopiaContext;
import org.nuiton.topia.TopiaContextFactory;
public class TopiaAbstractTest {
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaApplicationContext.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaApplicationContext.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaApplicationContext.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -115,7 +115,8 @@
persistenceContexts.add(persistenceContext);
}
- protected HibernateProvider getHibernateProvider() {
+ // TODO AThimel 25/11/13 I don't like it to be public, but necessary for services. Review it
+ public HibernateProvider getHibernateProvider() {
if (hibernateProvider == null) {
hibernateProvider = new HibernateProvider(configuration, topiaServiceSupport);
}
@@ -126,7 +127,7 @@
return topiaFiresSupport;
}
- protected ImmutableMap<String, String> getConfiguration() {
+ public ImmutableMap<String, String> getConfiguration() {
return configuration;
}
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaPersistenceContext.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaPersistenceContext.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaPersistenceContext.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -36,7 +36,7 @@
import org.hibernate.cfg.Configuration;
import org.nuiton.topia.framework.TopiaFiresSupport;
import org.nuiton.topia.persistence.AbstractTopiaDao;
-import org.nuiton.topia.persistence.TopiaDAO;
+import org.nuiton.topia.persistence.TopiaDao;
import org.nuiton.topia.persistence.TopiaEntity;
import org.nuiton.topia.persistence.TopiaIdFactory;
@@ -58,7 +58,7 @@
/**
* Already loaded DAO cache within this persistence context
*/
- protected Map<Class<? extends TopiaEntity>, TopiaDAO<? extends TopiaEntity>> daoCache = Maps.newConcurrentMap();
+ protected Map<Class<? extends TopiaEntity>, TopiaDao<? extends TopiaEntity>> daoCache = Maps.newConcurrentMap();
protected HibernateTopiaReplicationSupport hibernateTopiaReplicationSupport;
@@ -207,12 +207,16 @@
return firesSupport;
}
+ public TopiaHibernateSupport getHibernateSupport() {
+ return hibernateSupport;
+ }
+
@Override
public <E extends TopiaEntity> E findByTopiaId(String topiaId) {
checkClosed();
Class<E> entityClass = getTopiaIdFactory().getClassName(topiaId);
- TopiaDAO<E> dao = getDao(entityClass);
+ TopiaDao<E> dao = getDao(entityClass);
E result = dao.findByTopiaId(topiaId);
return result;
}
@@ -223,7 +227,7 @@
String topiaId = entity.getTopiaId();
Class<TopiaEntity> entityClass = getTopiaIdFactory().getClassName(topiaId);
- TopiaDAO<TopiaEntity> dao = getDao(entityClass);
+ TopiaDao<TopiaEntity> dao = getDao(entityClass);
dao.update(entity);
}
@@ -234,7 +238,12 @@
}
@Override
- public <E extends TopiaEntity> TopiaDAO<E> getDao(Class<E> entityClass) {
+ public TopiaFiresSupport getTopiaFiresSupport() {
+ return firesSupport;
+ }
+
+ @Override
+ public <E extends TopiaEntity> TopiaDao<E> getDao(Class<E> entityClass) {
Preconditions.checkArgument(entityClass != null, "The method 'getDao' requires a non null 'entityClass' parameter");
SessionFactory hibernateFactory = hibernateSupport.getHibernateFactory();
@@ -252,29 +261,29 @@
throw new TopiaException(message);
}
- TopiaDAO<E> dao = (TopiaDAO<E>) daoCache.get(entityClass);
+ TopiaDao<E> dao = (TopiaDao<E>) daoCache.get(entityClass);
if (dao == null) {
// Looking for specialized DAO
// This DAO is supposed to exist, as created by generation
String daoClassName = entityClass.getName() + "TopiaDao";
try {
- Class<TopiaDAO<E>> daoClass = (Class<TopiaDAO<E>>) Class.forName(daoClassName);
+ Class<TopiaDao<E>> daoClass = (Class<TopiaDao<E>>) Class.forName(daoClassName);
dao = daoClass.getConstructor().newInstance();
} catch (InstantiationException e) {
- log.fatal("unable to instantiate DAO class " + daoClassName, e);
+ log.fatal("Unable to instantiate DAO class " + daoClassName, e);
throw new TopiaException("unable to instantiate DAO class " + daoClassName, e);
} catch (IllegalAccessException e) {
- log.fatal("unable to instantiate DAO class " + daoClassName, e);
+ log.fatal("Unable to instantiate DAO class " + daoClassName, e);
throw new TopiaException("unable to instantiate DAO class " + daoClassName, e);
} catch (InvocationTargetException e) {
- log.fatal("unable to instantiate DAO class " + daoClassName, e);
+ log.fatal("Unable to instantiate DAO class " + daoClassName, e);
throw new TopiaException("unable to instantiate DAO class " + daoClassName, e);
} catch (NoSuchMethodException e) {
- log.fatal("unable to instantiate DAO class " + daoClassName, e);
+ log.fatal("Unable to instantiate DAO class " + daoClassName, e);
throw new TopiaException("unable to instantiate DAO class " + daoClassName, e);
} catch (ClassNotFoundException e) {
- log.fatal("unable to find DAO class " + daoClassName, e);
+ log.fatal("Unable to find DAO class " + daoClassName, e);
throw new TopiaException("unable to find DAO class " + daoClassName, e);
}
@@ -291,8 +300,8 @@
}
@Override
- public <E extends TopiaEntity, D extends TopiaDAO<E>> D getDao(Class<E> entityClass, Class<D> daoClass) {
- TopiaDAO<E> dao = getDao(entityClass);
+ public <E extends TopiaEntity, D extends TopiaDao<E>> D getDao(Class<E> entityClass, Class<D> daoClass) {
+ TopiaDao<E> dao = getDao(entityClass);
D result = (D) dao;
return result;
}
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/HibernateTopiaSqlSupport.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/HibernateTopiaSqlSupport.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/HibernateTopiaSqlSupport.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -63,6 +63,7 @@
}
}
+ // FIXME AThimel 22/11/2013 WTF name ?
public static class TopiaSQLWorkWork implements Work {
final TopiaSqlWork work;
@@ -77,7 +78,7 @@
}
}
- public static class TopiaSQLQueryWork<O> implements Work {
+ public static class TopiaSqlQueryWork<O> implements Work {
final TopiaSqlQuery<O> query;
@@ -85,7 +86,7 @@
final List<O> result = new ArrayList<O>();
- public TopiaSQLQueryWork(TopiaSqlQuery<O> query, boolean multipleResult) {
+ public TopiaSqlQueryWork(TopiaSqlQuery<O> query, boolean multipleResult) {
this.query = query;
this.multipleResult = multipleResult;
}
@@ -127,7 +128,7 @@
}
@Override
- public void executeSQL(String sqlScript) {
+ public void executeSql(String sqlScript) {
SQLWork work = new SQLWork(sqlScript);
try {
hibernateSupport.getHibernateSession().doWork(work);
@@ -137,7 +138,7 @@
}
@Override
- public void doSQLWork(TopiaSqlWork sqlWork) {
+ public void doSqlWork(TopiaSqlWork sqlWork) {
TopiaSQLWorkWork work = new TopiaSQLWorkWork(sqlWork);
try {
hibernateSupport.getHibernateSession().doWork(work);
@@ -149,7 +150,7 @@
@Override
public <O> O findSingleResult(final TopiaSqlQuery<O> query) throws TopiaException {
- TopiaSQLQueryWork<O> work = new TopiaSQLQueryWork<O>(query, false);
+ TopiaSqlQueryWork<O> work = new TopiaSqlQueryWork<O>(query, false);
hibernateSupport.getHibernateSession().doWork(work);
final List<O> result = work.getResult();
return result.isEmpty() ? null : result.get(0);
@@ -158,7 +159,7 @@
@Override
public <O> List<O> findMultipleResult(final TopiaSqlQuery<O> query) throws TopiaException {
- TopiaSQLQueryWork<O> work = new TopiaSQLQueryWork<O>(query, true);
+ TopiaSqlQueryWork<O> work = new TopiaSqlQueryWork<O>(query, true);
hibernateSupport.getHibernateSession().doWork(work);
final List<O> result = work.getResult();
return result;
Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaContext.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaContext.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaContext.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -1,607 +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%
- */
-
-package org.nuiton.topia;
-
-import org.nuiton.topia.event.TopiaContextListener;
-import org.nuiton.topia.event.TopiaEntitiesVetoable;
-import org.nuiton.topia.event.TopiaEntityListener;
-import org.nuiton.topia.event.TopiaEntityVetoable;
-import org.nuiton.topia.event.TopiaTransactionListener;
-import org.nuiton.topia.event.TopiaTransactionVetoable;
-import org.nuiton.topia.framework.TopiaService;
-import org.nuiton.topia.persistence.TopiaEntity;
-
-import java.beans.PropertyChangeListener;
-import java.io.File;
-import java.util.List;
-
-/**
- * The TopiaContext is the most important class of ToPIA. It contains all the
- * methods to manipulate data : transaction management, entities querying, event
- * firing, schema management, services management, ...
- * <p/>
- * To get an instance of TopiaContext, see {@link TopiaContextFactory#getContext(java.util.Properties)}
- * <p/>
- * <p/>
- * Created: 3 janv. 2006 21:18:34
- *
- * @author poussin <poussin(a)codelutin.com>
- * @author tchemit <tchemit(a)codelutin.com>
- * @author athimel <thimel(a)codelutin.com>
- * @version $Id$
- */
-@Deprecated
-public interface TopiaContext extends TopiaTransaction, TopiaListenableSupport, TopiaSqlSupport, TopiaJpaSupport,
- TopiaPersistenceContext, TopiaServiceSupport, TopiaReplicationSupport, TopiaReplicationDestination, TopiaHibernateSupport {
-
- /* -------------------- TRANSACTION MANAGEMENT --------------------------*/
-
- /**
- * Returns a new context containing its own transaction.
- *
- * @return new context with transaction
- * @throws TopiaException if any exception
- * @deprecated we need another method that returns a {@link TopiaTransaction} only. This method doesn't exist yet
- */
- @Deprecated
- TopiaContext beginTransaction() throws TopiaException;
-
- // TODO AThimel 03/08/13 We need another API to obtain a TopiaTransaction
- // TODO AThimel 03/08/13 This new method has to be located somewhere else (TopiaTransactionSupplier ? TopiaTransactionSupport ? or just TopiaPersistenceContext ?)
-
- /**
- * Applies all the modifications made to this context on the persistence
- * device. Once commit is done, a new transaction is started.
- *
- * @throws TopiaException if any exception
- * @deprecated use method from {@link TopiaTransaction}
- */
- @Deprecated
- void commit() throws TopiaException;
-
- /**
- * Cancels all the modifications made to this context, coming back to the
- * state on the last beginTransaction. Once rollback is done, a new
- * transaction is started.
- *
- * @throws TopiaException if any exception
- * @deprecated use method from {@link TopiaTransaction}
- */
- @Deprecated
- void rollback() throws TopiaException;
-
- /**
- * Closes the context. All the children contexts will be closed in the same
- * time.
- *
- * @throws TopiaException if any exception
- * @deprecated use method from {@link TopiaTransaction}
- */
- @Deprecated
- void closeContext() throws TopiaException;
-
- /**
- * Tells if the context is closed
- *
- * @return {@code true} if the context is closed, {@code false} otherwise
- * @deprecated use method from {@link TopiaTransaction}
- */
- @Deprecated
- boolean isClosed();
-
- /* ------------------------ EVENT FIRING --------------------------*/
-
- /* TopiaEntityListener */
-
- /**
- * Register to the context a TopiaEntityListener about any TopiaEntity.
- * <code>listener</code> instance will be notified AFTER any operation on
- * the entity.
- *
- * @param listener the listener instance to register
- * @deprecated use method from {@link TopiaListenableSupport}
- */
- @Deprecated
- void addTopiaEntityListener(TopiaEntityListener listener);
-
- /**
- * Register to the context a TopiaEntityListener about the given entity
- * class. <code>listener</code> instance will be notified AFTER any
- * operation on the entity.
- *
- * @param entityClass the TopiaEntity's class to listen
- * @param listener the listener instance to register
- * @deprecated use method from {@link TopiaListenableSupport}
- */
- @Deprecated
- void addTopiaEntityListener(Class<? extends TopiaEntity> entityClass,
- TopiaEntityListener listener);
-
- /**
- * Unregister the given TopiaEntityListener about any TopiaEntity from the
- * context
- *
- * @param listener the listener instance to unregister
- * @deprecated use method from {@link TopiaListenableSupport}
- */
- @Deprecated
- void removeTopiaEntityListener(TopiaEntityListener listener);
-
- /**
- * Unregister the given TopiaEntityListener about the given entity class
- * from the context
- *
- * @param entityClass the listened TopiaEntity's class
- * @param listener the listener instance to unregister
- * @deprecated use method from {@link TopiaListenableSupport}
- */
- @Deprecated
- void removeTopiaEntityListener(Class<? extends TopiaEntity> entityClass,
- TopiaEntityListener listener);
-
-
- /* TopiaEntityVetoable */
-
- /**
- * Register to the context a TopiaEntityVetoable about any TopiaEntity.
- * <code>vetoable</code> instance will be notified BEFORE any operation on
- * the entity.
- *
- * @param vetoable the vetoable instance to register
- * @deprecated use method from {@link TopiaListenableSupport}
- */
- @Deprecated
- void addTopiaEntityVetoable(TopiaEntityVetoable vetoable);
-
- /**
- * Register to the context a TopiaEntityVetoable about the given entity
- * class. <code>vetoable</code> instance will be notified BEFORE any
- * operation on the entity.
- *
- * @param entityClass the TopiaEntity's class to listen
- * @param vetoable the vetoable instance to register
- * @deprecated use method from {@link TopiaListenableSupport}
- */
- @Deprecated
- void addTopiaEntityVetoable(Class<? extends TopiaEntity> entityClass,
- TopiaEntityVetoable vetoable);
-
- /**
- * Unregister the given TopiaEntityVetoable about any TopiaEntity from the
- * context
- *
- * @param vetoable the vetoable instance to unregister
- * @deprecated use method from {@link TopiaListenableSupport}
- */
- @Deprecated
- void removeTopiaEntityVetoable(TopiaEntityVetoable vetoable);
-
- /**
- * Unregister the given TopiaEntityVetoable about the given entity class
- * from the context
- *
- * @param entityClass the listened TopiaEntity's class
- * @param vetoable the vetoable instance to unregister
- * @deprecated use method from {@link TopiaListenableSupport}
- */
- @Deprecated
- void removeTopiaEntityVetoable(Class<? extends TopiaEntity> entityClass,
- TopiaEntityVetoable vetoable);
-
-
- /* TopiaEntitiesVetoable */
-
- /**
- * Register to the context a TopiaEntitiesVetoable about any TopiaEntity.
- * <code>vetoable</code> instance will be notified BEFORE any entity load
- *
- * @param vetoable the vetoable instance to register
- * @deprecated use method from {@link TopiaListenableSupport}
- */
- @Deprecated
- void addTopiaEntitiesVetoable(TopiaEntitiesVetoable vetoable);
-
- /**
- * Unregister the given TopiaEntitiesVetoable about any TopiaEntity from the
- * context
- *
- * @param vetoable the vetoable instance to unregister
- * @deprecated use method from {@link TopiaListenableSupport}
- */
- @Deprecated
- void removeTopiaEntitiesVetoable(TopiaEntitiesVetoable vetoable);
-
-
- /* TopiaTransactionListener */
-
- /**
- * Register to the context a TopiaTransactionListener about the transaction.
- * <code>listener</code> instance will be notified AFTER any operation on
- * the transaction.
- *
- * @param listener the listener instance to register
- * @deprecated use method from {@link TopiaListenableSupport}
- */
- @Deprecated
- void addTopiaTransactionListener(TopiaTransactionListener listener);
-
- /**
- * Unregister the given TopiaTransactionListener about the transaction from
- * the context
- *
- * @param listener the listener instance to unregister
- * @deprecated use method from {@link TopiaListenableSupport}
- */
- @Deprecated
- void removeTopiaTransactionListener(TopiaTransactionListener listener);
-
-
- /* TopiaTransactionVetoable */
-
- /**
- * Register to the context a TopiaTransactionVetoable about the transaction.
- * <code>vetoable</code> instance will be notified BEFORE any operation on
- * the transaction.
- *
- * @param vetoable the vetoable instance to register
- * @deprecated use method from {@link TopiaListenableSupport}
- */
- @Deprecated
- void addTopiaTransactionVetoable(TopiaTransactionVetoable vetoable);
-
- /**
- * Unregister the given TopiaTransactionVetoable about the transaction from
- * the context
- *
- * @param vetoable the vetoable instance to unregister
- * @deprecated use method from {@link TopiaListenableSupport}
- */
- @Deprecated
- void removeTopiaTransactionVetoable(TopiaTransactionVetoable vetoable);
-
-
- /* PropertyChangeListener */
-
- /**
- * Register to the context a PropertyChangeListener about some entity's
- * property change. <code>listener</code> instance will be notified AFTER
- * any change on the entity's property
- *
- * @param listener the listener instance to register
- * @deprecated use method from {@link TopiaListenableSupport}
- */
- @Deprecated
- void addPropertyChangeListener(PropertyChangeListener listener);
-
- /**
- * Unregister the given PropertyChangeListener about some entity's
- * property change from the context
- *
- * @param listener the listener instance to unregister
- * @deprecated use method from {@link TopiaListenableSupport}
- */
- @Deprecated
- void removePropertyChangeListener(PropertyChangeListener listener);
-
-
- /* TopiaContextListener */
-
- /**
- * Register to the context a TopiaContextListener about any schema
- * modification. <code>listener</code> instance will be notified BEFORE and
- * AFTER any change on the schema
- *
- * @param listener the listener instance to register
- * @deprecated Use addTopiaSchemaListener
- */
- @Deprecated
- void addTopiaContextListener(TopiaContextListener listener);
-
- /**
- * Unregister the given TopiaContextListener about any schema modification
- * from the context
- *
- * @param listener the listener instance to unregister
- * @deprecated Use removeTopiaSchemaListener
- */
- @Deprecated
- void removeTopiaContextListener(TopiaContextListener listener);
-
- /* -------------------- GLOBAL OPERATIONS ON ENTITIES --------------------*/
-
- /**
- * Retrieve {@link TopiaEntity} using its unique {@code id}.
- *
- * @param topiaId unique identifier of the entity in all the application.
- * @return the entity found or null
- * @throws TopiaException for errors on retrieving the entity
- * @deprecated use {@link TopiaPersistenceContext#findByTopiaId(String)}
- */
- @Deprecated
- <E extends TopiaEntity> E findByTopiaId(String topiaId) throws TopiaException;
-
- /**
- * Add into this TopiaContext an entity created by another TopiaContext
- *
- * @param e the entity to add
- * @throws TopiaException if any exception
- * @deprecated use {@link TopiaPersistenceContext#update(org.nuiton.topia.persistence.TopiaEntity)}
- */
- @Deprecated
- void add(TopiaEntity e) throws TopiaException;
-
- /**
- * Clear persistence implementation cache.
- *
- * @since 2.6.13
- * @deprecated use {@link TopiaHibernateSupport#getHibernateSession().clear()}
- */
- @Deprecated
- void clearCache() throws TopiaException;
-
- /**
- * Allow to do some HQL query
- * <p/>
- * WARNING : Depending on the registered service, this method may not
- * support something else than queries on TopiaEntity
- *
- * @param hql the HQL query
- * @param propertyNamesAndValues the query parameters. Arguments are key-value paired :
- * [propertyName;value;propertyName;value;...]
- * @return The result list
- * @throws TopiaException for any error during querying
- * @deprecated use method from {@link TopiaJpaSupport}
- */
- @Deprecated
- <E> List<E> findAll(String hql,
- Object... propertyNamesAndValues) throws TopiaException;
-
- /**
- * Allow to do some JPA-QL query using the given bounds.
- * <p/>
- * No lower bound : <code>startIndex</code> = 0.<br/>
- * No upper bound : <code>endIndex</code> = -1.
- * <p/>
- * WARNING : Depending on the registered service, this method may not
- * support something else than queries on TopiaEntity
- *
- * @param hql the HQL query
- * @param startIndex first index of entity to return
- * @param endIndex last index of entity to return
- * @param propertyNamesAndValues the query parameters. Arguments are key-value paired :
- * [propertyName;value;propertyName;value;...]
- * @return The result list
- * @throws TopiaException for any error during querying
- * @deprecated use method from {@link TopiaJpaSupport}
- */
- @Deprecated
- <E> List<E> find(String hql,
- int startIndex,
- int endIndex,
- Object... propertyNamesAndValues) throws TopiaException;
-
- /**
- * Allow to do some HQL query and return an unique result. If nothing if
- * found by the query, will return null. If more than one result is found,
- * will throw an exception.
- * <p/>
- * WARNING : Depending on the registered service, this method may not
- * support something else than queries on TopiaEntity
- *
- * @param hql the HQL query
- * @param propertyNamesAndValues the query parameters. Arguments are key-value paired :
- * [propertyName;value;propertyName;value;...]
- * @return The result instance or null
- * @throws TopiaException for any error during querying or if the the query
- * returns more than one result.
- * @deprecated use method from {@link TopiaJpaSupport}
- */
- @Deprecated
- <E> E findUnique(String hql,
- Object... propertyNamesAndValues) throws TopiaException;
-
- /**
- * Execute HQL operation on data (Update, Delete).
- *
- * @param hql the HQL query
- * @param propertyNamesAndValues the query parameters. Arguments are key-value paired :
- * [propertyName;value;propertyName;value;...]
- * @return The number of entities updated or deleted.
- * @throws TopiaException if any exception
- * @deprecated use method from {@link TopiaJpaSupport}
- */
- @Deprecated
- int execute(String hql,
- Object... propertyNamesAndValues) throws TopiaException;
-
- /**
- * Execute a given sql code inside this transaction.
- *
- * @param sqlScript the sql script to execute
- * @throws TopiaException if any problem occurred while executing the sql script.
- * @deprecated use method from {@link TopiaSqlSupport}
- */
- @Deprecated
- void executeSQL(String sqlScript) throws TopiaException;
-
- /* -------------------- SCHEMA MANAGMENT -----------------------------*/
-
- /**
- * Triggers database schema creation
- *
- * @throws TopiaException if any exception
- * @deprecated use methods from {@link TopiaPersistenceContext}
- */
- @Deprecated
- void createSchema() throws TopiaException;
-
- /**
- * Displays the SQL queries that would be used for a schema creation
- *
- * @throws TopiaException if any exception
- * @deprecated use methods from {@link TopiaPersistenceContext}
- */
- @Deprecated
- void showCreateSchema() throws TopiaException;
-
- /**
- * Triggers database schema update
- *
- * @throws TopiaException if any exception
- * @deprecated use methods from {@link TopiaPersistenceContext}
- */
- @Deprecated
- void updateSchema() throws TopiaException;
-
- /* -------------------- SERVICES MANAGMENT -------------------------------*/
-
- /**
- * Return true if specific service is available.
- *
- * @param <E> type of service
- * @param interfaceService fqn of the service
- * @return the service
- * @deprecated use methods from {@link TopiaServiceSupport}
- */
- @Deprecated
- <E extends TopiaService> boolean serviceEnabled(Class<E> interfaceService);
-
- /**
- * Return the service. This service must be valid with public static final
- * SERVICE_NAME property.
- *
- * @param <E> type of service
- * @param interfaceService class of the service
- * @return the service
- * @throws TopiaNotFoundException if service can't be retrieved
- * @deprecated use methods from {@link TopiaServiceSupport}
- */
- @Deprecated
- <E extends TopiaService> E getService(Class<E> interfaceService) throws TopiaNotFoundException;
-
- /* ------------------ IMPORT / EXPORT / REPLICATION ---------------------*/
-
- /**
- * Makes a replication of some entities from this context to the given
- * context without any entity modification.
- * <p/>
- * <b>Note:</b> If the <code>entityAndCondition</code> parameter is empty,
- * all the database will be replicated
- * <p/>
- * <b>Note 2:</b> The simple replication may not be sufficent. You may want
- * to replicate only a part of some entities : use the method {@link
- * #replicateEntities(TopiaContext, List)}.
- *
- * @param destinationContext the destination context
- * @param entityAndCondition [key;value;...] parameter which key is the
- * entity class to replicate, and value the
- * "where" condition to use when querying entities
- * @throws TopiaException if any problem occurred during replicate
- * @throws IllegalArgumentException if one of the context is closed or if
- * trying to replicate within the same
- * database
- * @deprecated use methods from {@link TopiaReplicationSupport}
- */
- @Deprecated
- void replicate(TopiaContext destinationContext,
- Object... entityAndCondition) throws TopiaException, IllegalArgumentException;
-
- /**
- * Replicate a given entity from this context to the given context.
- *
- * @param destinationContext the destination context
- * @param entity the entity instance to replicate
- * @param <T> type of the entity to replicate
- * @throws TopiaException if any problem occurred during replicate
- * @throws IllegalArgumentException if one of the context is closed or if
- * trying to replicate within the same
- * database
- * @deprecated use methods from {@link TopiaReplicationSupport}
- */
- @Deprecated
- <T extends TopiaEntity> void replicateEntity(TopiaContext destinationContext,
- T entity) throws TopiaException, IllegalArgumentException;
-
- /**
- * Makes a replication of some entities from this context to the given
- * context without any entity modification.
- *
- * @param destinationContext the destination context
- * @param entities the list of entities instance to replicate
- * @param <T> type of the entities to replicate
- * @throws TopiaException if any problem occurred during replicate
- * @throws IllegalArgumentException if one of the context is closed or if
- * trying to replicate within the same
- * database
- * @deprecated use methods from {@link TopiaReplicationSupport}
- */
- @Deprecated
- <T extends TopiaEntity> void replicateEntities(TopiaContext destinationContext,
- List<T> entities) throws TopiaException, IllegalArgumentException;
-
- /* ------------------ H2 specific methods ---------------------*/
-
- /**
- * Sauve la base de données dans un format natif a la base, la
- * representation n'est pas portable d'une base a l'autre. Cette methode ne
- * doit être utilisé que pour un stockage temporaire utile à une
- * application.
- *
- * @param file le nom du fichier ou stocker les informations
- * @param compress si vrai compress le fichier avec gzip
- * @throws TopiaException if any exception
- * @deprecated Only H2 compatible : remove it, or move to another class
- */
- @Deprecated
- void backup(File file,
- boolean compress) throws TopiaException;
-
- /**
- * l'inverse de la methode {@link #backup(File, boolean)}.
- *
- * @param file le fichier ou prendre les informations, il peut-etre
- * compressé avec gzip ou non.
- * @throws TopiaException if any exception
- * @deprecated Only H2 compatible : remove it, or move to another class
- */
- @Deprecated
- void restore(File file) throws TopiaException;
-
-
- /**
- * Supprime toutes les tables et autres elements de la database.
- *
- * @param dropDatabase si vrai alors supprime aussi la base de données si la
- * base utilise des fichiers les fichiers seront
- * supprimé (ex: h2) ou sera fait sur la base
- * (postgresql)
- * @throws TopiaException if any exception
- * @deprecated Only H2 compatible : remove it, or move to another class
- */
- @Deprecated
- void clear(boolean dropDatabase) throws TopiaException;
-
-} //TopiaContext
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaContextFactory.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaContextFactory.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaContextFactory.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -30,7 +30,6 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.cfg.Environment;
-import org.nuiton.topia.framework.AbstractTopiaContext;
import org.nuiton.topia.framework.TopiaUtil;
import java.util.ArrayList;
@@ -39,6 +38,9 @@
import java.util.Map;
import java.util.Properties;
+import com.google.common.base.Function;
+import com.google.common.base.Supplier;
+
/**
* TODO-FD20100507 : Need javadoc + translate the one on methods.
* <p/>
@@ -48,6 +50,7 @@
* @author tchemit <tchemit(a)codelutin.com>
* @version $Id$
*/
+@Deprecated
public class TopiaContextFactory {
private static final Log log = LogFactory.getLog(TopiaContextFactory.class);
@@ -56,7 +59,7 @@
"TopiaContextImpl.properties";
/** Cache contenant tous les contexts deja créé. */
- protected static Map<Properties, TopiaContext> contextCache =
+ protected static Map<Properties, AbstractTopiaApplicationContext> contextCache =
new ReferenceMap(AbstractReferenceMap.HARD,
AbstractReferenceMap.SOFT);
@@ -131,7 +134,7 @@
*
* @param context closed
*/
- public static void removeContext(TopiaContext context) {
+ public static void removeContext(AbstractTopiaApplicationContext context) {
// Properties key = null;
// for (Entry<Properties, AbstractTopiaContext> e : contextCache.entrySet()) {
// if (e.getValue() == context) {
@@ -145,10 +148,10 @@
// Replaced by more powerful algorithm using iterator to remove context
- Iterator<TopiaContext> it = contextCache.values().iterator();
+ Iterator<AbstractTopiaApplicationContext> it = contextCache.values().iterator();
while (it.hasNext()) {
- TopiaContext curr = it.next();
+ AbstractTopiaApplicationContext curr = it.next();
if (curr == context) {
it.remove();
break;
@@ -163,9 +166,9 @@
* @throws TopiaNotFoundException Si le fichier de configuration par defaut
* n'est pas retrouvé.
*/
- public static TopiaContext getContext() throws TopiaNotFoundException {
+ public static AbstractTopiaApplicationContext getContext() throws TopiaNotFoundException {
Properties config = TopiaUtil.getProperties(DEFAULT_CONFIG_PROPERTIES);
- TopiaContext result = getContext(config);
+ AbstractTopiaApplicationContext result = getContext(config, null);
return result;
}
@@ -179,7 +182,8 @@
* @return Un TopiaContext ouvert
* @throws TopiaNotFoundException if any pb
*/
- public static TopiaContext getContext(Properties config)
+ public static AbstractTopiaApplicationContext getContext(
+ Properties config, Function<Properties, AbstractTopiaApplicationContext> createContextFunction)
throws TopiaNotFoundException {
// Put all properties from a hierarchy in the current properties object.
// Resolve problem with hibernate which used iterator to get properties
@@ -189,10 +193,13 @@
for (String key : config.stringPropertyNames()) {
cloned.setProperty(key, config.getProperty(key));
}
- TopiaContext result = contextCache.get(cloned);
- // useless test, context is automatically removed from Factory when closed
- if (result == null/* || result.isClosed()*/) {
- result = new AbstractTopiaContext(cloned);
+ AbstractTopiaApplicationContext result = contextCache.get(cloned);
+ if (result == null || result.isClosed()) {
+ if (createContextFunction == null) {
+ throw new TopiaException("Function<Properties, AbstractTopiaApplicationContext> is needed to create context");
+ } else {
+ result = createContextFunction.apply(cloned);
+ }
if (log.isDebugEnabled()) {
log.debug("instantiate new topiaContext : " + result);
}
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaDaoSupplier.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaDaoSupplier.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaDaoSupplier.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -24,7 +24,7 @@
* #L%
*/
-import org.nuiton.topia.persistence.TopiaDAO;
+import org.nuiton.topia.persistence.TopiaDao;
import org.nuiton.topia.persistence.TopiaEntity;
/**
@@ -33,22 +33,22 @@
public interface TopiaDaoSupplier {
/**
- * Get DAO for specified class. If Specialized DAO exists then it returned
- * otherwize TopiaDAO<entityClass> is returned
+ * Get Dao for specified class. If the specialized Dao exists then it is
+ * returned otherwise a TopiaException will be thrown
*
* @param entityClass type of entity
* @return the expected dao
*/
- <E extends TopiaEntity> TopiaDAO<E> getDao(Class<E> entityClass);
+ <E extends TopiaEntity> TopiaDao<E> getDao(Class<E> entityClass);
/**
- * Get DAO for specified class. If Specialized DAO exists then it returned
- * otherwize TopiaDAO<entityClass> is returned
+ * Get Dao for specified class. If the specialized Dao exists then it is
+ * returned otherwise a TopiaException will be thrown
*
* @param entityClass type of entity
* @param daoClass the concrete dao class to use
* @return the expected dao
*/
- <E extends TopiaEntity, D extends TopiaDAO<E>> D getDao(Class<E> entityClass, Class<D> daoClass);
+ <E extends TopiaEntity, D extends TopiaDao<E>> D getDao(Class<E> entityClass, Class<D> daoClass);
}
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaPersistenceContext.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaPersistenceContext.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaPersistenceContext.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -24,6 +24,7 @@
* #L%
*/
+import org.nuiton.topia.framework.TopiaFiresSupport;
import org.nuiton.topia.persistence.TopiaEntity;
import org.nuiton.topia.persistence.TopiaIdFactory;
@@ -78,4 +79,13 @@
*/
boolean isClosed();
+ /**
+ * Get the currently configured {@link TopiaFiresSupport}.
+ *
+ * @return the {@link TopiaFiresSupport} in use
+ * @see {@link TopiaFiresSupport}
+ * @since 3.0
+ */
+ TopiaFiresSupport getTopiaFiresSupport();
+
}
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaReplicationDestination.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaReplicationDestination.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaReplicationDestination.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -27,7 +27,7 @@
import org.nuiton.topia.persistence.TopiaEntity;
/**
- * Represent the destination of a replciation process. The source is
+ * Represent the destination of a replication process. The source is
* {@link TopiaReplicationSupport}
*/
public interface TopiaReplicationDestination {
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaServiceSupportImpl.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaServiceSupportImpl.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaServiceSupportImpl.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -59,7 +59,7 @@
protected void preInitServices(Map<String, TopiaService> services) {
for (TopiaService service : services.values()) {
- if (!service.preInit(null)) { // TODO AThimel 11/10/13 was: this (aka TopiaContext)
+ if (!service.preInit(applicationContext)) {
log.warn(String.format("The service named '%1$s' could not be post-initialized (service not activated)",
service.getServiceName()));
}
@@ -68,7 +68,7 @@
protected void postInitServices(Map<String, TopiaService> services) {
for (TopiaService service : services.values()) {
- if (!service.postInit(null)) { // TODO AThimel 11/10/13 was: this (aka TopiaContext)
+ if (!service.postInit(applicationContext)) {
log.warn(String.format("The service named '%1$s' could not be pre-initialized (service not activated)",
service.getServiceName()));
}
@@ -101,7 +101,7 @@
protected ImmutableMap<String, TopiaService> loadServices(ImmutableMap<String, String> configuration) {
Map<String, TopiaService> result = new HashMap<String, TopiaService>();
// recherche des services present dans la config
- for (String key : result.keySet()) {
+ for (String key : configuration.keySet()) {
if (key.matches("^topia\\.service\\.\\w+$")) {
String serviceClass = configuration.get(key);
try {
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaSqlSupport.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaSqlSupport.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaSqlSupport.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -39,14 +39,14 @@
*
* @param sqlScript the sql script to execute
*/
- void executeSQL(String sqlScript);
+ void executeSql(String sqlScript);
/**
* Runs the given SQL work on the current context
*
* @param sqlWork the SQL work instance to execute
*/
- void doSQLWork(TopiaSqlWork sqlWork);
+ void doSqlWork(TopiaSqlWork sqlWork);
/**
* Runs the given SQL query and return its first result if there is some.
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/event/TopiaContextAdapter.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/event/TopiaContextAdapter.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/event/TopiaContextAdapter.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -25,7 +25,7 @@
package org.nuiton.topia.event;
/**
- * Adapter pattern of {@link TopiaContextListener}.
+ * Adapter pattern of {@link TopiaSchemaListener}.
* <p/>
* This implementation does nothing but permits developpers to use this adapater
* without to have to implements all methods.
@@ -33,7 +33,7 @@
* @author tchemit <chemit(a)codelutin.com>
* @since 2.3.4
*/
-public class TopiaContextAdapter implements TopiaContextListener {
+public class TopiaContextAdapter implements TopiaSchemaListener {
@Override
public void preDropSchema(TopiaContextEvent event) {
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/event/TopiaContextEvent.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/event/TopiaContextEvent.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/event/TopiaContextEvent.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -25,10 +25,10 @@
package org.nuiton.topia.event;
-import org.nuiton.topia.TopiaContext;
-
import java.util.EventObject;
+import org.nuiton.topia.TopiaPersistenceContext;
+
/**
* TODO-fdesbois-20100507 : Need javadoc.
* Used for Migration service.
@@ -46,13 +46,13 @@
*
* @param source
*/
- public TopiaContextEvent(Object source) {
+ public TopiaContextEvent(TopiaPersistenceContext source) {
super(source);
}
@Override
- public TopiaContext getSource() {
- return (TopiaContext) source;
+ public TopiaPersistenceContext getSource() {
+ return (TopiaPersistenceContext) source;
}
}
Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/event/TopiaContextListener.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/event/TopiaContextListener.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/event/TopiaContextListener.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -1,80 +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%
- */
-
-package org.nuiton.topia.event;
-
-/**
- * Listener for TopiaContext actions.
- * <p/>
- * Listener are notified for action such as :
- * <ul>
- * <li>createSchema</li>
- * <li>updateSchema</li>
- * <li>...</li>
- * </ul>
- *
- * @author chatellier <chatellier(a)codelutin.com>
- * @version $Id$
- */
-@Deprecated
-public interface TopiaContextListener extends TopiaSchemaListener {
-
- /**
- * @deprecated Use {@link TopiaSchemaListener#preCreateSchema(TopiaContextEvent)}
- */
- @Deprecated
- void preCreateSchema(TopiaContextEvent event);
-
- /**
- * @deprecated Use {@link TopiaSchemaListener#postCreateSchema(TopiaContextEvent)}
- */
- @Deprecated
- void postCreateSchema(TopiaContextEvent event);
-
- /**
- * @deprecated Use {@link TopiaSchemaListener#preUpdateSchema(TopiaContextEvent)}
- */
- @Deprecated
- void preUpdateSchema(TopiaContextEvent event);
-
- /**
- * @deprecated Use {@link TopiaSchemaListener#postUpdateSchema(TopiaContextEvent)}
- */
- @Deprecated
- void postUpdateSchema(TopiaContextEvent event);
-
- /**
- * @deprecated Use {@link TopiaSchemaListener#preRestoreSchema(TopiaContextEvent)}
- */
- @Deprecated
- void preRestoreSchema(TopiaContextEvent event);
-
- /**
- * @deprecated Use {@link TopiaSchemaListener#postRestoreSchema(TopiaContextEvent)}
- */
- @Deprecated
- void postRestoreSchema(TopiaContextEvent event);
-
-}
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/event/TopiaEntitiesEvent.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/event/TopiaEntitiesEvent.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/event/TopiaEntitiesEvent.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -25,7 +25,7 @@
package org.nuiton.topia.event;
-import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.TopiaJpaSupport;
import org.nuiton.topia.persistence.TopiaEntity;
import java.util.EventObject;
@@ -43,7 +43,7 @@
private List<E> entities;
- public TopiaEntitiesEvent(Object source, List<E> entities) {
+ public TopiaEntitiesEvent(TopiaJpaSupport source, List<E> entities) {
super(source);
this.entities = entities;
}
@@ -53,7 +53,7 @@
}
@Override
- public TopiaContext getSource() {
- return (TopiaContext) super.getSource();
+ public TopiaJpaSupport getSource() {
+ return (TopiaJpaSupport) super.getSource();
}
}
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/event/TopiaEntityEvent.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/event/TopiaEntityEvent.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/event/TopiaEntityEvent.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -25,7 +25,7 @@
package org.nuiton.topia.event;
-import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.TopiaPersistenceContext;
import org.nuiton.topia.persistence.TopiaEntity;
import java.util.EventObject;
@@ -44,7 +44,7 @@
private Object[] state;
- public TopiaEntityEvent(Object source, TopiaEntity entity, Object[] state) {
+ public TopiaEntityEvent(TopiaPersistenceContext source, TopiaEntity entity, Object[] state) {
super(source);
this.entity = entity;
this.state = state;
@@ -55,8 +55,8 @@
}
@Override
- public TopiaContext getSource() {
- return (TopiaContext) super.getSource();
+ public TopiaPersistenceContext getSource() {
+ return (TopiaPersistenceContext) super.getSource();
}
public Object[] getState() {
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/event/TopiaTransactionEvent.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/event/TopiaTransactionEvent.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/event/TopiaTransactionEvent.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -26,7 +26,7 @@
package org.nuiton.topia.event;
import org.apache.commons.collections.map.IdentityMap;
-import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.TopiaPersistenceContext;
import org.nuiton.topia.TopiaTransaction;
import org.nuiton.topia.framework.EntityState;
import org.nuiton.topia.persistence.TopiaEntity;
@@ -48,11 +48,11 @@
private Map<TopiaEntity, EntityState> entities = new IdentityMap();
- public TopiaTransactionEvent(TopiaTransaction source) {
+ public TopiaTransactionEvent(TopiaPersistenceContext source) {
super(source);
}
- public TopiaTransactionEvent(TopiaTransaction source,
+ public TopiaTransactionEvent(TopiaPersistenceContext source,
Map<TopiaEntity, EntityState> entities) {
this(source);
this.entities.putAll(entities);
@@ -94,8 +94,8 @@
}
@Override
- public TopiaContext getSource() {
- return (TopiaContext) super.getSource();
+ public TopiaPersistenceContext getSource() {
+ return (TopiaPersistenceContext) super.getSource();
}
@Override
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/event/TopiaTransactionListener.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/event/TopiaTransactionListener.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/event/TopiaTransactionListener.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -25,8 +25,6 @@
package org.nuiton.topia.event;
-import org.nuiton.topia.TopiaContext;
-import org.nuiton.topia.framework.TopiaContextImplementor;
import org.nuiton.topia.framework.TopiaFiresSupport;
import java.util.EventListener;
Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/AbstractTopiaContext.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/AbstractTopiaContext.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/AbstractTopiaContext.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -1,1632 +0,0 @@
-/*
- * #%L
- * ToPIA :: Persistence
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2004 - 2013 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.framework;
-
-import org.apache.commons.lang3.StringUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.hibernate.FlushMode;
-import org.hibernate.HibernateException;
-import org.hibernate.Query;
-import org.hibernate.ReplicationMode;
-import org.hibernate.SQLQuery;
-import org.hibernate.Session;
-import org.hibernate.SessionFactory;
-import org.hibernate.Transaction;
-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.Stoppable;
-import org.hibernate.tool.hbm2ddl.SchemaExport;
-import org.hibernate.tool.hbm2ddl.SchemaUpdate;
-import org.nuiton.topia.HibernateTopiaSqlSupport;
-import org.nuiton.topia.TopiaContext;
-import org.nuiton.topia.TopiaContextFactory;
-import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.TopiaNotFoundException;
-import org.nuiton.topia.TopiaReplicationDestination;
-import org.nuiton.topia.TopiaSqlQuery;
-import org.nuiton.topia.TopiaSqlWork;
-import org.nuiton.topia.event.TopiaContextListener;
-import org.nuiton.topia.event.TopiaEntitiesVetoable;
-import org.nuiton.topia.event.TopiaEntityListener;
-import org.nuiton.topia.event.TopiaEntityVetoable;
-import org.nuiton.topia.event.TopiaSchemaListener;
-import org.nuiton.topia.event.TopiaTransactionListener;
-import org.nuiton.topia.event.TopiaTransactionVetoable;
-import org.nuiton.topia.persistence.AbstractTopiaDao;
-import org.nuiton.topia.persistence.DefaultTopiaIdFactory;
-import org.nuiton.topia.persistence.TopiaDAO;
-import org.nuiton.topia.persistence.TopiaDAOImpl;
-import org.nuiton.topia.persistence.TopiaEntity;
-import org.nuiton.topia.persistence.TopiaIdFactory;
-
-import java.beans.PropertyChangeListener;
-import java.io.BufferedInputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.InputStream;
-import java.lang.reflect.Field;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Set;
-import java.util.WeakHashMap;
-import java.util.zip.GZIPInputStream;
-
-import static org.nuiton.topia.HibernateTopiaSqlSupport.SQLWork;
-import static org.nuiton.topia.HibernateTopiaSqlSupport.TopiaSQLQueryWork;
-
-/**
- * Le AbstractTopiaContext est le point d'entre pour acceder aux donnees. Il est
- * configurer par un fichier de propriete
- * <p/>
- * List des proprietes disponible <dl> <dt> topia.persistence.properties.file
- * <dd> le fichier de propriété a utiliser pour configurer hibernate
- * <p/>
- * <dt> topia.persistence.directories <dd> la liste des repertoires contenant
- * les mappings hibernates (.hbm.xml) la liste de repertoire est separer par des
- * virgules ','
- * <p/>
- * <dt> topia.persistence.classes <dd> la liste des classes que doit géré
- * hibernate. On peut tres bien utiliser topia.persistence.directories pour un
- * ensemble d'entié du meme repertoire et topia.persistence.classes pour
- * d'autres classes </dl>
- * <p/>
- * AbstractTopiaContext.java
- * <p/>
- * Created: 23 déc. 2005 16:58:50
- *
- * @author bpoussin <poussin(a)codelutin.com>
- * @author tchemit <chemit(a)codelutin.com>
- * @author fdesbois <desbois(a)codelutin.com>
- * @version $Id$
- */
-//TODO-fdesbois-20100507 : Need translation of javadoc.
-// TODO AThimel 02/08/13 must be abstract
-public class AbstractTopiaContext implements TopiaContext, TopiaContextImplementor {
-
- /**
- * to use log facility, just put in your code: log.info(\"...\");
- */
- private static final Log log = LogFactory.getLog(AbstractTopiaContext.class);
-
- /**
- * Le pere de ce context, les contexts initaux n'ont pas de context pere
- *
- * @deprecated Hierarchical context are not supported anymore
- */
- @Deprecated
- protected TopiaContextImplementor parentContext;
-
- /**
- * L'objet configuration utilisé pour la creation de la factory hibernate
- */
- protected Configuration hibernateConfiguration;
-
- /**
- * la factory permettant de recuperer la session hibernate. Seul les
- * AbstractTopiaContext initiaux contiennent un hibernateFactory
- */
- protected SessionFactory hibernateFactory;
-
- /**
- * La session utilisé par le AbstractTopiaContext
- */
- protected Session hibernate;
-
- /**
- * Indique si le contexte a ete ferme
- */
- protected boolean closed;
-
- /**
- * This flag permits to use (or not) the flush mode when doing queries.
- * <p/>
- * The normal usage is to says yes (that's why the default value is
- * {@code true}), in that case whebn doing queries (says in method
- * {@link #findAll(String, Object...)} or {@link #find(String, int, int, Object...)})
- * it will use the flush mode {@link FlushMode#AUTO}).
- * <p/>
- * But sometimes, when doing a lot of queries (for some imports for example),
- * we do NOT want the session to be flushed each time we do a find, then you
- * can set this flag to {@code false} using the method {@link #setUseFlushMode(boolean)}
- *
- * @since 2.5
- */
- protected boolean useFlushMode = true;
-
- /**
- * Propriete de configuration
- */
- protected Properties config;
-
- /**
- * Used to affect a new topiaId when create is called.
- *
- * @since 3.0
- */
- protected TopiaIdFactory topiaIdFactory;
-
- /**
- * cache des DAO deja chargé pour ce context
- */
- protected Map<Class<? extends TopiaEntity>,
- TopiaDAO<? extends TopiaEntity>> daoCache =
- new HashMap<Class<? extends TopiaEntity>,
- TopiaDAO<? extends TopiaEntity>>();
-
- /**
- * Set of child context created with {@link #beginTransaction()}. We are
- * listener on these context. A WeakHashMap is used to remove old context
- * automically when it's not used anymore. The {@link #finalize} method will
- * be executed when Garbage collector is called when reference is removed.
- * The set is synchronized in case of using multi-threading.
- *
- * @see Collections#synchronizedSet(Set)
- * @see Collections#newSetFromMap(Map)
- */
- protected final Set<TopiaContextImplementor> childContext =
- Collections.synchronizedSet(
- Collections.newSetFromMap(
- new WeakHashMap<TopiaContextImplementor, Boolean>()));
-
- /**
- * key: service name; value: service instance
- */
- protected Map<String, TopiaService> services;
-
- protected TopiaFiresSupport firesSupport = new TopiaFiresSupport();
-
- /**
- * Liste des classes perssitance
- */
- protected List<Class<?>> persistenceClasses = new ArrayList<Class<?>>();
-
- /**
- * Default constructor, useful for tests.
- */
- protected AbstractTopiaContext() {
-
- }
-
- /**
- * Constructor used by {@link TopiaContextFactory} to initialize rootContext
- * using {@code config}.
- *
- * @param config for the new root context
- * @throws TopiaNotFoundException if one of persistent class from
- * configuration is not found
- */
- public AbstractTopiaContext(Properties config) throws TopiaNotFoundException {
- this.config = config;
- initTopiaIdFactory();
- services = loadServices(config);
- preInitServices(services);
- getHibernateConfiguration(); // force mapping loading
- postInitServices(services);
- }
-
- protected void initTopiaIdFactory() {
- String configTopiaIdFactoryClassName =
- getConfig().getProperty(TopiaContextFactory.CONFIG_PERSISTENCE_TOPIA_ID_FACTORY_CLASS_NAME, "");
- if (StringUtils.isEmpty(configTopiaIdFactoryClassName)) {
- topiaIdFactory = new DefaultTopiaIdFactory();
- } else {
- try {
- Class configPersistenceTopiaIdFactoryClass =
- Class.forName(configTopiaIdFactoryClassName);
- if (TopiaIdFactory.class.isAssignableFrom(configPersistenceTopiaIdFactoryClass)) {
- topiaIdFactory = (TopiaIdFactory) configPersistenceTopiaIdFactoryClass.newInstance();
- } else {
- throw new IllegalArgumentException(
- configTopiaIdFactoryClassName + " is not a valid class name. The class must implements "
- + TopiaIdFactory.class.getSimpleName());
- }
- } catch (ClassNotFoundException e) {
- throw new TopiaException(e);
- } catch (InstantiationException e) {
- throw new TopiaException(e);
- } catch (IllegalAccessException e) {
- throw new TopiaException(e);
- }
- }
- }
-
- protected String getProperExceptionMessage(Throwable eee) {
- return eee.getClass().getSimpleName() + " : " +
- eee.getMessage();
- }
-
- /* -------------------- SERVICES MANAGMENT -------------------------------*/
-
- protected Map<String, TopiaService> loadServices(Properties config) {
- Map<String, TopiaService> result = new HashMap<String, TopiaService>();
- // recherche des services present dans la config
- for (Enumeration<?> e = config.propertyNames(); e.hasMoreElements(); ) {
- String key = (String) e.nextElement();
- if (key.matches("^topia\\.service\\.\\w+$")) {
- String classService = config.getProperty(key);
- try {
- Class<?> forName = Class.forName(classService);
- Object newInstance = forName.getConstructor().newInstance();
- TopiaService service = (TopiaService) newInstance;
- if (key.equals("topia.service." + service.getServiceName())) {
- result.put(service.getServiceName(), service);
- log.info(String.format("Service '%1$s' loaded (implementation %2$s)",
- key, classService));
- } else {
- log.warn(String.format("The service with key '%1$s' has a different name '%2$s'! (service not activated)",
- key, service.getServiceName()));
- }
- } catch (Throwable eee) {
- String message =
- String.format("The service %1$s of type %2$s was not found.",
- key, classService);
- if (log.isDebugEnabled()) {
- log.debug(message, eee);
- } else if (log.isErrorEnabled()) {
- log.error(message);
- }
- }
- }
- }
- return result;
- }
-
- protected void preInitServices(Map<String, TopiaService> services) {
- for (TopiaService service : services.values()) {
- if (!service.preInit(this)) {
- log.warn(String.format("The service named '%1$s' could not be post-initialized (service not activated)",
- service.getServiceName()));
- }
- }
- }
-
- protected void postInitServices(Map<String, TopiaService> services) {
- for (TopiaService service : services.values()) {
- if (!service.postInit(this)) {
- log.warn(String.format("The service named '%1$s' could not be pre-initialized (service not activated)",
- service.getServiceName()));
- }
- }
- }
-
- protected TopiaService getService(String name) {
- TopiaService result = getServices().get(name);
- return result;
- }
-
- protected boolean serviceEnabled(String name) {
- boolean result = getServices().containsKey(name);
- return result;
- }
-
- /**
- * Retrieve service name using SERVICE_NAME static field on service
- * interface.
- *
- * @param interfaceService class of the service
- * @param <E> type of the service that extends {@link
- * TopiaService}
- * @return the service name
- * @throws IllegalAccessException if field SERVICE_NAME can't be accessed
- * @throws NoSuchFieldException if no field SERVICE_NAME is defined
- */
- protected <E extends TopiaService> String getServiceName(
- Class<E> interfaceService)
- throws IllegalAccessException, NoSuchFieldException {
- Field f = interfaceService.getField("SERVICE_NAME");
- String name = (String) f.get(null);
- return name;
- }
-
- @Override
- public Map<String, TopiaService> getServices() {
- TopiaContextImplementor parent = getParentContext();
-
- Map<String, TopiaService> result;
- if (parent != null) {
- result = parent.getServices();
- } else {
- result = services;
- }
- return result;
- }
-
- /**
- * Take one service, this service must be valid service interface with
- * public static final SERVICE_NAME declaration.
- *
- * @param <E> type of the service that extends {@link TopiaService}
- * @throws TopiaNotFoundException if an error appears or service not found.
- * @see #getServiceName(Class)
- */
- @Override
- public <E extends TopiaService> E getService(Class<E> interfaceService)
- throws TopiaNotFoundException {
- E result;
- try {
- String name = getServiceName(interfaceService);
- result = (E) getService(name);
- } catch (Exception eee) {
- throw new TopiaNotFoundException(
- String.format("Could not retreave service %1$s for following reason: %2$s",
- interfaceService, getProperExceptionMessage(eee)),
- eee);
- }
- if (result == null) {
- throw new TopiaNotFoundException(
- String.format("The service %1$s was not found.",
- interfaceService));
- }
- return result;
- }
-
- @Override
- public <E extends TopiaService> boolean serviceEnabled(
- Class<E> interfaceService) {
- boolean result = false;
- try {
- String name = getServiceName(interfaceService);
- result = serviceEnabled(name);
- } catch (Exception eee) {
- String message = String.format("The service named '%1$s' could not be found for following reason: %2$s",
- interfaceService, getProperExceptionMessage(eee));
- if (log.isDebugEnabled()) {
- log.debug(message, eee);
- } else if (log.isWarnEnabled()) {
- log.warn(message);
- }
- }
- return result;
- }
-
- /* -------------------- CONTEXT HIERARCHY MANAGMENT ----------------------*/
-
- /**
- * Constructor used by {@link #beginTransaction()} to instantiate child from
- * {@code parentContext}.
- *
- * @param parentContext context parent of the new TopiaContext child
- */
- protected AbstractTopiaContext(TopiaContextImplementor parentContext) {
- this.parentContext = parentContext;
- }
-
- @Override
- public Set<TopiaContextImplementor> getChildContext() {
- // fdesbois-20100421 : Ano #546
- // Copy the childContext into a new set
- Set<TopiaContextImplementor> values;
- // Synchronize copy to be thread-safe during iteration
- synchronized (childContext) {
- values = new HashSet<TopiaContextImplementor>(childContext);
- }
- return values;
- }
-
- protected void addChildContext(TopiaContextImplementor child) {
- childContext.add(child);
- }
-
- @Override
- public void removeChildContext(TopiaContext child) {
- // Remove child only if this context is not already closed.
- if (!closed) {
- childContext.remove(child);
- }
- }
-
- @Override
- public TopiaContextImplementor getParentContext() {
- return parentContext;
- }
-
- @Override
- public TopiaContextImplementor getRootContext() {
- TopiaContextImplementor result = this;
- if (getParentContext() != null) {
- result = getParentContext().getRootContext();
- }
- return result;
- }
-
- @Override
- public Properties getConfig() {
- if (config == null && getParentContext() != null) {
- config = getParentContext().getConfig();
- }
- return config;
- }
-
- @Override
- public TopiaIdFactory getTopiaIdFactory() {
- if (topiaIdFactory == null) {
- initTopiaIdFactory();
- }
- return topiaIdFactory;
- }
-
- /**
- * Change the value of flag {@link #useFlushMode}.
- *
- * @param useFlushMode the new value to set
- * @see #useFlushMode
- * @since 2.5
- */
- public void setUseFlushMode(boolean useFlushMode) {
- this.useFlushMode = useFlushMode;
- }
-
- /* -------------------- HIBERNATE MANAGMENT -----------------------------*/
-
- @Override
- public void createSchema() throws TopiaException {
- try {
- boolean showSchema = false;
- if (log.isDebugEnabled()) {
- showSchema = true;
- }
- getFiresSupport().firePreCreateSchema(this);
- new SchemaExport(getHibernateConfiguration()).execute(showSchema, true, false, true);
- getFiresSupport().firePostCreateSchema(this);
- } catch (HibernateException eee) {
- throw new TopiaException(
- String.format("Could not create schema for reason: %s",
- eee.getMessage()), eee);
- }
- }
-
- @Override
- public void showCreateSchema() throws TopiaException {
- try {
- new SchemaExport(getHibernateConfiguration()).
- execute(true, false, false, true);
- } catch (HibernateException eee) {
- throw new TopiaException(
- String.format("Could not show create schema for reason: %s",
- eee.getMessage()), eee);
- }
- }
-
- @Override
- public void updateSchema() throws TopiaException {
- try {
- boolean showSchema = false;
- if (log.isDebugEnabled()) {
- showSchema = true;
- }
- getFiresSupport().firePreUpdateSchema(this);
- new SchemaUpdate(getHibernateConfiguration()).execute(showSchema,
- true);
- getFiresSupport().firePostUpdateSchema(this);
- } catch (HibernateException eee) {
- throw new TopiaException(
- String.format("Could not update schema for reason: %s",
- eee.getMessage()), eee);
- }
- }
-
- public void dropSchema() throws TopiaException {
- try {
- boolean showSchema = false;
- if (log.isDebugEnabled()) {
- showSchema = true;
- }
- getFiresSupport().firePreDropSchema(this);
- new SchemaExport(getHibernateConfiguration()).execute(showSchema, true, true, false);
- getFiresSupport().firePostDropSchema(this);
- } catch (HibernateException eee) {
- throw new TopiaException(
- String.format("Could not drop schema for reason: %s",
- eee.getMessage()), eee);
- }
- }
-
- @Override
- public Session getHibernate() throws TopiaException {
- Session result = getHibernateSession();
- return result;
- }
-
- @Override
- public SessionFactory getHibernateFactory() {
- if (hibernateFactory == null) {
- if (getParentContext() != null) {
- hibernateFactory = getParentContext().getHibernateFactory();
- } else {
-
- // init service registry
- ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(
- getHibernateConfiguration().getProperties()).buildServiceRegistry();
-
- hibernateFactory = getHibernateConfiguration().buildSessionFactory(serviceRegistry);
-
- // we can't reuse original serviceRegistry instance
- // we must call getServiceRegistry on factory to get a working one
- ServiceRegistry serviceRegistryInit = ((SessionFactoryImplementor) hibernateFactory).getServiceRegistry();
- EventListenerRegistry eventListenerRegistry = serviceRegistryInit.getService(EventListenerRegistry.class);
- TopiaHibernateEventListener listener = new TopiaHibernateEventListener(this);
- 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 hibernateFactory;
- }
-
- @Override
- public Configuration getHibernateConfiguration() {
- if (hibernateConfiguration == null) {
- if (getParentContext() != null) {
- hibernateConfiguration = getParentContext().getHibernateConfiguration();
- } else {
- hibernateConfiguration = new Configuration();
-
- // ajout des repertoires contenant les mappings hibernate
- String[] dirs = getConfig().getProperty(
- TopiaContextFactory.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);
- }
- File dirFile = new File(dir);
- hibernateConfiguration.addDirectory(dirFile);
- }
- }
-
- // ajout des classes dites persistentes
- Set<Class<?>> hibernatePersistanceClasses = new HashSet<Class<?>>();
- for (TopiaService service : 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 = getConfig().getProperty(
- TopiaContextFactory.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));
- }
- persistenceClasses.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(getConfig());
-
- // 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(getConfig().
- getProperty(TopiaContextFactory.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;
- }
-
- /* -------------------- CHILD CONTEXT AND DAOS --------------------------*/
-
- @Override
- public <E extends TopiaEntity> TopiaDAO<E> getDao(Class<E> entityClass)
- throws TopiaException {
- if (entityClass == null) {
- throw new IllegalArgumentException(
- String.format("The method '%1$s' requires a non null parameter '%2$s'.",
- "entityClass", "getDao"));
- }
- if (equals(getRootContext())) {
- throw new TopiaException(
- "You are on root context, you MUST open a transaction to perform any database access.");
- }
- if (getHibernateFactory().getClassMetadata(entityClass) == null &&
- getHibernateFactory().getClassMetadata(
- entityClass.getName() + "Impl") == null &&
- getHibernateFactory().getClassMetadata(
- entityClass.getName() + "Abstract") == null) {
-
- log.info(String.format("List of supported persistence classes: %1$s",
- getHibernateFactory().getAllClassMetadata().keySet()));
- throw new TopiaException(
- String.format("The following entity type %1$s is not managed by this context, you probably forgot to declare it.",
- entityClass.getName()));
- }
-
- TopiaDAO<E> result = (TopiaDAO<E>) daoCache.get(entityClass);
- if (result == null) {
-
- // looking for specialized DAO
- // normalement il en existe un car il est généré automatiquement
- // si on utilise la génération
- String daoClassname = entityClass.getName() + "TopiaDao";
- try {
- Class<TopiaDAO<E>> daoClass =
- (Class<TopiaDAO<E>>) Class.forName(daoClassname);
- TopiaDAO<E> spe = daoClass.getConstructor().newInstance();
- result = spe;
- } catch (Exception eee) {
- log.warn("specialized DAO " + daoClassname +
- " not found, use default TopiaDAOHibernate");
- result = new TopiaDAOImpl<E>();
- }
-
- if (result instanceof TopiaDAOImpl) { // backward compatibility
- ((TopiaDAOImpl)result).init(this, entityClass, getFiresSupport());
- } else if (result instanceof AbstractTopiaDao) {
- ((AbstractTopiaDao)result).init(this, this, this, this, getTopiaIdFactory(), getFiresSupport(), this);
- }
- daoCache.put(entityClass, result);
- }
- return result;
- }
-
- @SuppressWarnings({"unchecked"})
- @Override
- public <E extends TopiaEntity, D extends TopiaDAO<E>> D getDao(Class<E> entityClass,
- Class<D> daoClass) throws TopiaException {
- TopiaDAO<E> dao = getDao(entityClass);
- D result = (D) dao;
- return result;
- }
-
- @Override
- public TopiaContext beginTransaction() throws TopiaException {
- checkClosed("Context is closed, no operation is possible.");
- AbstractTopiaContext result = new AbstractTopiaContext(this);
-
- SessionFactory factory = getHibernateFactory();
- result.hibernate = factory.openSession();
-
- // new TopiaInterceptor(result));
- // on ne synchronise jamais les données avec la base tant que
- // l'utilisateur n'a pas fait de commit du context
- result.hibernate.setFlushMode(FlushMode.MANUAL);
-
- // tchemit 2010-12-06 propagates the value of the flag
- result.useFlushMode = useFlushMode;
-
- // 20060926 poussin ajouter pour voir si ca regle les problemes de
- // deadlock h2. Conclusion, il faut bien ouvrir une transaction
- // maintenant, sinon lorsque l'on fait des acces a la base, une
- // transaction par defaut est utilisé mais elle n'est jamais vraiment
- // fermé ce qui pose des problemes de lock sur les tables.
- try {
- result.hibernate.beginTransaction();
- } catch (Exception eee) {
-
- // on a pas pu ouvrir la transaction, on faut donc tout fermer
- // et declancher une exception
- try {
- result.hibernate.close();
- } catch (HibernateException e1) {
- if (log.isErrorEnabled()) {
- log.error("Could not close hibernate session", e1);
- }
- }
-
- throw new TopiaException(
- String.format("An error occurs while asking a new transaction: %1$s",
- eee.getMessage()),
- eee);
- }
-
- // 20081217 : add child AFTER hibernate session is opened
- addChildContext(result);
-
- // fire event
- getFiresSupport().fireOnBeginTransaction(result);
- return result;
- }
-
- @Override
- public void commit() throws TopiaException {
- if (equals(getRootContext())) {
- throw new TopiaException(String.format("Unsupported operation %s on root context",
- "commit"));
- }
- checkClosed(String.format("This context is closed, it is not possible to release the operation '%1$s'",
- "commit"));
-
- try {
-// for (TopiaDAO<? extends TopiaEntity> dao : daoCache.values()) {
-// // TODO-fdesbois-20100507 : need to be removed for 2.5 version
-// dao.commit();
-// }
- Transaction tx = hibernate.getTransaction();
- // Transaction tx = hibernate.beginTransaction();
- hibernate.flush();
- tx.commit();
-
- getFiresSupport().fireOnPostCommit(this);
- TopiaContextImplementor parent = getParentContext();
- if (parent != null) {
- parent.getFiresSupport().fireOnPostCommit(this);
- }
-
- hibernate.beginTransaction();
-
- // it's seem necessary to change session after commit
- // NON, NON, NON, il ne faut surtout pas le faire, ca pose plein de
- // probleme
- // hibernate = getHibernateFactory().openSession();
- // hibernate.setFlushMode(FlushMode.NEVER);
- } catch (Exception eee) {
- throw new TopiaException(String.format("An error occurs while commit operation: %1$s",
- eee.getMessage()), eee);
- }
- }
-
- @Override
- public void rollback() throws TopiaException {
- if (equals(getRootContext())) {
- throw new TopiaException(String.format("Unsupported operation %s on root context",
- "rollback"));
- }
- checkClosed(String.format("This context is closed, it is not possible to release the operation '%1$s'",
- "rollback"));
- try {
-// for (TopiaDAO<? extends TopiaEntity> dao : daoCache.values()) {
-// // TODO-fdesbois-20100507 : need to be removed for 2.5 version
-// dao.rollback();
-// }
- Transaction tx = hibernate.getTransaction();
- // Transaction tx = hibernate.beginTransaction();
- hibernate.clear();
- tx.rollback();
- hibernate.close();
- // it's very important to change the session after rollback
- // otherwize there are many error during next Entity's modification
- hibernate = getHibernateFactory().openSession();
- hibernate.setFlushMode(FlushMode.MANUAL);
-
- hibernate.beginTransaction();
-
- getFiresSupport().fireOnPostRollback(this);
- TopiaContextImplementor parent = getParentContext();
- if (parent != null) {
- parent.getFiresSupport().fireOnPostRollback(this);
- }
-
- } catch (HibernateException eee) {
- throw new TopiaException(
- String.format("An error occurs while rollback operation: %1$s",
- eee.getMessage()), eee);
- }
- }
-
- @Override
- public void closeContext() throws TopiaException {
- // Throw exception if context is already closed
- checkClosed("Context was already closed");
-
- // FD-20100421 : Ano #546 : no need to copy childContext, the
- // {@link #getChildContext()} provides a thread-safe copy to iterate
- // on it.
-// TopiaContextImplementor[] children = childContext.toArray(
-// new TopiaContextImplementor[childContext.size()]);
-
- // Remove all children context
- for (TopiaContextImplementor child : getChildContext()) {
- // Avoid to have exception from checkClosed method on child
- if (!child.isClosed()) {
- child.closeContext();
- }
- }
-
- // on se desenregistre du context pere et on ferme les connexions si
- // on est pas le root context
- if (!equals(getRootContext())) {
- closed = true;
- hibernate.close();
- getParentContext().removeChildContext(this);
- } else {
- if (hibernateFactory != null) {
- hibernateFactory.close();
- // close connection provider if possible (http://nuiton.org/issues/2757)
- ConnectionProvider service = ((SessionFactoryImplementor) hibernateFactory).getServiceRegistry().getService(ConnectionProvider.class);
- if (service instanceof Stoppable) {
- Stoppable stoppable = (Stoppable) service;
- stoppable.stop();
- }
- closed = true;
- TopiaContextFactory.removeContext(this);
- log.debug("TopiaContext removed");
- }
- }
- }
-
- /**
- * Pour le context root on ferme tous les fils, et la factory hibernate.
- *
- * <strong>Note:</strong> Non, il n'est pas de la responsabilité du GC de
- * fermer de telles ressources, les devleoppeurs doivent gérer ça à la main...
- */
- @Override
- protected void finalize() throws Throwable {
-// if (hibernateFactory != null) {
-// closeContext();
-// hibernateFactory.close();
-// closed = true;
-// log.debug("TopiaContext finalized");
-// }
- if (!closed) {
-
- // means resource was not well closed, can't accept this!
- throw new TopiaException("TopiaContext " + this + " was not closed!");
- }
- super.finalize();
- }
-
- @Override
- public boolean isClosed() {
- return closed;
- }
-
- @Override
- public void executeSQL(String sqlScript) throws TopiaException {
- SQLWork sqlWork = new SQLWork(sqlScript);
- try {
- getHibernate().doWork(sqlWork);
- } catch (HibernateException e) {
- throw new TopiaException("Could not execute sql code", e);
- }
- }
-
- @Override
- public void doSQLWork(TopiaSqlWork sqlWork) {
- HibernateTopiaSqlSupport.TopiaSQLWorkWork work = new HibernateTopiaSqlSupport.TopiaSQLWorkWork(sqlWork);
- try {
- getHibernate().doWork(work);
- } catch (HibernateException e) {
- throw new TopiaException("Could not execute sql code", e);
- }
- }
-
- @Override
- public <O> O findSingleResult(TopiaSqlQuery<O> query) throws TopiaException {
- TopiaSQLQueryWork<O> work = new TopiaSQLQueryWork<O>(query, false);
- hibernate.doWork(work);
- List<O> result = work.getResult();
- return result.isEmpty() ? null : result.get(0);
- }
-
- @Override
- public <O> List<O> findMultipleResult(TopiaSqlQuery<O> query) throws TopiaException {
- TopiaSQLQueryWork<O> work = new TopiaSQLQueryWork<O>(query, true);
- hibernate.doWork(work);
- final List<O> result = work.getResult();
- return result;
- }
-
- protected void checkClosed(String message) throws TopiaException {
- if (closed) {
- throw new TopiaException(message);
- }
- }
-
- /* -------------------- GLOBAL OPERATIONS ON SCHEMA ----------------------*/
-
- @Override
- public <E extends TopiaEntity> E findByTopiaId(String id) throws TopiaException {
- checkClosed(String.format("This context is closed, it is not possible to release the operation '%1$s'",
- "findByTopiaId"));
-
- Class<E> entityClass = getTopiaIdFactory().getClassName(id);
- TopiaDAO<E> dao = getDao(entityClass);
- E result = dao.findByTopiaId(id);
- return result;
- }
-
- @Override
- public <E> List<E> findAll(String jpaql, Object... propertyNamesAndValues) throws TopiaException {
- checkClosed(String.format("This context is closed, it is not possible to release the operation '%1$s'",
- "findAll"));
-
- Map<String, Object> parameters = TopiaUtil.convertPropertiesArrayToMap(propertyNamesAndValues);
- List<E> result = findAll(jpaql, parameters);
- return result;
- }
-
- @Override
- public <E> List<E> find(String jpaql, int startIndex, int endIndex, Object... propertyNamesAndValues)
- throws TopiaException {
- checkClosed(String.format("This context is closed, it is not possible to release the operation '%1$s'",
- "find"));
-
- Map<String, Object> parameters = TopiaUtil.convertPropertiesArrayToMap(propertyNamesAndValues);
- List<E> result = find(jpaql, startIndex, endIndex, parameters);
- return result;
- }
-
- @Override
- public <E> E findUnique(String jpaql, Object... propertyNamesAndValues)
- throws TopiaException {
- checkClosed(String.format("This context is closed, it is not possible to release the operation '%1$s'",
- "findUnique"));
-
- Map<String, Object> parameters = TopiaUtil.convertPropertiesArrayToMap(propertyNamesAndValues);
- E result = findUnique(jpaql, parameters);
- return result;
- }
-
- /**
- * Execute HQL operation on data (Update, Delete)
- *
- * @param jpaql HQL query
- * @param propertyNamesAndValues arguments for query
- * @return The number of entities updated or deleted.
- * @throws TopiaException
- */
- @Override
- public int execute(String jpaql, Object... propertyNamesAndValues) throws TopiaException {
- checkClosed(String.format("This context is closed, it is not possible to release the operation '%1$s'",
- "find"));
-
- Map<String, Object> parameters = TopiaUtil.convertPropertiesArrayToMap(propertyNamesAndValues);
- int result = execute(jpaql, parameters);
- return result;
- }
-
-
- protected Query prepareQuery(String jpaql, Map<String, Object> parameters) {
- Query query = getHibernate().createQuery(jpaql);
- for (Map.Entry<String, Object> entry : parameters.entrySet()) {
- String name = entry.getKey();
- Object value = entry.getValue();
- if (value.getClass().isArray()) {
- query.setParameterList(name, (Object[]) value);
- } else if (value instanceof Collection<?>) {
- query.setParameterList(name, (Collection<?>) value);
- } else {
- query.setParameter(name, value);
- }
- }
- // tchemit 2010-11-30 reproduce the same behaviour than before with the dao legacy
- if (useFlushMode) {
- query.setFlushMode(FlushMode.AUTO);
- }
- return query;
- }
-
- @Override
- public <T> List<T> findAll(String jpaql, Map<String, Object> parameters) {
- checkClosed(String.format("This context is closed, it is not possible to release the operation '%1$s'",
- "findAll"));
-
- try {
- Query query = prepareQuery(jpaql, parameters);
-
- List result = query.list();
- result = firesSupport.fireEntitiesLoad(this, result);
- return result;
- } catch (HibernateException eee) {
- throw new TopiaException(String.format("An error occurs while query operation: %1$s : %2$s",
- jpaql, eee.getMessage()), eee);
- }
- }
-
- @Override
- public <T> List<T> find(String jpaql, int startIndex, int endIndex, Map<String, Object> parameters) {
- checkClosed(String.format("This context is closed, it is not possible to release the operation '%1$s'",
- "find"));
-
- try {
- Query query = prepareQuery(jpaql, parameters);
-
- query.setFirstResult(startIndex);
- query.setMaxResults(endIndex - startIndex + 1);
-
- List result = query.list();
- result = firesSupport.fireEntitiesLoad(this, result);
- return result;
- } catch (HibernateException eee) {
- throw new TopiaException(String.format("An error occurs while query operation: %1$s : %2$s",
- jpaql, eee.getMessage()), eee);
- }
- }
-
- @Override
- public <T> T findUnique(String jpaql, Map<String, Object> parameters) {
-
- List<T> results = find(jpaql, 0, 1, parameters);
-
- // If there is more than 1 result, throw an exception
- if (results.size() > 1) {
- String message = String.format(
- "Query '%s' returns more than 1 unique result", jpaql);
- throw new TopiaException(message);
- }
-
- // otherwise return the first one, or null
- T result = null;
- if (!results.isEmpty()) {
- result = results.get(0);
- }
- return result;
- }
-
- @Override
- public int execute(String jpaql, Map<String, Object> parameters) {
- checkClosed(String.format("This context is closed, it is not possible to release the operation '%1$s'",
- "find"));
-
- try {
- Query query = prepareQuery(jpaql, parameters);
-
- int result = query.executeUpdate();
- return result;
- } catch (HibernateException eee) {
- throw new TopiaException(String.format("An error occurs while query operation: %1$s : %2$s",
- jpaql, eee.getMessage()), eee);
- }
-
- }
-
- @Override
- public void add(TopiaEntity e) throws TopiaException {
- update(e);
- }
-
- @Override
- public void replicate(TopiaContext dstCtxt, Object... entityAndCondition)
- throws TopiaException, IllegalArgumentException {
- checkClosed(String.format("This context is closed, it is not possible to release the operation '%1$s'",
- "replicate"));
-
- AbstractTopiaContext dstContextImpl = (AbstractTopiaContext) dstCtxt;
- dstContextImpl.checkClosed(
- String.format("This context is closed, it is not possible to release the operation '%1$s'",
- "replicate"));
-
- if (getRootContext().equals(dstContextImpl.getRootContext())) {
- throw new IllegalArgumentException("Can not do a replication operation on same database.");
- }
-
- String[] queries = buildQueries(entityAndCondition);
- try {
- for (String query : queries) {
- if (log.isDebugEnabled()) {
- log.debug("acquire entities " + query);
- }
- // acquire data to replicate
- List<?> entities = findAll(query);
- replicate0(dstContextImpl, entities.toArray());
- if (log.isDebugEnabled()) {
- log.debug("replication of entities " + query +
- " was sucessfully done.");
- }
- }
- } catch (HibernateException eee) {
- throw new TopiaException(String.format("An error occurs while a replication operation: %s",
- eee.getMessage()), eee);
- }
- }
-
- @Override
- public <T extends TopiaEntity> void replicateEntity(TopiaContext dstCtxt,
- T entity)
- throws TopiaException, IllegalArgumentException {
- checkClosed(String.format("This context is closed, it is not possible to release the operation '%1$s'",
- "replicateEntity"));
-
- AbstractTopiaContext dstContextImpl = (AbstractTopiaContext) dstCtxt;
- dstContextImpl.checkClosed(String.format("This context is closed, it is not possible to release the operation '%1$s'",
- "replicateEntity"));
-
- if (getRootContext().equals(dstContextImpl.getRootContext())) {
- throw new IllegalArgumentException("Can not do a replication operation on same database.");
- }
- replicate0(dstContextImpl, entity);
- }
-
- @Override
- public <T extends TopiaEntity> void replicateEntities(TopiaContext dstCtxt,
- List<T> entities)
- throws TopiaException, IllegalArgumentException {
- checkClosed(String.format("This context is closed, it is not possible to release the operation '%1$s'",
- "replicateEntities"));
-
- AbstractTopiaContext dstContextImpl = (AbstractTopiaContext) dstCtxt;
- dstContextImpl.checkClosed(String.format("This context is closed, it is not possible to release the operation '%1$s'",
- "replicateEntities"));
-
- if (getRootContext().equals(dstContextImpl.getRootContext())) {
- throw new IllegalArgumentException("Can not do a replication operation on same database.");
- }
- replicate0(dstContextImpl, entities.toArray());
- }
-
- @Override
- public void replicate(TopiaEntity entity) {
- getHibernateSession().replicate(entity, ReplicationMode.EXCEPTION);
- }
-
- @Override
- public void replicate(TopiaReplicationDestination topiaReplicationDestination, Object... entityAndCondition) throws IllegalArgumentException {
- replicate((TopiaContext) topiaReplicationDestination, entityAndCondition);
- }
-
- @Override
- public <T extends TopiaEntity> void replicateEntity(TopiaReplicationDestination topiaReplicationDestination, T entity) throws IllegalArgumentException {
- replicateEntity((TopiaContext) topiaReplicationDestination, entity);
- }
-
- @Override
- public <T extends TopiaEntity> void replicateEntities(TopiaReplicationDestination topiaReplicationDestination, List<T> entities) throws IllegalArgumentException {
- replicateEntities((TopiaContext) topiaReplicationDestination, entities);
- }
-
- @Override
- public TopiaFiresSupport getFiresSupport() {
- return firesSupport;
- }
-
- /**
- * Backup database in gzip compressed file.
- * <p/>
- * <b>Note: </b> Only works for h2 database.
- *
- * @param file file to write backup
- * @param compress if true then use gzip to compress file
- * @see TopiaContext#backup(File, boolean)
- */
- @Override
- public void backup(File file, boolean compress) throws TopiaException {
- checkClosed(String.format("This context is closed, it is not possible to release the operation '%1$s'",
- "backup"));
- try {
- String options = "";
- if (compress) {
- options += " COMPRESSION GZIP";
- }
-
- SQLQuery query = getHibernate().createSQLQuery(
- "SCRIPT TO '" + file.getAbsolutePath() + "'" + options);
- query.list();
-
- } catch (Exception eee) {
- throw new TopiaException(String.format(
- "An error occurs while backup operation: %1$s",
- eee.getMessage()), eee);
- }
- }
-
- /**
- * Read database from gzip compressed file
- * <p/>
- * Only work for h2 database
- *
- * @see TopiaContext#restore(File)
- */
- @Override
- public void restore(File file) throws TopiaException {
- // send event
- getFiresSupport().firePreRestoreSchema(this);
- checkClosed(String.format("This context is closed, it is not possible to release the operation '%1$s'",
- "restore"));
-
- String sql = null;
- String options = "";
- try {
- // decompresse file in temporary file
- InputStream in = new BufferedInputStream(new FileInputStream(file));
- try {
- in.mark(2);
-
- // read header to see if is compressed file
- int b = in.read();
- // redundant cast : int magic = ((int) in.read() << 8) | b;
- int magic = in.read() << 8 | b;
- in.reset();
-
- if (magic == GZIPInputStream.GZIP_MAGIC) {
- options += " COMPRESSION GZIP";
- }
- } finally {
-
- in.close();
- }
-
- SQLQuery query = getHibernate().createSQLQuery(
- "RUNSCRIPT FROM '" + file.getAbsolutePath() + "'" + options);
-
- query.executeUpdate();
-
- // send event AFTER restore
- getFiresSupport().firePostRestoreSchema(this);
- } catch (Exception eee) {
- throw new TopiaException(String.format(
- String.format("An error occurs while restore operation: %1$s : %2$s",
- sql, eee.getMessage())), eee);
- }
- }
-
- /**
- * Only h2 supported for now
- *
- * @see TopiaContext#clear(boolean)
- */
- @Override
- public void clear(boolean dropDatabase) throws TopiaException {
- try {
- AbstractTopiaContext root = (AbstractTopiaContext) getRootContext();
- AbstractTopiaContext tx = (AbstractTopiaContext) root.beginTransaction();
-
- String sql = "DROP ALL OBJECTS";
- if (dropDatabase) {
- sql += " DELETE FILES";
- }
- Query query = tx.getHibernate().createSQLQuery(sql);
- query.executeUpdate();
- tx.closeContext();
- root.finalize();
- } catch (Throwable eee) {
- throw new TopiaException(
- String.format("Error %s on clear operation", eee.getMessage()), eee);
- }
- }
-
- /**
- * Clear hibernate cache to free memory.
- * <p/>
- * see http://docs.jboss.org/hibernate/orm/3.5/reference/en-US/html/transactions.h…
- */
- @Override
- public void clearCache() throws TopiaException {
- getHibernate().clear();
- }
-
- @Override
- public List<Class<?>> getPersistenceClasses() {
- return persistenceClasses;
- }
-
- @Override
- public boolean isSchemaExist(Class<?> clazz)
- throws TopiaException {
- return isTableExists(clazz);
- }
-
- public boolean isSchemaEmpty() {
- // TODO AThimel 02/08/13 Implement
- throw new UnsupportedOperationException("Not yet implemented");
- }
-
- public boolean isTableExists(Class<?> clazz) {
- checkClosed(String.format("This context is closed, it is not possible to release the operation '%1$s'",
- "replicateEntity"));
- boolean result = TopiaUtil.isSchemaExist(this, clazz.getName());
- return result;
- }
-
- public String getSchemaName() {
- // TODO AThimel 02/08/13 I absolutely don't know if it works
- return getConfig().getProperty(TopiaContextFactory.CONFIG_DEFAULT_SCHEMA);
- }
-
- /* Listeners adders */
-
- @Override
- public void addTopiaEntityListener(TopiaEntityListener listener) {
- getFiresSupport().addTopiaEntityListener(listener);
- }
-
- @Override
- public void addTopiaEntityListener(
- Class<? extends TopiaEntity> entityClass,
- TopiaEntityListener listener) {
- getFiresSupport().addTopiaEntityListener(entityClass, listener);
- }
-
- @Override
- public void addTopiaEntityVetoable(TopiaEntityVetoable vetoable) {
- getFiresSupport().addTopiaEntityVetoable(TopiaEntity.class, vetoable);
- }
-
- @Override
- public void addTopiaEntityVetoable(
- Class<? extends TopiaEntity> entityClass,
- TopiaEntityVetoable vetoable) {
- getFiresSupport().addTopiaEntityVetoable(entityClass, vetoable);
- }
-
- @Override
- public void addTopiaTransactionListener(TopiaTransactionListener listener) {
- getFiresSupport().addTopiaTransactionListener(listener);
- }
-
- @Override
- public void addTopiaTransactionVetoable(TopiaTransactionVetoable vetoable) {
- getFiresSupport().addTopiaTransactionVetoable(vetoable);
- }
-
- @Override
- public void addPropertyChangeListener(PropertyChangeListener listener) {
- getFiresSupport().addPropertyChangeListener(listener);
- }
-
- @Override
- @Deprecated
- public void addTopiaContextListener(TopiaContextListener listener) {
- getFiresSupport().addTopiaContextListener(listener);
- }
-
- @Override
- public void addTopiaSchemaListener(TopiaSchemaListener listener) {
- getFiresSupport().addTopiaSchemaListener(listener);
- }
-
- /* Listeners removers */
-
- @Override
- public void removeTopiaEntityListener(TopiaEntityListener listener) {
- getFiresSupport().removeTopiaEntityListener(TopiaEntity.class,
- listener);
- }
-
- @Override
- public void removeTopiaEntityListener(
- Class<? extends TopiaEntity> entityClass,
- TopiaEntityListener listener) {
- getFiresSupport().removeTopiaEntityListener(entityClass, listener);
- }
-
- @Override
- public void removeTopiaEntityVetoable(TopiaEntityVetoable vetoable) {
- getFiresSupport().removeTopiaEntityVetoable(TopiaEntity.class,
- vetoable);
- }
-
- @Override
- public void removeTopiaEntityVetoable(
- Class<? extends TopiaEntity> entityClass,
- TopiaEntityVetoable vetoable) {
- getFiresSupport().removeTopiaEntityVetoable(entityClass, vetoable);
- }
-
- @Override
- public void removeTopiaTransactionListener(
- TopiaTransactionListener listener) {
- getFiresSupport().removeTopiaTransactionListener(listener);
- }
-
- @Override
- public void removeTopiaTransactionVetoable(
- TopiaTransactionVetoable vetoable) {
- getFiresSupport().removeTopiaTransactionVetoable(vetoable);
- }
-
- @Override
- public void removePropertyChangeListener(PropertyChangeListener listener) {
- getFiresSupport().removePropertyChangeListener(listener);
- }
-
- @Override
- @Deprecated
- public void removeTopiaContextListener(TopiaContextListener listener) {
- getFiresSupport().removeTopiaContextListener(listener);
- }
-
- @Override
- public void removeTopiaSchemaListener(TopiaSchemaListener listener) {
- getFiresSupport().removeTopiaSchemaListener(listener);
- }
-
- @Override
- public void addTopiaEntitiesVetoable(TopiaEntitiesVetoable vetoable) {
- getFiresSupport().addTopiaEntitiesVetoable(vetoable);
- }
-
- @Override
- public void removeTopiaEntitiesVetoable(TopiaEntitiesVetoable vetoable) {
- getFiresSupport().removeTopiaEntitiesVetoable(vetoable);
- }
-
- /**
- * Build the list of queries from the given parameter
- * <code>entityAndCondition</code>.
- * <p/>
- * If no parameter is given, then build the queries for all entities is db,
- * with no condition.
- *
- * @param entityAndCondition the list of tuples (Class,String)
- * @return the list of queries.
- * @throws TopiaException if any pb of db while getting entities
- * classes.
- * @throws IllegalArgumentException if any pb with the given parameter
- * (mainly ClassCastException).
- */
- protected String[] buildQueries(Object... entityAndCondition)
- throws TopiaException, IllegalArgumentException {
- Class<?> entityClass;
- String condition;
-
- // si entityAndcondition est vide alors il faut le remplir
- // avec toutes les entités du mapping (class, null)
- if (entityAndCondition.length == 0) {
- Map<?, ?> classMetadata = getHibernateFactory().getAllClassMetadata();
- entityAndCondition = new Object[classMetadata.size() * 2];
- int i = 0;
- for (Object className : classMetadata.keySet()) {
- try {
- entityAndCondition[i++] = Class.forName((String) className);
- } catch (ClassNotFoundException e) {
- // should never happen!
- throw new TopiaException(
- "class cast exception for entity " + className);
- }
- entityAndCondition[i++] = null;
-
- }
- }
-
- // prepare queries to perform beofre opening any transaction
- if (entityAndCondition.length % 2 != 0) {
- throw new IllegalArgumentException(
- "entityAndCondition must be a couple of (Class, String)");
- }
- String queries[] = new String[entityAndCondition.length / 2];
- for (int i = 0; i < entityAndCondition.length; ) {
- try {
- entityClass = (Class<?>) entityAndCondition[i++];
- condition = (String) entityAndCondition[i++];
- String query = "from " + entityClass.getName();
- if (condition != null && !condition.isEmpty()) {
- query += " where " + condition;
- }
- queries[(i - 1) / 2] = query;
- } catch (ClassCastException e) {
- if (i % 2 == 0) {
- throw new IllegalArgumentException(
- "Others arguement must be String not " +
- entityAndCondition[i - 1], e);
- } else {
- throw new IllegalArgumentException(
- "Others arguement must be Class not " +
- entityAndCondition[i - 1], e);
- }
- }
- }
- return queries;
- }
-
- protected void replicate0(AbstractTopiaContext dstContextImpl,
- Object... entities) throws TopiaException {
- try {
- for (Object entity : entities) {
- // dettach entity to source session, to make possible copy of
- // collection without a hibernate exception (list opened in
- // two session...)
- getHibernate().evict(entity);
- dstContextImpl.getHibernate().replicate(entity,
- ReplicationMode.EXCEPTION);
- }
-
- } catch (HibernateException eee) {
- throw new TopiaException(String.format("An error occurs while a replication operation : %s",
- eee.getMessage()), eee);
- }
- }
-
- @Override
- public Session getHibernateSession() throws TopiaException {
- if (hibernate == null) {
- throw new TopiaException("No hibernate session");
- }
- return hibernate;
- }
-
- @Override
- public void update(TopiaEntity entity) throws TopiaException {
- checkClosed(String.format("This context is closed, it is not possible to release the operation '%1$s'",
- "add"));
-
- String id = entity.getTopiaId();
- Class<TopiaEntity> entityClass = getTopiaIdFactory().getClassName(id);
- TopiaDAO<TopiaEntity> dao = getDao(entityClass);
- dao.update(entity);
- }
-
-} //AbstractTopiaContext
-
Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaContextImplementor.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaContextImplementor.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaContextImplementor.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -1,186 +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%
- */
-
-package org.nuiton.topia.framework;
-
-import org.hibernate.Session;
-import org.hibernate.SessionFactory;
-import org.hibernate.cfg.Configuration;
-import org.nuiton.topia.TopiaContext;
-import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.TopiaNotFoundException;
-import org.nuiton.topia.persistence.TopiaDAO;
-import org.nuiton.topia.persistence.TopiaEntity;
-
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-import java.util.Set;
-
-/**
- * Technical contract of a {@link TopiaContext}.
- *
- * Any implementation of the {@link TopiaContext} should also implements this
- * contract.
- *
- * @author poussin <poussin(a)codelutin.com>
- * @version $Id$
- */
-//TODO-fdesbois-20100507 : Need more javadoc.
-@Deprecated
-public interface TopiaContextImplementor extends TopiaContext {
-
- /**
- * Retrieve a thread-safe copy of children context set.
- *
- * @return Returns the childContext.
- * @deprecated Hierarchical context are not supported anymore
- */
- @Deprecated
- Set<TopiaContextImplementor> getChildContext();
-
- /**
- * @return Returns the parentContext.
- * @deprecated Hierarchical context are not supported anymore
- */
- @Deprecated
- TopiaContextImplementor getParentContext();
-
- /**
- * @deprecated Hierarchical context are not supported anymore
- */
- @Deprecated
- TopiaContextImplementor getRootContext();
-
- /**
- * @deprecated Hierarchical context are not supported anymore
- */
- @Deprecated
- void removeChildContext(TopiaContext child);
-
- /** @return Returns the config.
- * @deprecated use method from {@link org.nuiton.topia.TopiaPersistenceContext}
- */
- @Deprecated
- Properties getConfig();
-
- /**
- * @return Returns the hibernate.
- * @throws TopiaException si aucune transaction n'est ouverte
- * @deprecated use method from {@link org.nuiton.topia.TopiaHibernateSupport}
- */
- @Deprecated
- Session getHibernate() throws TopiaException;
-
- /**
- * @return Returns the hibernateFactory.
- * @throws TopiaNotFoundException
- * @deprecated use method from {@link org.nuiton.topia.TopiaHibernateSupport}
- */
- @Deprecated
- SessionFactory getHibernateFactory() throws TopiaNotFoundException;
-
- /**
- * @return Returns the hibernate configuration
- * @throws TopiaNotFoundException
- * @deprecated use method from {@link org.nuiton.topia.TopiaHibernateSupport}
- */
- @Deprecated
- Configuration getHibernateConfiguration()
- throws TopiaNotFoundException;
-
- /**
- * Tells to the context if it has to use a flush mode before each query.
- *
- * By default, we use a flush mode, but in some case it costs to much doing
- * this, that's why you can desactivate it setting the value to {@code false}.
- *
- * @param useFlushMode the new value to set
- * @since 2.5
- * @deprecated use method from {@link org.nuiton.topia.TopiaJpaSupport}
- */
- @Deprecated
- void setUseFlushMode(boolean useFlushMode);
-
- /**
- * Detect if the table is created on storage for a given persistant class.
- *
- * @param clazz the researched class
- * @return Returns the hibernate.
- * @throws TopiaException si aucune transaction n'est ouverte
- * @deprecated use method from {@link org.nuiton.topia.TopiaPersistenceContext}
- */
- @Deprecated
- boolean isSchemaExist(Class<?> clazz) throws TopiaException;
-
- /**
- * Get DAO for specified class. If Specialized DAO exists then it returned
- * otherwize TopiaDAO<entityClass> is returned
- *
- * @param <E> type of entity
- * @param entityClass type of entity
- * @return the required dao
- * @throws TopiaException if any error
- * @deprecated use method from {@link org.nuiton.topia.TopiaPersistenceContext}
- */
- @Deprecated
- <E extends TopiaEntity> TopiaDAO<E> getDao(Class<E> entityClass)
- throws TopiaException;
-
- /**
- * Get DAO for specified class. If Specialized DAO exists then it returned
- * otherwize TopiaDAO<entityClass> is returned
- *
- * @param <E> type of entity
- * @param entityClass type of entity
- * @param daoClass the concrete dao class to use
- * @return the required dao
- * @throws TopiaException if any error
- * @deprecated use method from {@link org.nuiton.topia.TopiaPersistenceContext}
- */
- @Deprecated
- <E extends TopiaEntity, D extends TopiaDAO<E>> D getDao(Class<E> entityClass, Class<D> daoClass)
- throws TopiaException;
-
- /**
- * @deprecated internal usage
- */
- @Deprecated
- TopiaFiresSupport getFiresSupport();
-
- /**
- * @deprecated use methods from {@link org.nuiton.topia.TopiaServiceSupport}
- */
- @Deprecated
- Map<String, TopiaService> getServices();
-
- /**
- * @deprecated use method from {@link org.nuiton.topia.TopiaPersistenceContext}
- */
- @Deprecated
- List<Class<?>> getPersistenceClasses();
-
-} //TopiaContextImplementor
-
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaFiresSupport.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaFiresSupport.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaFiresSupport.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -41,10 +41,8 @@
import org.nuiton.topia.TopiaJpaSupport;
import org.nuiton.topia.TopiaListenableSupport;
import org.nuiton.topia.TopiaPersistenceContext;
-import org.nuiton.topia.TopiaTransaction;
import org.nuiton.topia.TopiaVetoException;
import org.nuiton.topia.event.TopiaContextEvent;
-import org.nuiton.topia.event.TopiaContextListener;
import org.nuiton.topia.event.TopiaEntitiesEvent;
import org.nuiton.topia.event.TopiaEntitiesVetoable;
import org.nuiton.topia.event.TopiaEntityEvent;
@@ -54,7 +52,6 @@
import org.nuiton.topia.event.TopiaTransactionEvent;
import org.nuiton.topia.event.TopiaTransactionListener;
import org.nuiton.topia.event.TopiaTransactionVetoable;
-import org.nuiton.topia.persistence.AbstractTopiaDao;
import org.nuiton.topia.persistence.TopiaEntity;
import org.nuiton.util.CategorisedListenerSet;
import org.nuiton.util.ListenerSet;
@@ -184,7 +181,7 @@
/* Fires sur les transactions */
- public void fireOnBeginTransaction(TopiaTransaction context) {
+ public void fireOnBeginTransaction(TopiaPersistenceContext context) {
if (log.isDebugEnabled()) {
log.debug("fireOnBeginTransaction");
}
@@ -198,7 +195,7 @@
}
}
- public void fireOnPostCommit(TopiaTransaction context) {
+ public void fireOnPostCommit(TopiaPersistenceContext context) {
if (log.isDebugEnabled()) {
log.debug("fireOnPostCommit");
}
@@ -215,7 +212,7 @@
transactionEntities.clear();
}
- public void fireOnPostRollback(TopiaTransaction context) {
+ public void fireOnPostRollback(TopiaPersistenceContext context) {
if (log.isDebugEnabled()) {
log.debug("fireOnPostRollback");
}
@@ -282,7 +279,7 @@
}
}
- public void fireOnPostLoad(AbstractTopiaDao context,
+ public void fireOnPostLoad(TopiaPersistenceContext context,
TopiaEntity entity, Object[] state) {
if (log.isDebugEnabled()) {
log.debug("fireOnPostLoad");
@@ -688,17 +685,6 @@
return transactionVetoables;
}
- @Deprecated
- public ListenerSet<TopiaContextListener> getTopiaContextListeners() {
- ListenerSet<TopiaContextListener> copy = new ListenerSet<TopiaContextListener>();
- for (TopiaSchemaListener topiaSchemaListener : topiaSchemaListeners) {
- if (topiaSchemaListener instanceof TopiaContextListener) {
- copy.add((TopiaContextListener)topiaSchemaListener);
- }
- }
- return copy;
- }
-
public ListenerSet<TopiaSchemaListener> getTopiaSchemaListeners() {
return topiaSchemaListeners;
}
@@ -756,14 +742,6 @@
propertyChangeListeners.add(listener);
}
- @Deprecated
- public void addTopiaContextListener(TopiaContextListener listener) {
- if (listener == null) {
- throw new NullPointerException("listener can not be null.");
- }
- topiaSchemaListeners.add(listener);
- }
-
public void addTopiaSchemaListener(TopiaSchemaListener listener) {
if (listener == null) {
throw new NullPointerException("listener can not be null.");
@@ -827,13 +805,6 @@
propertyChangeListeners.remove(listener);
}
- public void removeTopiaContextListener(TopiaContextListener listener) {
- if (listener == null) {
- throw new NullPointerException("listener can not be null.");
- }
- topiaSchemaListeners.remove(listener);
- }
-
public void removeTopiaSchemaListener(TopiaSchemaListener listener) {
if (listener == null) {
throw new NullPointerException("listener can not be null.");
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaHibernateEventListener.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaHibernateEventListener.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaHibernateEventListener.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -47,8 +47,10 @@
import org.hibernate.event.spi.PreUpdateEventListener;
import org.hibernate.event.spi.SaveOrUpdateEvent;
import org.hibernate.event.spi.SaveOrUpdateEventListener;
+import org.nuiton.topia.AbstractTopiaApplicationContext;
import org.nuiton.topia.TopiaDaoSupplier;
import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.TopiaPersistenceContext;
import org.nuiton.topia.persistence.AbstractTopiaDao;
import org.nuiton.topia.persistence.TopiaEntity;
import org.nuiton.topia.persistence.TopiaEntityContextable;
@@ -64,9 +66,9 @@
private static final long serialVersionUID = -9206039888626756924L;
- protected TopiaContextImplementor rootContext;
+ protected AbstractTopiaApplicationContext rootContext;
- public TopiaHibernateEventListener(TopiaContextImplementor rootContext) {
+ public TopiaHibernateEventListener(AbstractTopiaApplicationContext rootContext) {
this.rootContext = rootContext;
}
@@ -80,38 +82,39 @@
* @return le TopiaContext utilisant cette session hibernate ou null si
* aucun TopiaContext n'utilise cette session.
*/
- protected TopiaContextImplementor getContext(
- TopiaContextImplementor parent, Session hibernate) {
- TopiaContextImplementor result = null;
+ protected TopiaPersistenceContext getContext(
+ AbstractTopiaApplicationContext parent, Session hibernate) {
+ TopiaPersistenceContext result = null;
+ // FIXME AThimel 23/11/13 Find a way to implement it
- // FD-20100421 : Ano #546 : no need to copy childContext, the
- // {@link #getChildContext()} provides a thread-safe copy to iterate
- // on it.
-// Set<TopiaContextImplementor> contextChilds = new HashSet<TopiaContextImplementor>(parent.getChildContext());
- if (parent != null) { // TODO AThimel 11/10/13 It should never be null, fix it
- for (TopiaContextImplementor context : parent.getChildContext()) {
-
- // by sletellier 24/09/09 : Fix concurent acces error
- // ArrayList<TopiaContextImplementor> children = new ArrayList(parent.getChildContext());
- // for (TopiaContextImplementor context : children) {
- try {
- if (context.getHibernate() == hibernate) {
- result = context;
- } else {
- // TODO: poussin 20090706 on pourrait ameliorer en ne faisant pas un parcours recursif, en utilisant la liste children (sans doute a transformer en stack)
- result = getContext(context, hibernate);
- }
- if (result != null) {
- break;
- }
- } catch (TopiaException eee) {
- if (log.isWarnEnabled()) {
- log.warn("Error durant la recherche d'un context pour"
- + " lancer un event", eee);
- }
- }
- }
- }
+// // FD-20100421 : Ano #546 : no need to copy childContext, the
+// // {@link #getChildContext()} provides a thread-safe copy to iterate
+// // on it.
+//// Set<TopiaContextImplementor> contextChilds = new HashSet<TopiaContextImplementor>(parent.getChildContext());
+// if (parent != null) { // TODO AThimel 11/10/13 It should never be null, fix it
+// for (TopiaPersistenceContext context : parent.getChildContext()) {
+//
+// // by sletellier 24/09/09 : Fix concurent acces error
+// // ArrayList<TopiaContextImplementor> children = new ArrayList(parent.getChildContext());
+// // for (TopiaContextImplementor context : children) {
+// try {
+// if (context.getHibernate() == hibernate) {
+// result = context;
+// } else {
+// // TODO: poussin 20090706 on pourrait ameliorer en ne faisant pas un parcours recursif, en utilisant la liste children (sans doute a transformer en stack)
+// result = getContext(context, hibernate);
+// }
+// if (result != null) {
+// break;
+// }
+// } catch (TopiaException eee) {
+// if (log.isWarnEnabled()) {
+// log.warn("Error durant la recherche d'un context pour"
+// + " lancer un event", eee);
+// }
+// }
+// }
+// }
return result;
}
@@ -137,10 +140,11 @@
@Override
public boolean onPreInsert(PreInsertEvent event) {
- TopiaContextImplementor context = getContext(rootContext, event.getSession());
+ TopiaPersistenceContext context = getContext(rootContext, event.getSession());
if (context != null && event.getEntity() instanceof TopiaEntity) {
TopiaEntity entity = (TopiaEntity) event.getEntity();
- context.getFiresSupport().fireOnPreCreate(context, entity, event.getState());
+
+ context.getTopiaFiresSupport().fireOnPreCreate(context, entity, event.getState());
// when using composition, hibernate will persist entities by him self
// entity must have an id in this case.
@@ -156,10 +160,9 @@
@Override
public void onPostInsert(PostInsertEvent event) {
- TopiaContextImplementor context = getContext(rootContext, event
- .getSession());
+ TopiaPersistenceContext context = getContext(rootContext, event.getSession());
if (context != null && event.getEntity() instanceof TopiaEntity) {
- context.getFiresSupport().fireOnPostCreate(context, (TopiaEntity) event.getEntity(), event.getState());
+ context.getTopiaFiresSupport().fireOnPostCreate(context, (TopiaEntity) event.getEntity(), event.getState());
}
}
@@ -167,11 +170,10 @@
@Override
public void onPreLoad(PreLoadEvent event) {
- TopiaContextImplementor context = getContext(rootContext, event
- .getSession());
+ TopiaPersistenceContext context = getContext(rootContext, event.getSession());
if (context != null && event.getEntity() instanceof TopiaEntity) {
// try {
- context.getFiresSupport().fireOnPreLoad(context, (TopiaEntity) event.getEntity(), event.getState());
+ context.getTopiaFiresSupport().fireOnPreLoad(context, (TopiaEntity) event.getEntity(), event.getState());
//TODO (thimel 20071213) On commente pour le moment @see(TopiaDAOHibernate#filterElements)
// } catch (TopiaVetoException tve) {
// //On ne fait pas de remontee d'exception
@@ -182,14 +184,11 @@
@Override
public void onPostLoad(PostLoadEvent event) {
-// TopiaContextImplementor context = getContext(rootContext, event
-// .getSession());
- TopiaDaoSupplier daoSupplier = null; // TODO brendan 30/09/13 Implment
- if (daoSupplier != null && event.getEntity() instanceof TopiaEntity) {
- attachContext(event.getEntity(), daoSupplier);
+ TopiaPersistenceContext context = getContext(rootContext, event.getSession());
+ if (context != null && event.getEntity() instanceof TopiaEntity) {
+ attachContext(event.getEntity(), context);
TopiaEntity entity = (TopiaEntity) event.getEntity();
- AbstractTopiaDao<? extends TopiaEntity> dao = (AbstractTopiaDao) daoSupplier.getDao(entity.getClass());
- dao.getTopiaFiresSupport().fireOnPostLoad(dao, (TopiaEntity) event.getEntity(), new Object[]{});
+ context.getTopiaFiresSupport().fireOnPostLoad(context, (TopiaEntity) event.getEntity(), new Object[]{});
}
}
@@ -197,20 +196,18 @@
@Override
public boolean onPreUpdate(PreUpdateEvent event) {
- TopiaContextImplementor context = getContext(rootContext, event
- .getSession());
+ TopiaPersistenceContext context = getContext(rootContext, event.getSession());
if (context != null && event.getEntity() instanceof TopiaEntity) {
- context.getFiresSupport().fireOnPreUpdate(context, (TopiaEntity) event.getEntity(), event.getOldState());
+ context.getTopiaFiresSupport().fireOnPreUpdate(context, (TopiaEntity) event.getEntity(), event.getOldState());
}
return false;
}
@Override
public void onPostUpdate(PostUpdateEvent event) {
- TopiaContextImplementor context = getContext(rootContext, event
- .getSession());
+ TopiaPersistenceContext context = getContext(rootContext, event.getSession());
if (context != null && event.getEntity() instanceof TopiaEntity) {
- context.getFiresSupport().fireOnPostUpdate(context, (TopiaEntity) event.getEntity(), event.getState());
+ context.getTopiaFiresSupport().fireOnPostUpdate(context, (TopiaEntity) event.getEntity(), event.getState());
}
// FIXME indexation
// if (!(entity instanceof NotIndexable) && context.isIndexEnabled()) {
@@ -222,20 +219,18 @@
@Override
public boolean onPreDelete(PreDeleteEvent event) {
- TopiaContextImplementor context = getContext(rootContext, event
- .getSession());
+ TopiaPersistenceContext context = getContext(rootContext, event.getSession());
if (context != null && event.getEntity() instanceof TopiaEntity) {
- context.getFiresSupport().fireOnPreDelete(context, (TopiaEntity) event.getEntity(), event.getDeletedState());
+ context.getTopiaFiresSupport().fireOnPreDelete(context, (TopiaEntity) event.getEntity(), event.getDeletedState());
}
return false;
}
@Override
public void onPostDelete(PostDeleteEvent event) {
- TopiaContextImplementor context = getContext(rootContext, event
- .getSession());
+ TopiaPersistenceContext context = getContext(rootContext, event.getSession());
if (context != null && event.getEntity() instanceof TopiaEntity) {
- context.getFiresSupport().fireOnPostDelete(context, (TopiaEntity) event.getEntity(), event.getDeletedState());
+ context.getTopiaFiresSupport().fireOnPostDelete(context, (TopiaEntity) event.getEntity(), event.getDeletedState());
}
// FIXME indexation
// if (!(entity instanceof NotIndexable) && context.isIndexEnabled()) {
@@ -248,7 +243,7 @@
try {
// this event is called when hibernate try to persist entities
// using cascade (save)
- TopiaContextImplementor context = getContext(rootContext, event.getSession());
+ TopiaPersistenceContext context = getContext(rootContext, event.getSession());
// warning, event.getEntity() return null here :(
if (event.getObject() instanceof TopiaEntity) {
TopiaEntity entity = (TopiaEntity) event.getObject();
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaService.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaService.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaService.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -37,7 +37,7 @@
package org.nuiton.topia.framework;
-import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.AbstractTopiaApplicationContext;
/**
* Used to implement a service for Topia. You have to provide a static property
@@ -75,7 +75,7 @@
* @param context
* @return true if service need to be activated or not
*/
- boolean preInit(TopiaContext context);
+ boolean preInit(AbstractTopiaApplicationContext context);
/**
* Initiliaze the service after create the {@code context}.
@@ -83,6 +83,6 @@
* @param context
* @return true if service need to be activated or not
*/
- boolean postInit(TopiaContext context);
+ boolean postInit(AbstractTopiaApplicationContext context);
}
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaTransactionAware.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaTransactionAware.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaTransactionAware.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -24,7 +24,7 @@
*/
package org.nuiton.topia.framework;
-import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.TopiaTransaction;
/**
* Use this contract on a object which use a {@code TopiaContext} as a
@@ -32,7 +32,7 @@
* <p/>
* The method {@link #getTransaction()} returns the internal transaction used.
* <p/>
- * the method {@link #setTransaction(TopiaContext)} put the internal
+ * the method {@link #setTransaction(TopiaTransaction)} put the internal
* transaction.
*
* @author tchemit <chemit(a)codelutin.com>
@@ -47,12 +47,12 @@
*
* @return the current transaction (can be null or closed...).
*/
- TopiaContext getTransaction();
+ TopiaTransaction getTransaction();
/**
* Put in the instance, the given transaction.
*
* @param transaction the transaction to push
*/
- void setTransaction(TopiaContext transaction);
+ void setTransaction(TopiaTransaction transaction);
}
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaUtil.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaUtil.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaUtil.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -38,8 +38,8 @@
import org.hibernate.service.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.tool.hbm2ddl.DatabaseMetadata;
import org.hibernate.tool.hbm2ddl.TableMetadata;
-import org.nuiton.topia.TopiaContext;
import org.nuiton.topia.TopiaContextFactory;
+import org.nuiton.topia.TopiaHibernateSupport;
import org.nuiton.topia.TopiaNotFoundException;
import org.nuiton.topia.persistence.TopiaEntity;
import org.nuiton.util.RecursiveProperties;
@@ -164,25 +164,22 @@
* Test si une entite donnee correspondant a une configuration existe en
* base.
*
- * @param tx la session topia
+ * @param topiaHibernateSupport the Hibernate support required for this operation
* @param entityName le nom de l'entite a tester
* @return <tt>true</tt> si le schema de la table existe
* @since 2.6.4
*/
- public static boolean isSchemaExist(TopiaContext tx,
+ public static boolean isSchemaExist(TopiaHibernateSupport topiaHibernateSupport,
String entityName) {
- TopiaContextImplementor txi = (TopiaContextImplementor) tx;
-
ConnectionProviderSupplier connectionProviderSupplier =
- new ConnectionProviderSupplier(((SessionFactoryImplementor) txi.getHibernateFactory()).getServiceRegistry());
+ new ConnectionProviderSupplier(((SessionFactoryImplementor) topiaHibernateSupport.getHibernateFactory()).getServiceRegistry());
boolean exist = false;
try {
-
- Configuration configuration = txi.getHibernateConfiguration();
+ Configuration configuration = topiaHibernateSupport.getHibernateConfiguration();
PersistentClass classMapping =
configuration.getClassMapping(entityName);
if (classMapping == null) {
@@ -384,23 +381,20 @@
}
/**
- * Test if the db associated to the given {@code configuration} contaisn any of
+ * Test if the db associated to the given {@code configuration} contains any of
* the dealed entities.
*
- * @param tx topia context
+ * @param topiaHibernateSupport the Hibernate support required for this operation
* @return {@code true} if there is no schema for any of the dealed entities,
* {@code false} otherwise.
* @since 2.5.3
*/
- public static boolean isSchemaEmpty(TopiaContext tx) {
+ public static boolean isSchemaEmpty(TopiaHibernateSupport topiaHibernateSupport) {
+ Configuration configuration = topiaHibernateSupport.getHibernateConfiguration();
- TopiaContextImplementor txi = (TopiaContextImplementor) tx;
-
- Configuration configuration = txi.getHibernateConfiguration();
-
ConnectionProviderSupplier connectionProviderSupplier =
- new ConnectionProviderSupplier(((SessionFactoryImplementor) txi.getHibernateFactory()).getServiceRegistry());
+ new ConnectionProviderSupplier(((SessionFactoryImplementor) topiaHibernateSupport.getHibernateFactory()).getServiceRegistry());
try {
Modified: 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-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/AbstractTopiaDao.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -84,7 +84,7 @@
* @author bpoussin <poussin(a)codelutin.com>
* @version $Id$
*/
-public abstract class AbstractTopiaDao<E extends TopiaEntity> extends LegacyTopiaDao<E> implements TopiaDao<E> {
+public abstract class AbstractTopiaDao<E extends TopiaEntity> implements TopiaDao<E> {
/** to use log facility, just put in your code: log.info(\"...\"); */
private static Log log = LogFactory.getLog(AbstractTopiaDao.class);
@@ -96,6 +96,7 @@
*/
protected int batchSize = 1000;
+ @Deprecated // Should not be used here, cf http://nuiton.org/issues/2925
protected TopiaHibernateSupport topiaHibernateSupport;
protected TopiaJpaSupport topiaJpaSupport;
Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/LegacyTopiaDao.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/LegacyTopiaDao.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/LegacyTopiaDao.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -1,358 +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 com.google.common.base.Preconditions;
-import org.apache.commons.lang3.StringUtils;
-import org.nuiton.topia.TopiaContext;
-import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.framework.TopiaContextImplementor;
-import org.nuiton.topia.framework.TopiaUtil;
-import org.nuiton.topia.persistence.pager.TopiaPagerBean;
-import org.nuiton.util.PagerBeanUtil;
-
-import java.security.Permission;
-import java.util.List;
-import java.util.Map;
-
-/**
- * Implements deprecated method from {@link TopiaDAO}, should be deleted.
- */
-@Deprecated
-public abstract class LegacyTopiaDao<E extends TopiaEntity> implements TopiaDAO<E> {
-
- @Override
- public E create(Object... propertyNamesAndValues) {
- Map<String, Object> properties = TopiaUtil.convertPropertiesArrayToMap(propertyNamesAndValues);
- E result = create(properties);
- return result;
- }
-
- @Deprecated
- public boolean existByTopiaId(String topiaId) {
- return forTopiaIdEquals(topiaId).exists();
- }
-
- @Deprecated
- public boolean existByProperties(String propertyName, Object propertyValue,
- Object... propertyNamesAndValues) {
- return forProperties(propertyName, propertyValue, propertyNamesAndValues).exists();
- }
-
- @Deprecated
- protected String createSimpleQuery() {
- return newFromClause(null);
- }
-
- @Deprecated
- public String createSimpleQuery(String alias) {
- return newFromClause(alias);
- }
-
- protected abstract String newFromClause(String alias);
-
- @Deprecated
- public E findByTopiaId(String id) {
- return forTopiaIdEquals(id).findUniqueOrNull();
- }
-
- @Deprecated
- public E findByProperty(String propertyName, Object value) {
- return forProperties(propertyName, value).findAnyOrNull();
- }
-
- @Override
- @Deprecated
- public <R> R findByQuery(Class<R> type, String hql, Object... propertyNamesAndValues) {
- Map<String, Object> properties = TopiaUtil.convertPropertiesArrayToMap(propertyNamesAndValues);
- return findAnyOrNull(hql, properties, type);
- }
-
- @Override
- @Deprecated
- public E findByPrimaryKey(Map<String, Object> keys) {
- return forProperties(keys).findUniqueOrNull();
- }
-
- @Override
- @Deprecated
- public E findByPrimaryKey(Object... propertyNamesAndValues) {
- Map<String, Object> properties = TopiaUtil.convertPropertiesArrayToMap(propertyNamesAndValues);
- E byPrimaryKey = findByPrimaryKey(properties);
- return byPrimaryKey;
- }
-
- @Override
- @Deprecated
- public List<E> findAllWithOrder(String... propertyNames) {
- return newQueryBuilder().setOrderByArguments(propertyNames).findAll();
- }
-
- @Override
- @Deprecated
- public <R> List<R> findAllByQuery(Class<R> type, String hql, Object... propertyNamesAndValues) {
- Map<String, Object> hqlParameters = TopiaUtil.convertPropertiesArrayToMap(propertyNamesAndValues);
- List<R> all = findAll(hql, hqlParameters, type);
- return all;
- }
-
- @Deprecated
- public E findByProperties(String propertyName, Object value,
- Object... propertyNamesAndValues) {
- return forProperties(propertyName, value, propertyNamesAndValues).findUniqueOrNull();
- }
-
- @Deprecated
- public E findByProperties(Map<String, Object> properties) {
- return forProperties(properties).findUniqueOrNull();
- }
-
- @Deprecated
- public List<E> findAllByProperty(String propertyName, Object value) {
- List<E> all = forProperties(propertyName, value).findAll();
- return all;
- }
-
- @Deprecated
- public List<E> findAllByProperties(String propertyName, Object value, Object... propertyNamesAndValues) {
- List<E> all = forProperties(propertyName, value, propertyNamesAndValues).findAll();
- return all;
- }
-
- @Deprecated
- public List<E> findAllByProperties(Map<String, Object> properties) {
- return forProperties(properties).findAll();
- }
-
- @Deprecated
- public E findContains(String propertyName, Object value) {
- return newQueryBuilder().addContains(propertyName, value).findAny();
- }
-
- @Deprecated
- public List<E> findAllContains(String propertyName,
- Object value) {
- return newQueryBuilder().addContains(propertyName, value).findAll();
- }
-
- @Deprecated
- public boolean existsByQuery(String hql, Object... propertyNamesAndValues) {
- Map<String, Object> hqlParameters = TopiaUtil.convertPropertiesArrayToMap(propertyNamesAndValues);
- boolean exists = exists(hql, hqlParameters);
- return exists;
- }
-
- @Deprecated
- public long countByQuery(String hql,
- Object... propertyNamesAndValues) {
-
- Preconditions.checkNotNull(StringUtils.isNotBlank(hql));
- Preconditions.checkArgument(hql.toUpperCase().trim().startsWith("SELECT COUNT("));
- Map<String, Object> hqlParameters = TopiaUtil.convertPropertiesArrayToMap(propertyNamesAndValues);
- long count = findAny(hql, hqlParameters, Long.class);
- return count;
- }
-
- @Deprecated
- public E findByQuery(String hql,
- Object... propertyNamesAndValues) {
- Map<String, Object> hqlParameters = TopiaUtil.convertPropertiesArrayToMap(propertyNamesAndValues);
- E uniqueOrNull = forHql(hql, hqlParameters).findUniqueOrNull();
- return uniqueOrNull;
- }
-
- @Deprecated
- public List<E> findAllByQuery(String hql,
- Object... propertyNamesAndValues) {
- Map<String, Object> hqlParameters = TopiaUtil.convertPropertiesArrayToMap(propertyNamesAndValues);
- List<E> all = forHql(hql, hqlParameters).findAll();
- return all;
- }
-
- @Deprecated
- public Iterable<E> findAllLazyByQuery(String hql,
- Object... propertyNamesAndValues) {
- Map<String, Object> hqlParameters = TopiaUtil.convertPropertiesArrayToMap(propertyNamesAndValues);
- Iterable<E> result = findAllLazy(hql, hqlParameters);
- return result;
- }
-
- @Deprecated
- public <R> Iterable<R> findAllLazyByQuery(Class<R> type,
- String hql,
- Object... propertyNamesAndValues) {
- Map<String, Object> hqlParameters = TopiaUtil.convertPropertiesArrayToMap(propertyNamesAndValues);
- Iterable<R> result = findAllLazy(hql, hqlParameters, type);
- return result;
- }
-
- @Deprecated
- public Iterable<E> findAllLazyByQuery(int batchSize,
- String hql,
- Object... propertyNamesAndValues) {
- return findAllLazyByQuery(getEntityClass(), batchSize, hql, propertyNamesAndValues);
- }
-
-
- /**
- * @deprecated use {@link #findAllLazy(String, java.util.Map, Class)}
- */
- @Deprecated
- public <R> Iterable<R> findAllLazyByQuery(Class<R> type,
- int batchSize,
- String hql,
- Object... propertyNamesAndValues) {
- setBatchSize(batchSize);
- Map<String, Object> hqlParameters = TopiaUtil.convertPropertiesArrayToMap(propertyNamesAndValues);
- Iterable<R> allLazy = findAllLazy(hql, hqlParameters, type);
- return allLazy;
- }
-
- @Deprecated
- public <R> List<R> findAllByQueryWithBound(Class<R> type,
- String hql,
- int startIndex,
- int endIndex,
- Object... propertyNamesAndValues) {
- Map<String, Object> hqlParameters = TopiaUtil.convertPropertiesArrayToMap(propertyNamesAndValues);
- List<R> all = findAll(hql, hqlParameters, type, startIndex, endIndex);
- return all;
- }
-
- @Deprecated
- public List<E> findAllByQueryWithBound(String hql,
- int startIndex,
- int endIndex,
- Object... propertyNamesAndValues) {
- List<E> result = findAllByQueryWithBound(getEntityClass(),
- hql,
- startIndex,
- endIndex,
- propertyNamesAndValues);
- return result;
- }
-
-
- @Deprecated
- public <R> List<R> findAllByQueryAndPager(Class<R> type,
- String hql,
- TopiaPagerBean pager,
- Object... propertyNamesAndValues) {
- Preconditions.checkNotNull(pager);
- Preconditions.checkNotNull(hql);
-
- if (StringUtils.isNotBlank(pager.getSortColumn())) {
- hql += " ORDER BY " + pager.getSortColumn();
- if (!pager.isSortAscendant()) {
- hql += " DESC";
- }
- }
- List<R> result = findAllByQueryWithBound(type, hql,
- (int) pager.getRecordStartIndex(),
- (int) pager.getRecordEndIndex() - 1,
- propertyNamesAndValues);
- return result;
- }
-
- @Deprecated
- public List<E> findAllByQueryAndPager(String hql,
- TopiaPagerBean pager,
- Object... propertyNamesAndValues) {
-
- List<E> result = findAllByQueryAndPager(getEntityClass(),
- hql,
- pager,
- propertyNamesAndValues);
- return result;
- }
-
- @Deprecated
- public void computeAndAddRecordsToPager(String hql,
- TopiaPagerBean pager,
- Object... propertyNamesAndValues) {
-
- long records = countByQuery(hql, propertyNamesAndValues);
-
- pager.setRecords(records);
- PagerBeanUtil.computeRecordIndexesAndPagesNumber(pager);
- }
-
- @Override
- public List<Permission> getRequestPermission(String topiaId, int actions) {
- throw new UnsupportedOperationException();
- }
-
- @Override
- public TopiaContextImplementor getContext() {
- throw new UnsupportedOperationException();
- }
-
-
- @Override
- public TopiaContext getTopiaContext() {
- throw new UnsupportedOperationException();
- }
-
-
- // let's use method written in AbstractTopiaDao
-
- protected abstract Iterable<E> findAllLazy(String hql, Map<String, Object> hqlParameters);
-
- protected abstract <R> R findAny(String hql, Map<String, Object> properties, Class<R> type);
-
- protected abstract <R> R findAnyOrNull(String hql, Map<String, Object> hqlParameters, Class<R> type);
-
- protected abstract TopiaQueryBuilderRunQueryStep<E> forHql(String hql, Map<String, Object> hqlParameters);
-
- protected abstract <R> List<R> findAll(String hql, Map<String, Object> hqlParameters, Class<R> type);
-
- protected abstract <R> Iterable<R> findAllLazy(String hql, Map<String, Object> hqlParameters, Class<R> type);
-
- protected abstract <R> List<R> findAll(String hql, Map<String, Object> hqlParameters, Class<R> type, int startIndex, int endIndex);
-
- protected abstract <R> R findUnique(String hql, Map<String, Object> hqlParameters, Class<R> type);
-
- protected abstract boolean exists(String hql, Map<String, Object> hqlParameters);
-
- @Override
- @Deprecated
- public <E1> List<E1> findAll(String hql, Object... propertyNamesAndValues) throws TopiaException {
- return (List<E1>) findAllByQuery(hql, propertyNamesAndValues);
- }
-
- @Override
- @Deprecated
- public <E1> List<E1> find(String hql, int startIndex, int endIndex, Object... propertyNamesAndValues) throws TopiaException {
- return (List<E1>) findAllByQueryWithBound(hql, startIndex, endIndex, propertyNamesAndValues);
- }
-
- @Override
- @Deprecated
- public <E1> E1 findUnique(String hql, Object... propertyNamesAndValues) throws TopiaException {
- Map<String, Object> hqlParameters = TopiaUtil.convertPropertiesArrayToMap(propertyNamesAndValues);
- return (E1) findUnique(hql, hqlParameters, Object.class);
- }
-
-}
Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaDAO.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaDAO.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaDAO.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -1,686 +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%
- */
-
-/* *
- * TopiaDAO.java
- *
- * Created: 30 déc. 2005 03:00:57
- *
- * @author poussin <poussin(a)codelutin.com>
- * @version $Revision$
- *
- * Last update: $Date$
- * by : $Author$
- */
-package org.nuiton.topia.persistence;
-
-import org.nuiton.topia.TopiaContext;
-import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.framework.TopiaContextImplementor;
-import org.nuiton.topia.persistence.pager.TopiaPagerBean;
-
-import java.security.Permission;
-import java.util.List;
-import java.util.Map;
-
-/**
- * TopiaDAO is used to manipulate entities corresponding to {@code E} type :
- * create, delete, update or find entities.
- * <p/>
- * This interface is implemented by {@link TopiaDAOImpl} overridden by generation
- * from {@link org.nuiton.topia.generator.EntityDaoTransformer}.
- * <p/>
- *
- * @param <E> the entity type managed by the dao
- * @author bpoussin <poussin(a)codelutin.com>
- * @author fdesbois <fdesbois(a)codelutin.com>
- * @author tchemit <chemit(a)codelutin.com>
- * @version $Id$
- * @deprecated prefer {@link TopiaDao}
- */
-@Deprecated
-public interface TopiaDAO<E extends TopiaEntity> extends TopiaDao<E> {
-
- //------------------------------------------------------------------------//
- //-- Create - update - delete methods ------------------------------------//
- //------------------------------------------------------------------------//
-
- /**
- * Creates a new instance of the entity managed by the DAO
- *
- * @param propertyNamesAndValues the list of properties that the created entity will have. Arguments are key-value
- * paired : [propertyName;value;propertyName;value;...]
- * @return the newly created entity
- * @throws TopiaException if any problem during instantiation
- * @throws IllegalArgumentException if the arguments count is not correct or
- * if some property type is not the
- * expected one
- * @see #create(Map)
- * @deprecated use {@link TopiaDao#create(String, Object, Object...)}
- */
- E create(Object... propertyNamesAndValues) throws TopiaException;
-
- //------------------------------------------------------------------------//
- //-- findByXXX methods ---------------------------------------------------//
- //------------------------------------------------------------------------//
-
- /**
- * Find an entity corresponding to the {@code id}. If the {@code id} is
- * null, nothing will be searched.
- *
- * @param id topiaId of the entity to found
- * @return the entity found or null if not
- * @throws TopiaException for Topia errors on query
- * @deprecated ambiguous signature use new API and inline {@link TopiaDao#forTopiaIdEquals(String)}
- */
- E findByTopiaId(String id) throws TopiaException;
-
- /**
- * Find an entity matching {@code value} for the given {@code propertyName}.
- *
- * @param propertyName property name to filter
- * @param value value of the property to match
- * @return the first entity matching the request
- * @throws TopiaException if any pb while getting datas
- * @deprecated @deprecated use new API and inline {@link TopiaDao#forProperties(String, Object, Object...)}
- */
- E findByProperty(String propertyName,
- Object value) throws TopiaException;
-
- /**
- * Find an entity matching a succession of propertyName + value arguments.
- *
- * @param propertyName the first property name to filter
- * @param value the first value of the property to match
- * @param propertyNamesAndValues other property names and values. Arguments are key-value paired :
- * [propertyName;value;propertyName;value;...]
- * @return the first entity matching the request
- * @throws TopiaException if any pb while getting datas
- * @deprecated @deprecated use new API and inline {@link TopiaDao#forProperties(String, Object, Object...)}
- */
- E findByProperties(String propertyName,
- Object value,
- Object... propertyNamesAndValues) throws TopiaException;
-
- /**
- * Find an entity matching {@code properties}.
- *
- * @param properties the properties key + value to match
- * @return the first entity matching the request
- * @throws TopiaException if any pb while getting datas
- * @deprecated @deprecated use new API and inline {@link TopiaDao#forProperties(java.util.Map)}
- */
- E findByProperties(Map<String, Object> properties) throws TopiaException;
-
- /**
- * Executes and returns the result (entity E) of the given HQL query string.
- *
- * @param hql the HQL query
- * @param propertyNamesAndValues the query parameters. Arguments are key-value paired :
- * [propertyName;value;propertyName;value;...]
- * @return the entity E found or null
- * @throws TopiaException if any pb while getting datas
- * @since 2.6.12
- * @deprecated move your code inside the DAO and use a suitable protected method
- */
- E findByQuery(String hql,
- Object... propertyNamesAndValues) throws TopiaException;
-
- // TODO AThimel 20/07/13 Add this method : E findByQuery(String hql, Map<String, Object> propertyNamesAndValues) throws TopiaException;
-
- /**
- * Executes and returns the result (entity R) of the given HQL query string.
- *
- * @param type the expected result type
- * @param hql the HQL query
- * @param propertyNamesAndValues the query parameters. Arguments are key-value paired :
- * [propertyName;value;propertyName;value;...]
- * @return the entity R found or null
- * @throws TopiaException if any pb while getting datas
- * @throws ClassCastException if the found type is not the expected one
- * @since 2.6.12
- * @deprecated move your code inside the DAO and use a suitable protected method
- */
- <R> R findByQuery(Class<R> type,
- String hql,
- Object... propertyNamesAndValues) throws TopiaException;
-
- // TODO AThimel 20/07/13 Add this method : <R> R findByQuery(Class<R> type, String hql, Map<String, Object> propertyNamesAndValues) throws TopiaException;
-
- /**
- * Find an entity using the natural ids. Each field of the natural id has to be present in the given Map.
- *
- * @param keys Map with the natural id property name as Map.key, and value as Map.value
- * @return the entity E found or null
- * @throws TopiaException if any pb while getting datas
- * @deprecated use new API and inline {@link LegacyTopiaDao#findByPrimaryKey(java.util.Map)}
- */
- E findByPrimaryKey(Map<String, Object> keys) throws TopiaException;
-
- /**
- * Find an entity using the natural ids. Each field of the natural id has to
- * be present in the given Map.
- *
- * @param propertyNamesAndValues the query parameters. Arguments are key-value paired :
- * [propertyName;value;propertyName;value;...]
- * @return the entity E found or null
- * @throws TopiaException if any pb while getting datas
- * @deprecated use new API and inline {@link LegacyTopiaDao#findByPrimaryKey(Object...)}
- */
- E findByPrimaryKey(Object... propertyNamesAndValues) throws TopiaException;
-
- /**
- * Find the first entity which given collection (propertyName) contains the
- * given value
- *
- * @param propertyName the name of the property (must be a collection)
- * @param value the value to use for find
- * @return the entity E found or null
- * @throws TopiaException if any pb while getting datas
- * @since 2.5.4
- * @deprecated use new API and inline {@link TopiaDao#forContains(String, Object)}
- */
- E findContains(String propertyName,
- Object value) throws TopiaException;
-
- //------------------------------------------------------------------------//
- //-- findAllXXX methods --------------------------------------------------//
- //------------------------------------------------------------------------//
-
- /**
- * Finds all entites E managed by this DAO. The returned list will be ordered according to the given
- * {@code propertyNames}.
- * <p/>
- * You can add on each {@code property} {@code ASC} or {@code DESC} to force the result order
- * (by default is {@code ASC}).
- *
- * @param propertyNames property names of order to apply
- * @return all entities E of the dao entity type with given order
- * @throws TopiaException if any pb while getting datas
- * @deprecated use new API and inline {@link LegacyTopiaDao#findAllWithOrder(String...)}
- */
- List<E> findAllWithOrder(String... propertyNames) throws TopiaException;
-
- /**
- * Finds all entities E which value for the given {@code propertyName} is
- * {@code value}
- *
- * @param propertyName property name to use
- * @param value value to expect
- * @return the list of entities E having the given value
- * @throws TopiaException if any pb while getting datas
- * @deprecated use new API and inline {@link TopiaDao#forProperties(String, Object, Object...)}
- */
- List<E> findAllByProperty(String propertyName,
- Object value) throws TopiaException;
-
- /**
- * Finds all entities E matching the given {@code propertyName}, {@code value}
- * AND all other properties
- *
- * @param propertyName property name to use
- * @param value value to expect
- * @param propertyNamesAndValues the query parameters. Arguments are key-value paired :
- * [propertyName;value;propertyName;value;...]
- * @return the list of entities E having the given value
- * @throws TopiaException if any pb while getting datas
- * @deprecated use new API and inline {@link TopiaDao#forProperties(String, Object, Object...)}
- */
- List<E> findAllByProperties(String propertyName,
- Object value,
- Object... propertyNamesAndValues) throws TopiaException;
-
- /**
- * Finds all entities E matching all the {@code properties} values.
- *
- * @param properties properties to match
- * @return the list of entities E having the given values
- * @throws TopiaException if any pb while getting datas
- * @deprecated use new API and inline {@link TopiaDao#forProperties(java.util.Map)}
- */
- List<E> findAllByProperties(Map<String, Object> properties) throws TopiaException;
-
- /**
- * Finds all entities E when executing the given HQL query.
- *
- * @param hql the HQL query
- * @param propertyNamesAndValues the query parameters. Arguments are key-value paired :
- * [propertyName;value;propertyName;value;...]
- * @return the list of entities E found by the query and parameters
- * @throws TopiaException if any pb while getting datas
- * @since 2.6.12
- * @deprecated move your code inside the DAO and use {@link AbstractTopiaDao#findAll(String, java.util.Map)}
- */
- List<E> findAllByQuery(String hql,
- Object... propertyNamesAndValues) throws TopiaException;
-
- // TODO AThimel 20/07/13 Add this method : List<E> findAllByQuery(String hql, Map<String, Object> propertyNamesAndValues) throws TopiaException;
-
- /**
- * Gets all entities when executing the given select query for the given
- * {@code type} which may not be a entity type (int, long, map,...).
- *
- * @param type the expected result type
- * @param hql the HQL query
- * @param propertyNamesAndValues the query parameters. Arguments are key-value paired :
- * [propertyName;value;propertyName;value;...]
- * @return entites of the query result
- * @throws TopiaException if any pb while getting datas
- * @since 2.6.12
- * @deprecated move your code inside the DAO and use {@link AbstractTopiaDao#findAll(String, java.util.Map, Class)}
- */
- <R> List<R> findAllByQuery(Class<R> type,
- String hql,
- Object... propertyNamesAndValues) throws TopiaException;
-
- // TODO AThimel 20/07/13 Add this method : <R> List<R> findAllByQuery(Class<R> type, String hql, Map<String, Object> propertyNamesAndValues) throws TopiaException;
-
- /**
- * Finds all entities E in lazy mode when executing the given select query
- * for the dao entity type.
- * <p/>
- * <strong>Important note:</strong> // TODO AThimel 20/07/13 Write the important note...
- *
- * @param hql the HQL query
- * @param propertyNamesAndValues the query parameters. Arguments are key-value paired :
- * [propertyName;value;propertyName;value;...]
- * @return entites E of the query result
- * @throws TopiaException if any pb while getting datas
- * @since 2.6.14
- * @deprecated move your code inside the DAO and use {@link AbstractTopiaDao#findAllLazy(String, java.util.Map, Class)}
- */
- Iterable<E> findAllLazyByQuery(String hql,
- Object... propertyNamesAndValues) throws TopiaException;
-
- /**
- * Finds all entities R in lazy mode when executing the given select query
- * for the given {@code type} which may not be a entity type (int, long, map,...).
- * <p/>
- * <strong>Important note:</strong> // TODO AThimel 20/07/13 Write the important note...
- *
- * @param type the expected result type
- * @param hql the HQL query
- * @param propertyNamesAndValues the query parameters. Arguments are key-value paired :
- * [propertyName;value;propertyName;value;...]
- * @return entites R of the query result
- * @throws TopiaException if any pb while getting datas
- * @since 2.6.14
- * @deprecated move your code inside the DAO and use {@link AbstractTopiaDao#findAllLazy(String, java.util.Map, Class)}
- */
- <R> Iterable<R> findAllLazyByQuery(Class<R> type,
- String hql,
- Object... propertyNamesAndValues) throws TopiaException;
-
- /**
- * Finds all entities E in lazy mode when executing the given select query
- * for the dao entity type.
- * <p/>
- * <strong>Important note:</strong> // TODO AThimel 20/07/13 Write the important note...
- *
- * @param batchSize batch size
- * @param hql the HQL query
- * @param propertyNamesAndValues the query parameters. Arguments are key-value paired :
- * [propertyName;value;propertyName;value;...]
- * @return entites E of the query result
- * @throws TopiaException if any pb while getting datas
- * @since 2.6.14
- * @deprecated move your code inside the DAO and use {@link AbstractTopiaDao#findAllLazy(String, java.util.Map)}
- */
- Iterable<E> findAllLazyByQuery(int batchSize,
- String hql,
- Object... propertyNamesAndValues) throws TopiaException;
-
- /**
- * Finds all entities R in lazy mode when executing the given select query
- * for the given {@code type} which may not be a entity type (int, long, map,...).
- * <p/>
- * <strong>Important note:</strong> // TODO AThimel 20/07/13 Write the important note...
- *
- * @param type the expected result type
- * @param batchSize batch size
- * @param hql the HQL query
- * @param propertyNamesAndValues the query parameters. Arguments are key-value paired :
- * [propertyName;value;propertyName;value;...]
- * @return entites R of the query result
- * @throws TopiaException if any pb while getting datas
- * @since 2.6.14
- * @deprecated move your code inside the DAO and use {@link AbstractTopiaDao#findAllLazy(String, java.util.Map, Class)}
- */
- <R> Iterable<R> findAllLazyByQuery(Class<R> type,
- int batchSize,
- String hql,
- Object... propertyNamesAndValues) throws TopiaException;
-
- /**
- * Finds a page of entities E when executing the given select query for the dao
- * entity type (will only return the window of {@code startIndex -
- * endIndex} entities).
- * // TODO AThimel 20/07/13 Reformulate(?) the "window thing"
- *
- * @param hql the HQL query
- * @param startIndex first index of entity to return
- * @param endIndex last index of entity to return
- * @param propertyNamesAndValues the query parameters. Arguments are key-value paired :
- * [propertyName;value;propertyName;value;...]
- * @return entites E of the paginated query result
- * @throws TopiaException if any pb while getting datas
- * @since 2.6.12
- * @deprecated move your code inside the DAO and use {@link AbstractTopiaDao#findAll(String, java.util.Map, int, int)}
- */
- List<E> findAllByQueryWithBound(String hql,
- int startIndex,
- int endIndex,
- Object... propertyNamesAndValues) throws TopiaException;
-
- /**
- * Finds a page of entities R when executing the given select query for the dao
- * entity type (will only return the window of {@code startIndex -
- * endIndex} entities).
- * // TODO AThimel 20/07/13 Reformulate(?) the "window thing"
- *
- * @param type the expected result type
- * @param hql the HQL query
- * @param startIndex first index of entity to return
- * @param endIndex last index of entity to return
- * @param propertyNamesAndValues the query parameters. Arguments are key-value paired :
- * [propertyName;value;propertyName;value;...]
- * @return entites R of the paginated query result
- * @throws TopiaException if any pb while getting datas
- * @since 2.6.12
- * @deprecated move your code inside the DAO and use {@link AbstractTopiaDao#findAll(String, java.util.Map, Class, int, int)}
- */
- <R> List<R> findAllByQueryWithBound(Class<R> type,
- String hql,
- int startIndex,
- int endIndex,
- Object... propertyNamesAndValues) throws TopiaException;
-
- /**
- * Gets a page of entities E of the given select {@code hql} query using the
- * {@code pager} to obtain the window of entities to return.
- *
- * @param hql the HQL query
- * @param pager pager to obtain the correct window of data
- * @param propertyNamesAndValues the query parameters. Arguments are key-value paired :
- * [propertyName;value;propertyName;value;...]
- * @return entities E of the paginated query result
- * @throws TopiaException if any pb while getting datas
- * @see TopiaPagerBean
- * @since 2.6.12
- * @deprecated move your code inside the DAO and use {@link AbstractTopiaDao#findAll(String, java.util.Map, org.nuiton.topia.persistence.pager.TopiaPagerBean)}
- */
- List<E> findAllByQueryAndPager(String hql,
- TopiaPagerBean pager,
- Object... propertyNamesAndValues) throws TopiaException;
-
- /**
- * Finds a page of entities R of the given select {@code hql} query using the
- * {@code pager} to obtain the window of entities to return.
- *
- * @param type the expected result type
- * @param hql the HQL query
- * @param pager pager to obtain the correct window of data
- * @param propertyNamesAndValues the query parameters. Arguments are key-value paired :
- * [propertyName;value;propertyName;value;...]
- * @return entities R of the paginated query result
- * @throws TopiaException if any pb while getting datas
- * @see TopiaPagerBean
- * @since 2.6.12
- * @deprecated move your code inside the DAO and use {@link AbstractTopiaDao#findAll(String, java.util.Map, Class, org.nuiton.topia.persistence.pager.TopiaPagerBean)}
- */
- <R> List<R> findAllByQueryAndPager(Class<R> type,
- String hql,
- TopiaPagerBean pager,
- Object... propertyNamesAndValues) throws TopiaException;
-
- /**
- * Find all the entities E which given collection (propertyName) contains the
- * given value
- *
- * @param propertyName the name of the property (must be a collection)
- * @param value the value to use for find
- * @return all the entities E found
- * @throws TopiaException if any pb while getting datas
- * @since 2.5.4
- * @deprecated use new API and inline {@link TopiaDao#forContains(String, Object)}
- */
- List<E> findAllContains(String propertyName,
- Object value) throws TopiaException;
-
- //------------------------------------------------------------------------//
- //-- existsByXXX methods -------------------------------------------------//
- //------------------------------------------------------------------------//
-
- /**
- * Check the existence of an entity with technical {@code id}.
- *
- * @param id unique id of the entity to test existence.
- * @return true if entity exists, false otherwise
- * @throws TopiaException for any error
- * @since 2.3.4
- * @deprecated use new API and inline {@link TopiaDao#forTopiaIdEquals(String)}
- */
- boolean existByTopiaId(String id) throws TopiaException;
-
- /**
- * Check the existence of an entity with {@code propertyName} with {@code
- * propertyValue}. {@code others} properties can be added to test
- * existence.
- *
- * @param propertyName the first property name to test existence
- * @param propertyValue the first property value to test existence
- * @param propertyNamesAndValues the query parameters. Arguments are key-value paired :
- * [propertyName;value;propertyName;value;...]
- * @return true if entity exists, false otherwise
- * @throws TopiaException for Topia errors
- * @since 2.3.4
- * @deprecated move your code inside the DAO and use {@link AbstractTopiaDao#exists(String, java.util.Map)}
- */
- boolean existByProperties(String propertyName,
- Object propertyValue,
- Object... propertyNamesAndValues) throws TopiaException;
-
- /**
- * Check the existence of an entity using the given HQL query.
- *
- * @param hql the HQL query
- * @param propertyNamesAndValues the query parameters. Arguments are key-value paired :
- * [propertyName;value;propertyName;value;...]
- * @return true if entity exists, false otherwise
- * @throws TopiaException
- * @since 2.6.12
- * @deprecated move your code inside the DAO and use {@link AbstractTopiaDao#exists(String, java.util.Map)}
- */
- boolean existsByQuery(String hql,
- Object... propertyNamesAndValues) throws TopiaException;
-
- //------------------------------------------------------------------------//
- //-- countXXX methods ----------------------------------------------------//
- //------------------------------------------------------------------------//
-
- /**
- * Count the number of entities based on a the given HQL query.
- *
- * @param hql the HQL query to use
- * @param propertyNamesAndValues the query parameters. Arguments are key-value paired :
- * [propertyName;value;propertyName;value;...]
- * @return number of entities filtered by the query
- * @throws TopiaException if any pb while getting datas
- * @since 2.6.12
- * @deprecated move your call to inside the DAO and use {@link AbstractTopiaDao#count(String, java.util.Map)}
- */
- long countByQuery(String hql,
- Object... propertyNamesAndValues) throws TopiaException;
-
- //------------------------------------------------------------------------//
- //-- other request methods -----------------------------------------------//
- //------------------------------------------------------------------------//
-
- /**
- * Execute the count {@code hql} query and then synch the pager to this
- * result (says fill the
- * {@link TopiaPagerBean#records} field and then adapt
- * the number of pages available and the current number page).
- *
- * @param hql the HQL query to use
- * @param pager pager to obtain the correct window of data
- * @param propertyNamesAndValues the query parameters. Arguments are key-value paired :
- * [propertyName;value;propertyName;value;...]
- * @throws TopiaException if any pb while getting datas
- * @see TopiaPagerBean
- * @since 2.6.12
- * // TODO brendan 17/10/13 really ??
- * @deprecated
- */
- void computeAndAddRecordsToPager(String hql,
- TopiaPagerBean pager,
- Object... propertyNamesAndValues) throws TopiaException;
-
- //------------------------------------------------------------------------//
- //-- Misc methods --------------------------------------------------------//
- //------------------------------------------------------------------------//
-
- /**
- * Returns the context used by this DAO.
- *
- * @return Returns the context.
- * @deprecated use {@link #getTopiaContext()}
- */
- @Deprecated
- TopiaContextImplementor getContext();
-
- /**
- * Returns the context used by this DAO.
- *
- * @return Returns the context.
- */
- // TODO AThimel 02/08/13 Use only TopiaPersistenceContext and TopiaHibernateSupport
- TopiaContext getTopiaContext();
-
- /**
- * Get the entityEnum of the type of entity managed by this DAO.
- *
- * @return entity type enum managed by this DAO
- * @deprecated you should get it from persistence context or application context
- */
- @Deprecated
- TopiaEntityEnum getTopiaEntityEnum();
-
- /**
- * Create the simple HQL query for the entity managed by the dao.
- * <p/>
- * A optional alias can be passed:
- * <p/>
- * <pre>FROM MyEntityImpl myAlias</pre>
- *
- * @param alias optional alias to use in query
- * @return the hql query
- * @since 2.6.14
- * @deprecated no longer accessible from outside DAO
- */
- @Deprecated
- String createSimpleQuery(String alias);
-
- /**
- * Retourne les permissions a verifier pour l'acces a l'entite pour le
- * service Taas.
- *
- * @param topiaId topiaId d'une entite
- * @param actions encoded actions
- * @return la liste des permissions
- * @throws TopiaException if any pb while getting datas
- * @since 2.6.14
- * @deprecated topia-service-security will be removed in 3.0
- */
- @Deprecated
- List<Permission> getRequestPermission(String topiaId,
- int actions) throws TopiaException;
-
- // The next 3 methods are copied from TopiaContext in order to facilitate migration
-
- /**
- * Allow to do some HQL query
- * <p/>
- * WARNING : Depending on the registered service, this method may not
- * support something else than queries on TopiaEntity
- *
- * @param hql the HQL query
- * @param propertyNamesAndValues the query parameters. Arguments are key-value paired :
- * [propertyName;value;propertyName;value;...]
- * @return The result list
- * @throws TopiaException for any error during querying
- * @deprecated use method from {@link org.nuiton.topia.TopiaJpaSupport}
- */
- @Deprecated
- <E> List<E> findAll(String hql,
- Object... propertyNamesAndValues) throws TopiaException;
-
- /**
- * Allow to do some JPA-QL query using the given bounds.
- * <p/>
- * No lower bound : <code>startIndex</code> = 0.<br/>
- * No upper bound : <code>endIndex</code> = -1.
- * <p/>
- * WARNING : Depending on the registered service, this method may not
- * support something else than queries on TopiaEntity
- *
- * @param hql the HQL query
- * @param startIndex first index of entity to return
- * @param endIndex last index of entity to return
- * @param propertyNamesAndValues the query parameters. Arguments are key-value paired :
- * [propertyName;value;propertyName;value;...]
- * @return The result list
- * @throws TopiaException for any error during querying
- * @deprecated use method from {@link org.nuiton.topia.TopiaJpaSupport}
- */
- @Deprecated
- <E> List<E> find(String hql,
- int startIndex,
- int endIndex,
- Object... propertyNamesAndValues) throws TopiaException;
-
- /**
- * Allow to do some HQL query and return an unique result. If nothing if
- * found by the query, will return null. If more than one result is found,
- * will throw an exception.
- * <p/>
- * WARNING : Depending on the registered service, this method may not
- * support something else than queries on TopiaEntity
- *
- * @param hql the HQL query
- * @param propertyNamesAndValues the query parameters. Arguments are key-value paired :
- * [propertyName;value;propertyName;value;...]
- * @return The result instance or null
- * @throws TopiaException for any error during querying or if the the query
- * returns more than one result.
- * @deprecated use method from {@link org.nuiton.topia.TopiaJpaSupport}
- */
- @Deprecated
- <E> E findUnique(String hql,
- Object... propertyNamesAndValues) throws TopiaException;
-
-
-} //TopiaDAO
-
Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaDAOImpl.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaDAOImpl.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaDAOImpl.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -1,1065 +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.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.hibernate.Criteria;
-import org.hibernate.FlushMode;
-import org.hibernate.HibernateException;
-import org.hibernate.Session;
-import org.hibernate.criterion.Criterion;
-import org.hibernate.criterion.Order;
-import org.hibernate.criterion.Projections;
-import org.hibernate.criterion.Restrictions;
-import org.hibernate.metadata.ClassMetadata;
-import org.nuiton.topia.TopiaContext;
-import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.event.TopiaEntityListener;
-import org.nuiton.topia.event.TopiaEntityVetoable;
-import org.nuiton.topia.framework.TopiaContextImplementor;
-import org.nuiton.topia.framework.TopiaFiresSupport;
-import org.nuiton.topia.framework.TopiaUtil;
-import org.nuiton.topia.persistence.pager.TopiaPagerBean;
-import org.nuiton.util.PagerBeanUtil;
-
-import java.io.Serializable;
-import java.lang.reflect.InvocationTargetException;
-import java.security.Permission;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.NoSuchElementException;
-
-/**
- * Cette classe permet d'avoir un ensemble de méthode implantée de façon
- * standard et plus spécifiquement pour Hibernate.
- * <p/>
- * Certains accès à Hibernate sont tout de même fait ici, car on a pris le choix
- * de se baser entièrement sur hibernate pour la persistence, et il est ainsi
- * possible d'accèder au meta information hibernate sur les classes lorque l'on
- * en a besoin.
- *
- * @param <E> le type de l'entite
- * @author bpoussin <poussin(a)codelutin.com>
- * @version $Id$
- * @deprecated this class is replaced by {@link AbstractTopiaDao}
- */
-@Deprecated
-public class TopiaDAOImpl<E extends TopiaEntity> implements TopiaDAO<E> { // TopiaDAOImpl
-
- private static Log log = LogFactory.getLog(TopiaDAOImpl.class);
-
- /**
- * Type of entity managed by this dao.
- *
- * @since ever
- */
- protected Class<E> entityClass;
-
- /**
- * Underlying context used by this dao to do actions on db.
- *
- * @since ever
- */
- protected TopiaContext context;
-
- protected TopiaFiresSupport topiaFiresSupport;
-
- /**
- * Default batch size used to iterate on data.
- *
- * @since 2.6.14
- */
- private int batchSize = 1000;
-
- @Override
- public TopiaEntityEnum getTopiaEntityEnum() {
- throw new UnsupportedOperationException(
- "This method must be overided in generated DAO");
- }
-
- @Override
- public Class<E> getEntityClass() {
- throw new UnsupportedOperationException(
- "This method must be overided in generated DAO");
- }
-
- @Override
- public int getBatchSize() {
- return batchSize;
- }
-
- @Override
- public void setBatchSize(int batchSize) {
- this.batchSize = batchSize;
- }
-
- private E query(Criterion criterion) throws TopiaException {
- try {
- Criteria criteria = createCriteria(FlushMode.AUTO);
- criteria.add(criterion);
- criteria.setMaxResults(1);
- List<E> result = (List<E>) criteria.list();
- int sizeBefore = result != null ? result.size() : 0;
- result = topiaFiresSupport.fireEntitiesLoad(context, result);
- int sizeAfter = result != null ? result.size() : 0;
- if (sizeAfter < sizeBefore) {
- if (log.isDebugEnabled()) {
- log.debug((sizeBefore - sizeAfter)
- + " element(s) removed. Filter entity: "
- + entityClass.getName() + " - criterion: "
- + criterion);
- }
- }
- if (result != null && result.size() > 0) {
- E elem = result.get(0);
- return elem;
- }
- return null;
- } catch (HibernateException eee) {
- throw new TopiaException(eee);
- }
- }
-
- /**
- * Renvoie un Criteria créé avec l'entityClass
- *
- * @param mode le FlushMode du Criteria
- * @return le Criteria nouvellement créé
- * @throws TopiaException if any pb
- */
- private Criteria createCriteria(FlushMode mode) throws TopiaException {
- Criteria criteria = getSession().createCriteria(entityClass);
- criteria.setFlushMode(mode);
- return criteria;
- }
-
- @Override
- public Iterator<E> iterator() {
-
- Iterator<E> iterator = new FindAllIterator<E, E>(
- this,
- getEntityClass(),
- batchSize,
- "FROM " + getTopiaEntityEnum().getImplementationFQN() + " ORDER BY id");
-
- return iterator;
- }
-
- /**
- * Retourne l'id de l'entity
- *
- * @param e l'entity
- * @return l'id de l'entity ou null si pas trouvé
- * @throws TopiaException Si une erreur survient durant la recherche
- */
- protected Serializable getId(E e) throws TopiaException {
- ClassMetadata meta = getClassMetadata();
- String idPropName = meta.getIdentifierPropertyName();
-
- try {
- Serializable result;
- result = (Serializable) PropertyUtils.getSimpleProperty(e,
- idPropName);
- return result;
- } catch (Exception eee) {
- throw new TopiaException("Impossible de récuperer l'identifiant "
- + idPropName + " de l'entite: " + e);
- }
- }
-
- /**
- * Retourne l'id de l'entity representer comme une map
- *
- * @param map l'entity en representation map
- * @return l'id de l'entity ou null si pas trouvé
- * @throws TopiaException Si une erreur survient durant la recherche
- */
- protected Serializable getId(Map map) throws TopiaException {
- try {
- ClassMetadata meta = getClassMetadata();
- String idPropName = meta.getIdentifierPropertyName();
-
- Serializable id = (Serializable) map.get(idPropName);
- return id;
- } catch (HibernateException eee) {
- throw new TopiaException(eee);
- }
- }
-
- /**
- * When AbstractTopiaContext create the TopiaDAOHibernate, it must call this
- * method just after.
- *
- * @param entityClass
- */
- public void init(TopiaContext context, Class<E> entityClass, TopiaFiresSupport topiaFiresSupport)
- throws TopiaException {
- log.debug("init dao for " + entityClass.getName());
- this.context = context;
- this.entityClass = entityClass;
- this.topiaFiresSupport = topiaFiresSupport;
- }
-
- @Override
- public TopiaContextImplementor getContext() {
- return (TopiaContextImplementor) getTopiaContext();
- }
-
- @Override
- public TopiaContext getTopiaContext() {
- return context;
- }
-
- protected TopiaFiresSupport getTopiaFiresSupport() {
- return topiaFiresSupport;
- }
-
- @Override
- public String createSimpleQuery(String alias) {
- String hql = "FROM " + getTopiaEntityEnum().getImplementationFQN();
- if (StringUtils.isNotBlank(alias)) {
- hql += " " + alias;
- }
- return hql;
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public E newInstance() throws TopiaException {
- if (log.isDebugEnabled()) {
- log.debug("entityClass = " + entityClass);
- }
- Class<E> implementation = (Class<E>)
- getTopiaEntityEnum().getImplementation();
-
- try {
- E result = implementation.newInstance();
- return result;
- } catch (Exception e) {
- throw new TopiaException(
- "Impossible de trouver ou d'instancier la classe "
- + implementation);
- }
- }
-
- @Override
- public <U extends TopiaEntity> List<U> findUsages(Class<U> type, E e)
- throws TopiaException {
- // must be implemented by specialized dao
- throw new UnsupportedOperationException(
- "This method must be overided in generated DAO");
- }
-
- @Override
- public Map<Class<? extends TopiaEntity>, List<? extends TopiaEntity>> findAllUsages(E e)
- throws TopiaException {
- // must be implemented by specialized dao
- throw new UnsupportedOperationException(
- "This method must be overided in generated DAO");
- }
-
- @Override
- public List<Permission> getRequestPermission(String topiaId, int actions)
- throws TopiaException {
- return null;
- }
-
- @Override
- public void addTopiaEntityListener(TopiaEntityListener listener) {
- getContext().addTopiaEntityListener(entityClass, listener);
- }
-
- @Override
- public void addTopiaEntityVetoable(TopiaEntityVetoable vetoable) {
- getContext().addTopiaEntityVetoable(entityClass, vetoable);
- }
-
- @Override
- public void removeTopiaEntityListener(TopiaEntityListener listener) {
- getContext().removeTopiaEntityListener(entityClass, listener);
- }
-
- @Override
- public void removeTopiaEntityVetoable(TopiaEntityVetoable vetoable) {
- getContext().removeTopiaEntityVetoable(entityClass, vetoable);
- }
-
- @Override
- public E create(E entity) throws TopiaException {
-
- try {
- // first set topiaId
- if (StringUtils.isBlank(entity.getTopiaId())) {
-
- // only set id if not already on
- String topiaId = getContext().getTopiaIdFactory().newTopiaId(entityClass, entity);
- entity.setTopiaId(topiaId);
- }
-
- if (entity instanceof TopiaEntityContextable) {
- TopiaEntityContextable contextable = (TopiaEntityContextable)entity;
- // contextable.setTopiaContext(getContext());
- }
-
- // save entity
- getSession().save(entity);
- topiaFiresSupport.warnOnCreateEntity(entity);
- return entity;
- } catch (HibernateException eee) {
- throw new TopiaException(eee);
- }
- }
-
- @Override
- public E create(Object... propertyNamesAndValues) throws TopiaException {
-
- int propertiesLength = propertyNamesAndValues.length;
- Preconditions.checkArgument(propertiesLength % 2 == 0,
- "Wrong number of argument "
- + propertiesLength
- + ", you must have even number.");
-
- Map<String, Object> map = new HashMap<String, Object>();
- for (int i = 0; i < propertiesLength; ) {
- Object propertyName = propertyNamesAndValues[i++];
- Object value = propertyNamesAndValues[i++];
- Preconditions.checkArgument(
- propertyName instanceof String,
- "Argument at position [" + (i - 1) + "] " +
- "shoud be a property name (says a String) but was " +
- propertyName);
- map.put((String) propertyName, value);
- }
-
- E result = create(map);
- return result;
- }
-
- /**
- * Cette methode appelle fireVetoableCreate et fireOnCreated Si vous la
- * surchargé, faites attention a appeler le super ou a appeler vous aussi
- * ces deux methodes.
- */
- @Override
- public E create(Map<String, Object> properties) throws TopiaException {
-
- 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 update(E e) throws TopiaException {
- try {
- getSession().saveOrUpdate(e);
- topiaFiresSupport.warnOnUpdateEntity(e);
- return e;
- } catch (HibernateException eee) {
- throw new TopiaException(eee);
- }
- }
-
- @Override
- public void delete(E e) throws TopiaException {
- try {
- getSession().delete(e);
- e.notifyDeleted();
- topiaFiresSupport.warnOnDeleteEntity(e);
- } catch (HibernateException eee) {
- throw new TopiaException(eee);
- }
- }
-
- @Override
- public void deleteAll(Iterable<E> entities) throws TopiaException {
- for (E entity : entities) {
- delete(entity);
- }
- }
-
- @Override
- public E findByTopiaId(String id) throws TopiaException {
- E result = query(Restrictions.idEq(id));
- return result;
- }
-
- @Override
- public E findByProperty(String propertyName, Object value)
- throws TopiaException {
- Map<String, Object> properties = new HashMap<String, Object>();
- properties.put(propertyName, value);
- E result = findByProperties(properties);
- return result;
- }
-
- @Override
- public E findByProperties(String propertyName, Object value,
- Object... propertyNamesAndValues) throws TopiaException {
- Map<String, Object> properties =
- convertPropertiesArrayToMap(propertyName, value, propertyNamesAndValues);
- E result = findByProperties(properties);
- return result;
- }
-
- @Override
- public E findByProperties(Map<String, Object> properties)
- throws TopiaException {
- E result = query(Restrictions.allEq(properties));
- return result;
- }
-
- @Override
- public List<E> findAll() throws TopiaException {
- try {
- Criteria criteria = createCriteria(FlushMode.AUTO);
- List<E> result = (List<E>) criteria.list();
- result = topiaFiresSupport.fireEntitiesLoad(context,
- result);
- return result;
- } catch (HibernateException eee) {
- throw new TopiaException(eee);
- }
- }
-
- @Override
- public List<String> findAllIds() throws TopiaException {
- List<String> find = context.findAll("select src.topiaId from " + getEntityClass().getName() + " src");
- return find;
- }
-
- @Override
- public List<E> findAllByProperty(String propertyName, Object value)
- throws TopiaException {
- Map<String, Object> properties =
- convertPropertiesArrayToMap(propertyName, value);
- List<E> result = findAllByProperties(properties);
- return result;
- }
-
- @Override
- public List<E> findAllByProperties(String propertyName, Object value,
- Object... propertyNamesAndValues) throws TopiaException {
- Map<String, Object> properties =
- convertPropertiesArrayToMap(propertyName, value, propertyNamesAndValues);
- List<E> result = findAllByProperties(properties);
- return result;
- }
-
- @Override
- public List<E> findAllByProperties(Map<String, Object> properties)
- throws TopiaException {
- List<E> result = queryAll(Restrictions.allEq(properties));
- return result;
- }
-
- private List<E> queryAll(Criterion criterion) throws TopiaException {
- try {
- Criteria criteria = createCriteria(FlushMode.AUTO);
- criteria.add(criterion);
- List<E> result = (List<E>) criteria.list();
- result = topiaFiresSupport.fireEntitiesLoad(context,
- result);
- return result;
- } catch (HibernateException eee) {
- throw new TopiaException(eee);
- }
- }
-
- @Override
- public List<E> findAllWithOrder(String... propertyNames)
- throws TopiaException {
- try {
- Criteria criteria = createCriteria(FlushMode.AUTO);
- for (String propertyName : propertyNames) {
- criteria.addOrder(Order.asc(propertyName));
- }
- List<E> result = (List<E>) criteria.list();
- result = topiaFiresSupport.fireEntitiesLoad(context,
- result);
- return result;
- } catch (HibernateException eee) {
- throw new TopiaException(eee);
- }
- }
-
- @Override
- public E findContains(String propertyName,
- Object value) throws TopiaException {
- E find = context.findUnique("from " + getEntityClass().getName() +
- " WHERE :property in elements(" + propertyName + ")", "property", value);
- return find;
- }
-
- @Override
- public List<E> findAllContains(String propertyName,
- Object value) throws TopiaException {
- List<E> find = context.findAll("from " + getEntityClass().getName() +
- " WHERE :property in elements(" + propertyName + ")", "property", value);
- return find;
- }
-
- @Override
- public boolean existByTopiaId(String id) throws TopiaException {
- boolean result = existByProperties(TopiaEntity.PROPERTY_TOPIA_ID, id);
- return result;
- }
-
- @Override
- public boolean existByProperties(String propertyName, Object propertyValue,
- Object... propertyNamesAndValues) throws TopiaException {
- Map<String, Object> properties =
- convertPropertiesArrayToMap(propertyName, propertyValue, propertyNamesAndValues);
- try {
- Criteria criteria = createCriteria(FlushMode.AUTO);
- criteria.add(Restrictions.allEq(properties));
- criteria.setProjection(Projections.rowCount());
- Number count = (Number) criteria.uniqueResult();
- boolean result = count.intValue() > 0;
- return result;
- } catch (HibernateException eee) {
- throw new TopiaException(eee);
- }
- }
-
- @Override
- public long count() throws TopiaException {
- try {
- Criteria criteria = createCriteria(FlushMode.AUTO);
- criteria.setProjection(Projections.rowCount());
- long result = ((Number)criteria.uniqueResult()).longValue();
- return result;
- } catch (HibernateException eee) {
- throw new TopiaException(eee);
- }
- }
-
- /**
- * Convert a properties array to a proper map used to find entities in
- * methods {@link #findByProperties(String, Object, Object...)} and {@link
- * #findAllByProperties(String, Object, Object...)}.
- *
- * @param propertyName first property name to test existence
- * @param propertyValue first property value to test existence
- * @param others altern propertyName and propertyValue
- * @return a Map with properties, propertyName as key.
- * @throws IllegalArgumentException for ClassCast or ArrayIndexOutOfBounds
- * errors
- */
- private Map<String, Object> convertPropertiesArrayToMap(String propertyName,
- Object propertyValue,
- Object... others)
- throws IllegalArgumentException {
- Map<String, Object> properties = new HashMap<String, Object>();
- properties.put(propertyName, propertyValue);
- Object name = null;
- for (int i = 0; i < others.length; ) {
- try {
- name = others[i++];
- propertyValue = others[i++];
- properties.put((String) name, propertyValue);
- } catch (ClassCastException eee) {
- throw new IllegalArgumentException(
- "Les noms des propriétés doivent être des chaines et " +
- "non pas " + propertyName.getClass().getName(),
- eee);
- } catch (ArrayIndexOutOfBoundsException eee) {
- throw new IllegalArgumentException(
- "Le nombre d'argument n'est pas un nombre pair: "
- + (others.length + 2)
- + " La dernière propriété était: " + name, eee);
- }
- }
- return properties;
- }
-
- @Override
- public E findByPrimaryKey(Map<String, Object> keys)
- throws TopiaException {
- try {
- // we used hibernate meta information for all persistence type
- // it's more easy than create different for all persistence
- ClassMetadata meta = getClassMetadata();
- if (meta.hasNaturalIdentifier()) {
- E result = findByProperties(keys);
- return result;
- }
- } catch (HibernateException eee) {
- throw new TopiaException(eee);
- }
- throw new TopiaException("La classe " + entityClass.getName()
- + " n'a pas de cle primaire naturelle");
-
- }
-
- @Override
- public E findByPrimaryKey(Object... k) throws TopiaException {
- // TODO pour une meilleur gestion des problemes a la compilation
- // mettre un premier couple (propName, value) en argument ca evitera
- // de pouvoir appeler cette methode sans argument
- try {
- ClassMetadata meta = getClassMetadata();
- if (meta.hasNaturalIdentifier()) {
- int[] ikeys = meta.getNaturalIdentifierProperties();
- String[] pnames = meta.getPropertyNames();
-
- Map<String, Object> keys = new HashMap<String, Object>();
- for (int ikey : ikeys) {
- keys.put(pnames[ikey], k[ikey]);
- }
-
- E result = findByProperties(keys);
- return result;
- }
- } catch (HibernateException eee) {
- throw new TopiaException(eee);
- }
- throw new TopiaException("La classe " + entityClass.getName()
- + " n'a pas de cle primaire naturelle");
- }
-
- @Override
- public boolean existsByQuery(String hql,
- Object... propertyNamesAndValues) throws TopiaException {
- long count = countByQuery(hql, propertyNamesAndValues);
- return count > 0;
- }
-
- @Override
- public long countByQuery(String hql,
- Object... propertyNamesAndValues) throws TopiaException {
-
- Preconditions.checkNotNull(StringUtils.isNotBlank(hql));
- Preconditions.checkArgument(hql.toUpperCase().trim().startsWith("SELECT COUNT("));
-
- Long result = findByQuery(Long.class, hql, propertyNamesAndValues);
- return result;
- }
-
- @Override
- public E findByQuery(String hql,
- Object... propertyNamesAndValues) throws TopiaException {
- E result = findByQuery(getEntityClass(), hql, propertyNamesAndValues);
- return result;
- }
-
- @Override
- public <R> R findByQuery(Class<R> type,
- String hql,
- Object... params) throws TopiaException {
-
- Preconditions.checkNotNull(type);
- Preconditions.checkNotNull(hql);
-
- Object unique = getContext().findUnique(hql, params);
- Preconditions.checkState(unique == null ||
- type.isAssignableFrom(unique.getClass()));
- return (R) unique;
- }
-
- @Override
- public List<E> findAllByQuery(String hql,
- Object... propertyNamesAndValues) throws TopiaException {
-
- List<E> result = findAllByQuery(getEntityClass(), hql, propertyNamesAndValues);
- return result;
- }
-
- @Override
- public <R> List<R> findAllByQuery(Class<R> type,
- String hql,
- Object... propertyNamesAndValues) throws TopiaException {
-
- Preconditions.checkNotNull(type);
- Preconditions.checkNotNull(hql);
-
- List<R> result = getContext().findAll(hql, propertyNamesAndValues);
- return result;
- }
-
- @Override
- public Iterable<E> findAllLazyByQuery(String hql,
- Object... propertyNamesAndValues) throws TopiaException {
- Iterable<E> result = findAllLazyByQuery(batchSize, hql, propertyNamesAndValues);
- return result;
- }
-
- @Override
- public <R> Iterable<R> findAllLazyByQuery(Class<R> type,
- String hql,
- Object... propertyNamesAndValues) throws TopiaException {
- Iterable<R> result = findAllLazyByQuery(type, batchSize, hql, propertyNamesAndValues);
- return result;
- }
-
- @Override
- public Iterable<E> findAllLazyByQuery(int batchSize,
- String hql,
- Object... propertyNamesAndValues) throws TopiaException {
- return findAllLazyByQuery(getEntityClass(), batchSize, hql, propertyNamesAndValues);
- }
-
- @Override
- public <R> Iterable<R> findAllLazyByQuery(Class<R> type,
- int batchSize,
- String hql,
- Object... propertyNamesAndValues) throws TopiaException {
-
- final Iterator<R> iterator = new FindAllIterator<E, R>(this,
- type,
- batchSize,
- hql,
- propertyNamesAndValues);
- Iterable<R> result = new Iterable<R>() {
- @Override
- public Iterator<R> iterator() {
- return iterator;
- }
- };
- return result;
- }
-
- @Override
- public <R> List<R> findAllByQueryWithBound(Class<R> type,
- String hql,
- int startIndex,
- int endIndex,
- Object... propertyNamesAndValues) throws TopiaException {
- Preconditions.checkNotNull(type);
- Preconditions.checkNotNull(hql);
-
- List<R> result = getContext().find(hql, startIndex, endIndex, propertyNamesAndValues);
- return result;
- }
-
- @Override
- public List<E> findAllByQueryWithBound(String hql,
- int startIndex,
- int endIndex,
- Object... propertyNamesAndValues) throws TopiaException {
- List<E> result = findAllByQueryWithBound(getEntityClass(),
- hql,
- startIndex,
- endIndex,
- propertyNamesAndValues);
- return result;
- }
-
- @Override
- public <R> List<R> findAllByQueryAndPager(Class<R> type,
- String hql,
- TopiaPagerBean pager,
- Object... propertyNamesAndValues) throws TopiaException {
- Preconditions.checkNotNull(pager);
- Preconditions.checkNotNull(hql);
-
- if (StringUtils.isNotBlank(pager.getSortColumn())) {
- hql += " ORDER BY " + pager.getSortColumn();
- if (!pager.isSortAscendant()) {
- hql += " DESC";
- }
- }
- List<R> result = findAllByQueryWithBound(type, hql,
- (int) pager.getRecordStartIndex(),
- (int) pager.getRecordEndIndex() - 1,
- propertyNamesAndValues);
- return result;
- }
-
- @Override
- public List<E> findAllByQueryAndPager(String hql,
- TopiaPagerBean pager,
- Object... propertyNamesAndValues) throws TopiaException {
-
- List<E> result = findAllByQueryAndPager(getEntityClass(),
- hql,
- pager,
- propertyNamesAndValues);
- return result;
- }
-
- @Override
- public void computeAndAddRecordsToPager(String hql,
- TopiaPagerBean pager,
- Object... propertyNamesAndValues) throws TopiaException {
-
- long records = countByQuery(hql, propertyNamesAndValues);
-
- pager.setRecords(records);
- PagerBeanUtil.computeRecordIndexesAndPagesNumber(pager);
- }
-
- /**
- * Renvoie la Session contenue dans le contexte
- *
- * @return hibernate session
- * @throws TopiaException if any pb
- */
- protected Session getSession() throws TopiaException {
- Session result = getContext().getHibernateSession();
- return result;
- }
-
- /**
- * package locale method because this is hibernate specific method and
- * we don't want expose it.
- *
- * @return the meta-data of the entity
- * @throws TopiaException if any pb
- */
- protected ClassMetadata getClassMetadata() throws TopiaException {
- ClassMetadata meta = getContext().getHibernateFactory()
- .getClassMetadata(entityClass);
- if (meta == null) {
- meta = getContext().getHibernateFactory().getClassMetadata(
- getTopiaEntityEnum().getImplementationFQN());
- }
- return meta;
- }
-
- public static class FindAllIterator<E extends TopiaEntity, R> implements Iterator<R> {
-
- protected Iterator<R> data;
-
- protected final TopiaDAO<E> dao;
-
- protected final Class<R> type;
-
- protected final String hql;
-
- protected final Object[] params;
-
- protected TopiaPagerBean pager;
-
- public FindAllIterator(TopiaDAO<E> dao,
- Class<R> type,
- int batchSize,
- String hql,
- Object... params) {
- this.dao = dao;
- this.type = type;
- this.hql = hql;
- this.params = params;
-
- String hql2 = hql.toLowerCase();
- int i = hql2.indexOf("order by");
- if (i == -1) {
- throw new IllegalStateException(
- "must have a *order by* in hql, " +
- "but did not find it in " + hql);
- }
-
- // get the count (removing the order-by)
- long count2 = dao.countByQuery("SELECT COUNT(*) " +
- hql.substring(0, i), params);
- pager = new TopiaPagerBean();
- pager.setRecords(count2);
- pager.setPageSize(batchSize);
- PagerBeanUtil.computeRecordIndexesAndPagesNumber(pager);
-
- // empty iterator (will be changed at first next call)
- data = Iterators.emptyIterator();
- }
-
- @Override
- public boolean hasNext() {
- boolean result = data.hasNext() || // no more data
- pager.getPageIndex() < pager.getPagesNumber();
- return result;
- }
-
- @Override
- public R 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
- data = dao.findAllByQueryAndPager(type,
- hql,
- pager,
- params).iterator();
- }
-
- R next = data.next();
- return next;
- }
-
- @Override
- public void remove() {
- throw new UnsupportedOperationException(
- "This iterator does not support remove operation.");
- }
- }
-
- @Override
- public TopiaQueryBuilderRunQueryStep<E> forTopiaIdIn(Iterable<String> topiaIds) {
- throw new UnsupportedOperationException("Please use new Dao implementations");
- }
-
- @Override
- public TopiaQueryBuilderRunQueryStep<E> forTopiaIdEquals(String topiaId) {
- throw new UnsupportedOperationException("Please use new Dao implementations");
- }
-
- @Override
- public Optional<E> tryFindByTopiaId(String topiaId) {
- throw new UnsupportedOperationException("Please use new Dao implementations");
- }
-
- @Override
- public TopiaQueryBuilderRunQueryStep<E> forIn(String propertyName, Iterable<Object> propertyValues) {
- throw new UnsupportedOperationException("Please use new Dao implementations");
- }
-
- @Override
- public TopiaQueryBuilderRunQueryStep<E> forEquals(String propertyName, Object propertyValue) {
- throw new UnsupportedOperationException("Please use new Dao implementations");
- }
-
- @Override
- public TopiaQueryBuilderRunQueryStep<E> forContains(String propertyName, Object propertyValue) {
- throw new UnsupportedOperationException("Please use new Dao implementations");
- }
-
- @Override
- public TopiaQueryBuilderAddCriteriaStep<E> newQueryBuilder() {
- throw new UnsupportedOperationException("Please use new Dao implementations");
- }
-
- @Override
- public TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> forProperties(String propertyName, Object propertyValue, Object... otherPropertyNamesAndValues) {
- throw new UnsupportedOperationException("Please use new Dao implementations");
- }
-
- @Override
- public TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> forProperties(Map<String, Object> properties) {
- throw new UnsupportedOperationException("Please use new Dao implementations");
- }
-
- @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() {
- E result = newInstance();
- create(result);
- return result;
- }
-
- @Override
- public Iterable<E> findAllLazy() {
- String hql = "from " + getTopiaEntityEnum().getImplementationFQN() + " order by id";
- Map<String, Object> hqlParameters = Collections.emptyMap();
- Iterable<E> allLazy = findAllLazyByQuery(hql, hqlParameters);
- return allLazy;
- }
-
- @Override
- public Iterable<E> createAll(Iterable<E> entities) {
- for (E entity : entities) {
- create(entity);
- }
- return entities;
- }
-
- @Override
- public Iterable<E> updateAll(Iterable<E> entities) {
- for (E entity : entities) {
- update(entity);
- }
- return entities;
- }
-
- @Override
- public <E1> List<E1> findAll(String hql, Object... propertyNamesAndValues) throws TopiaException {
- throw new UnsupportedOperationException("Please use new Dao implementations");
- }
-
- @Override
- public <E1> List<E1> find(String hql, int startIndex, int endIndex, Object... propertyNamesAndValues) throws TopiaException {
- throw new UnsupportedOperationException("Please use new Dao implementations");
- }
-
- @Override
- public <E1> E1 findUnique(String hql, Object... propertyNamesAndValues) throws TopiaException {
- throw new UnsupportedOperationException("Please use new Dao implementations");
- }
-
-} //TopiaDAOImpl
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaEntityContextable.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaEntityContextable.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaEntityContextable.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -25,7 +25,6 @@
package org.nuiton.topia.persistence;
-import org.nuiton.topia.TopiaContext;
import org.nuiton.topia.TopiaDaoSupplier;
/**
Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaId.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaId.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaId.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -1,185 +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%
- */
-
-/* *
- * TopiaId.java
- *
- * Created: 6 juil. 2004
- *
- * @author Benjamin Poussin <poussin(a)codelutin.com>
- * Copyright Code Lutin
- * @version $Revision$
- *
- * Mise a jour: $Date$
- * par : $Author$
- */
-
-package org.nuiton.topia.persistence;
-
-import com.google.common.base.Function;
-import org.nuiton.topia.TopiaNotFoundException;
-
-import java.io.Serializable;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-/**
- * TODO-fdesbois-20100508 : Need translation of javadoc.
- * <p/>
- * Classe representant un Id, utilisable par JDO. Cette classe contient aussi un ensemble de methode
- * static utile pour la manipulation des topiaId.
- * <p/>
- * TODO-tchemit-2012-08-16 Rename this class to {@code TopiaIds}.
- *
- * @author poussin <poussing(a)codelutin.com>
- * @author tchemit <tchemit(a)codelutin.com>
- * @author chatellier <chatellier(a)codelutin.com>
- * @version $Id$
- * @deprecated since 3.0 depends on implementation of TopiaIdFactory. Will be removed in next versions
- */
-@Deprecated
-public class TopiaId implements Serializable { // TopiaId
-
- /** */
- private static final long serialVersionUID = 1L;
-
- /**
- * Function to obtain {@link TopiaEntity#getTopiaId()} from any entity.
- *
- * @since 2.6.12
- * @deprecated since 3.0 use {@link TopiaEntities#getTopiaIdFunction()}
- */
- @Deprecated
- public static final Function<TopiaEntity, String> GET_TOPIA_ID = TopiaEntities.getTopiaIdFunction();
-
- public String topiaId;
-
- public TopiaId() {
- }
-
- public TopiaId(String topiaId) {
- this.topiaId = topiaId;
- }
-
- @Override
- public int hashCode() {
- if (topiaId == null) {
- //TODO-TC20100225 : use commons-loggin api instead of jdk one
- Logger.getLogger(getClass().getName() + ".hashCode").log(
- Level.WARNING, "Use null topiaId", new Throwable());
- return 0;
- }
- return topiaId.hashCode();
- }
-
- @Override
- public boolean equals(Object o) {
- return topiaId.equals(o);
- }
-
- @Override
- public String toString() {
- return topiaId;
- }
-
- /**
- * Cree un topiaId pour une certaine classe
- *
- * @param clazz
- * @return a generated topiaId
- */
- public static String create(Class clazz) {
- if (!clazz.isInterface()) {
- throw new IllegalArgumentException(
- "Only interface is permit to create id: " + clazz);
- }
- double random = Math.random();
- while (Double.toString(random).contains("E-")) {
- random = Math.random();
- }
- return clazz.getName() + '#' + System.currentTimeMillis() + '#'
- + random;
- }
-
- /**
- * Extrait la classe du topiaId.
- *
- * @param topiaId
- * @return class
- * @throws TopiaNotFoundException
- */
- public static Class getClassName(String topiaId)
- throws TopiaNotFoundException {
- String classname = getClassNameAsString(topiaId);
- try {
- Class result = Class.forName(classname);
- return result;
- } catch (ClassNotFoundException eee) {
- throw new TopiaNotFoundException("Can't find class for " + topiaId,
- eee);
- }
- }
-
- /**
- * Return class name id topiaId is id, and empty string if topiaId is not an
- * id.
- *
- * @param topiaId
- * @return class name
- */
- public static String getClassNameAsString(String topiaId) {
- String result = "";
- int i = topiaId.indexOf('#');
- if (i > 0) {
- result = topiaId.substring(0, i);
- }
- return result;
- }
-
- /**
- * Verifie si l'id passé en paramètre est bien un Id topia, c-a-d si la
- * forme est bien classname#timemillis#random et si le classname est celui
- * d'une classe valide, c-a-d que le systeme arrive a trouver.
- *
- * @param topiaId
- * @return is valid topiaId
- */
- public static boolean isValidId(String topiaId) {
- try {
- if (topiaId.matches(".*?#[0-9]+#[0-9.]+")) {
- getClassName(topiaId);
- return true;
- }
- return false;
- } catch (Exception eee) {
- //TODO-TC20100225 : use commons-loggin api instead of jdk one
- Logger.getLogger(TopiaId.class.getName() + ".isValidId").log(
- Level.WARNING, "Error during verfication of topiaId", eee);
- return false;
- }
- }
-
-} // TopiaId
-
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaPersistenceHelper.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaPersistenceHelper.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaPersistenceHelper.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -23,8 +23,6 @@
* #L%
*/
-import org.nuiton.topia.TopiaContext;
-
/**
* Object which helps to wrap some static generated code
* (dao helper, entityEnum).
@@ -37,12 +35,12 @@
// TODO AThimel 20/07/13 Javadoc
<E extends TopiaEntity> T getEntityEnum(Class<E> type);
- // TODO AThimel 20/07/13 Javadoc
- <E extends TopiaEntity> TopiaDAO<E> getDAO(TopiaContext tx,
- Class<E> type);
+// // TODO AThimel 20/07/13 Javadoc
+// <E extends TopiaEntity> TopiaDao<E> getDAO(TopiaContext tx,
+// Class<E> type);
+//
+// // TODO AThimel 20/07/13 Javadoc
+// <E extends TopiaEntity> TopiaDao<E> getDAO(TopiaContext tx,
+// T type);
- // TODO AThimel 20/07/13 Javadoc
- <E extends TopiaEntity> TopiaDAO<E> getDAO(TopiaContext tx,
- T type);
-
}
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/csv/in/TopiaCsvImports.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/csv/in/TopiaCsvImports.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/csv/in/TopiaCsvImports.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -29,10 +29,10 @@
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.nuiton.topia.TopiaContext;
import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.framework.TopiaContextImplementor;
-import org.nuiton.topia.persistence.TopiaDAO;
+import org.nuiton.topia.TopiaHibernateSupport;
+import org.nuiton.topia.TopiaSqlSupport;
+import org.nuiton.topia.persistence.TopiaDao;
import org.nuiton.topia.persistence.TopiaEntity;
import org.nuiton.topia.persistence.TopiaEntityEnum;
import org.nuiton.topia.persistence.csv.CsvProgressModel;
@@ -243,7 +243,7 @@
}
}
- public static <T extends TopiaEntityEnum, E extends TopiaEntity> void importAllEntities(TopiaDAO<E> dao,
+ public static <T extends TopiaEntityEnum, E extends TopiaEntity> void importAllEntities(TopiaDao<E> dao,
TableMeta<T> meta,
Import<E> importer,
CsvImportResult<T> csvResult) throws TopiaException {
@@ -267,13 +267,13 @@
}
}
- public static <T extends TopiaEntityEnum, E extends TopiaEntity> void importAllEntities(TopiaDAO<E> dao,
+ 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 {
- TopiaContext context = dao.getContext();
+ TopiaHibernateSupport hibernateSupport = null; // FIXME AThimel 23/11/13 Get an hibernate support instance
CsvProgressModel progressModel = csvResult == null ? null :
csvResult.getProgressModel();
@@ -296,12 +296,12 @@
compt++;
if (compt % nbRowBuffer == 0) {
// flush it
- context.getHibernateSession().flush();
+ hibernateSupport.getHibernateSession().flush();
}
}
}
- public static <T extends TopiaEntityEnum, E extends TopiaEntity> Iterable<E> importAllEntitiesAndReturnThem(TopiaDAO<E> dao,
+ 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 {
@@ -329,7 +329,7 @@
return result;
}
- public static <T extends TopiaEntityEnum, E extends TopiaEntity> void importNotExistingEntities(TopiaDAO<E> dao,
+ public static <T extends TopiaEntityEnum, E extends TopiaEntity> void importNotExistingEntities(TopiaDao<E> dao,
TableMeta<T> meta,
Map<String, TopiaEntity> universe,
Import<E> importer,
@@ -342,7 +342,7 @@
String topiaId = entity.getTopiaId();
Map<String, Object> properties = meta.prepareCreate(entity, null);
- E existingEntity = dao.findByProperties(properties);
+ E existingEntity = dao.forProperties(properties).findAnyOrNull();
if (existingEntity == null) {
// new entity to create
@@ -377,7 +377,7 @@
}
}
- public static <T extends TopiaEntityEnum> void importAssociation(TopiaContext tx, AssociationMeta<T> meta,
+ public static <T extends TopiaEntityEnum> void importAssociation(TopiaSqlSupport sqlSupport, AssociationMeta<T> meta,
ImportToMap importer,
CsvImportResult<T> csvResult,
int nbRowBuffer) throws TopiaException {
@@ -408,7 +408,7 @@
compt++;
if (compt % nbRowBuffer == 0) {
// flush it
- tx.executeSQL(builder.toString());
+ sqlSupport.executeSql(builder.toString());
builder = new StringBuilder();
}
}
@@ -421,11 +421,11 @@
}
}
if (builder.length() > 0) {
- tx.executeSQL(builder.toString());
+ sqlSupport.executeSql(builder.toString());
}
}
- public static <T extends TopiaEntityEnum> void importNMAssociation(TopiaContext tx,
+ public static <T extends TopiaEntityEnum> void importNMAssociation(TopiaSqlSupport sqlSupport,
AssociationMeta<T> meta,
ImportToMap importer,
CsvImportResult<T> csvResult,
@@ -461,7 +461,7 @@
compt++;
if (compt % nbRowBuffer == 0) {
// flush it
- tx.executeSQL(builder.toString());
+ sqlSupport.executeSql(builder.toString());
builder = new StringBuilder();
}
}
@@ -474,11 +474,11 @@
}
}
if (builder.length() > 0) {
- tx.executeSQL(builder.toString());
+ sqlSupport.executeSql(builder.toString());
}
}
- public static <T extends TopiaEntityEnum> void importNMAssociation(TopiaContext tx,
+ public static <T extends TopiaEntityEnum> void importNMAssociation(TopiaSqlSupport sqlSupport,
AssociationMeta<T> meta,
Map<String, TopiaEntity> universe,
ImportToMap importer,
@@ -517,7 +517,7 @@
compt++;
if (compt % nbRowBuffer == 0) {
// flush it
- tx.executeSQL(builder.toString());
+ sqlSupport.executeSql(builder.toString());
builder = new StringBuilder();
}
}
@@ -530,11 +530,11 @@
}
}
if (builder.length() > 0) {
- tx.executeSQL(builder.toString());
+ sqlSupport.executeSql(builder.toString());
}
}
- public static <T extends TopiaEntityEnum> void importAssociation(TopiaContext tx,
+ public static <T extends TopiaEntityEnum> void importAssociation(TopiaSqlSupport sqlSupport,
AssociationMeta<T> meta,
Map<String, TopiaEntity> universe,
ImportToMap importer,
@@ -571,7 +571,7 @@
compt++;
if (compt % nbRowBuffer == 0) {
// flush it
- tx.executeSQL(builder.toString());
+ sqlSupport.executeSql(builder.toString());
builder = new StringBuilder();
}
}
@@ -584,7 +584,7 @@
}
}
if (builder.length() > 0) {
- tx.executeSQL(builder.toString());
+ sqlSupport.executeSql(builder.toString());
}
}
}
Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/Creator.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/Creator.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/Creator.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -1,57 +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%
- */
-
-package org.nuiton.topia.persistence.util;
-
-import org.nuiton.topia.TopiaContext;
-import org.nuiton.topia.TopiaException;
-
-/**
- * A simple contract to hook the creation phase of an entity associated (or not!) to
- * a parent entity.
- * <p/>
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @param <P> the type of the parent of the entity to create (if entity has
- * no parent then used the {@link Void} type).
- * @param <E> the type of entity to create
- */
-public interface Creator<P, E> {
- /**
- * Perform the creation of an entity.
- * <p/>
- * The given <code>from</code> entity should not have already been created in
- * database ? it should only be here to prepare the creation of the entity.
- * <p/>
- * TODO Review this explanation :)
- *
- * @param tx the current available transaction
- * @param parent the parent of the entity
- * @param from the entity to create
- * @return the really created entity in database
- * @throws TopiaException if any db problem.
- */
- E create(TopiaContext tx, P parent, E from) throws TopiaException;
-}
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/DBMapping.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/DBMapping.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/DBMapping.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -28,19 +28,20 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.exception.SQLGrammarException;
-import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.AbstractTopiaApplicationContext;
import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.framework.AbstractTopiaContext;
+import org.nuiton.topia.TopiaPersistenceContext;
+import org.nuiton.topia.TopiaSqlQuery;
+import org.nuiton.topia.TopiaSqlSupport;
import org.nuiton.topia.persistence.TopiaEntity;
-import org.hibernate.SQLQuery;
-import org.hibernate.jdbc.Work;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
import java.sql.SQLException;
-import java.sql.Statement;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
@@ -114,31 +115,32 @@
}
}
- public void init(TopiaContext ctxt, boolean doCreate, boolean doUpdate) throws TopiaException {
+ public void init(AbstractTopiaApplicationContext ctxt, boolean doCreate, boolean doUpdate) throws TopiaException {
if (sequences.isEmpty()) {
// no sequence registed
return;
}
String firstSequenceKey = sequences.keySet().iterator().next();
- TopiaContext newContext = ctxt.beginTransaction();
- boolean exists = existSequence(firstSequenceKey, newContext);
+ TopiaPersistenceContext newContext = ctxt.newPersistenceContext();
+ TopiaSqlSupport sqlSupport = null; // TODO AThimel 23/11/13 Get an instance of TopiaSqlSupprt
+ boolean exists = existSequence(firstSequenceKey, sqlSupport);
if (!exists) {
if (!doCreate) {
// not exists and do not create
return;
}
- createSequences(newContext);
+ createSequences(sqlSupport);
} else {
if (doUpdate) {
- updateSequences(newContext);
+ updateSequences(sqlSupport);
}
}
newContext.commit();
newContext.closeContext();
}
- public void createSequences(TopiaContext ctxt) throws TopiaException {
+ public void createSequences(TopiaSqlSupport ctxt) throws TopiaException {
if (log.isInfoEnabled()) {
log.info("start create db sequences...");
}
@@ -147,7 +149,7 @@
}
}
- public void updateSequences(TopiaContext ctxt) throws TopiaException {
+ public void updateSequences(TopiaSqlSupport ctxt) throws TopiaException {
if (log.isInfoEnabled()) {
log.info("start update db sequences...");
}
@@ -156,47 +158,47 @@
}
}
- public boolean existSequence(String sequenceKey, TopiaContext ctxt) throws TopiaException {
+ public boolean existSequence(String sequenceKey, TopiaSqlSupport ctxt) throws TopiaException {
return existSequence(sequenceKey, ctxt, true);
}
- public void createSequence(String sequenceKey, TopiaContext ctxt) throws TopiaException {
+ public void createSequence(String sequenceKey, TopiaSqlSupport ctxt) throws TopiaException {
createSequence(sequenceKey, ctxt, true);
}
- public void updateSequence(String sequenceKey, TopiaContext ctxt) throws TopiaException {
+ public void updateSequence(String sequenceKey, TopiaSqlSupport ctxt) throws TopiaException {
updateSequence(sequenceKey, ctxt, true);
}
- public BigInteger getCurrentValueFromSequence(String sequenceKey, TopiaContext ctxt) throws TopiaException {
+ public BigInteger getCurrentValueFromSequence(String sequenceKey, TopiaSqlSupport ctxt) throws TopiaException {
return getCurrentValueFromSequence(sequenceKey, ctxt, true);
}
- public BigInteger getNextValueFromSequence(String sequenceKey, TopiaContext ctxt) throws TopiaException {
+ public BigInteger getNextValueFromSequence(String sequenceKey, TopiaSqlSupport ctxt) throws TopiaException {
return getNextValueFromSequence(sequenceKey, ctxt, true);
}
- public boolean existSequence(Class<? extends TopiaEntity> entityClass, String propertyName, TopiaContext ctxt) throws TopiaException {
+ public boolean existSequence(Class<? extends TopiaEntity> entityClass, String propertyName, TopiaSqlSupport ctxt) throws TopiaException {
String sequenceKey = checkSequence(entityClass, propertyName);
return existSequence(sequenceKey, ctxt, false);
}
- public void createSequence(Class<? extends TopiaEntity> entityClass, String propertyName, TopiaContext ctxt) throws TopiaException {
+ public void createSequence(Class<? extends TopiaEntity> entityClass, String propertyName, TopiaSqlSupport ctxt) throws TopiaException {
String sequenceKey = checkSequence(entityClass, propertyName);
createSequence(sequenceKey, ctxt, false);
}
- public void updateSequence(Class<? extends TopiaEntity> entityClass, String propertyName, TopiaContext ctxt) throws TopiaException {
+ public void updateSequence(Class<? extends TopiaEntity> entityClass, String propertyName, TopiaSqlSupport ctxt) throws TopiaException {
String sequenceKey = checkSequence(entityClass, propertyName);
updateSequence(sequenceKey, ctxt, false);
}
- public BigInteger getCurrentValueFromSequence(Class<? extends TopiaEntity> entityClass, String propertyName, TopiaContext ctxt) throws TopiaException {
+ public BigInteger getCurrentValueFromSequence(Class<? extends TopiaEntity> entityClass, String propertyName, TopiaSqlSupport ctxt) throws TopiaException {
String sequenceKey = checkSequence(entityClass, propertyName);
return getCurrentValueFromSequence(sequenceKey, ctxt, false);
}
- public BigInteger getNextValueFromSequence(Class<? extends TopiaEntity> entityClass, String propertyName, TopiaContext ctxt) throws TopiaException {
+ public BigInteger getNextValueFromSequence(Class<? extends TopiaEntity> entityClass, String propertyName, TopiaSqlSupport ctxt) throws TopiaException {
String sequenceKey = checkSequence(entityClass, propertyName);
return getNextValueFromSequence(sequenceKey, ctxt, false);
}
@@ -205,7 +207,7 @@
return sequences.keySet().iterator();
}
- public boolean existSequence(String sequenceKey, TopiaContext ctxt, boolean check) throws TopiaException {
+ public boolean existSequence(String sequenceKey, TopiaSqlSupport ctxt, boolean check) throws TopiaException {
if (check) {
checkSequence(sequenceKey);
}
@@ -222,7 +224,7 @@
return true;
}
- public void createSequence(String sequenceKey, TopiaContext ctxt, boolean check) throws TopiaException {
+ public void createSequence(String sequenceKey, TopiaSqlSupport ctxt, boolean check) throws TopiaException {
if (check) {
checkSequence(sequenceKey);
}
@@ -235,30 +237,30 @@
}
}
- public void updateSequence(String sequenceKey, TopiaContext ctxt, boolean check) throws TopiaException {
+ public void updateSequence(String sequenceKey, TopiaSqlSupport sqlSupport, boolean check) throws TopiaException {
if (check) {
checkSequence(sequenceKey);
}
String sql = getSequenceSQL(UPDATE_SEQUENCE_FORMAT, sequenceKey);
- doSQLWork(ctxt, sql);
- BigInteger currentValue = getNextValueFromSequence(sequenceKey, ctxt, false);
+ doSQLWork(sqlSupport, sql);
+ BigInteger currentValue = getNextValueFromSequence(sequenceKey, sqlSupport, false);
if (log.isDebugEnabled()) {
log.debug(sequenceKey + " currentValue " + currentValue.intValue());
}
}
- public BigInteger getCurrentValueFromSequence(String sequenceKey, TopiaContext ctxt, boolean check) throws TopiaException {
+ public BigInteger getCurrentValueFromSequence(String sequenceKey, TopiaSqlSupport ctxt, boolean check) throws TopiaException {
if (check) {
checkSequence(sequenceKey);
}
String sql = getSequenceSQL(CURRENT_VALUE_SEQUENCE_FORMAT, sequenceKey);
- TopiaContext newCtxt = ctxt.beginTransaction();
- BigInteger bigInteger = getBigInteger(newCtxt, sql, BigInteger.ZERO);
- newCtxt.closeContext();
+// TopiaContext newCtxt = ctxt.beginTransaction();
+ BigInteger bigInteger = getBigInteger(ctxt, sql, BigInteger.ZERO);
+// newCtxt.closeContext();
return bigInteger;
}
- public BigInteger getNextValueFromSequence(String sequenceKey, TopiaContext ctxt, boolean check) throws TopiaException {
+ public BigInteger getNextValueFromSequence(String sequenceKey, TopiaSqlSupport ctxt, boolean check) throws TopiaException {
if (check) {
checkSequence(sequenceKey);
}
@@ -323,36 +325,36 @@
return sql;
}
- protected BigInteger getBigInteger(TopiaContext ctxt, String sql, BigInteger defaultSize) throws TopiaException {
+ protected BigInteger getBigInteger(TopiaSqlSupport sqlSupport, final String sql, BigInteger defaultSize) throws TopiaException {
BigInteger size = defaultSize;
- if (ctxt != null) {
- try {
- SQLQuery query = ((AbstractTopiaContext) ctxt).getHibernate().createSQLQuery(sql);
- size = (BigInteger) query.list().get(0);
- } catch (SQLGrammarException e) {
- // could not obtain sequence
- throw new TopiaException(e);
- }
- }
- return size;
- }
+ if (sqlSupport != null) {
+// try {
+// SQLQuery query = ((AbstractTopiaContext) ctxt).getHibernate().createSQLQuery(sql);
+// size = (BigInteger) query.list().get(0);
+// } catch (SQLGrammarException e) {
+// // could not obtain sequence
+// throw new TopiaException(e);
+// }
+ size = sqlSupport.findSingleResult(new TopiaSqlQuery<BigInteger>() {
+ @Override
+ protected PreparedStatement prepareQuery(Connection connection) throws SQLException {
+ return connection.prepareStatement(sql);
+ }
- protected void doSQLWork(TopiaContext ctxt, final String sql) throws TopiaException {
- if (ctxt != null) {
- //ctxt.beginTransaction();
- ((AbstractTopiaContext) ctxt).getHibernate().doWork(new Work() {
- public void execute(Connection connection) throws SQLException {
- if (log.isDebugEnabled()) {
- log.debug(sql);
- }
- Statement stmt = connection.createStatement();
- stmt.execute(sql);
+ @Override
+ protected BigInteger prepareResult(ResultSet set) throws SQLException {
+ return set.getBigDecimal(0).unscaledValue(); // TODO AThimel 23/11/13 Don't know if it may work or not
}
});
- //ctxt.commit();
+
}
+ return size;
}
+ protected void doSQLWork(TopiaSqlSupport sqlSupport, final String sql) throws TopiaException {
+ sqlSupport.executeSql(sql);
+ }
+
protected String getSequencePropertyName(String sequenceKey) {
int dotIndex = sequenceKey.lastIndexOf(DOT);
return sequenceKey.substring(dotIndex + 1);
Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/Deletor.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/Deletor.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/Deletor.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -1,48 +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%
- */
-
-package org.nuiton.topia.persistence.util;
-
-import org.nuiton.topia.TopiaContext;
-
-/**
- * A simple contract to hook the deletion of an entity.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @param <P> the parent of the entity to delete (if the entity has no parent
- * says is not in a association)
- * of another entity, just used the {@link Void} type).
- * @param <E> the type of the entity to delete.
- */
-public interface Deletor<P, E> {
- /**
- * Hook to delete an entity from a prent entity.
- *
- * @param tx current transaction
- * @param parent the parent of the entity
- * @param from the entity to delete.
- */
- void delete(TopiaContext tx, P parent, E from);
-}
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/TopiaEntityHelper.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/TopiaEntityHelper.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/TopiaEntityHelper.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -28,10 +28,10 @@
import com.google.common.base.Preconditions;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.nuiton.topia.TopiaContext;
import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.framework.TopiaContextImplementor;
-import org.nuiton.topia.persistence.TopiaDAO;
+import org.nuiton.topia.TopiaPersistenceContext;
+import org.nuiton.topia.TopiaReplicationSupport;
+import org.nuiton.topia.persistence.TopiaDao;
import org.nuiton.topia.persistence.TopiaEntity;
import org.nuiton.topia.persistence.TopiaEntityEnum;
import org.nuiton.util.FileUtil;
@@ -104,7 +104,7 @@
* @throws IllegalArgumentException si l'entité n'existe pas.
*/
public static <E extends TopiaEntity> E getExistingEntity(
- TopiaDAO<E> dao, String topiaId) throws TopiaException,
+ TopiaDao<E> dao, String topiaId) throws TopiaException,
IllegalArgumentException {
E entity = dao.findByTopiaId(topiaId);
Preconditions.checkArgument(entity != null,
@@ -168,107 +168,107 @@
"can not update " + bean.getClass() + " here...");
}
- /**
- * Create a new database from a sql dump locating in a gzip file.
- *
- * @param dbDirectory the directory where to create the db
- * @param topiaContext the topiaContext to use to create the databse
- * @param resource the url of the sql dump gzip file to use
- * @throws TopiaException if any pb while creating db
- * @throws IOException if any io exception
- * @throws NullPointerException if parameters are null
- */
- public static void createDBFromSQL(
- File dbDirectory,
- TopiaContext topiaContext,
- URI resource) throws IOException,
- TopiaException, NullPointerException {
- Preconditions.checkNotNull(dbDirectory, dbDirectory + " can not be null");
- Preconditions.checkNotNull(topiaContext, topiaContext + " can not be null");
- Preconditions.checkNotNull(resource, resource + " can not be null");
+// /**
+// * Create a new database from a sql dump locating in a gzip file.
+// *
+// * @param dbDirectory the directory where to create the db
+// * @param topiaContext the topiaContext to use to create the databse
+// * @param resource the url of the sql dump gzip file to use
+// * @throws TopiaException if any pb while creating db
+// * @throws IOException if any io exception
+// * @throws NullPointerException if parameters are null
+// */
+// public static void createDBFromSQL(
+// File dbDirectory,
+// TopiaContext topiaContext,
+// URI resource) throws IOException,
+// TopiaException, NullPointerException {
+// Preconditions.checkNotNull(dbDirectory, dbDirectory + " can not be null");
+// Preconditions.checkNotNull(topiaContext, topiaContext + " can not be null");
+// Preconditions.checkNotNull(resource, resource + " can not be null");
+//
+// File databaseDump;
+// if (resource.isOpaque()) {
+//
+// ByteArrayOutputStream output =
+// FileUtil.readBytesFrom(resource.toURL().openStream(), 8048);
+// File tempFile = File.createTempFile("topiaDumpDatabase", ".sql.gz");
+//
+// FileOutputStream stream = new FileOutputStream(tempFile);
+// try {
+// output.writeTo(stream);
+// } finally {
+// stream.close();
+// }
+//
+// tempFile.deleteOnExit();
+// databaseDump = tempFile;
+//
+// } else {
+//
+// databaseDump = new File(resource);
+// }
+//
+// if (!dbDirectory.exists()) {
+// if (!dbDirectory.mkdirs()) {
+// throw new IOException(
+// "could not create directory " + dbDirectory);
+// }
+// }
+//
+// log.info("create database from [" + databaseDump + "] at [" +
+// dbDirectory + "]");
+//
+// TopiaContext ctxt = topiaContext.beginTransaction();
+//
+// try {
+// ctxt.restore(databaseDump);
+// ctxt.commit();
+// } catch (TopiaException e) {
+// ctxt.rollback();
+// throw e;
+// } finally {
+// ctxt.closeContext();
+// }
+// }
- File databaseDump;
- if (resource.isOpaque()) {
+// /**
+// * Save the given database to a gzip file.
+// *
+// * @param gzipFile the file where to store db
+// * @param topiaContext the topiaContext of the db to store
+// * @throws TopiaException if any pb while saving db
+// * @throws NullPointerException if parameters are null
+// * @throws IOException if could not create gzipFile container
+// * directory
+// */
+// public static void saveDB(
+// File gzipFile, TopiaContext topiaContext)
+// throws TopiaException, IOException, NullPointerException {
+// Preconditions.checkNotNull(gzipFile, gzipFile + " can not be null");
+// Preconditions.checkNotNull(topiaContext, topiaContext + " can not be null");
+//
+// if (!gzipFile.getParentFile().exists()) {
+// if (!gzipFile.getParentFile().mkdirs()) {
+// throw new IOException("could not create directory " +
+// gzipFile.getParentFile());
+// }
+// }
+// log.info("store database to [" + gzipFile + "]");
+//
+// TopiaContext ctxt = null;
+//
+// try {
+// ctxt = topiaContext.beginTransaction();
+// ctxt.backup(gzipFile, true);
+// } finally {
+// if (ctxt != null) {
+// ctxt.closeContext();
+// }
+// }
+// }
- ByteArrayOutputStream output =
- FileUtil.readBytesFrom(resource.toURL().openStream(), 8048);
- File tempFile = File.createTempFile("topiaDumpDatabase", ".sql.gz");
-
- FileOutputStream stream = new FileOutputStream(tempFile);
- try {
- output.writeTo(stream);
- } finally {
- stream.close();
- }
-
- tempFile.deleteOnExit();
- databaseDump = tempFile;
-
- } else {
-
- databaseDump = new File(resource);
- }
-
- if (!dbDirectory.exists()) {
- if (!dbDirectory.mkdirs()) {
- throw new IOException(
- "could not create directory " + dbDirectory);
- }
- }
-
- log.info("create database from [" + databaseDump + "] at [" +
- dbDirectory + "]");
-
- TopiaContext ctxt = topiaContext.beginTransaction();
-
- try {
- ctxt.restore(databaseDump);
- ctxt.commit();
- } catch (TopiaException e) {
- ctxt.rollback();
- throw e;
- } finally {
- ctxt.closeContext();
- }
- }
-
/**
- * Save the given database to a gzip file.
- *
- * @param gzipFile the file where to store db
- * @param topiaContext the topiaContext of the db to store
- * @throws TopiaException if any pb while saving db
- * @throws NullPointerException if parameters are null
- * @throws IOException if could not create gzipFile container
- * directory
- */
- public static void saveDB(
- File gzipFile, TopiaContext topiaContext)
- throws TopiaException, IOException, NullPointerException {
- Preconditions.checkNotNull(gzipFile, gzipFile + " can not be null");
- Preconditions.checkNotNull(topiaContext, topiaContext + " can not be null");
-
- if (!gzipFile.getParentFile().exists()) {
- if (!gzipFile.getParentFile().mkdirs()) {
- throw new IOException("could not create directory " +
- gzipFile.getParentFile());
- }
- }
- log.info("store database to [" + gzipFile + "]");
-
- TopiaContext ctxt = null;
-
- try {
- ctxt = topiaContext.beginTransaction();
- ctxt.backup(gzipFile, true);
- } finally {
- if (ctxt != null) {
- ctxt.closeContext();
- }
- }
- }
-
- /**
* Obtain a new {@link Comparator} pour {@link TopiaEntity} based on the
* {@link TopiaEntity#getTopiaId()} method.
*
@@ -1084,7 +1084,7 @@
@SuppressWarnings({"unchecked"})
public static <E extends TopiaEntity> List<E> getEntities(
- TopiaContextImplementor srcCtxt,
+ TopiaPersistenceContext srcCtxt,
List<E> entityList,
boolean canBeNull) throws TopiaException {
List<E> srcList = new ArrayList<E>(entityList.size());
@@ -1098,7 +1098,7 @@
return srcList;
}
- public static TopiaEntity[] getEntities(TopiaContext srcCtxt,
+ public static TopiaEntity[] getEntities(TopiaPersistenceContext srcCtxt,
String... entityList)
throws TopiaException {
TopiaEntity[] srcList = new TopiaEntity[entityList.length];
@@ -1111,7 +1111,7 @@
}
public static List<? extends TopiaEntity> getEntitiesList(
- TopiaContext srcCtxt,
+ TopiaPersistenceContext srcCtxt,
String... entityList) throws TopiaException {
List<TopiaEntity> srcList = new ArrayList<TopiaEntity>(entityList.length);
for (String id : entityList) {
Copied: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/TopiaH2Util.java (from rev 2800, branches/topia-jpa/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaH2Util.java)
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/TopiaH2Util.java (rev 0)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/TopiaH2Util.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -0,0 +1,155 @@
+/*
+ * #%L
+ * ToPIA :: Persistence
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2004 - 2012 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%
+ */
+package org.nuiton.topia.persistence.util;
+
+import java.io.BufferedInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.InputStream;
+import java.util.zip.GZIPInputStream;
+
+import javax.persistence.Query;
+
+import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.TopiaPersistenceContext;
+import org.nuiton.topia.TopiaSqlSupport;
+import org.nuiton.topia.framework.TopiaFiresSupport;
+
+/**
+ * @author Arnaud Thimel <thimel(a)codelutin.com>
+ */
+public class TopiaH2Util {
+
+ protected TopiaFiresSupport firesSupport;
+ protected TopiaSqlSupport sqlSupport;
+ protected TopiaPersistenceContext persistenceContext;
+
+ public TopiaH2Util(TopiaPersistenceContext persistenceContext, TopiaSqlSupport context, TopiaFiresSupport firesSupport) {
+ this.persistenceContext = persistenceContext;
+ this.sqlSupport = context;
+ this.firesSupport = firesSupport;
+ }
+
+ /**
+ * Backup database in gzip compressed file.
+ *
+ * <b>Note: </b> Only works for h2 database.
+ *
+ * @param file file to write backup
+ * @param compress if true then use gzip to compress file
+ * @see org.nuiton.topia.TopiaContext#backup(java.io.File,boolean)
+ */
+ public void backup(File file, boolean compress) throws TopiaException {
+// context.checkClosed("backup");
+
+ String options = "";
+ if (compress) {
+ options += " COMPRESSION GZIP";
+ }
+
+ sqlSupport.executeSql("SCRIPT TO '" + file.getAbsolutePath() + "'" + options);
+ }
+
+ /**
+ * Read database from gzip compressed file
+ * <p/>
+ * Only work for h2 database
+ *
+ * @see org.nuiton.topia.TopiaContext#restore(java.io.File)
+ */
+ public void restore(File file) throws TopiaException {
+ // send event
+ firesSupport.firePreRestoreSchema(persistenceContext);
+
+ String sql = null;
+ String options = "";
+ try {
+ // decompresse file in temporary file
+ InputStream in = new BufferedInputStream(new FileInputStream(file));
+ try {
+ in.mark(2);
+
+ // read header to see if is compressed file
+ int b = in.read();
+ // redundant cast : int magic = ((int) in.read() << 8) | b;
+ int magic = in.read() << 8 | b;
+ in.reset();
+
+ if (magic == GZIPInputStream.GZIP_MAGIC) {
+ options += " COMPRESSION GZIP";
+ }
+ } finally {
+
+ in.close();
+ }
+
+ sqlSupport.executeSql(
+ "RUNSCRIPT FROM '" + file.getAbsolutePath() + "'" + options);
+
+ // send event AFTER restore
+ firesSupport.firePostRestoreSchema(persistenceContext);
+ } catch (Exception eee) {
+ throw new TopiaH2UtilException(
+ "Unable to restore from file : " + eee.getMessage() + ". " +
+ "SQL is " + sql, eee);
+ }
+ }
+
+// /**
+// * Only h2 supported for now
+// *
+// * @see org.nuiton.topia.TopiaContext#clear(boolean)
+// */
+// public void clear(boolean dropDatabase) throws TopiaException {
+// try {
+// TopiaContextImpl root = (TopiaContextImpl) context.getRootContext();
+// TopiaContextImpl tx = (TopiaContextImpl) root.beginTransaction();
+//
+// String sql = "DROP ALL OBJECTS";
+// if (dropDatabase) {
+// sql += " DELETE FILES";
+// }
+// Query query = tx.getEntityManager().createNativeQuery(sql);
+// query.executeUpdate();
+// tx.closeContext();
+// root.finalize();
+// } catch (Throwable eee) {
+// throw new TopiaH2UtilException(
+// "Unable to perform clear operation : " + eee.getMessage(), eee);
+// }
+// }
+
+ /**
+ * Exception only used within TopiaH2Util
+ */
+ private class TopiaH2UtilException extends TopiaException {
+
+ private static final long serialVersionUID = -7874205136201318340L;
+
+ public TopiaH2UtilException(String message, Throwable cause) {
+ super(message, cause);
+ }
+
+ }
+}
Modified: trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/AbstractTopiaMigrationCallback.java
===================================================================
--- trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/AbstractTopiaMigrationCallback.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/AbstractTopiaMigrationCallback.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -27,8 +27,11 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.jdbc.Work;
-import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.AbstractTopiaApplicationContext;
+import org.nuiton.topia.AbstractTopiaPersistenceContext;
import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.TopiaHibernateSupport;
+import org.nuiton.topia.TopiaPersistenceContext;
import org.nuiton.util.StringUtil;
import org.nuiton.util.Version;
@@ -37,6 +40,8 @@
import java.sql.SQLException;
import java.util.List;
+import com.google.common.base.Preconditions;
+
/**
* Abstract migration callback.
*
@@ -66,7 +71,7 @@
List<Version> versions);
protected abstract void migrateForVersion(Version version,
- TopiaContext tx,
+ TopiaHibernateSupport tx,
boolean showSql,
boolean showProgression) throws Exception;
@@ -83,7 +88,7 @@
* <p/>
* Note: pour chaque version a appliquer, on ouvre une nouvelle transaction.
*
- * @param ctxt topia context de la transaction en cours
+ * @param applicationContext topia context de la transaction en cours
* @param dbVersion database version
* @param showSql drapeau pour afficher les requete sql
* @param showProgression drapeau pour afficher la progression
@@ -91,7 +96,7 @@
* ggrement
* @return {@code true} si la migration est accepté, {@code false} autrement.
*/
- public boolean doMigration(TopiaContext ctxt,
+ public boolean doMigration(AbstractTopiaApplicationContext applicationContext,
Version dbVersion,
boolean showSql,
boolean showProgression,
@@ -107,28 +112,33 @@
// ouverture d'une connexion direct JDBC sur la base
try {
- TopiaContext tx = ctxt.beginTransaction();
+ TopiaPersistenceContext persistenceContext = applicationContext.newPersistenceContext();
+ TopiaHibernateSupport hibernateSupport = null;
+ if (persistenceContext instanceof AbstractTopiaPersistenceContext) {
+ hibernateSupport = ((AbstractTopiaPersistenceContext)persistenceContext).getHibernateSupport();
+ }
+ Preconditions.checkState(hibernateSupport != null);
try {
log.info(String.format("Start migration to version %s", v));
- migrateForVersion(v, tx, showSql, showProgression);
+ migrateForVersion(v, hibernateSupport, showSql, showProgression);
// commit des modifs
- tx.commit();
+ persistenceContext.commit();
} catch (Exception eee) {
// en cas d'erreur
log.error("Could not migrate database", eee);
// rollback du travail en cours
- tx.rollback();
+ persistenceContext.rollback();
// propagation de l'erreur
throw eee;
} finally {
// close database connexion
- if (tx != null) {
- tx.closeContext();
+ if (persistenceContext != null) {
+ persistenceContext.closeContext();
}
}
@@ -142,7 +152,7 @@
return doMigrate;
}
- public void executeSQL(TopiaContext tx, String... sqls)
+ public void executeSQL(TopiaHibernateSupport tx, String... sqls)
throws TopiaException {
executeSQL(tx, false, false, sqls);
}
@@ -157,7 +167,7 @@
* @throws TopiaException if any pb
* @since 2.3.0
*/
- public void executeSQL(TopiaContext tx,
+ public void executeSQL(TopiaHibernateSupport tx,
final boolean showSql,
final boolean showProgression,
final String... sqls) throws TopiaException {
Modified: trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TopiaMigrationCallbackByClass.java
===================================================================
--- trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TopiaMigrationCallbackByClass.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TopiaMigrationCallbackByClass.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -24,8 +24,8 @@
*/
package org.nuiton.topia.migration;
-import org.nuiton.topia.TopiaContext;
import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.TopiaHibernateSupport;
import org.nuiton.util.ObjectUtil;
import org.nuiton.util.Version;
@@ -67,7 +67,7 @@
@Override
protected void migrateForVersion(Version version,
- TopiaContext tx,
+ TopiaHibernateSupport tx,
boolean showSql,
boolean showProgression) throws Exception {
@@ -100,7 +100,7 @@
}
- protected String[] prepareMigration(TopiaContext tx,
+ protected String[] prepareMigration(TopiaHibernateSupport tx,
boolean showSql,
boolean showProgression) throws TopiaException {
@@ -111,17 +111,17 @@
return queries.toArray(new String[queries.size()]);
}
- protected abstract void prepareMigrationScript(TopiaContext tx,
+ protected abstract void prepareMigrationScript(TopiaHibernateSupport tx,
List<String> queries,
boolean showSql,
boolean showProgression) throws TopiaException;
- public void executeSQL(TopiaContext tx,
+ public void executeSQL(TopiaHibernateSupport tx,
String... sqls) throws TopiaException {
callBack.executeSQL(tx, sqls);
}
- public void executeSQL(TopiaContext tx,
+ public void executeSQL(TopiaHibernateSupport tx,
boolean showSql,
boolean showProgression,
String... sqls) throws TopiaException {
Modified: trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TopiaMigrationCallbackByClassNG.java
===================================================================
--- trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TopiaMigrationCallbackByClassNG.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TopiaMigrationCallbackByClassNG.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -26,8 +26,8 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.nuiton.topia.TopiaContext;
import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.TopiaHibernateSupport;
import org.nuiton.util.Version;
import org.nuiton.util.VersionUtil;
@@ -73,7 +73,7 @@
@Override
protected void migrateForVersion(Version version,
- TopiaContext tx,
+ TopiaHibernateSupport tx,
boolean showSql,
boolean showProgression) throws Exception {
@@ -103,7 +103,7 @@
this.callBack = callBack;
}
- protected String[] prepareMigration(TopiaContext tx,
+ protected String[] prepareMigration(TopiaHibernateSupport tx,
boolean showSql,
boolean showProgression) throws TopiaException {
@@ -114,17 +114,17 @@
return queries.toArray(new String[queries.size()]);
}
- protected abstract void prepareMigrationScript(TopiaContext tx,
+ protected abstract void prepareMigrationScript(TopiaHibernateSupport tx,
List<String> queries,
boolean showSql,
boolean showProgression) throws TopiaException;
- public void executeSQL(TopiaContext tx,
+ public void executeSQL(TopiaHibernateSupport tx,
String... sqls) throws TopiaException {
callBack.executeSQL(tx, sqls);
}
- public void executeSQL(TopiaContext tx,
+ public void executeSQL(TopiaHibernateSupport tx,
boolean showSql,
boolean showProgression,
String... sqls) throws TopiaException {
Modified: trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TopiaMigrationCallbackByMethod.java
===================================================================
--- trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TopiaMigrationCallbackByMethod.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TopiaMigrationCallbackByMethod.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -26,7 +26,7 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.TopiaHibernateSupport;
import org.nuiton.util.Version;
import java.lang.reflect.Method;
@@ -51,14 +51,14 @@
@Override
protected void migrateForVersion(Version version,
- TopiaContext tx,
+ TopiaHibernateSupport tx,
boolean showSql,
boolean showProgression) throws Exception {
String methodName = "migrateTo_" + version.getValidName();
Method m = getClass().getMethod(methodName,
- TopiaContext.class,
+ TopiaHibernateSupport.class,
boolean.class,
boolean.class
);
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-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TopiaMigrationEngine.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -26,19 +26,24 @@
package org.nuiton.topia.migration;
import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableMap;
+
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.cfg.Configuration;
-import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.AbstractTopiaApplicationContext;
+import org.nuiton.topia.AbstractTopiaPersistenceContext;
+import org.nuiton.topia.HibernateProvider;
import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.TopiaHibernateSupport;
import org.nuiton.topia.TopiaNotFoundException;
+import org.nuiton.topia.TopiaPersistenceContext;
import org.nuiton.topia.event.TopiaContextAdapter;
import org.nuiton.topia.event.TopiaContextEvent;
-import org.nuiton.topia.event.TopiaContextListener;
+import org.nuiton.topia.event.TopiaSchemaListener;
import org.nuiton.topia.event.TopiaTransactionEvent;
import org.nuiton.topia.event.TopiaTransactionVetoable;
-import org.nuiton.topia.framework.AbstractTopiaContext;
import org.nuiton.topia.framework.TopiaUtil;
import org.nuiton.topia.migration.mappings.TMSVersion;
import org.nuiton.topia.migration.mappings.TMSVersionDAO;
@@ -101,7 +106,7 @@
protected AbstractTopiaMigrationCallback callback;
/** topia root context (initialise en pre-init) */
- protected TopiaContext rootContext;
+ protected AbstractTopiaApplicationContext applicationContext;
/** Un drapeau pour savoir si le service a bien ete initialise (i.e a bien fini la methode preInit) */
protected boolean init;
@@ -120,7 +125,7 @@
protected boolean showProgression;
/** delegate context listener. */
- protected final TopiaContextListener contextListener;
+ protected final TopiaSchemaListener contextListener;
/** delgate transaction listener */
protected final TopiaTransactionVetoable transactionVetoable;
@@ -131,11 +136,11 @@
@Override
public void beginTransaction(TopiaTransactionEvent event) {
- TopiaContext context =
+ TopiaPersistenceContext context =
event.getSource();
// add topia context listener
- context.addTopiaContextListener(contextListener);
+ context.getTopiaFiresSupport().addTopiaSchemaListener(contextListener);
}
};
@@ -194,10 +199,10 @@
}
@Override
- public boolean preInit(TopiaContext context) {
- rootContext = context;
+ public boolean preInit(AbstractTopiaApplicationContext context) {
+ applicationContext = context;
- Properties config = ((AbstractTopiaContext)context).getConfig();
+ Properties config = null; //applicationContext.getConfig();
String callbackStr = getSafeParameter(config, MIGRATION_CALLBACK);
if (log.isDebugEnabled()) {
@@ -223,7 +228,7 @@
Class<?> clazz = Class.forName(callbackStr);
callback = (AbstractTopiaMigrationCallback) clazz.newInstance();
} catch (Exception e) {
- log.error("Could not instanciate CallbackHandler [" + callbackStr + "]", e);
+ log.error("Could not instantiate CallbackHandler [" + callbackStr + "]", e);
}
// creation de la configuration hibernate ne concernant que l'entite Version
@@ -239,7 +244,7 @@
init = true;
// add topia context listener
- context.addTopiaContextListener(contextListener);
+ context.addTopiaSchemaListener(contextListener);
context.addTopiaTransactionVetoable(transactionVetoable);
if (log.isDebugEnabled()) {
@@ -267,7 +272,7 @@
}
@Override
- public boolean postInit(TopiaContext context) {
+ public boolean postInit(AbstractTopiaApplicationContext context) {
// nothing to do in post-init
return true;
}
@@ -374,7 +379,7 @@
}
// perform the migration
- needToMigrate = callback.doMigration(rootContext,
+ needToMigrate = callback.doMigration(applicationContext,
dbVersion,
showSql,
showProgression,
@@ -449,11 +454,16 @@
}
// Set new version in database
- TopiaContext tx = rootContext.beginTransaction();
+ TopiaPersistenceContext tx = applicationContext.newPersistenceContext();
+ TopiaHibernateSupport hibernateSupport = null;
+ if (tx instanceof AbstractTopiaPersistenceContext) {
+ hibernateSupport = ((AbstractTopiaPersistenceContext)tx).getHibernateSupport();
+ }
+ Preconditions.checkState(hibernateSupport != null);
try {
// delete all previous data in table
- TMSVersionDAO.deleteAll(tx);
+ TMSVersionDAO.deleteAll(hibernateSupport);
if (log.isInfoEnabled()) {
log.info(String.format("Saving new database version: %1$s", version));
@@ -461,7 +471,7 @@
// create new version and store it in table
TMSVersion tmsVersion =
- TMSVersionDAO.create(tx, version.getVersion());
+ TMSVersionDAO.create(hibernateSupport, version.getVersion());
if (log.isDebugEnabled()) {
log.debug("Created version: " + tmsVersion.getVersion());
}
@@ -607,10 +617,10 @@
try {
boolean result;
// get db real hibernate configuration
-// Configuration rootConfiguration =
-// rootContext.getHibernateConfiguration();
+ HibernateProvider hibernateProvider =
+ applicationContext.getHibernateProvider();
- result = TopiaUtil.isSchemaEmpty(rootContext);
+ result = TopiaUtil.isSchemaEmpty(hibernateProvider.getHibernateConfiguration());
return result;
} catch (TopiaNotFoundException e) {
throw new RuntimeException(e);
@@ -625,9 +635,14 @@
return null;
}
try {
- TopiaContext tx = rootContext.beginTransaction();
+ TopiaPersistenceContext tx = applicationContext.newPersistenceContext();
+ TopiaHibernateSupport hibernateSupport = null;
+ if (tx instanceof AbstractTopiaPersistenceContext) {
+ hibernateSupport = ((AbstractTopiaPersistenceContext)tx).getHibernateSupport();
+ }
+ Preconditions.checkState(hibernateSupport != null);
try {
- Version v = TMSVersionDAO.getVersion(tx, tableName);
+ Version v = TMSVersionDAO.getVersion(hibernateSupport, tableName);
return v;
} finally {
if (tx != null) {
@@ -657,7 +672,7 @@
* @since 2.5.3
*/
protected Configuration createHibernateConfiguration(Configuration configuration) {
- Properties config = ((AbstractTopiaContext)rootContext).getConfig();
+ ImmutableMap config = applicationContext.getConfiguration();
Properties prop = new Properties();
prop.putAll(configuration.getProperties());
@@ -666,8 +681,6 @@
configuration.setProperties(prop);
configuration.buildMappings();
return configuration;
-
}
-
-}
\ No newline at end of file
+}
Modified: trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/mappings/TMSVersionDAO.java
===================================================================
--- trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/mappings/TMSVersionDAO.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/mappings/TMSVersionDAO.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -32,8 +32,8 @@
import org.hibernate.cfg.Configuration;
import org.hibernate.jdbc.Work;
import org.hibernate.tool.hbm2ddl.SchemaExport;
-import org.nuiton.topia.TopiaContext;
import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.TopiaHibernateSupport;
import org.nuiton.topia.framework.TopiaUtil;
import org.nuiton.util.Version;
import org.nuiton.util.VersionUtil;
@@ -59,7 +59,7 @@
public static final String TABLE_NAME = "tms_version";
- public static TMSVersion get(TopiaContext tx) throws TopiaException {
+ public static TMSVersion get(TopiaHibernateSupport tx) throws TopiaException {
try {
Session session = tx.getHibernateSession();
@@ -86,7 +86,7 @@
schemaExport.drop(log.isDebugEnabled(), true);
}
- public static TMSVersion create(TopiaContext tx, String version) throws TopiaException {
+ public static TMSVersion create(TopiaHibernateSupport tx, String version) throws TopiaException {
try {
Session session = tx.getHibernateSession();
@@ -100,17 +100,17 @@
}
}
- public static void update(TopiaContext tx, TMSVersion version) throws TopiaException {
+ public static void update(TopiaHibernateSupport tx, TMSVersion version) throws TopiaException {
try {
Session session = tx.getHibernateSession();
session.saveOrUpdate(version);
- tx.commit();
+// tx.commit(); // XXX AThimel 25/11/2013 I guess, this has nothing to do here
} catch (HibernateException e) {
throw new TopiaException("Could not update version " + version, e);
}
}
- public static void deleteAll(TopiaContext tx) throws TopiaException {
+ public static void deleteAll(TopiaHibernateSupport tx) throws TopiaException {
try {
Session session = tx.getHibernateSession();
Criteria criteria = session.createCriteria(TMSVersion.class);
@@ -132,7 +132,7 @@
" </class>\n" +
"</hibernate-mapping>";
- public static Version getVersion(TopiaContext tx, String tableName) {
+ public static Version getVersion(TopiaHibernateSupport tx, String tableName) {
try {
Configuration hibernateConfiguration = tx.getHibernateConfiguration();
Modified: trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/TopiaReplicationContext.java
===================================================================
--- trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/TopiaReplicationContext.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/TopiaReplicationContext.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -26,9 +26,11 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.AbstractTopiaApplicationContext;
import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.framework.TopiaContextImplementor;
+import org.nuiton.topia.TopiaPersistenceContext;
+import org.nuiton.topia.TopiaReplicationDestination;
+import org.nuiton.topia.TopiaReplicationSupport;
import org.nuiton.topia.persistence.TopiaEntity;
import org.nuiton.topia.persistence.TopiaEntityEnum;
import org.nuiton.topia.persistence.util.TopiaEntityHelper;
@@ -68,13 +70,13 @@
* root context of incoming data source (says where to obtain entities
* to replicate).
*/
- protected final TopiaContext sourceTx;
+ protected final AbstractTopiaApplicationContext sourceTx;
/**
* root context of outcmoing data source (says where to replicate
* entities).
*/
- protected final TopiaContext targetTx;
+ protected final AbstractTopiaApplicationContext targetTx;
/** dictionnary of data to replicate. */
protected TopiaEntityIdsMap data;
@@ -89,8 +91,8 @@
public TopiaReplicationContext(TopiaReplicationOperationProvider operationProvider,
ReplicationModel replicationModel,
- TopiaContext sourceTx,
- TopiaContext targetTx) {
+ AbstractTopiaApplicationContext sourceTx,
+ AbstractTopiaApplicationContext targetTx) {
this.operationProvider = operationProvider;
this.replicationModel = replicationModel;
this.sourceTx = sourceTx;
@@ -138,7 +140,7 @@
*/
public void init() throws TopiaException {
- TopiaContextImplementor srcCtxt = newSourceTx();
+ TopiaPersistenceContext srcCtxt = newSourceTx();
try {
// obtain all data to replicate
@@ -167,7 +169,7 @@
return nodeEntityIds;
}
- public List<? extends TopiaEntity> getEntities(TopiaContextImplementor tx,
+ public List<? extends TopiaEntity> getEntities(TopiaPersistenceContext tx,
ReplicationNode node) throws TopiaException {
List<String> nodeEntityIds = getEntityIds(node);
@@ -191,15 +193,15 @@
}
- public TopiaContextImplementor newSourceTx() throws TopiaException {
- return (TopiaContextImplementor) sourceTx.beginTransaction();
+ public TopiaPersistenceContext newSourceTx() throws TopiaException {
+ return sourceTx.newPersistenceContext();
}
- public TopiaContextImplementor newTargetTx() throws TopiaException {
- return (TopiaContextImplementor) targetTx.beginTransaction();
+ public TopiaPersistenceContext newTargetTx() throws TopiaException {
+ return targetTx.newPersistenceContext();
}
- public static void close(TopiaContext tx, boolean rollback) throws TopiaException {
+ public static void close(TopiaPersistenceContext tx, boolean rollback) throws TopiaException {
try {
if (rollback) {
@@ -219,7 +221,7 @@
}
}
- protected TopiaEntityIdsMap getIds(TopiaContextImplementor srcCtxt) throws TopiaException {
+ protected TopiaEntityIdsMap getIds(TopiaPersistenceContext srcCtxt) throws TopiaException {
TopiaEntityIdsMap data;
@@ -257,11 +259,11 @@
return treated;
}
- protected TopiaContext getSourceTx() {
+ protected AbstractTopiaApplicationContext getSourceTx() {
return sourceTx;
}
- protected TopiaContext getTargetTx() {
+ protected AbstractTopiaApplicationContext getTargetTx() {
return targetTx;
}
Modified: trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/TopiaReplicationModelBuilder.java
===================================================================
--- trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/TopiaReplicationModelBuilder.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/TopiaReplicationModelBuilder.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -26,8 +26,9 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.AbstractTopiaApplicationContext;
import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.TopiaPersistenceContext;
import org.nuiton.topia.persistence.TopiaEntity;
import org.nuiton.topia.persistence.TopiaEntityEnum;
import org.nuiton.topia.persistence.util.TopiaEntityHelper;
@@ -79,7 +80,7 @@
* @return le modele pour la replication
* @throws TopiaException pour toute erreur rencontree
*/
- public ReplicationModel prepare(TopiaContext context,
+ public ReplicationModel prepare(AbstractTopiaApplicationContext context,
TopiaEntityEnum[] contracts,
boolean computeOrder,
String... topiaIds) throws TopiaException {
@@ -204,7 +205,7 @@
* @return le modèle crée mais non initialisé.
* @throws TopiaException pour toute erreur lors de la création du modèle
*/
- public ReplicationModel createModel(TopiaContext context,
+ public ReplicationModel createModel(AbstractTopiaApplicationContext context,
TopiaEntityEnum[] contracts,
boolean computeOrder,
String... topiaIds)
@@ -254,11 +255,11 @@
return model;
}
- protected Set<Class<? extends TopiaEntity>> detectTypes(TopiaContext context,
+ protected Set<Class<? extends TopiaEntity>> detectTypes(AbstractTopiaApplicationContext context,
TopiaEntityEnum[] contracts,
String... ids) throws TopiaException {
- TopiaContext ctxt = context.beginTransaction();
+ TopiaPersistenceContext ctxt = context.newPersistenceContext();
try {
TopiaEntity[] entities = TopiaEntityHelper.getEntities(ctxt, ids);
Modified: trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/TopiaReplicationOperation.java
===================================================================
--- trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/TopiaReplicationOperation.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/TopiaReplicationOperation.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -25,7 +25,10 @@
package org.nuiton.topia.replication;
-import org.nuiton.topia.framework.TopiaContextImplementor;
+import org.nuiton.topia.TopiaPersistenceContext;
+import org.nuiton.topia.TopiaReplicationDestination;
+import org.nuiton.topia.TopiaReplicationSupport;
+import org.nuiton.topia.TopiaTransaction;
import org.nuiton.topia.persistence.TopiaEntity;
import org.nuiton.topia.persistence.TopiaEntityEnum;
import org.nuiton.topia.replication.model.ReplicationModel;
@@ -88,15 +91,15 @@
*
* @param replicationContext le contexte de replication
* @param operationDef la definition de l'operation a realiser
- * @param srcCtxt le context source
- * @param dstCtxt le context destination
+ * @param source le context source
+ * @param destination le context destination
* @param entities la liste des entités à traiter
* @throws Exception pour toute erreur
*/
void run(TopiaReplicationContext replicationContext,
ReplicationOperationDef operationDef,
- TopiaContextImplementor srcCtxt,
- TopiaContextImplementor dstCtxt,
+ TopiaPersistenceContext source,
+ TopiaPersistenceContext destination,
List<? extends TopiaEntity> entities) throws Exception;
}
Modified: trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/TopiaReplicationOperationUndoable.java
===================================================================
--- trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/TopiaReplicationOperationUndoable.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/TopiaReplicationOperationUndoable.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -25,7 +25,7 @@
package org.nuiton.topia.replication;
-import org.nuiton.topia.framework.TopiaContextImplementor;
+import org.nuiton.topia.TopiaPersistenceContext;
import org.nuiton.topia.replication.model.ReplicationOperationDef;
/**
@@ -51,6 +51,7 @@
*/
void rollback(ReplicationOperationDef operationDef,
TopiaReplicationContext replicationContext,
- TopiaContextImplementor dstCtxt
+ TopiaPersistenceContext dstCtxt
) throws Exception;
+
}
Modified: trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/TopiaReplicationService.java
===================================================================
--- trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/TopiaReplicationService.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/TopiaReplicationService.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -24,8 +24,9 @@
*/
package org.nuiton.topia.replication;
-import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.AbstractTopiaApplicationContext;
import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.TopiaPersistenceContext;
import org.nuiton.topia.framework.TopiaService;
import org.nuiton.topia.persistence.TopiaEntityEnum;
import org.nuiton.topia.replication.model.ReplicationModel;
@@ -42,7 +43,7 @@
* <li> - prepare the replication model - ({@link #prepare(TopiaEntityEnum[], boolean, String...)} - ({@link #prepareForAll(TopiaEntityEnum[])}
* <p/>
* <li> - lanch replication {@link #doReplicate(ReplicationModel,
- * TopiaContext)}
+ * AbstractTopiaApplicationContext)}
*
* @author tchemit <chemit(a)codelutin.com>
* @since 2.2.0
@@ -112,7 +113,7 @@
* @throws Exception pour toute erreur pendant la replication
*/
void doReplicate(ReplicationModel model,
- TopiaContext dstCtxt) throws Exception;
+ AbstractTopiaApplicationContext dstCtxt) throws Exception;
/**
* Pour revenir en arrière lorsque la réplication a échouée .
Modified: trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/TopiaReplicationServiceImpl.java
===================================================================
--- trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/TopiaReplicationServiceImpl.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/TopiaReplicationServiceImpl.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -27,9 +27,11 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.AbstractTopiaApplicationContext;
import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.framework.TopiaContextImplementor;
+import org.nuiton.topia.TopiaPersistenceContext;
+import org.nuiton.topia.TopiaReplicationDestination;
+import org.nuiton.topia.TopiaReplicationSupport;
import org.nuiton.topia.persistence.TopiaEntity;
import org.nuiton.topia.persistence.TopiaEntityEnum;
import org.nuiton.topia.persistence.util.TopiaEntityHelper;
@@ -52,7 +54,7 @@
LogFactory.getLog(TopiaReplicationServiceImpl.class);
/** le contexte sur la base source de la replication */
- protected TopiaContext context;
+ protected AbstractTopiaApplicationContext context;
/**
* le constructeur de modèle de réplication.
@@ -77,13 +79,13 @@
}
@Override
- public boolean preInit(TopiaContext context) {
+ public boolean preInit(AbstractTopiaApplicationContext context) {
// nothing to init
return true;
}
@Override
- public boolean postInit(TopiaContext context) {
+ public boolean postInit(AbstractTopiaApplicationContext context) {
// set the incoming root context from topia
this.context = context;
//TODO avoir un objet pour lire les contrainte de resolution de cycle
@@ -126,7 +128,7 @@
@Override
public void doReplicate(ReplicationModel model,
- TopiaContext targetTx) throws Exception {
+ AbstractTopiaApplicationContext targetTx) throws Exception {
TopiaEntityHelper.checkNotNull("doReplicate", "model", model);
TopiaEntityHelper.checkNotNull("doReplicate", "dstCtxt", targetTx);
@@ -211,12 +213,12 @@
// destination transaction will be opened at the last moment to avoid
// to open it if something was wrong before...
- TopiaContextImplementor dstCtxt = null;
+ TopiaPersistenceContext dstCtxt = null;
// open transaction on source db (to obtain entities to treate).
// this transaction must stay open the time of all operations of the
// node in order to make lazy association loaded by hibernate
- TopiaContextImplementor srcCtxt = replicationContext.newSourceTx();
+ TopiaPersistenceContext srcCtxt = replicationContext.newSourceTx();
try {
log.info("start replication for " + node + " : " + defs.length +
@@ -302,7 +304,7 @@
" reversible operation(s)");
// open transaction on target db
- TopiaContextImplementor dstCtxt = replicationContext.newTargetTx();
+ TopiaPersistenceContext dstCtxt = replicationContext.newTargetTx();
try {
Modified: trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/operation/AttachLink.java
===================================================================
--- trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/operation/AttachLink.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/operation/AttachLink.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -25,10 +25,14 @@
package org.nuiton.topia.replication.operation;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.framework.TopiaContextImplementor;
+import org.nuiton.topia.TopiaPersistenceContext;
import org.nuiton.topia.persistence.TopiaEntity;
import org.nuiton.topia.persistence.util.EntityOperator;
import org.nuiton.topia.persistence.util.TopiaEntityHelper;
@@ -40,10 +44,6 @@
import org.nuiton.topia.replication.model.ReplicationOperationDef;
import org.nuiton.topia.replication.model.ReplicationOperationPhase;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
-
/**
* Pour attacher une association.
* <p/>
@@ -85,8 +85,8 @@
@Override
public void run(TopiaReplicationContext replicationContext,
ReplicationOperationDef operationDef,
- TopiaContextImplementor srcCtxt,
- TopiaContextImplementor dstCtxt,
+ TopiaPersistenceContext srcCtxt,
+ TopiaPersistenceContext dstCtxt,
List<? extends TopiaEntity> nodeEntities
) throws TopiaException {
Modified: trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/operation/DettachAssociation.java
===================================================================
--- trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/operation/DettachAssociation.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/operation/DettachAssociation.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -25,10 +25,12 @@
package org.nuiton.topia.replication.operation;
+import java.util.List;
+
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.framework.TopiaContextImplementor;
+import org.nuiton.topia.TopiaPersistenceContext;
import org.nuiton.topia.persistence.TopiaEntity;
import org.nuiton.topia.persistence.util.EntityOperator;
import org.nuiton.topia.replication.TopiaReplicationContext;
@@ -38,8 +40,6 @@
import org.nuiton.topia.replication.model.ReplicationOperationDef;
import org.nuiton.topia.replication.model.ReplicationOperationPhase;
-import java.util.List;
-
/**
* Pour dettacher une association.
* <p/>
@@ -70,8 +70,8 @@
@Override
public void run(TopiaReplicationContext replicationContext,
ReplicationOperationDef operationDef,
- TopiaContextImplementor srcCtxt,
- TopiaContextImplementor dstCtxt,
+ TopiaPersistenceContext srcCtxt,
+ TopiaPersistenceContext dstCtxt,
List<? extends TopiaEntity> entities
) throws TopiaException {
Modified: trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/operation/Duplicate.java
===================================================================
--- trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/operation/Duplicate.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/operation/Duplicate.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -28,9 +28,10 @@
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.nuiton.topia.AbstractTopiaPersistenceContext;
import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.framework.TopiaContextImplementor;
-import org.nuiton.topia.persistence.TopiaDAO;
+import org.nuiton.topia.TopiaPersistenceContext;
+import org.nuiton.topia.persistence.TopiaDao;
import org.nuiton.topia.persistence.TopiaEntity;
import org.nuiton.topia.replication.TopiaReplicationContext;
import org.nuiton.topia.replication.TopiaReplicationOperationUndoable;
@@ -72,15 +73,17 @@
@Override
public void run(TopiaReplicationContext replicationContext,
ReplicationOperationDef operationDef,
- TopiaContextImplementor srcCtxt,
- TopiaContextImplementor dstCtxt,
+ TopiaPersistenceContext srcCtxt,
+ TopiaPersistenceContext dstCtxt,
List<? extends TopiaEntity> entities) throws TopiaException {
// fix http://nuiton.org/issues/1547
//FIXME tchemit-2011-06-03 : while using hibernate 3.5.6, while duplicating entities we can have some associations in double sessions
//FIXME This hack works but it should be better to resolve the bug :( perharps this is not possible
//FIXME since we can not have a fresh empty hibernate session...
- srcCtxt.getHibernate().clear();
+ if (srcCtxt instanceof AbstractTopiaPersistenceContext) {
+ ((AbstractTopiaPersistenceContext)srcCtxt).getHibernateSupport().getHibernateSession().clear();
+ }
// replication des donnees vers la destination
srcCtxt.replicateEntities(dstCtxt, entities);
@@ -93,7 +96,7 @@
@Override
public void rollback(ReplicationOperationDef operationDef,
TopiaReplicationContext replicationContext,
- TopiaContextImplementor dstCtxt) throws Exception {
+ TopiaPersistenceContext dstCtxt) throws Exception {
List<String> ids =
replicationContext.getEntityIds(operationDef.getNode());
@@ -105,8 +108,8 @@
}
Class<? extends TopiaEntity> entityClass = operationDef.getEntityType();
- TopiaDAO<TopiaEntity> dao =
- (TopiaDAO<TopiaEntity>) dstCtxt.getDao(entityClass);
+ TopiaDao<TopiaEntity> dao =
+ (TopiaDao<TopiaEntity>) dstCtxt.getDao(entityClass);
List<String> allIds = dao.findAllIds();
try {
Modified: trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/operation/LoadLink.java
===================================================================
--- trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/operation/LoadLink.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/operation/LoadLink.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -28,7 +28,7 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.framework.TopiaContextImplementor;
+import org.nuiton.topia.TopiaPersistenceContext;
import org.nuiton.topia.persistence.TopiaEntity;
import org.nuiton.topia.persistence.util.EntityOperator;
import org.nuiton.topia.replication.TopiaReplicationContext;
@@ -69,8 +69,8 @@
@Override
public void run(TopiaReplicationContext replicationContext,
ReplicationOperationDef operationDef,
- TopiaContextImplementor srcCtxt,
- TopiaContextImplementor dstCtxt,
+ TopiaPersistenceContext srcCtxt,
+ TopiaPersistenceContext dstCtxt,
List<? extends TopiaEntity> nodeEntities
) throws TopiaException {
Modified: trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/AbstractTopiaReplicationServiceTest.java
===================================================================
--- trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/AbstractTopiaReplicationServiceTest.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/AbstractTopiaReplicationServiceTest.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -27,10 +27,12 @@
import org.apache.commons.logging.Log;
import org.junit.Assert;
-import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.AbstractTopiaApplicationContext;
+import org.nuiton.topia.TopiaDaoSupplier;
import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.framework.TopiaContextImplementor;
-import org.nuiton.topia.persistence.TopiaDAO;
+import org.nuiton.topia.TopiaPersistenceContext;
+import org.nuiton.topia.it.legacy.TopiaTestTopiaApplicationContext;
+import org.nuiton.topia.persistence.TopiaDao;
import org.nuiton.topia.persistence.TopiaEntity;
import org.nuiton.topia.persistence.TopiaEntityEnum;
import org.nuiton.topia.persistence.util.EntityOperator;
@@ -48,8 +50,11 @@
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
+import java.util.Properties;
import java.util.Set;
+import com.google.common.base.Function;
+
/**
* TopiaReplicationServiceImplTest.
* <p/>
@@ -61,11 +66,11 @@
*/
public abstract class AbstractTopiaReplicationServiceTest extends Assert {
- static protected TopiaContext context;
+ static protected AbstractTopiaApplicationContext sourceContext;
- static protected TopiaContext ctxt;
+ static protected TopiaPersistenceContext sourcePC;
- protected TopiaContextImplementor dstCtxt;
+ protected AbstractTopiaApplicationContext destinationContext;
protected TopiaReplicationService service;
@@ -79,9 +84,16 @@
static private final String TEST_BASEDIR = "target%1$ssurefire-tests%1$s%2$td_%2$tm_%2$tY%1$s%2$tH_%2$tM_%2$tS";
+ protected static final Function<Properties,AbstractTopiaApplicationContext> CREATE_TOPIA_TEST_APPLICATION_CONTEXT = new Function<Properties, AbstractTopiaApplicationContext>() {
+ @Override
+ public AbstractTopiaApplicationContext apply(Properties input) {
+ return new TopiaTestTopiaApplicationContext(input);
+ }
+ };
+
public static void after() throws Exception {
- if (context != null && !context.isClosed()) {
- context.closeContext();
+ if (sourceContext != null && !sourceContext.isClosed()) {
+ sourceContext.closeContext();
}
init = false;
}
@@ -91,7 +103,7 @@
if (!init) {
try {
- context = createDb("source");
+ sourceContext = createDb("source");
} catch (Exception e) {
getLog().error("could not create db source.", e);
throw e;
@@ -99,16 +111,16 @@
init = true;
}
- ctxt = context.beginTransaction();
+ sourcePC = sourceContext.newPersistenceContext();
- service = context.getService(TopiaReplicationService.class);
+ service = (TopiaReplicationService) sourceContext.getService(TopiaReplicationService.class);
}
public void tearDown() throws Exception {
- if (ctxt != null) {
- ctxt.rollback();
- ctxt.closeContext();
- ctxt = null;
+ if (sourcePC != null) {
+ sourcePC.rollback();
+ sourcePC.closeContext();
+ sourcePC = null;
}
service = null;
}
@@ -118,12 +130,12 @@
return service.getModelBuilder();
}
- protected abstract TopiaContext createDb2(String name) throws Exception;
+ protected abstract AbstractTopiaApplicationContext createDb2(String name) throws Exception;
- protected abstract TopiaContext createDb(String name) throws Exception;
+ protected abstract AbstractTopiaApplicationContext createDb(String name) throws Exception;
- protected TopiaContext createReplicateDb(Object contract) throws Exception {
- TopiaContext rootCtxt = createDb2(contract.toString() + dbCounter++);
+ protected AbstractTopiaApplicationContext createReplicateDb(Object contract) throws Exception {
+ AbstractTopiaApplicationContext rootCtxt = createDb2(contract.toString() + dbCounter++);
return rootCtxt;
}
@@ -132,7 +144,7 @@
protected abstract Log getLog();
protected <E extends TopiaEntity> E update(E e) throws TopiaException {
- return (E) ctxt.findByTopiaId(e.getTopiaId());
+ return (E) sourcePC.findByTopiaId(e.getTopiaId());
}
/**
@@ -211,7 +223,7 @@
Set<?> detectTypes;
- detectTypes = service.getModelBuilder().detectTypes(context, getContracts(), entity.getTopiaId());
+ detectTypes = service.getModelBuilder().detectTypes(sourceContext, getContracts(), entity.getTopiaId());
assertEquals("expected types : " +
Arrays.toString(expectedCouple) +
" but was " + detectTypes,
@@ -398,83 +410,81 @@
protected void doReplicate(TopiaEntityEnum contract,
TopiaEntity... entity) throws Exception {
- TopiaContext rootCtxt = createReplicateDb("doReplicate_" + contract);
+ AbstractTopiaApplicationContext rootCtxt = createReplicateDb("doReplicate_" + contract);
List<String> ids = TopiaEntityHelper.getTopiaIdList(Arrays.asList(entity));
getLog().info("entity " + ids);
prepareModel(ids.toArray(new String[ids.size()]));
- dstCtxt = (TopiaContextImplementor) rootCtxt;
+ destinationContext = rootCtxt;
- service.doReplicate(model, dstCtxt);
+ service.doReplicate(model, rootCtxt);
- //dstCtxt.closeContext();
+ //destinationContext.closeContext();
if (entity.length == 0) {
return;
}
- dstCtxt = (TopiaContextImplementor) rootCtxt.beginTransaction();
+ TopiaPersistenceContext destinationPC = rootCtxt.newPersistenceContext();
for (TopiaEntity e : entity) {
- TopiaEntity actual = dstCtxt.findByTopiaId(e.getTopiaId());
+ TopiaEntity actual = destinationPC.findByTopiaId(e.getTopiaId());
assertNotNull(actual);
assertEquals(e, actual);
}
- dstCtxt.closeContext();
+ destinationPC.closeContext();
- dstCtxt = (TopiaContextImplementor) rootCtxt;
+ destinationContext = rootCtxt;
}
protected void doReplicateAll() throws Exception {
- TopiaContext rootCtxt = createReplicateDb("doReplicateAll");
+ AbstractTopiaApplicationContext rootCtxt = createReplicateDb("doReplicateAll");
prepareModelAll();
- dstCtxt = (TopiaContextImplementor) rootCtxt;
+ destinationContext = rootCtxt;
- service.doReplicate(model, dstCtxt);
+ service.doReplicate(model, destinationContext);
- TopiaContextImplementor ctxt2 = (TopiaContextImplementor) ctxt;
- dstCtxt = (TopiaContextImplementor) rootCtxt.beginTransaction();
+ TopiaPersistenceContext destinationPC = rootCtxt.newPersistenceContext();
- assertDbEquals(model.getContracts(), (TopiaContextImplementor) ctxt, ctxt2);
+ assertDbEquals(model.getContracts(), sourcePC, destinationPC);
- dstCtxt.closeContext();
+ destinationPC.closeContext();
- dstCtxt = (TopiaContextImplementor) rootCtxt;
+ destinationContext = rootCtxt;
}
protected void doReplicateWithComputedOrder(TopiaEntity... entity) throws Exception {
- TopiaContext rootCtxt = createReplicateDb("doReplicateWithComputedOrder");
+ AbstractTopiaApplicationContext rootCtxt = createReplicateDb("doReplicateWithComputedOrder");
List<String> ids = TopiaEntityHelper.getTopiaIdList(Arrays.asList(entity));
prepareModelWithComputedOrder(ids.toArray(new String[ids.size()]));
- dstCtxt = (TopiaContextImplementor) rootCtxt;
+ destinationContext = rootCtxt;
- service.doReplicate(model, dstCtxt);
+ service.doReplicate(model, destinationContext);
getLog().info("replication is done for " + Arrays.toString(entity) + ", will verify data...");
- TopiaContextImplementor ctxt2 = (TopiaContextImplementor) ctxt;
- dstCtxt = (TopiaContextImplementor) rootCtxt.beginTransaction();
+ TopiaPersistenceContext destinationPC = rootCtxt.newPersistenceContext();
- assertDbEquals(model.getContracts(), (TopiaContextImplementor) ctxt, ctxt2);
+ assertDbEquals(model.getContracts(), sourcePC, destinationPC);
- dstCtxt.closeContext();
+ destinationPC.closeContext();
- dstCtxt = (TopiaContextImplementor) rootCtxt;
+ destinationContext = rootCtxt;
}
protected void assertDbEquals(TopiaEntityEnum[] contracts,
- TopiaContextImplementor ctxt,
- TopiaContextImplementor ctxt2) throws TopiaException {
+ TopiaDaoSupplier ctxt,
+ TopiaDaoSupplier ctxt2) throws TopiaException {
Set<String> ids = new HashSet<String>();
if (getLog().isInfoEnabled()) {
@@ -484,8 +494,8 @@
if (getLog().isDebugEnabled()) {
getLog().debug("verify for contract " + c);
}
- TopiaDAO<? extends TopiaEntity> daoSrc = ctxt.getDao(c.getContract());
- TopiaDAO<? extends TopiaEntity> daoDst = ctxt2.getDao(c.getContract());
+ TopiaDao<? extends TopiaEntity> daoSrc = ctxt.getDao(c.getContract());
+ TopiaDao<? extends TopiaEntity> daoDst = ctxt2.getDao(c.getContract());
long nbSrc = daoSrc.count();
long nbDst = daoDst.count();
assertEquals("le nombres d'entites de type " + c + " devrait etre " + nbSrc + " mais est " + nbDst, nbSrc, nbDst);
@@ -635,7 +645,7 @@
}
protected void createModel(TopiaEntity entity) throws TopiaException {
- model = getModelBuilder().createModel(context,
+ model = getModelBuilder().createModel(sourceContext,
getContracts(),
true,
entity.getTopiaId()
Modified: trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationOperationTest.java
===================================================================
--- trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationOperationTest.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationOperationTest.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -32,9 +32,9 @@
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
-import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.AbstractTopiaApplicationContext;
import org.nuiton.topia.TopiaContextFactory;
-import org.nuiton.topia.framework.TopiaContextImplementor;
+import org.nuiton.topia.TopiaPersistenceContext;
import org.nuiton.topia.it.TopiaConfigurationHelper;
import org.nuiton.topia.it.legacy.TopiaTestDAOHelper.TopiaTestEntityEnum;
import org.nuiton.topia.it.legacy.test.entities.Person;
@@ -117,8 +117,8 @@
@Override
public void tearDown() throws Exception {
super.tearDown();
- if (dstCtxt != null && !dstCtxt.isClosed()) {
- dstCtxt.closeContext();
+ if (destinationContext != null && !destinationContext.isClosed()) {
+ destinationContext.closeContext();
}
}
@@ -151,28 +151,28 @@
@Test(expected = NullPointerException.class)
public void testCreateOperation_nullType() throws Exception {
- model = getModelBuilder().createModel(context, contracts, true);
+ model = getModelBuilder().createModel(sourceContext, contracts, true);
getModelBuilder().createOperation(model, null, null, null);
}
@Test(expected = NullPointerException.class)
public void testCreateOperation_nullPhase() throws Exception {
- model = getModelBuilder().createModel(context, contracts, true);
+ model = getModelBuilder().createModel(sourceContext, contracts, true);
getModelBuilder().createOperation(model, TopiaTestEntityEnum.Pet, null, null);
}
@Test(expected = NullPointerException.class)
public void testCreateOperation_nullOperationClass() throws Exception {
- model = getModelBuilder().createModel(context, contracts, true);
+ model = getModelBuilder().createModel(sourceContext, contracts, true);
getModelBuilder().createOperation(model, TopiaTestEntityEnum.Pet, ReplicationOperationPhase.before, null);
}
@Test(expected = IllegalArgumentException.class)
public void testCreateOperation_noNode() throws Exception {
- model = getModelBuilder().createModel(context, contracts, true);
+ model = getModelBuilder().createModel(sourceContext, contracts, true);
// le noeud Pet n'existe pas
getModelBuilder().addAfterOperation(model, TopiaTestEntityEnum.Pet, Duplicate.class);
}
@@ -180,7 +180,7 @@
@Test(expected = IllegalArgumentException.class)
public void testCreateOperation_noOperation() throws Exception {
- model = getModelBuilder().createModel(context, contracts, true);
+ model = getModelBuilder().createModel(sourceContext, contracts, true);
// le noeud Pet n'existe pas
getModelBuilder().addAfterOperation(model, TopiaTestEntityEnum.Pet, UnregistredOperation.class);
}
@@ -232,35 +232,35 @@
@Test(expected = IllegalArgumentException.class)
public void testCreateOperation_wrongParameterNumber() throws Exception {
- model = getModelBuilder().createModel(context, contracts, true, pet.getTopiaId());
+ model = getModelBuilder().createModel(sourceContext, contracts, true, pet.getTopiaId());
getModelBuilder().addBeforeOperation(model, TopiaTestEntityEnum.Pet, FakeOperation.class);
}
@Test(expected = IllegalArgumentException.class)
public void testCreateOperation_wrongParameterNumber2() throws Exception {
- model = getModelBuilder().createModel(context, contracts, true, pet.getTopiaId());
+ model = getModelBuilder().createModel(sourceContext, contracts, true, pet.getTopiaId());
getModelBuilder().addBeforeOperation(model, TopiaTestEntityEnum.Pet, FakeOperation.class, String.class, String.class);
}
@Test(expected = IllegalArgumentException.class)
public void testCreateOperation_wrongParameterType() throws Exception {
- model = getModelBuilder().createModel(context, contracts, true, pet.getTopiaId());
+ model = getModelBuilder().createModel(sourceContext, contracts, true, pet.getTopiaId());
getModelBuilder().addBeforeOperation(model, TopiaTestEntityEnum.Pet, FakeOperation.class, Integer.class);
}
@Test(expected = IllegalArgumentException.class)
public void testCreateOperation_nullParameter() throws Exception {
- model = getModelBuilder().createModel(context, contracts, true, pet.getTopiaId());
+ model = getModelBuilder().createModel(sourceContext, contracts, true, pet.getTopiaId());
getModelBuilder().addBeforeOperation(model, TopiaTestEntityEnum.Pet, FakeOperation.class, (Object) null);
}
@Test
public void testCreateOperation() throws Exception {
- model = getModelBuilder().createModel(context, contracts, true, pet.getTopiaId());
+ model = getModelBuilder().createModel(sourceContext, contracts, true, pet.getTopiaId());
getModelBuilder().addBeforeOperation(model, TopiaTestEntityEnum.Pet, FakeOperation.class, "before");
getModelBuilder().addAfterOperation(model, TopiaTestEntityEnum.Race, FakeOperation.class, "after");
}
@@ -274,21 +274,20 @@
@Test(expected = NullPointerException.class)
public void testDoReplicate_nullDstCtxt() throws Exception {
- model = getModelBuilder().createModel(context, contracts, true);
+ model = getModelBuilder().createModel(sourceContext, contracts, true);
service.doReplicate(model, null);
}
@Override
- protected TopiaContext createDb(String name) throws Exception {
+ protected AbstractTopiaApplicationContext createDb(String name) throws Exception {
// File localDB = new File(getTestDir(getClass()), "db_" + name);
Properties config = getH2Properties(name);
- context = TopiaContextFactory.getContext(config);
+ sourceContext = TopiaContextFactory.getContext(config, CREATE_TOPIA_TEST_APPLICATION_CONTEXT);
- TopiaContextImplementor tx =
- (TopiaContextImplementor) context.beginTransaction();
+ TopiaPersistenceContext tx = sourceContext.newPersistenceContext();
person = tx.getDao(Person.class).create(Person.PROPERTY_NAME, "pudding master");
race = tx.getDao(Race.class).create(Race.PROPERTY_NAME, "race I");
@@ -300,7 +299,7 @@
tx.commit();
tx.closeContext();
- return context;
+ return sourceContext;
}
@Override
@@ -333,7 +332,7 @@
}
@Override
- protected TopiaContext createDb2(String name) throws Exception {
+ protected AbstractTopiaApplicationContext createDb2(String name) throws Exception {
throw new UnsupportedOperationException("Not supported yet.");
}
Modified: trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplAllTest.java
===================================================================
--- trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplAllTest.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplAllTest.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -32,10 +32,10 @@
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
-import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.AbstractTopiaApplicationContext;
import org.nuiton.topia.TopiaContextFactory;
import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.framework.TopiaContextImplementor;
+import org.nuiton.topia.TopiaPersistenceContext;
import org.nuiton.topia.it.TopiaConfigurationHelper;
import org.nuiton.topia.it.legacy.test.entities.Person;
import org.nuiton.topia.it.legacy.test.entities.PersonImpl;
@@ -113,8 +113,8 @@
@Override
public void tearDown() throws Exception {
super.tearDown();
- if (dstCtxt != null && !dstCtxt.isClosed()) {
- dstCtxt.closeContext();
+ if (destinationContext != null && !destinationContext.isClosed()) {
+ destinationContext.closeContext();
}
}
@@ -227,15 +227,15 @@
}
@Override
- protected TopiaContext createDb(String name) throws Exception {
+ protected AbstractTopiaApplicationContext createDb(String name) throws Exception {
// File localDB = new File(getTestDir(getClass()), "db_" + name);
Properties config = getH2Properties(name);
- context = TopiaContextFactory.getContext(config);
+ sourceContext = TopiaContextFactory.getContext(config, CREATE_TOPIA_TEST_APPLICATION_CONTEXT);
- TopiaContextImplementor tx = (TopiaContextImplementor) context.beginTransaction();
+ TopiaPersistenceContext tx = sourceContext.newPersistenceContext();
person = tx.getDao(Person.class).create(Person.PROPERTY_NAME, "pudding master");
race = tx.getDao(Race.class).create(Race.PROPERTY_NAME, "race I");
@@ -250,17 +250,17 @@
tx.commit();
tx.closeContext();
- return context;
+ return sourceContext;
}
@Override
- protected TopiaContext createDb2(String name) throws Exception {
+ protected AbstractTopiaApplicationContext createDb2(String name) throws Exception {
// File localDB = new File(getTestDir(getClass()), "db_" + name);
Properties config = getH2Properties(name);
- return TopiaContextFactory.getContext(config);
+ return TopiaContextFactory.getContext(config, CREATE_TOPIA_TEST_APPLICATION_CONTEXT);
}
@Override
Modified: trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplTest.java
===================================================================
--- trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplTest.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplTest.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -32,10 +32,10 @@
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
-import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.AbstractTopiaApplicationContext;
import org.nuiton.topia.TopiaContextFactory;
import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.framework.TopiaContextImplementor;
+import org.nuiton.topia.TopiaPersistenceContext;
import org.nuiton.topia.it.TopiaConfigurationHelper;
import org.nuiton.topia.it.legacy.test.entities.Person;
import org.nuiton.topia.it.legacy.test.entities.PersonImpl;
@@ -114,8 +114,8 @@
@Override
public void tearDown() throws Exception {
super.tearDown();
- if (dstCtxt != null && !dstCtxt.isClosed()) {
- dstCtxt.closeContext();
+ if (destinationContext != null && !destinationContext.isClosed()) {
+ destinationContext.closeContext();
}
}
@@ -252,7 +252,7 @@
/**
* Cette methode montre pourquoi la simple replication ne peut pas
- * fonctionne :)
+ * fonctionner :)
* <p/>
* Le replicateur ne deplique pas dans le bon ordre et on a donc des
* violations de clef etrangeres...
@@ -262,23 +262,23 @@
@Test(expected = TopiaException.class)
public void testSimpleReplicateFailed() throws Exception {
- TopiaContext dstRootCtxt = createDb2("testSimpleReplicateFailed");
+ AbstractTopiaApplicationContext dstRootCtxt = createDb2("testSimpleReplicateFailed");
//model = service.prepare(contracts, pet.getTopiaId());
- TopiaContext srcCtxt = ctxt.beginTransaction();
- dstCtxt = (TopiaContextImplementor) dstRootCtxt.beginTransaction();
+ TopiaPersistenceContext srcCtxt = sourceContext.newPersistenceContext();
+ TopiaPersistenceContext destinationPC = dstRootCtxt.newPersistenceContext();
try {
- srcCtxt.replicateEntity(dstCtxt, pet);
+ srcCtxt.replicateEntity(destinationPC, pet);
- dstCtxt.commit();
+ destinationPC.commit();
} finally {
srcCtxt.rollback();
srcCtxt.closeContext();
- dstCtxt.closeContext();
+ destinationPC.closeContext();
}
}
@@ -294,38 +294,38 @@
@Test
public void testSimpleReplicateNotSure() throws Exception {
- TopiaContext dstRootCtxt = createDb2("testSimpleReplicateNotSure");
+ AbstractTopiaApplicationContext dstRootCtxt = createDb2("testSimpleReplicateNotSure");
//model = service.prepare(contracts, pet.getTopiaId());
- TopiaContext srcCtxt = ctxt;
- dstCtxt = (TopiaContextImplementor) dstRootCtxt.beginTransaction();
+ TopiaPersistenceContext srcCtxt = sourcePC;
+ TopiaPersistenceContext destinationPC = dstRootCtxt.newPersistenceContext();
try {
- srcCtxt.replicateEntity(dstCtxt, race);
+ srcCtxt.replicateEntity(destinationPC, race);
// on dettache l'entite qui pose probleme
pet.setPerson(null);
- srcCtxt.replicateEntity(dstCtxt, pet);
+ srcCtxt.replicateEntity(destinationPC, pet);
srcCtxt.rollback();
- srcCtxt.replicateEntity(dstCtxt, person);
+ srcCtxt.replicateEntity(destinationPC, person);
- dstCtxt.commit();
- ((Pet) dstCtxt.findByTopiaId(pet.getTopiaId())).setPerson((Person) dstCtxt.findByTopiaId(person.getTopiaId()));
- dstCtxt.commit();
+ destinationPC.commit();
+ ((Pet) destinationPC.findByTopiaId(pet.getTopiaId())).setPerson((Person) destinationPC.findByTopiaId(person.getTopiaId()));
+ destinationPC.commit();
srcCtxt.rollback();
person = update(person);
- assertEntityEquals(person, dstCtxt.findByTopiaId(person.getTopiaId()), null);
+ assertEntityEquals(person, destinationPC.findByTopiaId(person.getTopiaId()), null);
} finally {
srcCtxt.rollback();
//srcCtxt.closeContext();
- dstCtxt.closeContext();
+ destinationPC.closeContext();
}
}
@@ -347,54 +347,54 @@
@Test
public void testSimpleReplicateSure() throws Exception {
- TopiaContext dstRootCtxt = createDb2("testSimpleReplicateSure");
+ AbstractTopiaApplicationContext dstRootCtxt = createDb2("testSimpleReplicateSure");
//model = service.prepare(contracts, pet.getTopiaId());
- TopiaContext srcCtxt = ctxt;
- dstCtxt = (TopiaContextImplementor) dstRootCtxt.beginTransaction();
+ TopiaPersistenceContext srcCtxt = sourcePC;
+ TopiaPersistenceContext destinationPC = dstRootCtxt.newPersistenceContext();
try {
- srcCtxt.replicateEntity(dstCtxt, race);
+ srcCtxt.replicateEntity(destinationPC, race);
// on dettache l'association qui pose probleme
person.setPet(null);
- srcCtxt.replicateEntity(dstCtxt, person);
+ srcCtxt.replicateEntity(destinationPC, person);
- srcCtxt.replicateEntity(dstCtxt, pet);
+ srcCtxt.replicateEntity(destinationPC, pet);
srcCtxt.rollback();
- dstCtxt.commit();
+ destinationPC.commit();
- //((Person) dstCtxt.findByTopiaId(person.getTopiaId())).addPet(((Pet) dstCtxt.findByTopiaId(pet.getTopiaId())));
- //dstCtxt.commit();
+ //((Person) destinationContext.findByTopiaId(person.getTopiaId())).addPet(((Pet) destinationContext.findByTopiaId(pet.getTopiaId())));
+ //destinationContext.commit();
srcCtxt.rollback();
srcCtxt.closeContext();
- dstCtxt.closeContext();
+ destinationPC.closeContext();
- ctxt = context.beginTransaction();
- dstCtxt = (TopiaContextImplementor) dstRootCtxt.beginTransaction();
+ sourcePC = sourceContext.newPersistenceContext();
+ destinationPC = dstRootCtxt.newPersistenceContext();
person = update(person);
- assertEntityEquals(person, dstCtxt.findByTopiaId(person.getTopiaId()), null);
+ assertEntityEquals(person, destinationPC.findByTopiaId(person.getTopiaId()), null);
} finally {
- dstCtxt.closeContext();
+ destinationPC.closeContext();
}
}
@Override
- protected TopiaContext createDb(String name) throws Exception {
+ protected AbstractTopiaApplicationContext createDb(String name) throws Exception {
// File localDB = new File(getTestDir(getClass()), "db_" + name);
Properties config = getH2Properties(name);
- context = TopiaContextFactory.getContext(config);
+ sourceContext = TopiaContextFactory.getContext(config, CREATE_TOPIA_TEST_APPLICATION_CONTEXT);
- TopiaContextImplementor tx = (TopiaContextImplementor) context.beginTransaction();
+ TopiaPersistenceContext tx = sourceContext.newPersistenceContext();
person = tx.getDao(Person.class).create(Person.PROPERTY_NAME, "pudding master");
race = tx.getDao(Race.class).create(Race.PROPERTY_NAME, "race I");
@@ -409,11 +409,11 @@
tx.commit();
tx.closeContext();
- return context;
+ return sourceContext;
}
@Override
- protected TopiaContext createDb2(String name) throws Exception {
+ protected AbstractTopiaApplicationContext createDb2(String name) throws Exception {
// File localDB = new File(getTestDir(getClass()), "db_" + name);
//
@@ -421,7 +421,7 @@
Properties config = getH2Properties(name);
- return TopiaContextFactory.getContext(config);
+ return TopiaContextFactory.getContext(config, CREATE_TOPIA_TEST_APPLICATION_CONTEXT);
}
@Override
Modified: trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/operation/FakeOperation.java
===================================================================
--- trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/operation/FakeOperation.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/operation/FakeOperation.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -26,7 +26,7 @@
package org.nuiton.topia.replication.operation;
import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.framework.TopiaContextImplementor;
+import org.nuiton.topia.TopiaPersistenceContext;
import org.nuiton.topia.persistence.TopiaEntity;
import org.nuiton.topia.persistence.util.TopiaEntityHelper;
import org.nuiton.topia.replication.TopiaReplicationContext;
@@ -66,8 +66,8 @@
@Override
public void run(TopiaReplicationContext replicationContext,
ReplicationOperationDef operationDef,
- TopiaContextImplementor srcCtxt,
- TopiaContextImplementor dstCtxt,
+ TopiaPersistenceContext srcCtxt,
+ TopiaPersistenceContext dstCtxt,
List<? extends TopiaEntity> nodeEntities
)
throws TopiaException {
Modified: trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/operation/UncreatableOperation.java
===================================================================
--- trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/operation/UncreatableOperation.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/operation/UncreatableOperation.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -26,7 +26,7 @@
package org.nuiton.topia.replication.operation;
import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.framework.TopiaContextImplementor;
+import org.nuiton.topia.TopiaPersistenceContext;
import org.nuiton.topia.persistence.TopiaEntity;
import org.nuiton.topia.replication.TopiaReplicationContext;
import org.nuiton.topia.replication.TopiaReplicationOperation;
@@ -57,8 +57,8 @@
@Override
public void run(TopiaReplicationContext replicationContext,
ReplicationOperationDef operationDef,
- TopiaContextImplementor srcCtxt,
- TopiaContextImplementor dstCtxt,
+ TopiaPersistenceContext srcCtxt,
+ TopiaPersistenceContext dstCtxt,
List<? extends TopiaEntity> nodeEntities
)
throws TopiaException {
Modified: trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/operation/UnregistredOperation.java
===================================================================
--- trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/operation/UnregistredOperation.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/operation/UnregistredOperation.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -26,7 +26,7 @@
package org.nuiton.topia.replication.operation;
import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.framework.TopiaContextImplementor;
+import org.nuiton.topia.TopiaPersistenceContext;
import org.nuiton.topia.persistence.TopiaEntity;
import org.nuiton.topia.replication.TopiaReplicationContext;
import org.nuiton.topia.replication.TopiaReplicationOperation;
@@ -55,8 +55,8 @@
public void run(
TopiaReplicationContext replicationContext,
ReplicationOperationDef operationDef,
- TopiaContextImplementor srcCtxt,
- TopiaContextImplementor dstCtxt,
+ TopiaPersistenceContext srcCtxt,
+ TopiaPersistenceContext dstCtxt,
List<? extends TopiaEntity> nodeEntities
)
throws TopiaException {
Modified: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/DAOHelperTransformer.java
===================================================================
--- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/DAOHelperTransformer.java 2013-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/DAOHelperTransformer.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -37,10 +37,9 @@
import org.nuiton.eugene.models.object.ObjectModelType;
import org.nuiton.eugene.models.object.xml.ObjectModelAttributeImpl;
import org.nuiton.eugene.models.object.xml.ObjectModelEnumerationImpl;
-import org.nuiton.topia.TopiaContext;
import org.nuiton.topia.TopiaDaoSupplier;
import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.persistence.TopiaDAO;
+import org.nuiton.topia.persistence.TopiaDao;
import org.nuiton.topia.persistence.TopiaEntity;
import org.nuiton.topia.persistence.TopiaEntityEnum;
import org.nuiton.topia.persistence.util.EntityOperator;
@@ -143,9 +142,9 @@
String modelName = model.getName();
String modelVersion = model.getVersion();
- addImport(daoHelper, TopiaDAO.class);
+ addImport(daoHelper, TopiaDao.class);
addImport(daoHelper, TopiaEntity.class);
- addImport(daoHelper, TopiaContext.class);
+ addImport(daoHelper, TopiaDaoSupplier.class);
addImport(daoHelper, Array.class);
if (generateOperator) {
@@ -180,57 +179,46 @@
for (ObjectModelClass clazz : classes) {
- String clazzName = clazz.getName();
- String daoClazzName = clazzName + "DAO";
+ String className = clazz.getName();
+ String concreteDaoClassName = TopiaGeneratorUtil.getConcreteDaoName(clazz);
- // specialized getXXXDao method
- op = addOperation(daoHelper, "get" + daoClazzName, clazz.getPackageName() + '.' + daoClazzName, ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
+ // specialized getXxxDao method
+ String concreteDaoFqn = TopiaGeneratorUtil.getConcreteDaoFqn(clazz);
+ String methodName = "get" + concreteDaoClassName;
+ op = addOperation(daoHelper, methodName, concreteDaoFqn, ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
addParameter(op, TopiaDaoSupplier.class, "supplier");
addImport(daoHelper, clazz);
addException(op, TopiaException.class);
setOperationBody(op, ""
/*{
- <%=daoClazzName%> result = supplier.getDao(<%=clazzName%>.class, <%=daoClazzName%>.class);
+ <%=concreteDaoClassName%> result = supplier.getDao(<%=className%>.class, <%=concreteDaoClassName%>.class);
return result;
}*/
);
}
- // obsolete generic getDAO method
- op = addOperation(daoHelper, "getDAO", "<T extends TopiaEntity, D extends TopiaDAO<? super T>> D", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
- addParameter(op, TopiaContext.class, "context");
- addParameter(op, "Class<T>", "klass");
- addException(op, TopiaException.class);
- addAnnotation(daoHelper, op, Deprecated.class);
- setOperationBody(op, ""
-/*{
- D dao = getDao(context, klass);
- return dao;
- }*/
- );
-
// generic getDao method
- op = addOperation(daoHelper, "getDao", "<T extends TopiaEntity, D extends TopiaDAO<? super T>> D", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
- addParameter(op, TopiaContext.class, "context");
+ op = addOperation(daoHelper, "getDao", "<T extends TopiaEntity, D extends TopiaDao<? super T>> D", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
+ addParameter(op, TopiaDaoSupplier.class, "daoSupplier");
addParameter(op, "Class<T>", "klass");
addException(op, TopiaException.class);
setOperationBody(op, ""
/*{
<%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass);
- D dao = (D) context.getDao(constant.getContract());
+ D dao = (D) daoSupplier.getDao(constant.getContract());
return dao;
}*/
);
- op = addOperation(daoHelper, "getDao", "<T extends TopiaEntity, D extends TopiaDAO<? super T>> D", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
- addParameter(op, TopiaContext.class, "context");
+ op = addOperation(daoHelper, "getDao", "<T extends TopiaEntity, D extends TopiaDao<? super T>> D", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
+ addParameter(op, TopiaDaoSupplier.class, "daoSupplier");
addParameter(op, "T", "entity");
addException(op, TopiaException.class);
setOperationBody(op, ""
/*{
<%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(entity);
- D dao = (D) context.getDao(constant.getContract());
+ D dao = (D) daoSupplier.getDao(constant.getContract());
return dao;
}*/
);
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-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityDaoTransformer.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -223,9 +223,9 @@
generateAbstractDao(clazz, clazzName, clazzFQN);
}
- if (isGenerateLegacyDao(clazz)) {
- generateLegacyDao(clazz, clazzName, clazzFQN);
- }
+// if (isGenerateLegacyDao(clazz)) {
+// generateLegacyDao(clazz, clazzName, clazzFQN);
+// }
if (isGenerateConcreteDao(clazz)) {
generateConcreteDao(clazz, clazzName, clazzFQN);
@@ -233,20 +233,20 @@
}
- protected boolean isGenerateLegacyDao(ObjectModelClass input) {
+// protected boolean isGenerateLegacyDao(ObjectModelClass input) {
+//
+// String daoLegacyFqn = TopiaGeneratorUtil.getLegacyDaoFqn(input);
+//
+// if (isInClassPath(daoLegacyFqn)) {
+//
+// // already in class-path
+// return false;
+// }
+//
+// // can safely generate the dao impl
+// return true;
+// }
- String daoLegacyFqn = TopiaGeneratorUtil.getLegacyDaoFqn(input);
-
- if (isInClassPath(daoLegacyFqn)) {
-
- // already in class-path
- return false;
- }
-
- // can safely generate the dao impl
- return true;
- }
-
protected boolean isGenerateConcreteDao(ObjectModelClass input) {
String daoConcreteFqn = TopiaGeneratorUtil.getConcreteDaoFqn(input);
@@ -300,16 +300,16 @@
}
- protected void generateLegacyDao(ObjectModelClass clazz, String clazzName, String clazzFQN) {
- ObjectModelClass daoClass = createClass(TopiaGeneratorUtil.getLegacyDaoName(clazz), clazz.getPackageName());
- addAnnotation(daoClass, daoClass, Deprecated.class);
- setDocumentation(daoClass, "/**\n" +
- " * Cette classe etend le DAOImpl pour parametrer la classe avec le bon type\n" +
- " * Cette classe est marque finale car l'heritage entre les DAO se fait\n" +
- " * sur les DOAImpl, c-a-d que DAOAbstract peut etendre le DAOImpl\n" +
- " */");
- setSuperClass(daoClass, TopiaGeneratorUtil.getAbstractDaoFqn(clazz) + "<" + clazzName + ">");
- }
+// protected void generateLegacyDao(ObjectModelClass clazz, String clazzName, String clazzFQN) {
+// ObjectModelClass daoClass = createClass(TopiaGeneratorUtil.getLegacyDaoName(clazz), clazz.getPackageName());
+// addAnnotation(daoClass, daoClass, Deprecated.class);
+// setDocumentation(daoClass, "/**\n" +
+// " * Cette classe etend le DAOImpl pour parametrer la classe avec le bon type\n" +
+// " * Cette classe est marque finale car l'heritage entre les DAO se fait\n" +
+// " * sur les DOAImpl, c-a-d que DAOAbstract peut etendre le DAOImpl\n" +
+// " */");
+// setSuperClass(daoClass, TopiaGeneratorUtil.getAbstractDaoFqn(clazz) + "<" + clazzName + ">");
+// }
protected void generateConcreteDao(ObjectModelClass clazz, String clazzName, String clazzFQN) {
String concreteDaoName = TopiaGeneratorUtil.getConcreteDaoName(clazz);
@@ -319,10 +319,8 @@
" * Cette classe est marque finale car l'heritage entre les DAO se fait\n" +
" * sur les DOAImpl, c-a-d que DAOAbstract peut etendre le DAOImpl\n" +
" */");
- // to support legacy dao
- String superclassQualifiedName = TopiaGeneratorUtil.getLegacyDaoFqn(clazz);
- // TODO brendan 04/10/13 above line should be replaced by
-// String superclassQualifiedName = TopiaGeneratorUtil.getAbstractDaoFqn(clazz) + "<" + clazzName + ">";
+
+ String superclassQualifiedName = TopiaGeneratorUtil.getAbstractDaoFqn(clazz) + "<" + clazzName + ">";
setSuperClass(daoClass, superclassQualifiedName);
// TODO AThimel 25/10/13 Remove the next lines in ToPIA 3.1
@@ -723,6 +721,7 @@
for (ObjectModelClass usageClass : usagesForclass) {
String usageType = usageClass.getQualifiedName();
builder.addImport(result, usageType);
+ builder.addImport(result, TopiaGeneratorUtil.getConcreteDaoFqn(usageClass));
String usageSimpleType =
TopiaGeneratorUtil.getClassNameFromQualifiedName(usageType);
String usageSimplePropertyMethod = "findAllBy" + usageSimpleType;
@@ -762,7 +761,7 @@
} else {
methodName = getJavaBeanMethodName("findAllBy", attrName);
}
- String daoName = StringUtils.capitalize(usageSimpleType) + "DAO";
+ String daoName = TopiaGeneratorUtil.getConcreteDaoName(usageClass);
builder.addImport(result, usageClass.getPackageName() + '.' + daoName);
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-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaGeneratorUtil.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -44,7 +44,6 @@
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.TopiaDAOImpl;
import java.util.ArrayList;
import java.util.Arrays;
@@ -219,10 +218,10 @@
return input.getPackageName() + "." + getConcreteDaoName(input);
}
- @Deprecated
- public static String getLegacyDaoFqn(ObjectModelClass input) {
- return input.getPackageName() + "." + getLegacyDaoName(input);
- }
+// @Deprecated
+// public static String getLegacyDaoFqn(ObjectModelClass input) {
+// return input.getPackageName() + "." + getLegacyDaoName(input);
+// }
public static String getEntityPackage(ObjectModelTransformerToJava transformer,
ObjectModel model,
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-11-22 21:50:19 UTC (rev 2891)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaTagValues.java 2013-11-25 15:28:01 UTC (rev 2892)
@@ -30,7 +30,6 @@
import org.nuiton.eugene.models.object.ObjectModelClass;
import org.nuiton.eugene.models.object.ObjectModelClassifier;
import org.nuiton.eugene.models.object.ObjectModelElement;
-import org.nuiton.topia.TopiaContext;
import org.nuiton.topia.persistence.TopiaEntityContextable;
import org.nuiton.topia.persistence.TopiaEntityEnum;
1
0
r2891 - in trunk: src/site/rst topia-persistence/src/main/java/org/nuiton/topia topia-persistence/src/main/java/org/nuiton/topia/framework
by tchemit@users.nuiton.org Nov. 22, 2013
by tchemit@users.nuiton.org Nov. 22, 2013
Nov. 22, 2013
Author: tchemit
Date: 2013-11-22 22:50:19 +0100 (Fri, 22 Nov 2013)
New Revision: 2891
Url: http://nuiton.org/projects/topia/repository/revisions/2891
Log:
fixes #2926: Improve Sql APIs
update migration guide
Added:
trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaSqlQuery.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaSqlWork.java
Removed:
trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaSQLQuery.java
Modified:
trunk/src/site/rst/migrate_to_3.0.rst
trunk/topia-persistence/src/main/java/org/nuiton/topia/HibernateTopiaSqlSupport.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaSqlSupport.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/AbstractTopiaContext.java
Modified: trunk/src/site/rst/migrate_to_3.0.rst
===================================================================
--- trunk/src/site/rst/migrate_to_3.0.rst 2013-11-22 21:20:24 UTC (rev 2890)
+++ trunk/src/site/rst/migrate_to_3.0.rst 2013-11-22 21:50:19 UTC (rev 2891)
@@ -49,6 +49,8 @@
Gérer les impacts n'est pas *nécessaire* pour passer à ToPIA 3.0, mais c'est fortement recommandé. En effet, ce code
deviendra incompatible avec ToPIA 3.1, gérer les impacts au plus tôt permettra une migration en douceur.
+Pas vrai, à partir de la 3.0-alpha-6, on casse la rétro-compatibilité car sinon
+c'est trop compliqué à gérer.
Propriétés TOPIA_*
------------------
@@ -218,9 +220,31 @@
méthodes les remplacer. S'il n'y pas de documentation, il faut remplacer le code appellant par le corps de la méthode dépréciée
(fonctionnalité « inline » dans l'IDE).
+Utilisation des templates de générations
+----------------------------------------
+Les templates sont contenues dans un modules à part, il faut désormais utiliser
+cette dépendance dans le plugin eugene.
+::
+ <dependency>
+ <groupId>org.nuiton.topia</groupId>
+ <artifactId>topia-templates</artifactId>
+ <version>3.0</version>
+ </dependency>
+De plus les templates ont changé de paquetage, le nouveau paquetage est le suivant :
+
+::
+
+ org.nuiton.topia.templates
+
+Amélioration du code sql
+------------------------
+
+Voir TopiaSqlQuery, TopiaSqlWork et TopiaSqlSupport.
+
+
.. |RECOMMENDED| image:: recommended.png
.. |MANDATORY| image:: mandatory.png
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/HibernateTopiaSqlSupport.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/HibernateTopiaSqlSupport.java 2013-11-22 21:20:24 UTC (rev 2890)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/HibernateTopiaSqlSupport.java 2013-11-22 21:50:19 UTC (rev 2891)
@@ -24,13 +24,16 @@
* #L%
*/
+import org.hibernate.HibernateException;
+import org.hibernate.jdbc.Work;
+
import java.sql.Connection;
import java.sql.PreparedStatement;
+import java.sql.ResultSet;
import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.List;
-import org.hibernate.HibernateException;
-import org.hibernate.jdbc.Work;
-
/**
* @author Arnaud Thimel <thimel(a)codelutin.com>
*/
@@ -42,16 +45,6 @@
this.hibernateSupport = hibernateSupport;
}
- @Override
- public void executeSQL(String sqlScript) {
- SQLWork sqlWork = new SQLWork(sqlScript);
- try {
- hibernateSupport.getHibernateSession().doWork(sqlWork);
- } catch (HibernateException e) {
- throw new TopiaException("Could not execute sql code", e);
- }
- }
-
public static class SQLWork implements Work {
private final String script;
@@ -70,4 +63,105 @@
}
}
+ public static class TopiaSQLWorkWork implements Work {
+
+ final TopiaSqlWork work;
+
+ public TopiaSQLWorkWork(TopiaSqlWork work) {
+ this.work = work;
+ }
+
+ @Override
+ public void execute(Connection connection) throws SQLException {
+ work.execute(connection);
+ }
+ }
+
+ public static class TopiaSQLQueryWork<O> implements Work {
+
+ final TopiaSqlQuery<O> query;
+
+ final boolean multipleResult;
+
+ final List<O> result = new ArrayList<O>();
+
+ public TopiaSQLQueryWork(TopiaSqlQuery<O> query, boolean multipleResult) {
+ this.query = query;
+ this.multipleResult = multipleResult;
+ }
+
+ @Override
+ public void execute(Connection connection) throws SQLException {
+
+ PreparedStatement ps = query.prepareQuery(connection);
+ try {
+ ResultSet set = ps.executeQuery();
+
+ query.afterExecuteQuery(set);
+
+ if (set.next()) {
+ O singleResult = query.prepareResult(set);
+ if (singleResult != null) {
+ result.add(singleResult);
+ }
+ if (multipleResult) {
+ while (set.next()) {
+ singleResult = query.prepareResult(set);
+ if (singleResult != null) {
+ result.add(singleResult);
+ }
+ }
+ }
+ }
+
+ } catch (Exception e) {
+ throw new TopiaException("Could not execute query", e);
+ } finally {
+ ps.close();
+ }
+ }
+
+ public List<O> getResult() {
+ return result;
+ }
+ }
+
+ @Override
+ public void executeSQL(String sqlScript) {
+ SQLWork work = new SQLWork(sqlScript);
+ try {
+ hibernateSupport.getHibernateSession().doWork(work);
+ } catch (HibernateException e) {
+ throw new TopiaException("Could not execute sql code", e);
+ }
+ }
+
+ @Override
+ public void doSQLWork(TopiaSqlWork sqlWork) {
+ TopiaSQLWorkWork work = new TopiaSQLWorkWork(sqlWork);
+ try {
+ hibernateSupport.getHibernateSession().doWork(work);
+ } catch (HibernateException e) {
+ throw new TopiaException("Could not execute sql code", e);
+ }
+ }
+
+ @Override
+ public <O> O findSingleResult(final TopiaSqlQuery<O> query) throws TopiaException {
+
+ TopiaSQLQueryWork<O> work = new TopiaSQLQueryWork<O>(query, false);
+ hibernateSupport.getHibernateSession().doWork(work);
+ final List<O> result = work.getResult();
+ return result.isEmpty() ? null : result.get(0);
+ }
+
+ @Override
+ public <O> List<O> findMultipleResult(final TopiaSqlQuery<O> query) throws TopiaException {
+
+ TopiaSQLQueryWork<O> work = new TopiaSQLQueryWork<O>(query, true);
+ hibernateSupport.getHibernateSession().doWork(work);
+ final List<O> result = work.getResult();
+ return result;
+ }
+
}
Copied: trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaSqlQuery.java (from rev 2886, trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaSQLQuery.java)
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaSqlQuery.java (rev 0)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaSqlQuery.java 2013-11-22 21:50:19 UTC (rev 2891)
@@ -0,0 +1,142 @@
+/*
+ * #%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%
+ */
+package org.nuiton.topia;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.ResultSetMetaData;
+import java.sql.SQLException;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * Wrap a Sql query some object.
+ *
+ * Implements the {@link #prepareResult(ResultSet)} to transforma result set
+ * row to an object.
+ *
+ * You can also do some stuff on the result set just after the query was
+ * executed using method {@link #afterExecuteQuery(ResultSet)}.
+ *
+ * @param <O> the type of result data
+ * @since 2.5
+ */
+public abstract class TopiaSqlQuery<O> {
+
+ /**
+ * Prepare the statement used to do the sql query.
+ *
+ * @param connection jdbc connection to use
+ * @return the statement containing the query to execute
+ * @throws SQLException if any problem
+ */
+ protected abstract PreparedStatement prepareQuery(Connection connection) throws SQLException;
+
+ /**
+ * given a result set, extract the data.
+ *
+ * @param set the result set
+ * @return the data extracted from the current set, or {@code null}
+ * @throws SQLException if any prob
+ */
+ protected abstract O prepareResult(ResultSet set) throws SQLException;
+
+ /**
+ * A hook to obtain the result set just after the query execute.
+ *
+ * @param set the result set just obtained
+ * @throws SQLException if any prob
+ * @since 2.6.4
+ */
+ protected void afterExecuteQuery(ResultSet set) throws SQLException {
+ // by default do nothing
+ }
+
+ /**
+ * Obtain the column names of a given result set using his metadata.
+ *
+ * @param set the result set to inspect
+ * @return the column names of the result set
+ * @throws SQLException if any pb
+ * @since 2.6.4
+ */
+ protected String[] getColumnNames(ResultSet set) throws SQLException {
+ ResultSetMetaData metaData = set.getMetaData();
+ int columnCount = metaData.getColumnCount();
+ String[] result = new String[columnCount];
+ for (int i = 0; i < columnCount; i++) {
+ result[i] = metaData.getColumnName(i + 1);
+ }
+ return result;
+ }
+
+ /**
+ * From a given result set, let's count his number of row.
+ * <p/>
+ * <strong>Note:</strong> the result set must be scrollable to go back to
+ * before first row.
+ *
+ * @param set the result set to inspect
+ * @return the number of row of the given result set
+ * @throws SQLException if any pb
+ * @since 2.6.4
+ */
+ protected long getNbRows(ResultSet set) throws SQLException {
+
+ //FIXME tchemit-2012-11-22 use set.last()
+ long nbRows = 0;
+ while (set.next()) {
+ nbRows++;
+ }
+ // go back before first row (be ware the resultset must be scrollable)
+ set.beforeFirst();
+ return nbRows;
+ }
+
+ /**
+ * Given the column names of the result set, transform the row of the
+ * result set to a map with column name as key.
+ *
+ * @param columnNames column names of the result set
+ * @param set the set to inspect
+ * @return the map for the given row of the result set
+ * @throws SQLException if any pb
+ * @since 2.6.4
+ */
+ protected Map<String, Object> getRowAsMap(String[] columnNames,
+ ResultSet set) throws SQLException {
+
+ Map<String, Object> result = new LinkedHashMap<String, Object>();
+ int length = columnNames.length;
+ for (int i = 0; i < length; i++) {
+ String name = columnNames[i];
+ Object value = set.getObject(i + 1);
+ result.put(name, value);
+ }
+ return result;
+ }
+
+}
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaSqlSupport.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaSqlSupport.java 2013-11-22 21:20:24 UTC (rev 2890)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaSqlSupport.java 2013-11-22 21:50:19 UTC (rev 2891)
@@ -24,6 +24,8 @@
* #L%
*/
+import java.util.List;
+
/**
* This API provides methods to run SQL queries
*
@@ -33,12 +35,35 @@
public interface TopiaSqlSupport {
/**
- * Execute a given sql code inside this transaction.
+ * Execute a given SQL code inside this transaction.
*
* @param sqlScript the sql script to execute
*/
void executeSQL(String sqlScript);
- // TODO AThimel 20/07/13 Copy "void doSQLWork(TopiaSQLWork sqlWork);" from topia-3.0-jpa
+ /**
+ * Runs the given SQL work on the current context
+ *
+ * @param sqlWork the SQL work instance to execute
+ */
+ void doSQLWork(TopiaSqlWork sqlWork);
+ /**
+ * Runs the given SQL query and return its first result if there is some.
+ *
+ * @param query query to play
+ * @return the single result or {@code null} if none found.
+ * @throws TopiaException for any pb
+ */
+ <O> O findSingleResult(TopiaSqlQuery<O> query) throws TopiaException;
+
+ /**
+ * Runs the given SQL query and return all his result if there is some.
+ *
+ * @param query query to play
+ * @return the list of results (the list is empty if query returns no result).
+ * @throws TopiaException for any pb
+ */
+ <O> List<O> findMultipleResult(TopiaSqlQuery<O> query) throws TopiaException;
+
}
Added: trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaSqlWork.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaSqlWork.java (rev 0)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaSqlWork.java 2013-11-22 21:50:19 UTC (rev 2891)
@@ -0,0 +1,25 @@
+package org.nuiton.topia;
+
+import java.sql.Connection;
+import java.sql.SQLException;
+
+/**
+ * Interface used for any native SQL batch. This interface is highly inspired
+ * of org.hibernate.jdbc.Work.
+ *
+ * @author Arnaud Thimel <thimel(a)codelutin.com>
+ * @since 3.0
+ */
+public interface TopiaSqlWork {
+
+ /**
+ * Execute the discrete work encapsulated by this work instance using the
+ * supplied connection.
+ *
+ * @param connection The connection on which to perform the work.
+ * @throws SQLException Thrown during execution of the underlying JDBC
+ * interaction.
+ */
+ void execute(Connection connection) throws SQLException;
+
+}
\ No newline at end of file
Property changes on: trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaSqlWork.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision
Added: svn:eol-style
+ native
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/AbstractTopiaContext.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/AbstractTopiaContext.java 2013-11-22 21:20:24 UTC (rev 2890)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/AbstractTopiaContext.java 2013-11-22 21:50:19 UTC (rev 2891)
@@ -40,18 +40,20 @@
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.event.service.spi.EventListenerRegistry;
import org.hibernate.event.spi.EventType;
-import org.hibernate.jdbc.Work;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.service.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.service.spi.Stoppable;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.hbm2ddl.SchemaUpdate;
+import org.nuiton.topia.HibernateTopiaSqlSupport;
import org.nuiton.topia.TopiaContext;
import org.nuiton.topia.TopiaContextFactory;
import org.nuiton.topia.TopiaException;
import org.nuiton.topia.TopiaNotFoundException;
import org.nuiton.topia.TopiaReplicationDestination;
+import org.nuiton.topia.TopiaSqlQuery;
+import org.nuiton.topia.TopiaSqlWork;
import org.nuiton.topia.event.TopiaContextListener;
import org.nuiton.topia.event.TopiaEntitiesVetoable;
import org.nuiton.topia.event.TopiaEntityListener;
@@ -72,9 +74,6 @@
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
@@ -89,6 +88,9 @@
import java.util.WeakHashMap;
import java.util.zip.GZIPInputStream;
+import static org.nuiton.topia.HibernateTopiaSqlSupport.SQLWork;
+import static org.nuiton.topia.HibernateTopiaSqlSupport.TopiaSQLQueryWork;
+
/**
* Le AbstractTopiaContext est le point d'entre pour acceder aux donnees. Il est
* configurer par un fichier de propriete
@@ -971,6 +973,32 @@
}
}
+ @Override
+ public void doSQLWork(TopiaSqlWork sqlWork) {
+ HibernateTopiaSqlSupport.TopiaSQLWorkWork work = new HibernateTopiaSqlSupport.TopiaSQLWorkWork(sqlWork);
+ try {
+ getHibernate().doWork(work);
+ } catch (HibernateException e) {
+ throw new TopiaException("Could not execute sql code", e);
+ }
+ }
+
+ @Override
+ public <O> O findSingleResult(TopiaSqlQuery<O> query) throws TopiaException {
+ TopiaSQLQueryWork<O> work = new TopiaSQLQueryWork<O>(query, false);
+ hibernate.doWork(work);
+ List<O> result = work.getResult();
+ return result.isEmpty() ? null : result.get(0);
+ }
+
+ @Override
+ public <O> List<O> findMultipleResult(TopiaSqlQuery<O> query) throws TopiaException {
+ TopiaSQLQueryWork<O> work = new TopiaSQLQueryWork<O>(query, true);
+ hibernate.doWork(work);
+ final List<O> result = work.getResult();
+ return result;
+ }
+
protected void checkClosed(String message) throws TopiaException {
if (closed) {
throw new TopiaException(message);
@@ -1581,24 +1609,6 @@
}
}
- public static class SQLWork implements Work {
- private final String script;
-
- public SQLWork(String script) {
- this.script = script;
- }
-
- @Override
- public void execute(Connection connection) throws SQLException {
- PreparedStatement sta = connection.prepareStatement(script);
- try {
- sta.execute();
- } finally {
- sta.close();
- }
- }
- }
-
@Override
public Session getHibernateSession() throws TopiaException {
if (hibernate == null) {
Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaSQLQuery.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaSQLQuery.java 2013-11-22 21:20:24 UTC (rev 2890)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaSQLQuery.java 2013-11-22 21:50:19 UTC (rev 2891)
@@ -1,275 +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%
- */
-package org.nuiton.topia.framework;
-
-import org.hibernate.jdbc.Work;
-import org.nuiton.topia.TopiaContext;
-import org.nuiton.topia.TopiaException;
-
-import java.sql.Connection;
-import java.sql.PreparedStatement;
-import java.sql.ResultSet;
-import java.sql.ResultSetMetaData;
-import java.sql.SQLException;
-import java.util.ArrayList;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-
-/**
- * An executor of sql query which permits to obtain a single result via
- * the method {@link #findSingleResult(TopiaContext)}
- * or a multiple result with method {@link #findMultipleResult(TopiaContext)}.
- *
- * @param <O> the type of result data
- * @since 2.5
- */
-public abstract class TopiaSQLQuery<O> {
-
- /**
- * Prepare the statement used to do the sql query.
- *
- * @param connection jdbc connection to use
- * @return the statement containing the query to execute
- * @throws SQLException if any problem
- */
- protected abstract PreparedStatement prepareQuery(Connection connection) throws SQLException;
-
- /**
- * given a result set, extract the data.
- *
- * @param set the result set
- * @return the data extracted from the current set, or {@code null}
- * @throws SQLException if any prob
- */
- protected abstract O prepareResult(ResultSet set) throws SQLException;
-
- /**
- * Obtain a single result from the builded sql query.
- *
- * @param tx the transaction used to execute the query.
- * @return the single result or {@code null} if none found.
- * @throws TopiaException for any pb
- * @deprecated since 3.0, use now {@link #findSingleResult(TopiaContext)}.
- */
- @Deprecated
- public O findSingleResult(TopiaContextImplementor tx) throws TopiaException {
- return findSingleResult((TopiaContext) tx);
- }
-
- /**
- * Obtain a single result from the builded sql query.
- *
- * @param tx the transaction used to execute the query.
- * @return the single result or {@code null} if none found.
- * @throws TopiaException for any pb
- */
- public O findSingleResult(TopiaContext tx) throws TopiaException {
- final List<O> result = new ArrayList<O>();
-
- tx.getHibernateSession().doWork(new Work() {
-
- @Override
- public void execute(Connection connection) throws SQLException {
-
- PreparedStatement ps = prepareQuery(connection);
-
- try {
- ResultSet set = ps.executeQuery();
-
- findSingleResult(result, set);
-
- } catch (Exception e) {
- throw new TopiaException("Could not execute query", e);
- } finally {
- ps.close();
- }
- }
- });
- return result.isEmpty() ? null : result.get(0);
- }
-
- /**
- * Obtain a multiple results fro the builded sql query.
- *
- * @param tx the transaction used to execute the query.
- * @return the list of results (the list is empty if non result is found).
- * @throws TopiaException for any pb
- * @deprecated since 3.0, use now {@link #findMultipleResult(TopiaContext)}.
- */
- @Deprecated
- public List<O> findMultipleResult(TopiaContextImplementor tx) throws TopiaException {
- return findMultipleResult((TopiaContext) tx);
- }
-
- /**
- * Obtain a multiple results fro the builded sql query.
- *
- * @param tx the transaction used to execute the query.
- * @return the list of results (the list is empty if non result is found).
- * @throws TopiaException for any pb
- */
- public List<O> findMultipleResult(TopiaContext tx) throws TopiaException {
- final List<O> result = new ArrayList<O>();
-
- tx.getHibernateSession().doWork(new Work() {
-
- @Override
- public void execute(Connection connection) throws SQLException {
-
- PreparedStatement ps = prepareQuery(connection);
- try {
- ResultSet set = ps.executeQuery();
-
- findMultipleResult(result, set);
-
- } catch (Exception e) {
- throw new TopiaException("Could not execute query", e);
- } finally {
- ps.close();
- }
- }
- });
- return result;
- }
-
- /**
- * A hook to obtain the result set just after the query execute.
- *
- * @param set the result set just obtained
- * @throws SQLException if any prob
- * @since 2.6.4
- */
- protected void afterExecuteQuery(ResultSet set) throws SQLException {
- // by default do nothing
- }
-
- /**
- * Obtain a single result given the result set and push in in the result list.
- *
- * @param result the result list
- * @param set the set of the executed sql query
- * @throws SQLException if any pb
- * @since 2.6.4
- */
- protected void findSingleResult(List<O> result,
- ResultSet set) throws SQLException {
-
- afterExecuteQuery(set);
-
- if (set.next()) {
- O singleResult = prepareResult(set);
- if (singleResult != null) {
- result.add(singleResult);
- }
- }
- }
-
- /**
- * Obtain a multi result given the result set and push in in the result list.
- *
- * @param result the result list
- * @param set the set of the executed sql query
- * @throws SQLException if any pb
- * @since 2.6.4
- */
- protected void findMultipleResult(List<O> result,
- ResultSet set) throws SQLException {
-
- afterExecuteQuery(set);
-
- while (set.next()) {
- O singleResult = prepareResult(set);
-
- if (singleResult != null) {
- result.add(singleResult);
- }
- }
- }
-
- /**
- * Obtain the column names of a given result set using his metadata.
- *
- * @param set the result set to inspect
- * @return the column names of the result set
- * @throws SQLException if any pb
- * @since 2.6.4
- */
- protected String[] getColumnNames(ResultSet set) throws SQLException {
- ResultSetMetaData metaData = set.getMetaData();
- int columnCount = metaData.getColumnCount();
- String[] result = new String[columnCount];
- for (int i = 0; i < columnCount; i++) {
- result[i] = metaData.getColumnName(i + 1);
- }
- return result;
- }
-
- /**
- * From a given result set, let's count his number of row.
- * <p/>
- * <strong>Note:</strong> the result set must be scrollable to go back to
- * before first row.
- *
- * @param set the result set to inspect
- * @return the number of row of the given result set
- * @throws SQLException if any pb
- * @since 2.6.4
- */
- protected long getNbRows(ResultSet set) throws SQLException {
-
- long nbRows = 0;
- while (set.next()) {
- nbRows++;
- }
- // go back before first row (be ware the resultset must be scrollable)
- set.beforeFirst();
- return nbRows;
- }
-
- /**
- * Given the column names of the result set, transform the row of the
- * result set to a map with column name as key.
- *
- * @param columnNames column names of the result set
- * @param set the set to inspect
- * @return the map for the given row of the result set
- * @throws SQLException if any pb
- * @since 2.6.4
- */
- protected Map<String, Object> getRowAsMap(String[] columnNames,
- ResultSet set) throws SQLException {
-
- Map<String, Object> result = new LinkedHashMap<String, Object>();
- int length = columnNames.length;
- for (int i = 0; i < length; i++) {
- String name = columnNames[i];
- Object value = set.getObject(i + 1);
- result.put(name, value);
- }
- return result;
- }
-
-}
1
0
r2890 - trunk/topia-persistence/src/main/java/org/nuiton/topia
by athimel@users.nuiton.org Nov. 22, 2013
by athimel@users.nuiton.org Nov. 22, 2013
Nov. 22, 2013
Author: athimel
Date: 2013-11-22 22:20:24 +0100 (Fri, 22 Nov 2013)
New Revision: 2890
Url: http://nuiton.org/projects/topia/repository/revisions/2890
Log:
refs #2922 Don't let any exception stop the application closing
Modified:
trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaApplicationContext.java
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaApplicationContext.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaApplicationContext.java 2013-11-22 20:45:02 UTC (rev 2889)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaApplicationContext.java 2013-11-22 21:20:24 UTC (rev 2890)
@@ -363,8 +363,15 @@
}
} else {
// Avoid to have exception from checkClosed method on child
- if (!persistenceContext.isClosed()) {
- persistenceContext.closeContext();
+ try {
+ if (!persistenceContext.isClosed()) {
+ persistenceContext.closeContext();
+ }
+ } catch (Exception eee) {
+ // Don't let any exception stop the application closing
+ if (log.isWarnEnabled()) {
+ log.warn("Unable to close TopiaPersistenceContext", eee);
+ }
}
}
}
1
0
r2889 - in trunk/topia-persistence/src/main: java/org/nuiton/topia java/org/nuiton/topia/framework java/org/nuiton/topia/persistence resources/META-INF
by tchemit@users.nuiton.org Nov. 22, 2013
by tchemit@users.nuiton.org Nov. 22, 2013
Nov. 22, 2013
Author: tchemit
Date: 2013-11-22 21:45:02 +0100 (Fri, 22 Nov 2013)
New Revision: 2889
Url: http://nuiton.org/projects/topia/repository/revisions/2889
Log:
refs #2923: Drop all deprecated code (me first\!)
Removed:
trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaRuntimeException.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/EntityFilter.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaFilter.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/
trunk/topia-persistence/src/main/resources/META-INF/services/
Modified:
trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaException.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaDAO.java
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaException.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaException.java 2013-11-22 20:28:56 UTC (rev 2888)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaException.java 2013-11-22 20:45:02 UTC (rev 2889)
@@ -33,7 +33,7 @@
* @author poussin <poussin(a)codelutin.com>
* @version $Id$
*/
-public class TopiaException extends TopiaRuntimeException {
+public class TopiaException extends RuntimeException {
/** Version UID */
private static final long serialVersionUID = -1251439453383121393L;
Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaRuntimeException.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaRuntimeException.java 2013-11-22 20:28:56 UTC (rev 2888)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaRuntimeException.java 2013-11-22 20:45:02 UTC (rev 2889)
@@ -1,75 +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%
- */
-
-package org.nuiton.topia;
-
-/**
- * TODO bleny 03072013 remove this class and use TopiaException everywhere
- *
- * @author chatellier <chatellier(a)codelutin.com>
- * @version $Id$
- * @deprecated since 3.0, to be replaced by TopiaException
- */
-public class TopiaRuntimeException extends RuntimeException {
-
- /** Version UID */
- private static final long serialVersionUID = 4706337137948838375L;
-
- /**
- * Default constructor.
- */
- public TopiaRuntimeException() {
- }
-
- /**
- * Constructor with {@code message}.
- *
- * @param message exception message
- */
- public TopiaRuntimeException(String message) {
- super(message);
- }
-
- /**
- * Constructor for a wrapped TopiaRuntimeException over a {@code cause}
- * with a {@code message}.
- *
- * @param message exception message
- * @param cause exception cause
- */
- public TopiaRuntimeException(String message, Throwable cause) {
- super(message, cause);
- }
-
- /**
- * Constructor for a wrapped TopiaRuntimeException over a {@code cause}.
- *
- * @param cause exception cause
- */
- public TopiaRuntimeException(Throwable cause) {
- super(cause);
- }
-
-}
Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/EntityFilter.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/EntityFilter.java 2013-11-22 20:28:56 UTC (rev 2888)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/EntityFilter.java 2013-11-22 20:45:02 UTC (rev 2889)
@@ -1,172 +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%
- */
-package org.nuiton.topia.framework;
-
-import java.beans.PropertyChangeListener;
-
-/**
- * Created: 3 juin 2010
- *
- * @author fdesbois <fdesbois(a)codelutin.com>
- * @version $Id$
- * @deprecated since 3.0
- */
-@Deprecated
-public interface EntityFilter {
-
- String PROPERTY_START_INDEX = "startIndex";
-
- String PROPERTY_END_INDEX = "endIndex";
-
- String PROPERTY_ORDER_BY = "orderBy";
-
- String PROPERTY_REFERENCE_ID = "referenceId";
-
- String PROPERTY_REFERENCE_PROPERTY = "referenceProperty";
-
- /**
- * Get the value of startIndex
- *
- * @return the value of startIndex
- */
- Integer getStartIndex();
-
- /**
- * Set the value of startIndex
- *
- * @param startIndex new value of startIndex
- */
- void setStartIndex(Integer startIndex);
-
- /**
- * Get the value of orderBy
- *
- * @return the value of orderBy
- */
- String getOrderBy();
-
- /**
- * Set the value of orderBy
- *
- * @param orderBy new value of orderBy
- */
- void setOrderBy(String orderBy);
-
- /**
- * Get the value of endIndex
- *
- * @return the value of endIndex
- */
- Integer getEndIndex();
-
- /**
- * Set the value of endIndex
- *
- * @param endIndex new value of endIndex
- */
- void setEndIndex(Integer endIndex);
-
- /**
- * Get the value of referenceId
- *
- * @return the value of referenceId
- */
- String getReferenceId();
-
- /**
- * Set the value of referenceId
- *
- * @param referenceId
- */
- void setReferenceId(String referenceId);
-
- /**
- * Set the value of referenceId from {@code entity}
- *
- * @param entity
- */
- void setReference(Object entity) throws IllegalArgumentException;
-
- /**
- * Used to check if the filter contains a reference.
- *
- * @return true if the filter contains a reference
- */
- boolean hasReference();
-
- /**
- * Use to check if {@code reference} class is supported by the current
- * filter reference. The reference can be not {@code mandatory}. Exceptions
- * are thrown if the check failed. If you prefer to have a boolean instead
- * of exceptions, you can use {@link #isClassReference(Class)}.
- *
- * @param reference Class reference to check
- * @param mandatory If the existence of the reference is mandatory
- * @throws IllegalArgumentException for errors on check
- * @see #hasReference()
- * @see #isClassReference(Class)
- */
- void checkReference(Class<?> reference, boolean mandatory)
- throws IllegalArgumentException;
-
- /**
- * Test if the {@code entityClass} is corresponding to the current reference
- * in the filter. Will return false if no reference is set in the filter.
- *
- * @param entityClass Class reference to test
- * @return true if the classReference is corresponding, false otherwise
- * @see #checkReference(Class, boolean)
- */
- boolean isClassReference(Class<?> entityClass);
-
- /**
- * Get the value of referenceProperty
- *
- * @return the value of referenceProperty
- */
- String getReferenceProperty();
-
- /**
- * Set the value of referenceProperty
- *
- * @param referenceProperty
- */
- void setReferenceProperty(String referenceProperty);
-
- /**
- * Add PropertyChangeListener.
- *
- * @param listener
- */
- void addPropertyChangeListener(PropertyChangeListener listener);
-
- /**
- * Remove PropertyChangeListener.
- *
- * @param listener
- */
- void removePropertyChangeListener(PropertyChangeListener listener);
-
-}
\ No newline at end of file
Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaFilter.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaFilter.java 2013-11-22 20:28:56 UTC (rev 2888)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/TopiaFilter.java 2013-11-22 20:45:02 UTC (rev 2889)
@@ -1,232 +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%
- */
-package org.nuiton.topia.framework;
-
-import org.apache.commons.lang3.StringUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.nuiton.topia.TopiaNotFoundException;
-import org.nuiton.topia.persistence.TopiaEntity;
-import org.nuiton.topia.persistence.TopiaId;
-
-import java.beans.PropertyChangeListener;
-import java.beans.PropertyChangeSupport;
-
-/**
- * Filter
- * <p/>
- * Created: 23 avr. 2010
- *
- * @author fdesbois
- * @since 2.0
- * @deprecated since 3.0
- */
-@Deprecated
-public class TopiaFilter implements EntityFilter {
-
- private static final Log log = LogFactory.getLog(TopiaFilter.class);
-
- protected Integer startIndex;
-
- protected Integer endIndex;
-
- protected String orderBy;
-
- protected String referenceId;
-
- protected String referenceProperty;
-
- private PropertyChangeSupport propertyChangeSupport =
- new PropertyChangeSupport(this);
-
- @Override
- public Integer getStartIndex() {
- return startIndex;
- }
-
- @Override
- public void setStartIndex(Integer startIndex) {
- Integer oldStartIndex = this.startIndex;
- this.startIndex = startIndex;
- propertyChangeSupport.firePropertyChange(PROPERTY_START_INDEX,
- oldStartIndex, startIndex);
- }
-
- @Override
- public String getOrderBy() {
- return orderBy;
- }
-
- @Override
- public void setOrderBy(String orderBy) {
- String oldOrderBy = this.orderBy;
- this.orderBy = orderBy;
- propertyChangeSupport.firePropertyChange(PROPERTY_ORDER_BY,
- oldOrderBy, orderBy);
- }
-
- @Override
- public Integer getEndIndex() {
- return endIndex;
- }
-
- @Override
- public void setEndIndex(Integer endIndex) {
- Integer oldEndIndex = this.endIndex;
- this.endIndex = endIndex;
- propertyChangeSupport.firePropertyChange(PROPERTY_END_INDEX,
- oldEndIndex, endIndex);
- }
-
- @Override
- public String getReferenceId() {
- return referenceId;
- }
-
- @Override
- public void setReferenceId(String referenceId) {
- String oldReferenceId = this.referenceId;
- this.referenceId = referenceId;
- propertyChangeSupport.firePropertyChange(PROPERTY_REFERENCE_ID,
- oldReferenceId, referenceId);
- }
-
- @Override
- public void setReference(Object entity) throws IllegalArgumentException {
-
- if (! (entity instanceof TopiaEntity)) {
- throw new IllegalArgumentException("Can't set reference of type '" +
- entity.getClass().getName() + "' need a TopiaEntity");
- }
-
- setReferenceId(((TopiaEntity)entity).getTopiaId());
- }
-
- @Override
- public boolean hasReference() {
- return StringUtils.isNotEmpty(referenceId);
- }
-
- @Override
- public String getReferenceProperty() {
- return referenceProperty;
- }
-
- @Override
- public void setReferenceProperty(String referenceProperty) {
- String oldReferenceProperty = this.referenceProperty;
- this.referenceProperty = referenceProperty;
- propertyChangeSupport.firePropertyChange(PROPERTY_REFERENCE_PROPERTY,
- oldReferenceProperty, referenceProperty);
- }
-
- @Override
- public void addPropertyChangeListener(PropertyChangeListener listener) {
- propertyChangeSupport.addPropertyChangeListener(listener);
- }
-
- @Override
- public void removePropertyChangeListener(PropertyChangeListener listener) {
- propertyChangeSupport.removePropertyChangeListener(listener);
- }
-
- /**
- * Test if the {@code entityClass} is corresponding to the current reference
- * in the filter. Will return false if no reference is set in the filter.
- *
- * @param entityClass Class reference to test
- * @return true if the classReference is corresponding, false otherwise
- * @see #checkReference(Class, boolean)
- */
- @Override
- public boolean isClassReference(Class<?> entityClass) {
-
- boolean result = false;
-
- if (hasReference()) {
- try {
- Class<?> referenceClass = TopiaId.getClassName(referenceId);
- if (referenceClass.isAssignableFrom(entityClass)) {
- result = true;
- }
- } catch (TopiaNotFoundException eee) {
- if (log.isWarnEnabled()) {
- log.warn("ReferenceId '" + referenceId + "' is not a" +
- " compatible topiaId : " + eee.getMessage());
- }
- }
- }
- return result;
- }
-
- /**
- * Use to check if {@code reference} class is supported by the current
- * filter reference. The reference can be not {@code mandatory}. Exceptions
- * are thrown if the check failed. If you prefer to have a boolean instead
- * of exceptions, you can use {@link #isClassReference(Class)}.
- *
- * @param reference Class reference to check
- * @param mandatory If the existence of the reference is mandatory
- * @throws IllegalArgumentException for errors on check
- * @see #hasReference()
- * @see #isClassReference(Class)
- */
- @Override
- public void checkReference(Class<?> reference, boolean mandatory)
- throws IllegalArgumentException {
-
- if (log.isTraceEnabled()) {
- log.trace("referenceClass to check : " + reference.getName());
- log.trace("mandatory : " + mandatory);
- log.trace("filter hasReference : " + hasReference());
- log.trace("filter isClassReference : " + isClassReference(reference));
- }
-
- if (mandatory && !hasReference()) {
- throw new IllegalArgumentException("The filter reference" +
- " of type '" + reference.getSimpleName() + "' is mandatory !");
- }
-
- if (hasReference() &&
- !isClassReference(reference)) {
- throw new IllegalArgumentException("Reference filtered need to be" +
- " a '" + reference.getSimpleName() + "' (referenceId = " +
- referenceId + ")");
- }
-
- }
-
- @Override
- public String toString() {
- StringBuilder builder = new StringBuilder("TopiaFilter{").
- append("referenceProperty = '").append(referenceProperty).
- append("', startIndex = ").append(startIndex).
- append(", endIndex = ").append(endIndex).
- append(", orderBy = '").append(orderBy).
- append("' , referenceId = '").append(referenceId).
- append("'}");
- return builder.toString();
- }
-}
\ No newline at end of file
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaDAO.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaDAO.java 2013-11-22 20:28:56 UTC (rev 2888)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaDAO.java 2013-11-22 20:45:02 UTC (rev 2889)
@@ -104,7 +104,7 @@
* @param value value of the property to match
* @return the first entity matching the request
* @throws TopiaException if any pb while getting datas
- * @deprecated @deprecated use new API and inline {@link LegacyTopiaDao#findByProperties(String, Object, Object...)}
+ * @deprecated @deprecated use new API and inline {@link TopiaDao#forProperties(String, Object, Object...)}
*/
E findByProperty(String propertyName,
Object value) throws TopiaException;
@@ -118,7 +118,7 @@
* [propertyName;value;propertyName;value;...]
* @return the first entity matching the request
* @throws TopiaException if any pb while getting datas
- * @deprecated @deprecated use new API and inline {@link LegacyTopiaDao#findByProperties(String, Object, Object...)}
+ * @deprecated @deprecated use new API and inline {@link TopiaDao#forProperties(String, Object, Object...)}
*/
E findByProperties(String propertyName,
Object value,
@@ -130,7 +130,7 @@
* @param properties the properties key + value to match
* @return the first entity matching the request
* @throws TopiaException if any pb while getting datas
- * @deprecated @deprecated use new API and inline {@link LegacyTopiaDao#findByProperties(java.util.Map)}
+ * @deprecated @deprecated use new API and inline {@link TopiaDao#forProperties(java.util.Map)}
*/
E findByProperties(Map<String, Object> properties) throws TopiaException;
@@ -200,7 +200,7 @@
* @return the entity E found or null
* @throws TopiaException if any pb while getting datas
* @since 2.5.4
- * @deprecated use new API and inline {@link LegacyTopiaDao#findContains(String, Object)}
+ * @deprecated use new API and inline {@link TopiaDao#forContains(String, Object)}
*/
E findContains(String propertyName,
Object value) throws TopiaException;
@@ -231,7 +231,7 @@
* @param value value to expect
* @return the list of entities E having the given value
* @throws TopiaException if any pb while getting datas
- * @deprecated use new API and inline {@link LegacyTopiaDao#findAllByProperties(String, Object, Object...)}
+ * @deprecated use new API and inline {@link TopiaDao#forProperties(String, Object, Object...)}
*/
List<E> findAllByProperty(String propertyName,
Object value) throws TopiaException;
@@ -246,7 +246,7 @@
* [propertyName;value;propertyName;value;...]
* @return the list of entities E having the given value
* @throws TopiaException if any pb while getting datas
- * @deprecated use new API and inline {@link LegacyTopiaDao#findAllByProperties(String, Object, Object...)}
+ * @deprecated use new API and inline {@link TopiaDao#forProperties(String, Object, Object...)}
*/
List<E> findAllByProperties(String propertyName,
Object value,
@@ -258,7 +258,7 @@
* @param properties properties to match
* @return the list of entities E having the given values
* @throws TopiaException if any pb while getting datas
- * @deprecated use new API and inline {@link LegacyTopiaDao#findAllByProperties(java.util.Map)}
+ * @deprecated use new API and inline {@link TopiaDao#forProperties(java.util.Map)}
*/
List<E> findAllByProperties(Map<String, Object> properties) throws TopiaException;
@@ -464,7 +464,7 @@
* @return all the entities E found
* @throws TopiaException if any pb while getting datas
* @since 2.5.4
- * @deprecated use new API and inline {@link LegacyTopiaDao#findAllContains(String, Object)}
+ * @deprecated use new API and inline {@link TopiaDao#forContains(String, Object)}
*/
List<E> findAllContains(String propertyName,
Object value) throws TopiaException;
@@ -480,7 +480,7 @@
* @return true if entity exists, false otherwise
* @throws TopiaException for any error
* @since 2.3.4
- * @deprecated use new API and inline {@link LegacyTopiaDao#existByTopiaId(String)}
+ * @deprecated use new API and inline {@link TopiaDao#forTopiaIdEquals(String)}
*/
boolean existByTopiaId(String id) throws TopiaException;
1
0
Nov. 22, 2013
Author: tchemit
Date: 2013-11-22 21:28:56 +0100 (Fri, 22 Nov 2013)
New Revision: 2888
Url: http://nuiton.org/projects/topia/repository/revisions/2888
Log:
fixes #2899: Rename commitTransaction() and rollbackTransaction() to commit() and rollback()
Modified:
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaJpaSupportTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaConnectionProviderTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextImplTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextReplicateTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/generator/TopiaTestCase.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/EntityVisitorExportXmlTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/NaturalIdTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/TopiaDAOTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/ano1882/DAOAbstractTransformerTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/EnumTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/DeleteEntityTest.java
trunk/topia-persistence/src/it/ANOMALIE-1640/src/test/java/org/nuiton/topia/testabstract/TopiaAbstractTest.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaPersistenceContext.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaContext.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaTransaction.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/AbstractTopiaContext.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/DBMapping.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/TopiaEntityHelper.java
trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/AbstractTopiaMigrationCallback.java
trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TopiaMigrationEngine.java
trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/mappings/TMSVersionDAO.java
trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/TopiaReplicationContext.java
trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/operation/AttachLink.java
trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/operation/Duplicate.java
trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/AbstractTopiaReplicationServiceTest.java
trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationOperationTest.java
trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplAllTest.java
trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplTest.java
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaJpaSupportTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaJpaSupportTest.java 2013-11-22 20:13:35 UTC (rev 2887)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaJpaSupportTest.java 2013-11-22 20:28:56 UTC (rev 2888)
@@ -83,7 +83,7 @@
personneDAO.create(
Personne.PROPERTY_NAME, "Hortense",
Personne.PROPERTY_GENDER, Gender.FEMALE);
- persistenceContext.commitTransaction();
+ persistenceContext.commit();
}
@Test
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaConnectionProviderTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaConnectionProviderTest.java 2013-11-22 20:13:35 UTC (rev 2887)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaConnectionProviderTest.java 2013-11-22 20:28:56 UTC (rev 2888)
@@ -129,11 +129,11 @@
PersonDAO dao = TopiaTestDAOHelper.getPersonDAO(transaction);
Person personne = dao.create(Personne.PROPERTY_NAME, "Jack Bauer");
- transaction.commitTransaction();
+ transaction.commit();
String idPersonne = personne.getTopiaId();
assertNotNull(idPersonne);
- transaction.commitTransaction();
+ transaction.commit();
} finally {
transaction.closeContext();
}
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextImplTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextImplTest.java 2013-11-22 20:13:35 UTC (rev 2887)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextImplTest.java 2013-11-22 20:28:56 UTC (rev 2888)
@@ -429,7 +429,7 @@
//
// personSource.addPet(petSource);
//
-// txSource.commitTransaction();
+// txSource.commit();
//
// daoSource = TopiaTestDAOHelper.getPersonDAO(txSource);
//
@@ -446,7 +446,7 @@
// txSource.replicateEntity(txTarget, petSource);
// txSource.replicateEntity(txTarget, personSource);
//
-// txTarget.commitTransaction();
+// txTarget.commit();
//
// daoTarget = TopiaTestDAOHelper.getPersonDAO(txTarget);
// petDAOTarget = TopiaTestDAOHelper.getPetDAO(txTarget);
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextReplicateTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextReplicateTest.java 2013-11-22 20:13:35 UTC (rev 2887)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextReplicateTest.java 2013-11-22 20:28:56 UTC (rev 2888)
@@ -112,7 +112,7 @@
personSource.addPet(petSource);
- txSource.commitTransaction();
+ txSource.commit();
daoSource = TopiaTestDAOHelper.getPersonDAO(txSource);
@@ -129,7 +129,7 @@
txSource.replicateEntity(txTarget, petSource);
txSource.replicateEntity(txTarget, personSource);
- txTarget.commitTransaction();
+ txTarget.commit();
daoTarget = TopiaTestDAOHelper.getPersonDAO(txTarget);
petDAOTarget = TopiaTestDAOHelper.getPetDAO(txTarget);
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/generator/TopiaTestCase.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/generator/TopiaTestCase.java 2013-11-22 20:13:35 UTC (rev 2887)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/generator/TopiaTestCase.java 2013-11-22 20:28:56 UTC (rev 2888)
@@ -150,7 +150,7 @@
company.addDepartment(dep4);
companyDAO.update(company);
- newContext.commitTransaction();
+ newContext.commit();
newContext = db.beginTransaction();
@@ -161,7 +161,7 @@
Assert.assertEquals(company.getName(), "Ma société");
Assert.assertEquals(company.getDepartment().size(), 4);
- newContext.commitTransaction();
+ newContext.commit();
// newContext.closeContext();
// } catch (TopiaException e) {
// log.error("Erreur pendant le test testCompositeAssociations", e);
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/EntityVisitorExportXmlTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/EntityVisitorExportXmlTest.java 2013-11-22 20:13:35 UTC (rev 2887)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/EntityVisitorExportXmlTest.java 2013-11-22 20:28:56 UTC (rev 2888)
@@ -99,7 +99,7 @@
clCompany.addDepartment(depComm);
clCompany.addDepartment(depDev);
- newContext.commitTransaction();
+ newContext.commit();
} finally {
newContext.closeContext();
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/NaturalIdTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/NaturalIdTest.java 2013-11-22 20:13:35 UTC (rev 2887)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/NaturalIdTest.java 2013-11-22 20:28:56 UTC (rev 2888)
@@ -66,15 +66,15 @@
// No exception will be thrown with the two properties
dao.createByNaturalId(5, "str");
- persistenceContext.commitTransaction();
+ persistenceContext.commit();
// No exception will only the need property
dao.createByNotNull(3);
- persistenceContext.commitTransaction();
+ persistenceContext.commit();
// No exception will only the need property
dao.create(NaturalizedEntity.PROPERTY_NATURAL_ID_NOT_NULL, 3);
- persistenceContext.commitTransaction();
+ persistenceContext.commit();
}
@Test
@@ -88,7 +88,7 @@
// Exception will be throw
try {
dao.create();
- persistenceContext.commitTransaction();
+ persistenceContext.commit();
// Note : this is possible to create an empty entity if the type
// is primitive like 'int' which have a default value of '0'
@@ -113,12 +113,12 @@
NaturalizedEntity entity =
dao.createByNaturalId(5, "str");
- persistenceContext.commitTransaction();
+ persistenceContext.commit();
// Exception will be throw : not allowed to modify a naturalId property
try {
entity.setNaturalIdNotNull(8);
- persistenceContext.commitTransaction();
+ persistenceContext.commit();
} catch (TopiaException eee) {
Assert.assertEquals("org.hibernate.HibernateException",
eee.getCause().getClass().getName());
@@ -136,7 +136,7 @@
NaturalizedEntity entity =
dao.createByNaturalId(5, "str");
- persistenceContext.commitTransaction();
+ persistenceContext.commit();
NaturalizedEntity result = dao.findByNaturalId(5, "str");
@@ -153,7 +153,7 @@
persistenceContext.getNaturalizedEntityDao();
dao.createByNaturalId(5, "str");
- persistenceContext.commitTransaction();
+ persistenceContext.commit();
boolean result = dao.existByNaturalId(5, "str");
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/TopiaDAOTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/TopiaDAOTest.java 2013-11-22 20:13:35 UTC (rev 2887)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/TopiaDAOTest.java 2013-11-22 20:28:56 UTC (rev 2888)
@@ -79,7 +79,7 @@
createPerson("toto");
List<Person> allPerson = dao.findAll();
Assert.assertEquals(1, allPerson.size());
- context.commitTransaction();
+ context.commit();
// recherce la personne créée dans la même transaction
Person person2 = createPerson("titi");
@@ -87,7 +87,7 @@
Assert.assertEquals(2, allPerson.size());
Assert.assertThat(allPerson, CoreMatchers.hasItem(person2));
- context.rollbackTransaction();
+ context.rollback();
// meme test apres roolback
Person person3 = createPerson("tata");
@@ -95,7 +95,7 @@
Assert.assertEquals(2, allPerson.size());
Assert.assertThat(allPerson, CoreMatchers.hasItem(person3));
- context.commitTransaction();
+ context.commit();
}
@Test
@@ -193,7 +193,7 @@
createPerson("toto" + i);
}
- context.commitTransaction();
+ context.commit();
}
protected Person createPerson(String name) throws TopiaException {
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/ano1882/DAOAbstractTransformerTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/ano1882/DAOAbstractTransformerTest.java 2013-11-22 20:13:35 UTC (rev 2887)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/ano1882/DAOAbstractTransformerTest.java 2013-11-22 20:28:56 UTC (rev 2888)
@@ -50,8 +50,8 @@
FrenchCompany.PROPERTY_SIREN2, null,
FrenchCompany.PROPERTY_S_IRET, Arrays.asList(siret),
FrenchCompany.PROPERTY_SIRET2, null);
- transaction.commitTransaction();
+ transaction.commit();
dao.delete(entity);
- transaction.commitTransaction();
+ transaction.commit();
}
}
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/EnumTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/EnumTest.java 2013-11-22 20:13:35 UTC (rev 2887)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/EnumTest.java 2013-11-22 20:28:56 UTC (rev 2888)
@@ -59,7 +59,7 @@
personne.setOtherGender(Gender.MALE);
dao.create(personne);
String topiaId = personne.getTopiaId();
- transaction.commitTransaction();
+ transaction.commit();
transaction.closeContext();
transaction = db.beginTransaction();
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/DeleteEntityTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/DeleteEntityTest.java 2013-11-22 20:13:35 UTC (rev 2887)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/DeleteEntityTest.java 2013-11-22 20:28:56 UTC (rev 2888)
@@ -88,21 +88,21 @@
log.debug("CREATE PERSONNE : Bob Marley");
Personne personne = dao.create(Personne.PROPERTY_NAME, "Bob Marley");
- transaction.commitTransaction();
+ transaction.commit();
String idPersonne = personne.getTopiaId();
assertNotNull(idPersonne);
log.debug("ENTITY PERSONNE SAVED !");
log.debug("DELETE PERSONNE");
dao.delete(personne);
- transaction.commitTransaction();
+ transaction.commit();
Personne res = dao.forTopiaIdEquals(idPersonne).findAnyOrNull();
assertNull(res);
log.debug("ENTITY PERSONNE DELETED !");
log.debug("CREATE PERSONNE : Ziggy Marley");
Personne personne2 = dao.create(Personne.PROPERTY_NAME, "Ziggy Marley");
- transaction.commitTransaction();
+ transaction.commit();
String idPersonne2 = personne2.getTopiaId();
assertNotNull(idPersonne2);
log.debug("ENTITY PERSONNE SAVED !");
@@ -112,7 +112,7 @@
log.debug("DELETE PERSONNE with PartyDAO");
dao2.delete(personne2);
- transaction.commitTransaction();
+ transaction.commit();
Party2 res2 = dao2.forTopiaIdEquals(idPersonne2).findAnyOrNull();
assertNull(res2);
log.debug("ENTITY PERSONNE DELETED !");
@@ -138,7 +138,7 @@
log.debug("CREATE PERSONNE : Bob Marley");
Personne personne = dao.create(Personne.PROPERTY_NAME, "Bob Marley");
- transaction.commitTransaction();
+ transaction.commit();
String idPersonne = personne.getTopiaId();
assertNotNull(idPersonne);
log.debug("ENTITY PERSONNE SAVED !");
@@ -147,20 +147,20 @@
log.debug("CREATE CONTACT : jaja(a)codelutin.com");
Contact2 contact = contactDAO.create(Contact2.PROPERTY_CONTACT_VALUE, "jaja(a)codelutin.com");
- transaction.commitTransaction();
+ transaction.commit();
String idContact = contact.getTopiaId();
assertNotNull(idContact);
log.debug("ENTITY CONTACT SAVED !");
log.debug("ADD CONTACT TO PERSONNE");
personne.addContacts(contact);
- transaction.commitTransaction();
+ transaction.commit();
assertEquals(1, personne.getContacts().size());
log.debug("CONTACT ADDED !");
log.debug("DELETE PERSONNE");
dao.delete(personne);
- transaction.commitTransaction();
+ transaction.commit();
Personne res = dao.forTopiaIdEquals(idPersonne).findAnyOrNull();
assertNull(res);
log.debug("ENTITY PERSONNE DELETED !");
@@ -169,7 +169,7 @@
log.debug("DELETE CONTACT");
contactDAO.delete(contact);
- transaction.commitTransaction();
+ transaction.commit();
Contact2 res2 = contactDAO.forTopiaIdEquals(idContact).findAnyOrNull();
assertNull(res2);
log.debug("ENTITY PERSONNE DELETED !");
Modified: trunk/topia-persistence/src/it/ANOMALIE-1640/src/test/java/org/nuiton/topia/testabstract/TopiaAbstractTest.java
===================================================================
--- trunk/topia-persistence/src/it/ANOMALIE-1640/src/test/java/org/nuiton/topia/testabstract/TopiaAbstractTest.java 2013-11-22 20:13:35 UTC (rev 2887)
+++ trunk/topia-persistence/src/it/ANOMALIE-1640/src/test/java/org/nuiton/topia/testabstract/TopiaAbstractTest.java 2013-11-22 20:28:56 UTC (rev 2888)
@@ -27,7 +27,6 @@
import org.junit.Test;
import org.nuiton.topia.TopiaContext;
import org.nuiton.topia.TopiaContextFactory;
-import org.nuiton.topia.TopiaException;
public class TopiaAbstractTest {
@@ -40,7 +39,7 @@
CarDAO carDAO = TopiaTestAbstractDAOHelper.getCarDAO(transaction);
carDAO.create();
- transaction.commitTransaction();
+ transaction.commit();
} finally {
context.closeContext();
}
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaPersistenceContext.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaPersistenceContext.java 2013-11-22 20:13:35 UTC (rev 2887)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaPersistenceContext.java 2013-11-22 20:28:56 UTC (rev 2888)
@@ -298,7 +298,7 @@
}
@Override
- public void commitTransaction() {
+ public void commit() {
checkClosed();
try {
@@ -329,7 +329,7 @@
}
@Override
- public void rollbackTransaction() {
+ public void rollback() {
checkClosed();
try {
Session hibernateSession = hibernateSupport.getHibernateSession();
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaContext.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaContext.java 2013-11-22 20:13:35 UTC (rev 2887)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaContext.java 2013-11-22 20:28:56 UTC (rev 2888)
@@ -80,7 +80,7 @@
* @deprecated use method from {@link TopiaTransaction}
*/
@Deprecated
- void commitTransaction() throws TopiaException;
+ void commit() throws TopiaException;
/**
* Cancels all the modifications made to this context, coming back to the
@@ -91,7 +91,7 @@
* @deprecated use method from {@link TopiaTransaction}
*/
@Deprecated
- void rollbackTransaction() throws TopiaException;
+ void rollback() throws TopiaException;
/**
* Closes the context. All the children contexts will be closed in the same
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaTransaction.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaTransaction.java 2013-11-22 20:13:35 UTC (rev 2887)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/TopiaTransaction.java 2013-11-22 20:28:56 UTC (rev 2888)
@@ -36,13 +36,13 @@
* Applies all the modifications made to this context on the persistence
* device. Once commit is done, a new transaction is started.
*/
- void commitTransaction();
+ void commit();
/**
* Cancels all the modifications made to this context, coming back to the
* state on the last beginTransaction. Once rollback is done, a new
* transaction is started.
*/
- void rollbackTransaction();
+ void rollback();
}
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/AbstractTopiaContext.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/AbstractTopiaContext.java 2013-11-22 20:13:35 UTC (rev 2887)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/framework/AbstractTopiaContext.java 2013-11-22 20:28:56 UTC (rev 2888)
@@ -818,7 +818,7 @@
}
@Override
- public void commitTransaction() throws TopiaException {
+ public void commit() throws TopiaException {
if (equals(getRootContext())) {
throw new TopiaException(String.format("Unsupported operation %s on root context",
"commit"));
@@ -829,7 +829,7 @@
try {
// for (TopiaDAO<? extends TopiaEntity> dao : daoCache.values()) {
// // TODO-fdesbois-20100507 : need to be removed for 2.5 version
-// dao.commitTransaction();
+// dao.commit();
// }
Transaction tx = hibernate.getTransaction();
// Transaction tx = hibernate.beginTransaction();
@@ -856,7 +856,7 @@
}
@Override
- public void rollbackTransaction() throws TopiaException {
+ public void rollback() throws TopiaException {
if (equals(getRootContext())) {
throw new TopiaException(String.format("Unsupported operation %s on root context",
"rollback"));
@@ -866,7 +866,7 @@
try {
// for (TopiaDAO<? extends TopiaEntity> dao : daoCache.values()) {
// // TODO-fdesbois-20100507 : need to be removed for 2.5 version
-// dao.rollbackTransaction();
+// dao.rollback();
// }
Transaction tx = hibernate.getTransaction();
// Transaction tx = hibernate.beginTransaction();
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/DBMapping.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/DBMapping.java 2013-11-22 20:13:35 UTC (rev 2887)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/DBMapping.java 2013-11-22 20:28:56 UTC (rev 2888)
@@ -134,7 +134,7 @@
updateSequences(newContext);
}
}
- newContext.commitTransaction();
+ newContext.commit();
newContext.closeContext();
}
@@ -349,7 +349,7 @@
stmt.execute(sql);
}
});
- //ctxt.commitTransaction();
+ //ctxt.commit();
}
}
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/TopiaEntityHelper.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/TopiaEntityHelper.java 2013-11-22 20:13:35 UTC (rev 2887)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/util/TopiaEntityHelper.java 2013-11-22 20:28:56 UTC (rev 2888)
@@ -223,9 +223,9 @@
try {
ctxt.restore(databaseDump);
- ctxt.commitTransaction();
+ ctxt.commit();
} catch (TopiaException e) {
- ctxt.rollbackTransaction();
+ ctxt.rollback();
throw e;
} finally {
ctxt.closeContext();
Modified: trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/AbstractTopiaMigrationCallback.java
===================================================================
--- trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/AbstractTopiaMigrationCallback.java 2013-11-22 20:13:35 UTC (rev 2887)
+++ trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/AbstractTopiaMigrationCallback.java 2013-11-22 20:28:56 UTC (rev 2888)
@@ -116,13 +116,13 @@
migrateForVersion(v, tx, showSql, showProgression);
// commit des modifs
- tx.commitTransaction();
+ tx.commit();
} catch (Exception eee) {
// en cas d'erreur
log.error("Could not migrate database", eee);
// rollback du travail en cours
- tx.rollbackTransaction();
+ tx.rollback();
// propagation de l'erreur
throw eee;
} finally {
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-11-22 20:13:35 UTC (rev 2887)
+++ trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/TopiaMigrationEngine.java 2013-11-22 20:28:56 UTC (rev 2888)
@@ -39,7 +39,6 @@
import org.nuiton.topia.event.TopiaTransactionEvent;
import org.nuiton.topia.event.TopiaTransactionVetoable;
import org.nuiton.topia.framework.AbstractTopiaContext;
-import org.nuiton.topia.framework.TopiaContextImplementor;
import org.nuiton.topia.framework.TopiaUtil;
import org.nuiton.topia.migration.mappings.TMSVersion;
import org.nuiton.topia.migration.mappings.TMSVersionDAO;
@@ -467,10 +466,10 @@
log.debug("Created version: " + tmsVersion.getVersion());
}
- tx.commitTransaction();
+ tx.commit();
} catch (TopiaException e) {
if (tx != null) {
- tx.rollbackTransaction();
+ tx.rollback();
}
throw e;
} finally {
Modified: trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/mappings/TMSVersionDAO.java
===================================================================
--- trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/mappings/TMSVersionDAO.java 2013-11-22 20:13:35 UTC (rev 2887)
+++ trunk/topia-service-migration/src/main/java/org/nuiton/topia/migration/mappings/TMSVersionDAO.java 2013-11-22 20:28:56 UTC (rev 2888)
@@ -104,7 +104,7 @@
try {
Session session = tx.getHibernateSession();
session.saveOrUpdate(version);
- tx.commitTransaction();
+ tx.commit();
} catch (HibernateException e) {
throw new TopiaException("Could not update version " + version, e);
}
Modified: trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/TopiaReplicationContext.java
===================================================================
--- trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/TopiaReplicationContext.java 2013-11-22 20:13:35 UTC (rev 2887)
+++ trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/TopiaReplicationContext.java 2013-11-22 20:28:56 UTC (rev 2888)
@@ -203,7 +203,7 @@
try {
if (rollback) {
- tx.rollbackTransaction();
+ tx.rollback();
}
} finally {
tx.closeContext();
Modified: trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/operation/AttachLink.java
===================================================================
--- trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/operation/AttachLink.java 2013-11-22 20:13:35 UTC (rev 2887)
+++ trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/operation/AttachLink.java 2013-11-22 20:28:56 UTC (rev 2888)
@@ -236,7 +236,7 @@
}
if (shouldCommit) {
- dstCtxt.commitTransaction();
+ dstCtxt.commit();
}
}
}
Modified: trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/operation/Duplicate.java
===================================================================
--- trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/operation/Duplicate.java 2013-11-22 20:13:35 UTC (rev 2887)
+++ trunk/topia-service-replication/src/main/java/org/nuiton/topia/replication/operation/Duplicate.java 2013-11-22 20:28:56 UTC (rev 2888)
@@ -86,7 +86,7 @@
srcCtxt.replicateEntities(dstCtxt, entities);
// sauvegarde de la destination
- dstCtxt.commitTransaction();
+ dstCtxt.commit();
}
@@ -123,7 +123,7 @@
allIds.clear();
// commit des suppressions
- dstCtxt.commitTransaction();
+ dstCtxt.commit();
}
}
}
Modified: trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/AbstractTopiaReplicationServiceTest.java
===================================================================
--- trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/AbstractTopiaReplicationServiceTest.java 2013-11-22 20:13:35 UTC (rev 2887)
+++ trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/AbstractTopiaReplicationServiceTest.java 2013-11-22 20:28:56 UTC (rev 2888)
@@ -106,7 +106,7 @@
public void tearDown() throws Exception {
if (ctxt != null) {
- ctxt.rollbackTransaction();
+ ctxt.rollback();
ctxt.closeContext();
ctxt = null;
}
Modified: trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationOperationTest.java
===================================================================
--- trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationOperationTest.java 2013-11-22 20:13:35 UTC (rev 2887)
+++ trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationOperationTest.java 2013-11-22 20:28:56 UTC (rev 2888)
@@ -298,7 +298,7 @@
pet2 = tx.getDao(Pet.class).create(Pet.PROPERTY_NAME, "pudding II");
race2 = tx.getDao(Race.class).create(Race.PROPERTY_NAME, "race II");
- tx.commitTransaction();
+ tx.commit();
tx.closeContext();
return context;
}
Modified: trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplAllTest.java
===================================================================
--- trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplAllTest.java 2013-11-22 20:13:35 UTC (rev 2887)
+++ trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplAllTest.java 2013-11-22 20:28:56 UTC (rev 2888)
@@ -248,7 +248,7 @@
race3 = tx.getDao(Race.class).create(Race.PROPERTY_NAME, "race III");
pet3 = tx.getDao(Pet.class).create(Pet.PROPERTY_NAME, "pudding III", Pet.PROPERTY_RACE, race3);
- tx.commitTransaction();
+ tx.commit();
tx.closeContext();
return context;
}
Modified: trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplTest.java
===================================================================
--- trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplTest.java 2013-11-22 20:13:35 UTC (rev 2887)
+++ trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplTest.java 2013-11-22 20:28:56 UTC (rev 2888)
@@ -273,10 +273,10 @@
srcCtxt.replicateEntity(dstCtxt, pet);
- dstCtxt.commitTransaction();
+ dstCtxt.commit();
} finally {
- srcCtxt.rollbackTransaction();
+ srcCtxt.rollback();
srcCtxt.closeContext();
dstCtxt.closeContext();
}
@@ -310,20 +310,20 @@
pet.setPerson(null);
srcCtxt.replicateEntity(dstCtxt, pet);
- srcCtxt.rollbackTransaction();
+ srcCtxt.rollback();
srcCtxt.replicateEntity(dstCtxt, person);
- dstCtxt.commitTransaction();
+ dstCtxt.commit();
((Pet) dstCtxt.findByTopiaId(pet.getTopiaId())).setPerson((Person) dstCtxt.findByTopiaId(person.getTopiaId()));
- dstCtxt.commitTransaction();
+ dstCtxt.commit();
- srcCtxt.rollbackTransaction();
+ srcCtxt.rollback();
person = update(person);
assertEntityEquals(person, dstCtxt.findByTopiaId(person.getTopiaId()), null);
} finally {
- srcCtxt.rollbackTransaction();
+ srcCtxt.rollback();
//srcCtxt.closeContext();
dstCtxt.closeContext();
}
@@ -362,13 +362,13 @@
srcCtxt.replicateEntity(dstCtxt, person);
srcCtxt.replicateEntity(dstCtxt, pet);
- srcCtxt.rollbackTransaction();
- dstCtxt.commitTransaction();
+ srcCtxt.rollback();
+ dstCtxt.commit();
//((Person) dstCtxt.findByTopiaId(person.getTopiaId())).addPet(((Pet) dstCtxt.findByTopiaId(pet.getTopiaId())));
- //dstCtxt.commitTransaction();
+ //dstCtxt.commit();
- srcCtxt.rollbackTransaction();
+ srcCtxt.rollback();
srcCtxt.closeContext();
dstCtxt.closeContext();
@@ -407,7 +407,7 @@
race3 = tx.getDao(Race.class).create(Race.PROPERTY_NAME, "race III");
pet3 = tx.getDao(Pet.class).create(Pet.PROPERTY_NAME, "pudding III", Pet.PROPERTY_RACE, race3);
- tx.commitTransaction();
+ tx.commit();
tx.closeContext();
return context;
}
1
0
Nov. 22, 2013
Author: tchemit
Date: 2013-11-22 21:13:35 +0100 (Fri, 22 Nov 2013)
New Revision: 2887
Url: http://nuiton.org/projects/topia/repository/revisions/2887
Log:
refs #299: Refactor modules (remove obsolete directory)
Removed:
trunk/topia-persistence/src/test/java/org/nuiton/topiatest/
1
0
r2886 - trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy
by tchemit@users.nuiton.org Nov. 22, 2013
by tchemit@users.nuiton.org Nov. 22, 2013
Nov. 22, 2013
Author: tchemit
Date: 2013-11-22 21:05:53 +0100 (Fri, 22 Nov 2013)
New Revision: 2886
Url: http://nuiton.org/projects/topia/repository/revisions/2886
Log:
refs #299: Refactor modules (clean tests)
Modified:
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaContextFactoryTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaJpaSupportTest.java
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaContextFactoryTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaContextFactoryTest.java 2013-11-22 20:03:11 UTC (rev 2885)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaContextFactoryTest.java 2013-11-22 20:05:53 UTC (rev 2886)
@@ -24,6 +24,7 @@
*/
package org.nuiton.topia.it.legacy;
+import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Assert;
@@ -37,6 +38,7 @@
import java.io.File;
import java.io.IOException;
+import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.Properties;
@@ -49,23 +51,21 @@
*/
public class TopiaContextFactoryTest {
- static class MyTopiaContextFactory extends TopiaContextFactory {
-
- static Map<Properties, TopiaContext> getContextCache() {return contextCache;}
- }
private static final Log log =
LogFactory.getLog(TopiaContextFactoryTest.class);
protected static Map<Properties, TopiaContext> contextCache;
+
protected static File testBasedir;
protected Properties properties;
@BeforeClass
- public static void init() throws IOException {
+ public static void init() throws IOException, IllegalAccessException {
testBasedir = ConfigurationHelper.getTestSpecificDirectory(TopiaContextFactoryTest.class, "dummy");
- contextCache = MyTopiaContextFactory.getContextCache();
+ Field field = FieldUtils.getField(TopiaContextFactory.class, "contextCache", true);
+ contextCache = (Map<Properties, TopiaContext>) field.get(null);
}
@Before
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaJpaSupportTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaJpaSupportTest.java 2013-11-22 20:03:11 UTC (rev 2885)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaJpaSupportTest.java 2013-11-22 20:05:53 UTC (rev 2886)
@@ -64,10 +64,8 @@
@Before
public void createCompanies() throws TopiaException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
persistenceContext = db.beginTransaction();
-// jpaSupport = persistenceContext.jpaSupport;
Field field = FieldUtils.getField(AbstractTopiaPersistenceContext.class, "jpaSupport", true);
- field.setAccessible(true);
jpaSupport = (TopiaJpaSupport) field.get(persistenceContext);
personneDAO = persistenceContext.getPersonneDao();
1
0
Nov. 22, 2013
Author: tchemit
Date: 2013-11-22 21:03:11 +0100 (Fri, 22 Nov 2013)
New Revision: 2885
Url: http://nuiton.org/projects/topia/repository/revisions/2885
Log:
refs #299: Refactor modules
Added:
trunk/topia-it/src/main/java/org/nuiton/topia/it/TopiaConfigurationHelper.java
trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/
trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/AbstractEmployeTopiaDao.java
trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/AbstractPersonneTopiaDao.java
trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/EmployeTopiaDao.java
trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/EmployeeDao.java
trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/GeneratedEmployeeTopiaDao.java
trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/GeneratedPersonneTopiaDao.java
trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/PersonneDao.java
trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/PersonneTopiaDao.java
trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/
trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/AbstractExtraDAOEntityTopiaDao.java
trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/Gender.java
trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/Title.java
trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/beangen/
trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/beangen/RoueImpl.java
trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/deletetest/
trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/deletetest/AbstractContact2TopiaDao.java
trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/persistence/
trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1.java
trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Abstract.java
trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Impl.hbm.xml
trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Impl.java
trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/persistence/package-info.java
trunk/topia-it/src/main/resources/
trunk/topia-it/src/main/resources/TopiaContextImpl.properties
trunk/topia-junit/src/main/java/org/nuiton/topia/junit/AbstractDatabaseResource.java
trunk/topia-junit/src/main/java/org/nuiton/topia/junit/ConfigurationHelper.java
Removed:
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/AbstractEmployeTopiaDao.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/AbstractPersonneTopiaDao.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/EmployeTopiaDao.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/EmployeeDao.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/GeneratedEmployeeTopiaDao.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/GeneratedPersonneTopiaDao.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/PersonneDao.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/PersonneTopiaDao.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/AbstractExtraDAOEntityTopiaDao.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/Gender.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/Title.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/beangen/RoueImpl.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/AbstractContact2TopiaDao.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Abstract.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Impl.hbm.xml
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Impl.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/package-info.java
trunk/topia-it/src/test/resources/TopiaContextImpl.properties
trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/
trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/
trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/
trunk/topia-persistence/src/test/java/org/nuiton/topia/test/
Modified:
trunk/topia-it/LICENSE.txt
trunk/topia-it/README.txt
trunk/topia-it/pom.xml
trunk/topia-it/src/main/xmi/topiatest.properties
trunk/topia-it/src/main/xmi/topiatest.zargo
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TestHelper.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaContextFactoryTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaDatabase.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaJpaSupportTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaConnectionProviderTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextImplTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextReplicateTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaUtilTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/generator/TopiaTestCase.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/EntityVisitorExportXmlTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/ExportXMLVisitor.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/HqlAndParametersBuilderTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/NaturalIdTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/TopiaDAOTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/CollectorTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/EntityOperatorTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityBinderTest.java
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/TopiaEntityRefTester.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityRefTesterTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/ano1882/DAOAbstractTransformerTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/evo1912/EntityDTOTransformerTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/EnumTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/DeleteEntityTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/FakeService.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/TestService.java
trunk/topia-it/src/test/resources/log4j.properties
trunk/topia-junit/LICENSE.txt
trunk/topia-junit/README.txt
trunk/topia-junit/pom.xml
trunk/topia-service-replication/pom.xml
trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationOperationTest.java
trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplAllTest.java
trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplTest.java
trunk/topia-templates/LICENSE.txt
trunk/topia-templates/README.txt
trunk/topia-templates/pom.xml
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/ApplicationContextTransformer.java
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/BinderHelperTransformer.java
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/DAOHelperTransformer.java
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/DTOTransformer.java
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityDTOTransformer.java
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityDaoTransformer.java
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityHibernateMappingGenerator.java
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityTransformer.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/TopiaJavaValidator.java
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaMetaTransformer.java
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaRelationValidator.java
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaStereoTypes.java
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaTagValues.java
trunk/topia-templates/src/test/java/org/nuiton/topia/templates/TopiaGeneratorUtilTest.java
trunk/topia-templates/src/test/java/org/nuiton/topia/templates/TopiaModelPropertiesProviderTest.java
Property changes on: trunk/topia-it/LICENSE.txt
___________________________________________________________________
Modified: svn:keywords
- Author Date Id Revision
+ Author Date Id Revision HeadURL
Property changes on: trunk/topia-it/README.txt
___________________________________________________________________
Modified: svn:keywords
- Author Date Id Revision
+ Author Date Id Revision HeadURL
Modified: trunk/topia-it/pom.xml
===================================================================
--- trunk/topia-it/pom.xml 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/pom.xml 2013-11-22 20:03:11 UTC (rev 2885)
@@ -4,7 +4,7 @@
ToPIA :: Persistence
$Id$
- $HeadURL: http://svn.nuiton.org/svn/topia/trunk/topia-persistence/pom.xml $
+ $HeadURL$
%%
Copyright (C) 2004 - 2010 CodeLutin
%%
@@ -106,8 +106,8 @@
org.nuiton.topia.templates.EntityDTOTransformer,
org.nuiton.topia.templates.BinderHelperTransformer
</templates>
- <fullPackagePath>org.nuiton.topia</fullPackagePath>
- <defaultPackage>org.nuiton.topia</defaultPackage>
+ <fullPackagePath>org.nuiton.topia.it.legacy</fullPackagePath>
+ <defaultPackage>org.nuiton.topia.it.legacy</defaultPackage>
</configuration>
<goals>
<goal>generate</goal>
Property changes on: trunk/topia-it/pom.xml
___________________________________________________________________
Modified: svn:keywords
- Author Date Id Revision
+ Author Date Id Revision HeadURL
Added: trunk/topia-it/src/main/java/org/nuiton/topia/it/TopiaConfigurationHelper.java
===================================================================
--- trunk/topia-it/src/main/java/org/nuiton/topia/it/TopiaConfigurationHelper.java (rev 0)
+++ trunk/topia-it/src/main/java/org/nuiton/topia/it/TopiaConfigurationHelper.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -0,0 +1,128 @@
+package org.nuiton.topia.it;
+
+/*
+ * #%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%
+ */
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.hibernate.cfg.Environment;
+import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.TopiaContextFactory;
+import org.nuiton.topia.TopiaNotFoundException;
+import org.nuiton.topia.it.legacy.TopiaTestDAOHelper;
+import org.nuiton.topia.junit.ConfigurationHelper;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Properties;
+
+/**
+ * Created on 11/22/13.
+ *
+ * @author Tony Chemit <chemit(a)codelutin.com>
+ * @since 3.0
+ */
+public class TopiaConfigurationHelper extends ConfigurationHelper {
+
+ /** Logger. */
+ private static final Log log = LogFactory.getLog(TopiaConfigurationHelper.class);
+
+ public static final String DEFAULT_CONFIGURATION_LOCATION = "/TopiaContextImpl.properties";
+
+ public static TopiaContext initTopiaContext(File testDirectory,
+ String dbname)
+ throws IOException, TopiaNotFoundException {
+
+
+ TopiaContext topiaContext = initTopiaContext(
+ testDirectory,
+ DEFAULT_CONFIGURATION_LOCATION,
+ dbname
+ );
+ return topiaContext;
+ }
+
+ public static TopiaContext initTopiaContext(File testDirectory,
+ String dbPropertiesPath,
+ String dbname)
+ throws IOException, TopiaNotFoundException {
+
+ Properties configuration = initTopiaContextConfiguration(
+ testDirectory,
+ dbPropertiesPath,
+ dbname);
+ return TopiaContextFactory.getContext(configuration);
+ }
+
+ public static Properties initTopiaContextConfiguration(File testDirectory,
+ String dbPropertiesPath,
+ String dbname)
+ throws IOException {
+
+ Properties configuration = loadHibernateConfiguration(dbPropertiesPath);
+
+ // make sure we always use a different directory
+
+ String dbPath = getDbName(testDirectory, dbname);
+
+ if (log.isInfoEnabled()) {
+ log.info("dbPath = " + dbPath);
+ }
+ configuration.setProperty(
+ Environment.URL,
+// "hibernate.connection.url",
+ "jdbc:h2:file:" + dbPath);
+
+ return configuration;
+ }
+
+ public static Properties loadHibernateConfiguration(String dbPropertiesPath) throws IOException {
+ InputStream stream = TopiaConfigurationHelper.class.getResourceAsStream(dbPropertiesPath);
+
+ Properties configuration = new Properties();
+
+ configuration.load(stream);
+ configuration.setProperty(
+ TopiaContextFactory.CONFIG_PERSISTENCE_CLASSES,
+ TopiaTestDAOHelper.getImplementationClassesAsString());
+ return configuration;
+ }
+
+ public static String getDbName(File testDirectory, String dbname) {
+ return new File(testDirectory,
+ dbname + '_' + System.nanoTime()).getAbsolutePath();
+ }
+
+ public static Properties initTopiaContextConfiguration(File testDirectory,
+ String dbname)
+ throws IOException {
+
+ return initTopiaContextConfiguration(
+ testDirectory,
+ DEFAULT_CONFIGURATION_LOCATION,
+ dbname
+ );
+ }
+}
Property changes on: trunk/topia-it/src/main/java/org/nuiton/topia/it/TopiaConfigurationHelper.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Copied: trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/AbstractEmployeTopiaDao.java (from rev 2884, trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/AbstractEmployeTopiaDao.java)
===================================================================
--- trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/AbstractEmployeTopiaDao.java (rev 0)
+++ trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/AbstractEmployeTopiaDao.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -0,0 +1,33 @@
+package org.nuiton.topia.it.legacy;
+
+/*
+ * #%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.nuiton.topia.it.legacy.topiatest.Employe;
+
+/**
+ * @author Arnaud Thimel <thimel(a)codelutin.com>
+ */
+public abstract class AbstractEmployeTopiaDao<E extends Employe> extends GeneratedEmployeeTopiaDao<E> {
+}
Copied: trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/AbstractPersonneTopiaDao.java (from rev 2884, trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/AbstractPersonneTopiaDao.java)
===================================================================
--- trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/AbstractPersonneTopiaDao.java (rev 0)
+++ trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/AbstractPersonneTopiaDao.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -0,0 +1,34 @@
+package org.nuiton.topia.it.legacy;
+
+/*
+ * #%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.nuiton.topia.it.legacy.topiatest.Personne;
+
+/**
+ * @author Arnaud Thimel <thimel(a)codelutin.com>
+ */
+public abstract class AbstractPersonneTopiaDao<E extends Personne> extends GeneratedPersonneTopiaDao<E> {
+
+}
Copied: trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/EmployeTopiaDao.java (from rev 2884, trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/EmployeTopiaDao.java)
===================================================================
--- trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/EmployeTopiaDao.java (rev 0)
+++ trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/EmployeTopiaDao.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -0,0 +1,42 @@
+package org.nuiton.topia.it.legacy;
+
+/*
+ * #%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.util.List;
+
+import org.nuiton.topia.it.legacy.topiatest.Employe;
+import org.nuiton.topia.it.legacy.topiatest.Personne;
+
+/**
+ * @author Arnaud Thimel <thimel(a)codelutin.com>
+ */
+public class EmployeTopiaDao extends AbstractEmployeTopiaDao<Employe> {
+
+ @Override
+ public List<Personne> findAllPersonnesByXAndY(int x, int y) {
+ return null;
+ }
+
+}
Copied: trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/EmployeeDao.java (from rev 2884, trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/EmployeeDao.java)
===================================================================
--- trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/EmployeeDao.java (rev 0)
+++ trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/EmployeeDao.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -0,0 +1,31 @@
+package org.nuiton.topia.it.legacy;
+
+/*
+ * #%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%
+ */
+
+/**
+ * @author Arnaud Thimel <thimel(a)codelutin.com>
+ */
+public interface EmployeeDao {
+}
Copied: trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/GeneratedEmployeeTopiaDao.java (from rev 2884, trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/GeneratedEmployeeTopiaDao.java)
===================================================================
--- trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/GeneratedEmployeeTopiaDao.java (rev 0)
+++ trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/GeneratedEmployeeTopiaDao.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -0,0 +1,33 @@
+package org.nuiton.topia.it.legacy;
+
+/*
+ * #%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.nuiton.topia.it.legacy.topiatest.Employe;
+
+/**
+ * @author Arnaud Thimel <thimel(a)codelutin.com>
+ */
+public abstract class GeneratedEmployeeTopiaDao<E extends Employe> extends AbstractPersonneTopiaDao<E> {
+}
Copied: trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/GeneratedPersonneTopiaDao.java (from rev 2884, trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/GeneratedPersonneTopiaDao.java)
===================================================================
--- trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/GeneratedPersonneTopiaDao.java (rev 0)
+++ trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/GeneratedPersonneTopiaDao.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -0,0 +1,61 @@
+package org.nuiton.topia.it.legacy;
+
+/*
+ * #%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.util.List;
+import java.util.Map;
+
+import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.persistence.AbstractTopiaDao;
+import org.nuiton.topia.persistence.TopiaEntity;
+import org.nuiton.topia.persistence.TopiaEntityEnum;
+import org.nuiton.topia.it.legacy.topiatest.Personne;
+
+/**
+ * @author Arnaud Thimel <thimel(a)codelutin.com>
+ */
+public abstract class GeneratedPersonneTopiaDao<E extends Personne> extends AbstractTopiaDao<E> implements PersonneDao {
+
+ @Override
+ public TopiaEntityEnum getTopiaEntityEnum() {
+ return null;
+ }
+
+ @Override
+ public <R extends TopiaEntity> List<R> findUsages(Class<R> type, E entity) throws TopiaException {
+ return null;
+ }
+
+ @Override
+ public Map<Class<? extends TopiaEntity>, List<? extends TopiaEntity>> findAllUsages(E entity) throws TopiaException {
+ return null;
+ }
+
+ @Override
+ public Class<E> getEntityClass() {
+ return null;
+ }
+
+}
Copied: trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/PersonneDao.java (from rev 2884, trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/PersonneDao.java)
===================================================================
--- trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/PersonneDao.java (rev 0)
+++ trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/PersonneDao.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -0,0 +1,38 @@
+package org.nuiton.topia.it.legacy;
+
+/*
+ * #%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.util.List;
+
+import org.nuiton.topia.it.legacy.topiatest.Personne;
+
+/**
+ * @author Arnaud Thimel <thimel(a)codelutin.com>
+ */
+public interface PersonneDao {
+
+ List<Personne> findAllPersonnesByXAndY(int x, int y);
+
+}
Copied: trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/PersonneTopiaDao.java (from rev 2884, trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/PersonneTopiaDao.java)
===================================================================
--- trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/PersonneTopiaDao.java (rev 0)
+++ trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/PersonneTopiaDao.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -0,0 +1,41 @@
+package org.nuiton.topia.it.legacy;
+
+/*
+ * #%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.util.List;
+
+import org.nuiton.topia.it.legacy.topiatest.Personne;
+
+/**
+ * @author Arnaud Thimel <thimel(a)codelutin.com>
+ */
+public class PersonneTopiaDao extends AbstractPersonneTopiaDao<Personne> {
+
+ @Override
+ public List<Personne> findAllPersonnesByXAndY(int x, int y) {
+ return null;
+ }
+
+}
Copied: trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/AbstractExtraDAOEntityTopiaDao.java (from rev 2884, trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/AbstractExtraDAOEntityTopiaDao.java)
===================================================================
--- trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/AbstractExtraDAOEntityTopiaDao.java (rev 0)
+++ trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/AbstractExtraDAOEntityTopiaDao.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -0,0 +1,40 @@
+/*
+ * #%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%
+ */
+package org.nuiton.topia.it.legacy.topiatest;
+
+import org.nuiton.topia.TopiaException;
+
+/**
+ * Created: 26 mai 2010
+ *
+ * @author fdesbois <fdesbois(a)codelutin.com>
+ * @version $Id$
+ */
+public class AbstractExtraDAOEntityTopiaDao<E extends ExtraDAOEntity> extends GeneratedExtraDAOEntityTopiaDao<E> {
+
+ @Override
+ public void extra() throws TopiaException {
+ }
+}
Copied: trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/Gender.java (from rev 2884, trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/Gender.java)
===================================================================
--- trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/Gender.java (rev 0)
+++ trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/Gender.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -0,0 +1,29 @@
+/*
+ * #%L
+ * ToPIA :: Persistence
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2004 - 2011 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%
+ */
+package org.nuiton.topia.it.legacy.topiatest;
+
+public enum Gender {
+ MALE, FEMALE
+}
Copied: trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/Title.java (from rev 2884, trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/Title.java)
===================================================================
--- trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/Title.java (rev 0)
+++ trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/Title.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -0,0 +1,37 @@
+/*
+ * #%L
+ * ToPIA :: Persistence
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2004 - 2011 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%
+ */
+package org.nuiton.topia.it.legacy.topiatest;
+
+/**
+ * To test http://nuiton.org/issues/1732.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.6.2
+ */
+public enum Title {
+ Mr,
+ Madam,
+ Other
+}
Copied: trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/beangen/RoueImpl.java (from rev 2884, trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/beangen/RoueImpl.java)
===================================================================
--- trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/beangen/RoueImpl.java (rev 0)
+++ trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/beangen/RoueImpl.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -0,0 +1,53 @@
+/*
+ * #%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%
+ */
+
+package org.nuiton.topia.it.legacy.topiatest.beangen;
+
+import org.nuiton.topia.it.legacy.topiatest.Product;
+
+/**
+ * RoueImpl
+ *
+ * Created: 14 janv. 2010
+ *
+ * @author fdesbois
+ * @version $Revision$
+ *
+ * Mise a jour: $Date$
+ * par : $Author$
+ */
+public class RoueImpl extends Roue {
+
+ @Override
+ public void mount() {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public Product getModel(String id) {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+}
Copied: trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/deletetest/AbstractContact2TopiaDao.java (from rev 2884, trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/AbstractContact2TopiaDao.java)
===================================================================
--- trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/deletetest/AbstractContact2TopiaDao.java (rev 0)
+++ trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/deletetest/AbstractContact2TopiaDao.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -0,0 +1,51 @@
+/*
+ * #%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%
+ */
+
+package org.nuiton.topia.it.legacy.topiatest.deletetest;
+
+
+import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.it.legacy.topiatest.Company;
+import org.nuiton.topia.it.legacy.topiatest.Employe;
+
+import java.util.Set;
+import java.util.TreeSet;
+
+/**
+ *
+ * @author desbois
+ */
+public class AbstractContact2TopiaDao<E extends Contact2> extends GeneratedContact2TopiaDao<E> {
+
+ @Override
+ public Set<Contact2> findAllByCompany(Company company) throws TopiaException {
+ Set<Contact2> contacts = new TreeSet<Contact2>();
+ for (Employe e : company.getEmploye()) {
+ contacts.addAll(e.getContacts());
+ }
+ return contacts;
+ }
+
+}
Copied: trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1.java (from rev 2884, trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1.java)
===================================================================
--- trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1.java (rev 0)
+++ trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -0,0 +1,49 @@
+/*
+ * #%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%
+ */
+package org.nuiton.topia.it.legacy.topiatest.persistence;
+
+import org.nuiton.topia.persistence.TopiaEntity;
+
+/**
+ * Created: 11 mai 2010
+ *
+ * @author fdesbois <fdesbois(a)codelutin.com>
+ * @version $Id$
+ */
+public interface Entity1 extends TopiaEntity {
+
+ String ATTR_1 = "attr1";
+
+ String ATTR_2 = "attr2";
+
+ String getAttr1();
+
+ void setAttr1(String attr1);
+
+ String getAttr2();
+
+ void setAttr2(String attr2);
+
+}
Copied: trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Abstract.java (from rev 2884, trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Abstract.java)
===================================================================
--- trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Abstract.java (rev 0)
+++ trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Abstract.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -0,0 +1,83 @@
+/*
+ * #%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%
+ */
+package org.nuiton.topia.it.legacy.topiatest.persistence;
+
+import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.persistence.EntityVisitor;
+import org.nuiton.topia.persistence.TopiaEntityAbstract;
+
+/**
+ * Created: 11 mai 2010
+ *
+ * @author fdesbois <fdesbois(a)codelutin.com>
+ * @version $Id$
+ */
+public abstract class Entity1Abstract extends TopiaEntityAbstract
+ implements Entity1 {
+
+ protected String attr1;
+
+ protected String attr2;
+
+ @Override
+ public String getAttr1() {
+ fireOnPreRead(ATTR_1, attr1);
+ String result = attr1;
+ fireOnPostRead(ATTR_1, attr1);
+ return result;
+ }
+
+ @Override
+ public void setAttr1(String attr1) {
+ String _oldValue = this.attr1;
+ fireOnPreWrite(ATTR_1, _oldValue, attr1);
+ this.attr1 = attr1;
+ fireOnPostWrite(ATTR_1, _oldValue, attr1);
+ }
+
+ @Override
+ public String getAttr2() {
+ fireOnPreRead(ATTR_2, attr2);
+ String result = attr2;
+ fireOnPostRead(ATTR_2, attr2);
+ return result;
+ }
+
+ @Override
+ public void setAttr2(String attr2) {
+ String _oldValue = this.attr2;
+ fireOnPreWrite(ATTR_2, _oldValue, attr2);
+ this.attr2 = attr2;
+ fireOnPostWrite(ATTR_2, _oldValue, attr2);
+ }
+
+ @Override
+ public void accept(EntityVisitor visitor) throws TopiaException {
+ visitor.start(this);
+ visitor.visit(this, ATTR_1, String.class, attr1);
+ visitor.visit(this, ATTR_2, String.class, attr2);
+ visitor.end(this);
+ }
+}
Copied: trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Impl.hbm.xml (from rev 2884, trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Impl.hbm.xml)
===================================================================
--- trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Impl.hbm.xml (rev 0)
+++ trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Impl.hbm.xml 2013-11-22 20:03:11 UTC (rev 2885)
@@ -0,0 +1,37 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ #%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%
+ -->
+
+<!--<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">-->
+<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
+<hibernate-mapping default-access="field" auto-import="true" package="org.nuiton.topia.it.legacy.topiatest">
+ <class name="org.nuiton.topia.it.legacy.topiatest.persistence.Entity1Impl" table="entity1" node="org.nuiton.topia.it.legacy.topiatest.persistence.Entity1Impl" abstract="false" proxy="org.nuiton.topia.it.legacy.topiatest.persistence.Entity1" >
+ <id name="topiaId" type="string" length="255" node="@topiaId"/>
+ <version name="topiaVersion" type="long" node="@topiaVersion"/>
+ <property name="topiaCreateDate" type="timestamp" node="@topiaCreateDate"/>
+ <property name="attr1" type="java.lang.String" access="field" column="attr1" node="attr1"/>
+ <property name="attr2" type="java.lang.String" access="field" column="attr2" node="attr2"/>
+ </class>
+</hibernate-mapping>
Copied: trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Impl.java (from rev 2884, trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Impl.java)
===================================================================
--- trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Impl.java (rev 0)
+++ trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Impl.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -0,0 +1,34 @@
+/*
+ * #%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%
+ */
+package org.nuiton.topia.it.legacy.topiatest.persistence;
+
+/**
+ * Created: 11 mai 2010
+ *
+ * @author fdesbois <fdesbois(a)codelutin.com>
+ * @version $Id$
+ */
+public class Entity1Impl extends Entity1Abstract {
+}
Copied: trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/persistence/package-info.java (from rev 2884, trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/package-info.java)
===================================================================
--- trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/persistence/package-info.java (rev 0)
+++ trunk/topia-it/src/main/java/org/nuiton/topia/it/legacy/topiatest/persistence/package-info.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -0,0 +1,28 @@
+/*
+ * #%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%
+ */
+/**
+ * Contains persistent entities for Tests.
+ */
+package org.nuiton.topia.it.legacy.topiatest.persistence;
\ No newline at end of file
Copied: trunk/topia-it/src/main/resources/TopiaContextImpl.properties (from rev 2884, trunk/topia-it/src/test/resources/TopiaContextImpl.properties)
===================================================================
--- trunk/topia-it/src/main/resources/TopiaContextImpl.properties (rev 0)
+++ trunk/topia-it/src/main/resources/TopiaContextImpl.properties 2013-11-22 20:03:11 UTC (rev 2885)
@@ -0,0 +1,34 @@
+###
+# #%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%
+###
+# Proprietes par defaut pour une base de donnees de type H2
+hibernate.hbm2ddl.auto=update
+hibernate.show_sql=false
+
+hibernate.dialect=org.hibernate.dialect.H2Dialect
+hibernate.connection.username=sa
+hibernate.connection.password=
+hibernate.connection.driver_class=org.h2.Driver
+# tchemit 2010-11-28 : comment this line, each test must define his own db path
+#hibernate.connection.url=jdbc:h2:file:target/surefire-workdir/h2data
\ No newline at end of file
Modified: trunk/topia-it/src/main/xmi/topiatest.properties
===================================================================
--- trunk/topia-it/src/main/xmi/topiatest.properties 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/main/xmi/topiatest.properties 2013-11-22 20:03:11 UTC (rev 2885)
@@ -27,13 +27,13 @@
model.tagvalue.constantPrefix=PROPERTY_
model.tagvalue.generateDTOTopiaId=true
-#org.nuiton.topiatest.Company.class.tagvalue.naturalIdMutable=false
-#org.nuiton.topiatest.Company.attribute.siret.tagvalue.naturalId=true
-#org.nuiton.topiatest.Company.attribute.name.tagvalue.naturalId=true
-#org.nuiton.topiatest.Company.attribute.name.tagvalue.notNull=false
+#org.nuiton.topia.it.legacy.topiatest.Company.class.tagvalue.naturalIdMutable=false
+#org.nuiton.topia.it.legacy.topiatest.Company.attribute.siret.tagvalue.naturalId=true
+#org.nuiton.topia.it.legacy.topiatest.Company.attribute.name.tagvalue.naturalId=true
+#org.nuiton.topia.it.legacy.topiatest.Company.attribute.name.tagvalue.notNull=false
-org.nuiton.topiatest.NaturalizedEntity.attribute.naturalIdNotNull.tagvalue.naturalId=true
-org.nuiton.topiatest.NaturalizedEntity.attribute.naturalIdNull.tagvalue.naturalId=true
-org.nuiton.topiatest.NaturalizedEntity.attribute.naturalIdNull.tagvalue.notNull=false
+org.nuiton.topia.it.legacy.topiatest.NaturalizedEntity.attribute.naturalIdNotNull.tagvalue.naturalId=true
+org.nuiton.topia.it.legacy.topiatest.NaturalizedEntity.attribute.naturalIdNull.tagvalue.naturalId=true
+org.nuiton.topia.it.legacy.topiatest.NaturalizedEntity.attribute.naturalIdNull.tagvalue.notNull=false
-org.nuiton.topiatest.Personne.attribute.otherGender.tagValue.useEnumerationName=true
\ No newline at end of file
+org.nuiton.topia.it.legacy.topiatest.Personne.attribute.otherGender.tagValue.useEnumerationName=true
\ No newline at end of file
Modified: trunk/topia-it/src/main/xmi/topiatest.zargo
===================================================================
(Binary files differ)
Deleted: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/AbstractEmployeTopiaDao.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/AbstractEmployeTopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/AbstractEmployeTopiaDao.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -1,33 +0,0 @@
-package org.nuiton.topia.it.legacy;
-
-/*
- * #%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.nuiton.topiatest.Employe;
-
-/**
- * @author Arnaud Thimel <thimel(a)codelutin.com>
- */
-public abstract class AbstractEmployeTopiaDao<E extends Employe> extends GeneratedEmployeeTopiaDao<E> {
-}
Deleted: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/AbstractPersonneTopiaDao.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/AbstractPersonneTopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/AbstractPersonneTopiaDao.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -1,34 +0,0 @@
-package org.nuiton.topia.it.legacy;
-
-/*
- * #%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.nuiton.topiatest.Personne;
-
-/**
- * @author Arnaud Thimel <thimel(a)codelutin.com>
- */
-public abstract class AbstractPersonneTopiaDao<E extends Personne> extends GeneratedPersonneTopiaDao<E> {
-
-}
Deleted: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/EmployeTopiaDao.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/EmployeTopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/EmployeTopiaDao.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -1,42 +0,0 @@
-package org.nuiton.topia.it.legacy;
-
-/*
- * #%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.util.List;
-
-import org.nuiton.topiatest.Employe;
-import org.nuiton.topiatest.Personne;
-
-/**
- * @author Arnaud Thimel <thimel(a)codelutin.com>
- */
-public class EmployeTopiaDao extends AbstractEmployeTopiaDao<Employe> {
-
- @Override
- public List<Personne> findAllPersonnesByXAndY(int x, int y) {
- return null;
- }
-
-}
Deleted: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/EmployeeDao.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/EmployeeDao.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/EmployeeDao.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -1,31 +0,0 @@
-package org.nuiton.topia.it.legacy;
-
-/*
- * #%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%
- */
-
-/**
- * @author Arnaud Thimel <thimel(a)codelutin.com>
- */
-public interface EmployeeDao {
-}
Deleted: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/GeneratedEmployeeTopiaDao.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/GeneratedEmployeeTopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/GeneratedEmployeeTopiaDao.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -1,33 +0,0 @@
-package org.nuiton.topia.it.legacy;
-
-/*
- * #%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.nuiton.topiatest.Employe;
-
-/**
- * @author Arnaud Thimel <thimel(a)codelutin.com>
- */
-public abstract class GeneratedEmployeeTopiaDao<E extends Employe> extends AbstractPersonneTopiaDao<E> {
-}
Deleted: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/GeneratedPersonneTopiaDao.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/GeneratedPersonneTopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/GeneratedPersonneTopiaDao.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -1,60 +0,0 @@
-package org.nuiton.topia.it.legacy;
-
-/*
- * #%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.util.List;
-import java.util.Map;
-
-import org.nuiton.topia.persistence.AbstractTopiaDao;
-import org.nuiton.topia.persistence.TopiaEntity;
-import org.nuiton.topia.persistence.TopiaEntityEnum;
-import org.nuiton.topiatest.Personne;
-
-/**
- * @author Arnaud Thimel <thimel(a)codelutin.com>
- */
-public abstract class GeneratedPersonneTopiaDao<E extends Personne> extends AbstractTopiaDao<E> implements PersonneDao {
-
- @Override
- public TopiaEntityEnum getTopiaEntityEnum() {
- return null;
- }
-
- @Override
- public <R extends TopiaEntity> List<R> findUsages(Class<R> type, E entity) throws TopiaException {
- return null;
- }
-
- @Override
- public Map<Class<? extends TopiaEntity>, List<? extends TopiaEntity>> findAllUsages(E entity) throws TopiaException {
- return null;
- }
-
- @Override
- public Class<E> getEntityClass() {
- return null;
- }
-
-}
Deleted: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/PersonneDao.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/PersonneDao.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/PersonneDao.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -1,38 +0,0 @@
-package org.nuiton.topia.it.legacy;
-
-/*
- * #%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.util.List;
-
-import org.nuiton.topiatest.Personne;
-
-/**
- * @author Arnaud Thimel <thimel(a)codelutin.com>
- */
-public interface PersonneDao {
-
- List<Personne> findAllPersonnesByXAndY(int x, int y);
-
-}
Deleted: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/PersonneTopiaDao.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/PersonneTopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/PersonneTopiaDao.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -1,41 +0,0 @@
-package org.nuiton.topia.it.legacy;
-
-/*
- * #%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.util.List;
-
-import org.nuiton.topiatest.Personne;
-
-/**
- * @author Arnaud Thimel <thimel(a)codelutin.com>
- */
-public class PersonneTopiaDao extends AbstractPersonneTopiaDao<Personne> {
-
- @Override
- public List<Personne> findAllPersonnesByXAndY(int x, int y) {
- return null;
- }
-
-}
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TestHelper.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TestHelper.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TestHelper.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -29,6 +29,9 @@
import org.apache.commons.logging.LogFactory;
import org.hibernate.cfg.Environment;
import org.junit.Ignore;
+import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.TopiaContextFactory;
+import org.nuiton.topia.TopiaNotFoundException;
import org.nuiton.util.FileUtil;
import java.io.File;
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaContextFactoryTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaContextFactoryTest.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaContextFactoryTest.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -30,11 +30,15 @@
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
+import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.TopiaContextFactory;
import org.nuiton.topia.framework.AbstractTopiaContext;
+import org.nuiton.topia.junit.ConfigurationHelper;
import java.io.File;
import java.io.IOException;
import java.util.List;
+import java.util.Map;
import java.util.Properties;
/**
@@ -45,9 +49,14 @@
*/
public class TopiaContextFactoryTest {
+ static class MyTopiaContextFactory extends TopiaContextFactory {
+
+ static Map<Properties, TopiaContext> getContextCache() {return contextCache;}
+ }
private static final Log log =
LogFactory.getLog(TopiaContextFactoryTest.class);
+ protected static Map<Properties, TopiaContext> contextCache;
protected static File testBasedir;
protected Properties properties;
@@ -55,8 +64,8 @@
@BeforeClass
public static void init() throws IOException {
- testBasedir = TopiaDatabase.getTestSpecificDirectory(TopiaContextFactoryTest.class, "dummy");
-
+ testBasedir = ConfigurationHelper.getTestSpecificDirectory(TopiaContextFactoryTest.class, "dummy");
+ contextCache = MyTopiaContextFactory.getContextCache();
}
@Before
@@ -64,7 +73,7 @@
properties = new Properties();
properties.setProperty("prop1", "value1");
properties.setProperty("prop2", "value2");
- TopiaContextFactory.contextCache.clear();
+ contextCache.clear();
}
@Test
@@ -78,7 +87,7 @@
properties.setProperty("hibernate.connection.url", url);
AbstractTopiaContext test = new AbstractTopiaContext(properties);
- TopiaContextFactory.contextCache.put(properties, test);
+ contextCache.put(properties, test);
/** EXEC METHOD **/
List<String> result = TopiaContextFactory.getContextOpened();
@@ -92,11 +101,11 @@
/** PREPARE DATA **/
AbstractTopiaContext test = new AbstractTopiaContext(properties);
- TopiaContextFactory.contextCache.put(properties, test);
+ contextCache.put(properties, test);
/** EXEC METHOD **/
TopiaContextFactory.removeContext(test);
- Assert.assertEquals(0, TopiaContextFactory.contextCache.size());
+ Assert.assertEquals(0, contextCache.size());
}
//@Test
@@ -131,29 +140,29 @@
" TopiaContext");
TopiaContext test1 = TopiaContextFactory.getContext(propertiesParent);
Assert.assertNotNull(test1);
- Assert.assertEquals(1, TopiaContextFactory.contextCache.size());
+ Assert.assertEquals(1, contextCache.size());
log.info("test 2 : with same properties, will retrieve existing" +
" TopiaContext");
TopiaContext test2 = TopiaContextFactory.getContext(propertiesParent);
Assert.assertEquals(test1, test2);
- Assert.assertEquals(1, TopiaContextFactory.contextCache.size());
+ Assert.assertEquals(1, contextCache.size());
log.info("test 3 : use other properties, will instantiate a different" +
"TopiaContext");
TopiaContext test3 = TopiaContextFactory.getContext(properties);
- log.debug("cache size : " + TopiaContextFactory.contextCache.size());
+ log.debug("cache size : " + contextCache.size());
log.debug("result : " + test1);
log.debug("result3 : " + test3);
Assert.assertNotSame(test1, test3);
- Assert.assertEquals(2, TopiaContextFactory.contextCache.size());
+ Assert.assertEquals(2, contextCache.size());
log.info("test 4 : use other properties but equivalent to existing " +
"TopiaContext");
// Test flating of properties
TopiaContext test4 = TopiaContextFactory.getContext(propertiesAll);
Assert.assertEquals(test1, test4);
- Assert.assertEquals(2, TopiaContextFactory.contextCache.size());
+ Assert.assertEquals(2, contextCache.size());
log.info("test5a : reinstantiate new TopiaContext after one is closed.");
// TEST
@@ -175,7 +184,7 @@
TopiaContext test5 = TopiaContextFactory.getContext(properties);
Assert.assertNotSame(test1, test5);
- Assert.assertEquals(3, TopiaContextFactory.contextCache.size());
+ Assert.assertEquals(3, contextCache.size());
log.info("test5b : beginTransaction to properly close the context");
test5.beginTransaction();
@@ -184,6 +193,6 @@
TopiaContext result = TopiaContextFactory.getContext(properties);
Assert.assertNotSame(test5, result);
- Assert.assertEquals(3, TopiaContextFactory.contextCache.size());
+ Assert.assertEquals(3, contextCache.size());
}
}
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaDatabase.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaDatabase.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaDatabase.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -24,17 +24,8 @@
*/
package org.nuiton.topia.it.legacy;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.hibernate.cfg.Configuration;
-import org.junit.rules.TestWatcher;
-import org.junit.runner.Description;
-import org.nuiton.topia.HibernateProvider;
-import org.nuiton.topia.TopiaContextFactory;
-import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.junit.AbstractDatabaseResource;
-import java.io.File;
-import java.io.InputStream;
import java.util.Properties;
/**
@@ -62,149 +53,27 @@
* @author tchemit <chemit(a)codelutin.com>
* @since 2.6.8
*/
-public class TopiaDatabase extends TestWatcher {
+public class TopiaDatabase extends AbstractDatabaseResource<TopiaTestTopiaPersistenceContext, TopiaTestTopiaApplicationContext> {
- /** Logger. */
- private static final Log log = LogFactory.getLog(TopiaDatabase.class);
+ public static final String DEFAULT_CONFIGURATION_LOCATION = "/TopiaContextImpl.properties";
- /** A time-stamp, allow to make multiple build and keep the tests data. */
- public static final String TIMESTAMP = String.valueOf(System.nanoTime());
-
- private File testBasedir;
-
- private Properties dbConfiguration;
-
- private TopiaTestTopiaApplicationContext applicationContext;
-
- private Configuration hibernateCfg;
-
- private final String configurationPath;
-
public TopiaDatabase() {
- this(TestHelper.DEFAULT_CONFIGURATION_LOCATION);
+ this(DEFAULT_CONFIGURATION_LOCATION);
}
public TopiaDatabase(String configurationPath) {
- this.configurationPath = configurationPath;
+ super(configurationPath);
}
@Override
- protected void starting(Description description) {
-
- // get test directory
- testBasedir = getTestSpecificDirectory(
- description.getTestClass(),
- description.getMethodName());
-
- if (log.isDebugEnabled()) {
- log.debug("testBasedir = " + testBasedir);
- }
-
- // create the root context
- try {
-
- dbConfiguration = new Properties();
- InputStream stream =
- getClass().getResourceAsStream(configurationPath);
-
- try {
- dbConfiguration.load(stream);
- } finally {
- stream.close();
- }
- dbConfiguration.setProperty(
- TopiaContextFactory.CONFIG_PERSISTENCE_CLASSES,
- TopiaTestDAOHelper.getImplementationClassesAsString());
-
- // make sure we always use a different directory
-
- String dbPath = new File(testBasedir, "db").getAbsolutePath();
-
- if (log.isDebugEnabled()) {
- log.debug("dbPath = " + dbPath);
- }
- dbConfiguration.setProperty(
- TopiaContextFactory.CONFIG_URL, "jdbc:h2:file:" + dbPath);
-
- onDbConfigurationCreate(dbConfiguration, testBasedir, dbPath);
-
-// rootCtxt = TopiaContextFactory.getContext(dbConfiguration);
- applicationContext = new TopiaTestTopiaApplicationContext(dbConfiguration) {
- @Override
- protected HibernateProvider getHibernateProvider() {
- HibernateProvider provider = super.getHibernateProvider();
- hibernateCfg = provider.getHibernateConfiguration();
- return provider;
- }
- };
- } catch (Exception e) {
- throw new IllegalStateException(
- "Could not start db at " + testBasedir, e);
- }
+ protected TopiaTestTopiaApplicationContext createApplicationContext(Properties dbConfiguration) {
+ return new TopiaTestTopiaApplicationContext(dbConfiguration);
}
@Override
- public void finished(Description description) {
-
- if (applicationContext != null && !applicationContext.isClosed()) {
- try {
- applicationContext.closeContext();
- } catch (TopiaException e) {
- if (log.isErrorEnabled()) {
- log.error("Could not close topia root context", e);
- }
- }
- }
- applicationContext = null;
- dbConfiguration = null;
+ protected String getImplementationClassesAsString() {
+ return TopiaTestDAOHelper.getImplementationClassesAsString();
}
- public File getTestBasedir() {
- return testBasedir;
- }
-
- public Properties getDbConfiguration() {
- return dbConfiguration;
- }
-
- public TopiaTestTopiaApplicationContext getApplicationContext() {
- return applicationContext;
- }
-
- public Configuration getHibernateCfg() {
- return hibernateCfg;
- }
-
- public TopiaTestTopiaPersistenceContext beginTransaction() throws TopiaException {
- return applicationContext.newPersistenceContext();
- }
-
- protected void onDbConfigurationCreate(Properties configuration,
- File testDir,
- String dbPath) {
-
- }
-
- public static File getTestSpecificDirectory(Class<?> testClassName, String methodName) {
- // Trying to look for the temporary folder to store data for the test
- String tempDirPath = System.getProperty("java.io.tmpdir");
- if (tempDirPath == null) {
- // can this really occur ?
- tempDirPath = "";
- if (log.isWarnEnabled()) {
- log.warn("'\"java.io.tmpdir\" not defined");
- }
- }
- File tempDirFile = new File(tempDirPath);
-
- // create the directory to store database data
- String dataBasePath = testClassName.getName()
- + File.separator // a directory with the test class name
- + methodName// a sub-directory with the method name
- + '_'
- + TIMESTAMP; // and a timestamp
- File databaseFile = new File(tempDirFile, dataBasePath);
- return databaseFile;
- }
}
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaJpaSupportTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaJpaSupportTest.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaJpaSupportTest.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -23,16 +23,22 @@
*/
package org.nuiton.topia.it.legacy;
+import org.apache.commons.lang3.reflect.FieldUtils;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-import org.nuiton.topiatest.Address;
-import org.nuiton.topiatest.AddressTopiaDao;
-import org.nuiton.topiatest.Gender;
-import org.nuiton.topiatest.Personne;
-import org.nuiton.topiatest.PersonneTopiaDao;
+import org.nuiton.topia.AbstractTopiaPersistenceContext;
+import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.TopiaJpaSupport;
+import org.nuiton.topia.it.legacy.topiatest.Address;
+import org.nuiton.topia.it.legacy.topiatest.AddressTopiaDao;
+import org.nuiton.topia.it.legacy.topiatest.Gender;
+import org.nuiton.topia.it.legacy.topiatest.Personne;
+import org.nuiton.topia.it.legacy.topiatest.PersonneTopiaDao;
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
import java.util.List;
/**
@@ -46,16 +52,24 @@
public final TopiaDatabase db = new TopiaDatabase();
protected TopiaTestTopiaPersistenceContext persistenceContext;
+
protected TopiaJpaSupport jpaSupport;
+
protected AddressTopiaDao addressDAO;
+
protected PersonneTopiaDao personneDAO;
+
protected Address address;
@Before
- public void createCompanies() throws TopiaException {
+ public void createCompanies() throws TopiaException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
persistenceContext = db.beginTransaction();
- jpaSupport = persistenceContext.jpaSupport;
+// jpaSupport = persistenceContext.jpaSupport;
+ Field field = FieldUtils.getField(AbstractTopiaPersistenceContext.class, "jpaSupport", true);
+ field.setAccessible(true);
+ jpaSupport = (TopiaJpaSupport) field.get(persistenceContext);
+
personneDAO = persistenceContext.getPersonneDao();
addressDAO = persistenceContext.getAddressDao();
@@ -91,7 +105,7 @@
Assert.assertEquals(3, personneDAO.count());
String query = "from " + Personne.class.getName() +
- " where " + Personne.PROPERTY_GENDER + "=:g";
+ " where " + Personne.PROPERTY_GENDER + "=:g";
List females = jpaSupport.findAll(query, "g", Gender.FEMALE);
Assert.assertEquals(2, females.size());
@@ -103,7 +117,7 @@
Assert.assertEquals(3, all.size());
List none = jpaSupport.findAll("from " + Personne.class.getName() +
- " where " + Personne.PROPERTY_NAME + "=:pax", "pax", "nobody");
+ " where " + Personne.PROPERTY_NAME + "=:pax", "pax", "nobody");
Assert.assertEquals(0, none.size());
}
@@ -112,18 +126,18 @@
Assert.assertEquals(3, personneDAO.count());
String query = "from " + Personne.class.getName() +
- " where " + Personne.PROPERTY_GENDER + "=:g";
+ " where " + Personne.PROPERTY_GENDER + "=:g";
List females = jpaSupport.find(query, 0, 100, "g", Gender.FEMALE);
Assert.assertEquals(2, females.size());
females = jpaSupport.find(query, 0, 0, "g", Gender.FEMALE);
Assert.assertEquals(1, females.size());
- Personne charlotte = (Personne)females.get(0);
+ Personne charlotte = (Personne) females.get(0);
females = jpaSupport.find(query, 1, 1, "g", Gender.FEMALE);
Assert.assertEquals(1, females.size());
- Personne hortense = (Personne)females.get(0);
+ Personne hortense = (Personne) females.get(0);
Assert.assertFalse(hortense.equals(charlotte));
@@ -137,13 +151,13 @@
Assert.assertEquals(3, personneDAO.count());
String query = "from " + Personne.class.getName() +
- " where " + Personne.PROPERTY_GENDER + "=:g";
+ " where " + Personne.PROPERTY_GENDER + "=:g";
Object male = jpaSupport.findUnique(query, "g", Gender.MALE);
Assert.assertNotNull(male);
Object none = jpaSupport.findUnique("from " + Personne.class.getName() +
- " where " + Personne.PROPERTY_NAME + "=:pax", "pax", "nobody");
+ " where " + Personne.PROPERTY_NAME + "=:pax", "pax", "nobody");
Assert.assertNull(none);
}
@@ -152,7 +166,7 @@
Assert.assertEquals(3, personneDAO.count());
String query = "from " + Personne.class.getName() +
- " where " + Personne.PROPERTY_GENDER + "=:g";
+ " where " + Personne.PROPERTY_GENDER + "=:g";
Object female = jpaSupport.findUnique(query, "g", Gender.FEMALE);
Assert.assertNotNull(female);
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaConnectionProviderTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaConnectionProviderTest.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaConnectionProviderTest.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -28,15 +28,14 @@
import org.junit.Rule;
import org.junit.Test;
import org.nuiton.topia.TopiaContextFactory;
-import org.nuiton.topia.TopiaDatabase;
import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.TopiaTestDAOHelper;
-import org.nuiton.topia.TopiaTestTopiaPersistenceContext;
+import org.nuiton.topia.it.legacy.TopiaTestDAOHelper;
+import org.nuiton.topia.it.legacy.TopiaTestTopiaPersistenceContext;
import org.nuiton.topia.framework.TopiaConnectionProvider;
-import org.nuiton.topia.test.entities.Person;
-import org.nuiton.topia.test.entities.PersonDAO;
-import org.nuiton.topia.test.entities.PersonTopiaDao;
-import org.nuiton.topiatest.Personne;
+import org.nuiton.topia.it.legacy.TopiaDatabase;
+import org.nuiton.topia.it.legacy.test.entities.Person;
+import org.nuiton.topia.it.legacy.test.entities.PersonDAO;
+import org.nuiton.topia.it.legacy.topiatest.Personne;
import java.io.File;
import java.util.Locale;
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextImplTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextImplTest.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextImplTest.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -26,27 +26,20 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.h2.Driver;
-import org.hibernate.cfg.Configuration;
-import org.hibernate.mapping.PersistentClass;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
-import org.nuiton.topia.TopiaContextFactory;
-import org.nuiton.topia.TopiaDatabase;
import org.nuiton.topia.TopiaNotFoundException;
import org.nuiton.topia.framework.AbstractTopiaContext;
import org.nuiton.topia.framework.TopiaContextImplementor;
import org.nuiton.topia.framework.TopiaService;
-import org.nuiton.topiatest.persistence.Entity1;
-import org.nuiton.topia.it.legacy.topiatest.persistence.Entity1Impl;
-import org.nuiton.topiatest.service.FakeService;
-import org.nuiton.topiatest.service.TestService;
+import org.nuiton.topia.it.legacy.topiatest.service.FakeService;
+import org.nuiton.topia.it.legacy.topiatest.service.TestService;
+import org.nuiton.topia.junit.ConfigurationHelper;
import java.io.File;
-import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
@@ -58,6 +51,35 @@
*/
public class TopiaContextImplTest {
+ class MyAbstractTopiaContext extends AbstractTopiaContext {
+
+ MyAbstractTopiaContext(TopiaContextImplementor parentContext) {
+ super(parentContext);
+ }
+
+ MyAbstractTopiaContext(Properties config) throws TopiaNotFoundException {
+ super(config);
+ }
+
+ MyAbstractTopiaContext() {
+ }
+
+ @Override
+ protected Map<String, TopiaService> loadServices(Properties config) {
+ return super.loadServices(config);
+ }
+
+ @Override
+ protected boolean serviceEnabled(String name) {
+ return super.serviceEnabled(name);
+ }
+
+ @Override
+ protected TopiaService getService(String name) {
+ return super.getService(name);
+ }
+ }
+
private static final Log log =
LogFactory.getLog(TopiaContextImplTest.class);
@@ -68,7 +90,7 @@
@BeforeClass
public static void setUpClass() throws Exception {
- testBasedir = TopiaDatabase.getTestSpecificDirectory(TopiaContextImplTest.class, "dummy");
+ testBasedir = ConfigurationHelper.getTestSpecificDirectory(TopiaContextImplTest.class, "dummy");
}
@Before
@@ -90,7 +112,7 @@
properties.setProperty("topia.service.test",
TestService.class.getName());
- AbstractTopiaContext context = new AbstractTopiaContext();
+ MyAbstractTopiaContext context = new MyAbstractTopiaContext();
/** EXEC METHOD **/
if (log.isInfoEnabled()) {
@@ -140,7 +162,7 @@
AbstractTopiaContext context = new AbstractTopiaContext(properties);
// Instantiate a child context and set its parent
- AbstractTopiaContext child = new AbstractTopiaContext(context);
+ MyAbstractTopiaContext child = new MyAbstractTopiaContext(context);
/** EXEC METHOD **/
if (log.isInfoEnabled()) {
@@ -204,55 +226,55 @@
}
}
- @Test
- public void testContextHierarchy() throws Exception {
- if (log.isDebugEnabled()) {
- log.debug("## testContextHierarchy");
- }
-
- /** PREPARE DATA **/
- AbstractTopiaContext context = new AbstractTopiaContext(properties);
-
- /** EXEC METHODS **/
- if (log.isInfoEnabled()) {
- log.info("test 1 : constructor with parent context");
- }
- AbstractTopiaContext test1 = new AbstractTopiaContext(context);
- Assert.assertEquals(context, test1.parentContext);
-
- if (log.isInfoEnabled()) {
- log.info("test 2 : addChildContext");
- }
- AbstractTopiaContext test2 = new AbstractTopiaContext(properties);
- AbstractTopiaContext child2 = new AbstractTopiaContext();
- test2.addChildContext(child2);
- Assert.assertEquals(1, test2.childContext.size());
-
- if (log.isInfoEnabled()) {
- log.info("test 3 : removeChildContext");
- }
- AbstractTopiaContext test3 = new AbstractTopiaContext(properties);
- AbstractTopiaContext child3 = new AbstractTopiaContext(test3);
- test3.childContext.add(child3);
- test3.removeChildContext(child3);
- Assert.assertEquals(0, test3.childContext.size());
-
- // No remove if context is closed
- test3.childContext.add(child3);
- test3.closed = true;
- test3.removeChildContext(child3);
- Assert.assertEquals(1, test3.childContext.size());
-
- if (log.isInfoEnabled()) {
- log.info("test 4 : getRootContext");
- }
- TopiaContextImplementor test4 = child3.getRootContext();
- Assert.assertEquals(test3, test4);
-
- // Note : existing test is already done for concurrency problem on
- // getChildContext(). Go to : http://www.nuiton.org/repositories/browse/sandbox/testTopiaPostgresError/tr…
- }
+// @Test
+// public void testContextHierarchy() throws Exception {
+// if (log.isDebugEnabled()) {
+// log.debug("## testContextHierarchy");
+// }
//
+// /** PREPARE DATA **/
+// MyAbstractTopiaContext context = new MyAbstractTopiaContext(properties);
+//
+// /** EXEC METHODS **/
+// if (log.isInfoEnabled()) {
+// log.info("test 1 : constructor with parent context");
+// }
+// AbstractTopiaContext test1 = new AbstractTopiaContext(context);
+// Assert.assertEquals(context, test1.parentContext);
+//
+// if (log.isInfoEnabled()) {
+// log.info("test 2 : addChildContext");
+// }
+// AbstractTopiaContext test2 = new AbstractTopiaContext(properties);
+// AbstractTopiaContext child2 = new AbstractTopiaContext();
+// test2.addChildContext(child2);
+// Assert.assertEquals(1, test2.childContext.size());
+//
+// if (log.isInfoEnabled()) {
+// log.info("test 3 : removeChildContext");
+// }
+// AbstractTopiaContext test3 = new AbstractTopiaContext(properties);
+// AbstractTopiaContext child3 = new AbstractTopiaContext(test3);
+// test3.childContext.add(child3);
+// test3.removeChildContext(child3);
+// Assert.assertEquals(0, test3.childContext.size());
+//
+// // No remove if context is closed
+// test3.childContext.add(child3);
+// test3.closed = true;
+// test3.removeChildContext(child3);
+// Assert.assertEquals(1, test3.childContext.size());
+//
+// if (log.isInfoEnabled()) {
+// log.info("test 4 : getRootContext");
+// }
+// TopiaContextImplementor test4 = child3.getRootContext();
+// Assert.assertEquals(test3, test4);
+//
+// // Note : existing test is already done for concurrency problem on
+// // getChildContext(). Go to : http://www.nuiton.org/repositories/browse/sandbox/testTopiaPostgresError/tr…
+// }
+//
// @Test
// public void testCreateSchema() throws Exception {
// }
@@ -270,100 +292,100 @@
// }
//
- @Test
- public void testGetHibernateFactory() throws Exception {
- if (log.isDebugEnabled()) {
- log.debug("## testGetHibernateFactory");
- }
-
- /** PREPARE DATA **/
- AbstractTopiaContext context = new AbstractTopiaContext();
- context.services = new HashMap<String, TopiaService>();
-
- String basedir = System.getenv("basedir");
- if (basedir == null) {
-
- // says basedir is where we start tests.
- basedir = new File("").getAbsolutePath();
- }
-
- if (log.isDebugEnabled()) {
- log.debug("baseDir : " + basedir);
- }
- File persistenceDir = new File(basedir,
- "target" + File.separator +
- "test-classes" + File.separator +
- "org" + File.separator +
- "nuiton" + File.separator +
- "topiatest" + File.separator +
- "persistence");
- if (log.isDebugEnabled()) {
- log.debug("persistenceDir : " + persistenceDir);
- }
- File resourcesDir = new File(basedir,
- "target" + File.separator +
- "test-classes");
-
- /** EXEC METHOD **/
- if (log.isInfoEnabled()) {
- log.info("test 1 : load mappings from directory");
- }
-
- properties.setProperty(TopiaContextFactory.CONFIG_PERSISTENCE_DIRECTORIES,
- persistenceDir.getAbsolutePath());
- context.config = properties;
-
- Configuration test1 = context.getHibernateConfiguration();
- PersistentClass persistentClass =
- test1.getClassMapping(Entity1Impl.class.getName());
- Assert.assertNotNull(persistentClass);
- Assert.assertEquals(Entity1.class, persistentClass.getProxyInterface());
-
-// for (Iterator<RootClass> it = test1.getClassMappings(); it.hasNext();) {
-// RootClass o = it.next();
-// log.debug("entity : " + o.getEntityName());
+// @Test
+// public void testGetHibernateFactory() throws Exception {
+// if (log.isDebugEnabled()) {
+// log.debug("## testGetHibernateFactory");
// }
+//
+// /** PREPARE DATA **/
+// AbstractTopiaContext context = new AbstractTopiaContext();
+// context.services = new HashMap<String, TopiaService>();
+//
+// String basedir = System.getenv("basedir");
+// if (basedir == null) {
+//
+// // says basedir is where we start tests.
+// basedir = new File("").getAbsolutePath();
+// }
+//
+// if (log.isDebugEnabled()) {
+// log.debug("baseDir : " + basedir);
+// }
+// File persistenceDir = new File(basedir,
+// "target" + File.separator +
+// "test-classes" + File.separator +
+// "org" + File.separator +
+// "nuiton" + File.separator +
+// "topiatest" + File.separator +
+// "persistence");
+// if (log.isDebugEnabled()) {
+// log.debug("persistenceDir : " + persistenceDir);
+// }
+// File resourcesDir = new File(basedir,
+// "target" + File.separator +
+// "test-classes");
+//
+// /** EXEC METHOD **/
+// if (log.isInfoEnabled()) {
+// log.info("test 1 : load mappings from directory");
+// }
+//
+// properties.setProperty(TopiaContextFactory.CONFIG_PERSISTENCE_DIRECTORIES,
+// persistenceDir.getAbsolutePath());
+// context.config = properties;
+//
+// Configuration test1 = context.getHibernateConfiguration();
+// PersistentClass persistentClass =
+// test1.getClassMapping(Entity1Impl.class.getName());
+// Assert.assertNotNull(persistentClass);
+// Assert.assertEquals(Entity1.class, persistentClass.getProxyInterface());
+//
+//// for (Iterator<RootClass> it = test1.getClassMappings(); it.hasNext();) {
+//// RootClass o = it.next();
+//// log.debug("entity : " + o.getEntityName());
+//// }
+//
+// if (log.isInfoEnabled()) {
+// log.info("test 2 : load mappings for all entities");
+// }
+// //reset from previous test
+// context = new AbstractTopiaContext();
+// context.services = new HashMap<String, TopiaService>();
+// properties.clear();
+//
+// // use property TOPIA_PERSISTENCE_CLASSES
+// properties.setProperty(TopiaContextFactory.CONFIG_PERSISTENCE_CLASSES,
+// Entity1Impl.class.getName());
+// context.config = properties;
+//
+// Configuration test2 = context.getHibernateConfiguration();
+// persistentClass = test2.getClassMapping(Entity1Impl.class.getName());
+// Assert.assertNotNull(persistentClass);
+// Assert.assertEquals(Entity1.class, persistentClass.getProxyInterface());
+//
+// if (log.isInfoEnabled()) {
+// log.info("test 3 : add properties from file");
+// }
+// //reset from previous test
+// context = new AbstractTopiaContext();
+// context.services = new HashMap<String, TopiaService>();
+// properties.clear();
+//
+// // use property TOPIA_PERSISTENCE_PROPERTIES_FILE to add default
+// // properties from file
+// properties.setProperty(TopiaContextFactory.CONFIG_PERSISTENCE_PROPERTIES_FILE,
+// resourcesDir + File.separator + "TopiaContextImpl.properties");
+// context.config = properties;
+//
+// Configuration test3 = context.getHibernateConfiguration();
+// Assert.assertEquals(
+// test3.getProperty("hibernate.connection.driver_class"),
+// Driver.class.getName());
+//
+// // Note : maybe add a test to load classes from services
+// }
- if (log.isInfoEnabled()) {
- log.info("test 2 : load mappings for all entities");
- }
- //reset from previous test
- context = new AbstractTopiaContext();
- context.services = new HashMap<String, TopiaService>();
- properties.clear();
-
- // use property TOPIA_PERSISTENCE_CLASSES
- properties.setProperty(TopiaContextFactory.CONFIG_PERSISTENCE_CLASSES,
- Entity1Impl.class.getName());
- context.config = properties;
-
- Configuration test2 = context.getHibernateConfiguration();
- persistentClass = test2.getClassMapping(Entity1Impl.class.getName());
- Assert.assertNotNull(persistentClass);
- Assert.assertEquals(Entity1.class, persistentClass.getProxyInterface());
-
- if (log.isInfoEnabled()) {
- log.info("test 3 : add properties from file");
- }
- //reset from previous test
- context = new AbstractTopiaContext();
- context.services = new HashMap<String, TopiaService>();
- properties.clear();
-
- // use property TOPIA_PERSISTENCE_PROPERTIES_FILE to add default
- // properties from file
- properties.setProperty(TopiaContextFactory.CONFIG_PERSISTENCE_PROPERTIES_FILE,
- resourcesDir + File.separator + "TopiaContextImpl.properties");
- context.config = properties;
-
- Configuration test3 = context.getHibernateConfiguration();
- Assert.assertEquals(
- test3.getProperty("hibernate.connection.driver_class"),
- Driver.class.getName());
-
- // Note : maybe add a test to load classes from services
- }
-
// @Test
// public void replicateEntity() throws Exception {
//
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextReplicateTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextReplicateTest.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextReplicateTest.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -28,13 +28,13 @@
import org.junit.Rule;
import org.junit.Test;
import org.nuiton.topia.TopiaContextFactory;
-import org.nuiton.topia.TopiaDatabase;
-import org.nuiton.topia.TopiaTestDAOHelper;
-import org.nuiton.topia.TopiaTestTopiaPersistenceContext;
-import org.nuiton.topia.test.entities.Person;
-import org.nuiton.topia.test.entities.PersonDAO;
-import org.nuiton.topia.test.entities.Pet;
-import org.nuiton.topia.test.entities.PetDAO;
+import org.nuiton.topia.it.legacy.TopiaDatabase;
+import org.nuiton.topia.it.legacy.TopiaTestDAOHelper;
+import org.nuiton.topia.it.legacy.TopiaTestTopiaPersistenceContext;
+import org.nuiton.topia.it.legacy.test.entities.Person;
+import org.nuiton.topia.it.legacy.test.entities.PersonDAO;
+import org.nuiton.topia.it.legacy.test.entities.Pet;
+import org.nuiton.topia.it.legacy.test.entities.PetDAO;
import java.io.File;
import java.util.Properties;
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaUtilTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaUtilTest.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaUtilTest.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -31,10 +31,10 @@
import org.hibernate.cfg.Configuration;
import org.junit.Rule;
import org.junit.Test;
-import org.nuiton.topia.TopiaDatabase;
+import org.nuiton.topia.it.legacy.TopiaDatabase;
import org.nuiton.topia.framework.TopiaUtil;
-import org.nuiton.topia.test.entities.PersonImpl;
-import org.nuiton.topiatest.Personne;
+import org.nuiton.topia.it.legacy.test.entities.PersonImpl;
+import org.nuiton.topia.it.legacy.topiatest.Personne;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@@ -51,9 +51,9 @@
*/
public class TopiaUtilTest {
- protected static final String PERSON_ID = "org.nuiton.topiatest.Personne#1226701039001#0.6502325993664224";
+ protected static final String PERSON_ID = "org.nuiton.topia.it.legacy.topiatest.Personne#1226701039001#0.6502325993664224";
- protected static final String PERSON_ID2 = "org.nuiton.topiatest.Personne#1226701039001#0.6502325993664999";
+ protected static final String PERSON_ID2 = "org.nuiton.topia.it.legacy.topiatest.Personne#1226701039001#0.6502325993664999";
@Rule
public final TopiaDatabase db = new TopiaDatabase();
@@ -63,7 +63,7 @@
String expected;
String actual;
- expected = "org\\.nuiton\\.topiatest\\.Personne#(?:\\d+?)#(?:\\d+)\\.(?:\\d+)";
+ expected = "org\\.nuiton\\.topia\\.it\\.legacy\\.topiatest\\.Personne#(?:\\d+?)#(?:\\d+)\\.(?:\\d+)";
actual = TopiaUtil.getTopiaIdPattern(Personne.class);
assertEquals(expected, actual);
}
@@ -73,7 +73,7 @@
String expected;
Pattern pattern;
- expected = "(\\d+)-(org\\.nuiton\\.topiatest\\.Personne#(?:\\d+?)#(?:\\d+)\\.(?:\\d+))-(org\\.nuiton\\.topiatest\\.Personne#(?:\\d+?)#(?:\\d+)\\.(?:\\d+))(.*)";
+ expected = "(\\d+)-(org\\.nuiton\\.topia\\.it\\.legacy\\.topiatest\\.Personne#(?:\\d+?)#(?:\\d+)\\.(?:\\d+))-(org\\.nuiton\\.topia\\.it\\.legacy\\.topiatest\\.Personne#(?:\\d+?)#(?:\\d+)\\.(?:\\d+))(.*)";
pattern = TopiaUtil.getTopiaPattern("(\\d+)-%1$s-%1$s(.*)", Personne.class);
assertEquals(expected, pattern.toString());
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/generator/TopiaTestCase.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/generator/TopiaTestCase.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/generator/TopiaTestCase.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -30,14 +30,14 @@
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
-import org.nuiton.topia.TopiaDatabase;
+import org.nuiton.topia.it.legacy.TopiaDatabase;
import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.TopiaTestDAOHelper;
-import org.nuiton.topia.TopiaTestTopiaPersistenceContext;
-import org.nuiton.topiatest.Company;
-import org.nuiton.topiatest.CompanyDAO;
-import org.nuiton.topiatest.Department;
-import org.nuiton.topiatest.DepartmentDAO;
+import org.nuiton.topia.it.legacy.TopiaTestDAOHelper;
+import org.nuiton.topia.it.legacy.TopiaTestTopiaPersistenceContext;
+import org.nuiton.topia.it.legacy.topiatest.Company;
+import org.nuiton.topia.it.legacy.topiatest.CompanyDAO;
+import org.nuiton.topia.it.legacy.topiatest.Department;
+import org.nuiton.topia.it.legacy.topiatest.DepartmentDAO;
/**
* TopiaTestCase.
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/EntityVisitorExportXmlTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/EntityVisitorExportXmlTest.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/EntityVisitorExportXmlTest.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -23,24 +23,26 @@
* #L%
*/
-package org.nuiton.topia.persistence;
+package org.nuiton.topia.it.legacy.persistence;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-import org.nuiton.topia.TopiaDatabase;
+import org.nuiton.topia.it.legacy.TopiaDatabase;
import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.TopiaTestTopiaPersistenceContext;
-import org.nuiton.topiatest.Address;
-import org.nuiton.topiatest.AddressTopiaDao;
-import org.nuiton.topiatest.Company;
-import org.nuiton.topiatest.CompanyTopiaDao;
-import org.nuiton.topiatest.Department;
-import org.nuiton.topiatest.DepartmentTopiaDao;
-import org.nuiton.topiatest.Employe;
-import org.nuiton.topiatest.EmployeTopiaDao;
+import org.nuiton.topia.it.legacy.TopiaTestTopiaPersistenceContext;
+import org.nuiton.topia.it.legacy.topiatest.Address;
+import org.nuiton.topia.it.legacy.topiatest.AddressTopiaDao;
+import org.nuiton.topia.it.legacy.topiatest.Company;
+import org.nuiton.topia.it.legacy.topiatest.CompanyTopiaDao;
+import org.nuiton.topia.it.legacy.topiatest.Department;
+import org.nuiton.topia.it.legacy.topiatest.DepartmentTopiaDao;
+import org.nuiton.topia.it.legacy.topiatest.Employe;
+import org.nuiton.topia.it.legacy.topiatest.EmployeTopiaDao;
+import org.nuiton.topia.persistence.DepthEntityVisitor;
+import org.nuiton.topia.persistence.EntityVisitor;
/**
* Test de visitor.
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/ExportXMLVisitor.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/ExportXMLVisitor.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/ExportXMLVisitor.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -23,12 +23,14 @@
* #L%
*/
-package org.nuiton.topia.persistence;
+package org.nuiton.topia.it.legacy.persistence;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Ignore;
+import org.nuiton.topia.persistence.EntityVisitor;
+import org.nuiton.topia.persistence.TopiaEntity;
/**
* Visitor pour export xml.
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/HqlAndParametersBuilderTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/HqlAndParametersBuilderTest.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/HqlAndParametersBuilderTest.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -34,9 +34,20 @@
public class HqlAndParametersBuilderTest {
- protected HqlAndParametersBuilder hqlAndParametersBuilder =
- new HqlAndParametersBuilder(TopiaEntity.class);
+ class MyHqlAndParametersBuilder extends HqlAndParametersBuilder {
+ public MyHqlAndParametersBuilder(Class entityClass) {
+ super(entityClass);
+ }
+
+ @Override
+ public String putHqlParameterWithAvailableName(String propertyName, Object value) {
+ return super.putHqlParameterWithAvailableName(propertyName, value);
+ }
+ }
+ protected MyHqlAndParametersBuilder hqlAndParametersBuilder =
+ new MyHqlAndParametersBuilder(TopiaEntity.class);
+
protected static final Collection<String> SOME_VALUES =
Lists.newArrayList("value1", "value2", "value3");
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/NaturalIdTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/NaturalIdTest.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/NaturalIdTest.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -23,7 +23,7 @@
* #L%
*/
-package org.nuiton.topia.persistence;
+package org.nuiton.topia.it.legacy.persistence;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -31,12 +31,12 @@
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
-import org.nuiton.topia.TopiaDatabase;
+import org.nuiton.topia.it.legacy.TopiaDatabase;
import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.TopiaTestDAOHelper;
-import org.nuiton.topia.TopiaTestTopiaPersistenceContext;
-import org.nuiton.topiatest.NaturalizedEntity;
-import org.nuiton.topiatest.NaturalizedEntityDAO;
+import org.nuiton.topia.it.legacy.TopiaTestDAOHelper;
+import org.nuiton.topia.it.legacy.TopiaTestTopiaPersistenceContext;
+import org.nuiton.topia.it.legacy.topiatest.NaturalizedEntity;
+import org.nuiton.topia.it.legacy.topiatest.NaturalizedEntityDAO;
/**
* NaturalIdTest
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/TopiaDAOTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/TopiaDAOTest.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/TopiaDAOTest.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -23,7 +23,7 @@
* #L%
*/
-package org.nuiton.topia.persistence;
+package org.nuiton.topia.it.legacy.persistence;
import java.util.List;
@@ -32,13 +32,14 @@
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
-import org.nuiton.topia.TopiaDatabase;
+import org.nuiton.topia.it.legacy.TopiaDatabase;
import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.TopiaTestTopiaPersistenceContext;
-import org.nuiton.topia.test.entities.Person;
-import org.nuiton.topia.test.entities.PersonDAO;
+import org.nuiton.topia.it.legacy.TopiaTestTopiaPersistenceContext;
+import org.nuiton.topia.it.legacy.test.entities.Person;
+import org.nuiton.topia.it.legacy.test.entities.PersonDAO;
import com.google.common.collect.Lists;
+import org.nuiton.topia.persistence.TopiaDAO;
/**
* Test on {@link TopiaDAO}.
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/CollectorTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/CollectorTest.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/CollectorTest.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -23,7 +23,7 @@
* #L%
*/
-package org.nuiton.topia.persistence.util;
+package org.nuiton.topia.it.legacy.persistence.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -32,14 +32,15 @@
import org.junit.BeforeClass;
import org.junit.Test;
import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.TopiaTestDAOHelper;
+import org.nuiton.topia.it.legacy.TopiaTestDAOHelper;
import org.nuiton.topia.persistence.TopiaEntity;
import org.nuiton.topia.persistence.TopiaEntityEnum;
-import org.nuiton.topiatest.Company;
-import org.nuiton.topiatest.CompanyImpl;
-import org.nuiton.topiatest.Department;
-import org.nuiton.topiatest.DepartmentImpl;
-import org.nuiton.topiatest.EmployeImpl;
+import org.nuiton.topia.it.legacy.topiatest.Company;
+import org.nuiton.topia.it.legacy.topiatest.CompanyImpl;
+import org.nuiton.topia.it.legacy.topiatest.Department;
+import org.nuiton.topia.it.legacy.topiatest.DepartmentImpl;
+import org.nuiton.topia.it.legacy.topiatest.EmployeImpl;
+import org.nuiton.topia.persistence.util.Collector;
/** @author tchemit <chemit(a)codelutin.com> */
public class CollectorTest {
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/EntityOperatorTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/EntityOperatorTest.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/EntityOperatorTest.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -23,22 +23,23 @@
* #L%
*/
-package org.nuiton.topia.persistence.util;
+package org.nuiton.topia.it.legacy.persistence.util;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
-import org.nuiton.topia.TopiaTestDAOHelper;
-import org.nuiton.topiatest.Company;
-import org.nuiton.topiatest.CompanyImpl;
-import org.nuiton.topiatest.Department;
-import org.nuiton.topiatest.DepartmentImpl;
-import org.nuiton.topiatest.Employe;
-import org.nuiton.topiatest.EmployeImpl;
-import org.nuiton.topiatest.Personne;
-import org.nuiton.topiatest.PersonneImpl;
+import org.nuiton.topia.it.legacy.TopiaTestDAOHelper;
+import org.nuiton.topia.it.legacy.topiatest.Company;
+import org.nuiton.topia.it.legacy.topiatest.CompanyImpl;
+import org.nuiton.topia.it.legacy.topiatest.Department;
+import org.nuiton.topia.it.legacy.topiatest.DepartmentImpl;
+import org.nuiton.topia.it.legacy.topiatest.Employe;
+import org.nuiton.topia.it.legacy.topiatest.EmployeImpl;
+import org.nuiton.topia.it.legacy.topiatest.Personne;
+import org.nuiton.topia.it.legacy.topiatest.PersonneImpl;
+import org.nuiton.topia.persistence.util.EntityOperator;
import java.util.Collection;
@@ -80,10 +81,10 @@
@AfterClass
public static void tearDownClass() throws Throwable {
- operationC.finalize();
- operationE.finalize();
- operationP.finalize();
- operationD.finalize();
+// operationC.finalize();
+// operationE.finalize();
+// operationP.finalize();
+// operationD.finalize();
}
@Before
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityBinderTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityBinderTest.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityBinderTest.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -23,17 +23,17 @@
* #L%
*/
-package org.nuiton.topia.persistence.util;
+package org.nuiton.topia.it.legacy.persistence.util;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
-import org.nuiton.topia.TopiaTestDAOHelper;
+import org.nuiton.topia.it.legacy.TopiaTestDAOHelper;
import org.nuiton.topia.persistence.TopiaEntity;
import org.nuiton.topia.persistence.TopiaEntityEnum;
-import org.nuiton.topiatest.Company;
+import org.nuiton.topia.it.legacy.topiatest.Company;
import org.nuiton.util.beans.Binder;
import org.nuiton.util.beans.BinderFactory;
import org.nuiton.util.beans.BinderModelBuilder;
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-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityHelperTest.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -23,28 +23,30 @@
* #L%
*/
-package org.nuiton.topia.persistence.util;
+package org.nuiton.topia.it.legacy.persistence.util;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.TopiaTestDAOHelper;
+import org.nuiton.topia.it.legacy.TopiaTestDAOHelper;
import org.nuiton.topia.persistence.DefaultTopiaIdFactory;
import org.nuiton.topia.persistence.TopiaEntity;
import org.nuiton.topia.persistence.TopiaEntityEnum;
import org.nuiton.topia.persistence.TopiaIdFactory;
-import org.nuiton.topiatest.Company;
-import org.nuiton.topiatest.CompanyImpl;
-import org.nuiton.topiatest.Department;
-import org.nuiton.topiatest.DepartmentImpl;
-import org.nuiton.topiatest.Employe;
-import org.nuiton.topiatest.EmployeAbstract;
-import org.nuiton.topiatest.EmployeImpl;
-import org.nuiton.topiatest.Personne;
-import org.nuiton.topiatest.PersonneAbstract;
-import org.nuiton.topiatest.PersonneImpl;
+import org.nuiton.topia.it.legacy.topiatest.Company;
+import org.nuiton.topia.it.legacy.topiatest.CompanyImpl;
+import org.nuiton.topia.it.legacy.topiatest.Department;
+import org.nuiton.topia.it.legacy.topiatest.DepartmentImpl;
+import org.nuiton.topia.it.legacy.topiatest.Employe;
+import org.nuiton.topia.it.legacy.topiatest.EmployeAbstract;
+import org.nuiton.topia.it.legacy.topiatest.EmployeImpl;
+import org.nuiton.topia.it.legacy.topiatest.Personne;
+import org.nuiton.topia.it.legacy.topiatest.PersonneAbstract;
+import org.nuiton.topia.it.legacy.topiatest.PersonneImpl;
+import org.nuiton.topia.persistence.util.TopiaEntityHelper;
+import org.nuiton.topia.persistence.util.TopiaEntityIdsMap;
import java.util.HashSet;
import java.util.List;
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityRefTester.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityRefTester.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityRefTester.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -23,13 +23,15 @@
* #L%
*/
-package org.nuiton.topia.persistence.util;
+package org.nuiton.topia.it.legacy.persistence.util;
import org.junit.After;
import org.junit.Assert;
import org.nuiton.topia.TopiaException;
import org.nuiton.topia.persistence.TopiaEntity;
import org.nuiton.topia.persistence.TopiaEntityEnum;
+import org.nuiton.topia.persistence.util.TopiaEntityHelper;
+import org.nuiton.topia.persistence.util.TopiaEntityRef;
import java.util.Collection;
import java.util.HashSet;
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityRefTesterTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityRefTesterTest.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityRefTesterTest.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -23,15 +23,15 @@
* #L%
*/
-package org.nuiton.topia.persistence.util;
+package org.nuiton.topia.it.legacy.persistence.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Test;
-import org.nuiton.topia.TopiaTestDAOHelper.TopiaTestEntityEnum;
-import org.nuiton.topia.test.entities.Person;
-import org.nuiton.topia.test.entities.Pet;
-import org.nuiton.topia.test.entities.Race;
+import org.nuiton.topia.it.legacy.TopiaTestDAOHelper.TopiaTestEntityEnum;
+import org.nuiton.topia.it.legacy.test.entities.Person;
+import org.nuiton.topia.it.legacy.test.entities.Pet;
+import org.nuiton.topia.it.legacy.test.entities.Race;
/**
* Test the {@link TopiaEntityRefTester} on
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/ano1882/DAOAbstractTransformerTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/ano1882/DAOAbstractTransformerTest.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/ano1882/DAOAbstractTransformerTest.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -22,13 +22,13 @@
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
-package org.nuiton.topia.test.ano1882;
+package org.nuiton.topia.it.legacy.test.ano1882;
import org.junit.Rule;
import org.junit.Test;
-import org.nuiton.topia.TopiaDatabase;
-import org.nuiton.topia.TopiaTestDAOHelper;
-import org.nuiton.topia.TopiaTestTopiaPersistenceContext;
+import org.nuiton.topia.it.legacy.TopiaDatabase;
+import org.nuiton.topia.it.legacy.TopiaTestDAOHelper;
+import org.nuiton.topia.it.legacy.TopiaTestTopiaPersistenceContext;
import java.util.Arrays;
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/evo1912/EntityDTOTransformerTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/evo1912/EntityDTOTransformerTest.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/evo1912/EntityDTOTransformerTest.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -22,11 +22,11 @@
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
-package org.nuiton.topia.test.evo1912;
+package org.nuiton.topia.it.legacy.test.evo1912;
import org.junit.Assert;
import org.junit.Test;
-import org.nuiton.topiatest.CompanyDTO;
+import org.nuiton.topia.it.legacy.topiatest.CompanyDTO;
/** @author ymartel <martel(a)codelutin.com> */
public class EntityDTOTransformerTest {
Deleted: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/AbstractExtraDAOEntityTopiaDao.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/AbstractExtraDAOEntityTopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/AbstractExtraDAOEntityTopiaDao.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -1,40 +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%
- */
-package org.nuiton.topiatest;
-
-import org.nuiton.topia.TopiaException;
-
-/**
- * Created: 26 mai 2010
- *
- * @author fdesbois <fdesbois(a)codelutin.com>
- * @version $Id$
- */
-public class AbstractExtraDAOEntityTopiaDao<E extends ExtraDAOEntity> extends GeneratedExtraDAOEntityTopiaDao<E> {
-
- @Override
- public void extra() throws TopiaException {
- }
-}
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/EnumTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/EnumTest.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/EnumTest.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -22,15 +22,15 @@
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
-package org.nuiton.topiatest;
+package org.nuiton.topia.it.legacy.topiatest;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
-import org.nuiton.topia.TopiaDatabase;
+import org.nuiton.topia.it.legacy.TopiaDatabase;
import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.TopiaTestDAOHelper;
-import org.nuiton.topia.TopiaTestTopiaPersistenceContext;
+import org.nuiton.topia.it.legacy.TopiaTestDAOHelper;
+import org.nuiton.topia.it.legacy.TopiaTestTopiaPersistenceContext;
/**
* Test the support of possibility to have an attribute of type enumeration
Deleted: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/Gender.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/Gender.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/Gender.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -1,29 +0,0 @@
-/*
- * #%L
- * ToPIA :: Persistence
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2004 - 2011 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%
- */
-package org.nuiton.topiatest;
-
-public enum Gender {
- MALE, FEMALE
-}
Deleted: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/Title.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/Title.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/Title.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -1,37 +0,0 @@
-/*
- * #%L
- * ToPIA :: Persistence
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2004 - 2011 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%
- */
-package org.nuiton.topiatest;
-
-/**
- * To test http://nuiton.org/issues/1732.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 2.6.2
- */
-public enum Title {
- Mr,
- Madam,
- Other
-}
Deleted: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/beangen/RoueImpl.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/beangen/RoueImpl.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/beangen/RoueImpl.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -1,53 +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%
- */
-
-package org.nuiton.topiatest.beangen;
-
-import org.nuiton.topiatest.Product;
-
-/**
- * RoueImpl
- *
- * Created: 14 janv. 2010
- *
- * @author fdesbois
- * @version $Revision$
- *
- * Mise a jour: $Date$
- * par : $Author$
- */
-public class RoueImpl extends Roue {
-
- @Override
- public void mount() {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- @Override
- public Product getModel(String id) {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
-}
Deleted: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/AbstractContact2TopiaDao.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/AbstractContact2TopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/AbstractContact2TopiaDao.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -1,51 +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%
- */
-
-package org.nuiton.topiatest.deletetest;
-
-
-import org.nuiton.topia.TopiaException;
-import org.nuiton.topiatest.Company;
-import org.nuiton.topiatest.Employe;
-
-import java.util.Set;
-import java.util.TreeSet;
-
-/**
- *
- * @author desbois
- */
-public class AbstractContact2TopiaDao<E extends Contact2> extends GeneratedContact2TopiaDao<E> {
-
- @Override
- public Set<Contact2> findAllByCompany(Company company) throws TopiaException {
- Set<Contact2> contacts = new TreeSet<Contact2>();
- for (Employe e : company.getEmploye()) {
- contacts.addAll(e.getContacts());
- }
- return contacts;
- }
-
-}
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/DeleteEntityTest.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/DeleteEntityTest.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/DeleteEntityTest.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -36,20 +36,20 @@
* par : $Author$
*/
-package org.nuiton.topiatest.deletetest;
+package org.nuiton.topia.it.legacy.topiatest.deletetest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
-import org.nuiton.topia.TopiaDatabase;
+import org.nuiton.topia.it.legacy.TopiaDatabase;
import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.TopiaTestDAOHelper;
-import org.nuiton.topia.TopiaTestTopiaPersistenceContext;
-import org.nuiton.topiatest.Gender;
-import org.nuiton.topiatest.Personne;
-import org.nuiton.topiatest.PersonneDAO;
+import org.nuiton.topia.it.legacy.TopiaTestDAOHelper;
+import org.nuiton.topia.it.legacy.TopiaTestTopiaPersistenceContext;
+import org.nuiton.topia.it.legacy.topiatest.Gender;
+import org.nuiton.topia.it.legacy.topiatest.Personne;
+import org.nuiton.topia.it.legacy.topiatest.PersonneDAO;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
Deleted: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -1,49 +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%
- */
-package org.nuiton.topia.it.legacy.topiatest.persistence;
-
-import org.nuiton.topia.persistence.TopiaEntity;
-
-/**
- * Created: 11 mai 2010
- *
- * @author fdesbois <fdesbois(a)codelutin.com>
- * @version $Id$
- */
-public interface Entity1 extends TopiaEntity {
-
- String ATTR_1 = "attr1";
-
- String ATTR_2 = "attr2";
-
- String getAttr1();
-
- void setAttr1(String attr1);
-
- String getAttr2();
-
- void setAttr2(String attr2);
-
-}
Deleted: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Abstract.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Abstract.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Abstract.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -1,83 +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%
- */
-package org.nuiton.topia.it.legacy.topiatest.persistence;
-
-import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.persistence.EntityVisitor;
-import org.nuiton.topia.persistence.TopiaEntityAbstract;
-
-/**
- * Created: 11 mai 2010
- *
- * @author fdesbois <fdesbois(a)codelutin.com>
- * @version $Id$
- */
-public abstract class Entity1Abstract extends TopiaEntityAbstract
- implements Entity1 {
-
- protected String attr1;
-
- protected String attr2;
-
- @Override
- public String getAttr1() {
- fireOnPreRead(ATTR_1, attr1);
- String result = attr1;
- fireOnPostRead(ATTR_1, attr1);
- return result;
- }
-
- @Override
- public void setAttr1(String attr1) {
- String _oldValue = this.attr1;
- fireOnPreWrite(ATTR_1, _oldValue, attr1);
- this.attr1 = attr1;
- fireOnPostWrite(ATTR_1, _oldValue, attr1);
- }
-
- @Override
- public String getAttr2() {
- fireOnPreRead(ATTR_2, attr2);
- String result = attr2;
- fireOnPostRead(ATTR_2, attr2);
- return result;
- }
-
- @Override
- public void setAttr2(String attr2) {
- String _oldValue = this.attr2;
- fireOnPreWrite(ATTR_2, _oldValue, attr2);
- this.attr2 = attr2;
- fireOnPostWrite(ATTR_2, _oldValue, attr2);
- }
-
- @Override
- public void accept(EntityVisitor visitor) throws TopiaException {
- visitor.start(this);
- visitor.visit(this, ATTR_1, String.class, attr1);
- visitor.visit(this, ATTR_2, String.class, attr2);
- visitor.end(this);
- }
-}
Deleted: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Impl.hbm.xml
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Impl.hbm.xml 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Impl.hbm.xml 2013-11-22 20:03:11 UTC (rev 2885)
@@ -1,37 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- #%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%
- -->
-
-<!--<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">-->
-<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
-<hibernate-mapping default-access="field" auto-import="true" package="org.nuiton.topia.it.legacy.topiatest">
- <class name="org.nuiton.topia.it.legacy.topiatest.persistence.Entity1Impl" table="entity1" node="org.nuiton.topia.it.legacy.topiatest.persistence.Entity1Impl" abstract="false" proxy="org.nuiton.topia.it.legacy.topiatest.persistence.Entity1" >
- <id name="topiaId" type="string" length="255" node="@topiaId"/>
- <version name="topiaVersion" type="long" node="@topiaVersion"/>
- <property name="topiaCreateDate" type="timestamp" node="@topiaCreateDate"/>
- <property name="attr1" type="java.lang.String" access="field" column="attr1" node="attr1"/>
- <property name="attr2" type="java.lang.String" access="field" column="attr2" node="attr2"/>
- </class>
-</hibernate-mapping>
Deleted: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Impl.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Impl.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Impl.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -1,37 +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%
- */
-package org.nuiton.topia.it.legacy.topiatest.persistence;
-
-import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.persistence.EntityVisitor;
-
-/**
- * Created: 11 mai 2010
- *
- * @author fdesbois <fdesbois(a)codelutin.com>
- * @version $Id$
- */
-public class Entity1Impl extends Entity1Abstract {
-}
Deleted: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/package-info.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/package-info.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/package-info.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -1,28 +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%
- */
-/**
- * Contains persistent entities for Tests.
- */
-package org.nuiton.topiatest.persistence;
\ No newline at end of file
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/FakeService.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/FakeService.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/FakeService.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -25,8 +25,8 @@
package org.nuiton.topia.it.legacy.topiatest.service;
import org.nuiton.topia.TopiaContext;
-import org.nuiton.topia.framework.TopiaContextImplTest;
import org.nuiton.topia.framework.TopiaService;
+import org.nuiton.topia.it.legacy.framework.TopiaContextImplTest;
/**
* FakeService which implements {@link TopiaService} to test existing service
Modified: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/TestService.java
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/TestService.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/TestService.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -26,7 +26,7 @@
import org.junit.Ignore;
import org.nuiton.topia.TopiaContext;
-import org.nuiton.topia.framework.TopiaContextImplTest;
+import org.nuiton.topia.it.legacy.framework.TopiaContextImplTest;
import org.nuiton.topia.framework.TopiaService;
/**
Deleted: trunk/topia-it/src/test/resources/TopiaContextImpl.properties
===================================================================
--- trunk/topia-it/src/test/resources/TopiaContextImpl.properties 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/resources/TopiaContextImpl.properties 2013-11-22 20:03:11 UTC (rev 2885)
@@ -1,34 +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%
-###
-# Proprietes par defaut pour une base de donnees de type H2
-hibernate.hbm2ddl.auto=update
-hibernate.show_sql=false
-
-hibernate.dialect=org.hibernate.dialect.H2Dialect
-hibernate.connection.username=sa
-hibernate.connection.password=
-hibernate.connection.driver_class=org.h2.Driver
-# tchemit 2010-11-28 : comment this line, each test must define his own db path
-#hibernate.connection.url=jdbc:h2:file:target/surefire-workdir/h2data
\ No newline at end of file
Modified: trunk/topia-it/src/test/resources/log4j.properties
===================================================================
--- trunk/topia-it/src/test/resources/log4j.properties 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-it/src/test/resources/log4j.properties 2013-11-22 20:03:11 UTC (rev 2885)
@@ -32,5 +32,5 @@
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) %M - %m%n
# package level
log4j.logger.org.nuiton.topia=INFO
-#log4j.logger.org.nuiton.topiatest=DEBUG
+#log4j.logger.org.nuiton.topia.it.legacy.topiatest=DEBUG
log4j.logger.org.nuiton.topia.persistence.util=INFO
Property changes on: trunk/topia-junit/LICENSE.txt
___________________________________________________________________
Modified: svn:keywords
- Author Date Id Revision
+ Author Date Id Revision HeadURL
Property changes on: trunk/topia-junit/README.txt
___________________________________________________________________
Modified: svn:keywords
- Author Date Id Revision
+ Author Date Id Revision HeadURL
Modified: trunk/topia-junit/pom.xml
===================================================================
--- trunk/topia-junit/pom.xml 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-junit/pom.xml 2013-11-22 20:03:11 UTC (rev 2885)
@@ -4,7 +4,7 @@
ToPIA :: Persistence
$Id$
- $HeadURL: http://svn.nuiton.org/svn/topia/trunk/topia-persistence/pom.xml $
+ $HeadURL$
%%
Copyright (C) 2004 - 2010 CodeLutin
%%
Property changes on: trunk/topia-junit/pom.xml
___________________________________________________________________
Modified: svn:keywords
- Author Date Id Revision
+ Author Date Id Revision HeadURL
Added: trunk/topia-junit/src/main/java/org/nuiton/topia/junit/AbstractDatabaseResource.java
===================================================================
--- trunk/topia-junit/src/main/java/org/nuiton/topia/junit/AbstractDatabaseResource.java (rev 0)
+++ trunk/topia-junit/src/main/java/org/nuiton/topia/junit/AbstractDatabaseResource.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -0,0 +1,189 @@
+package org.nuiton.topia.junit;
+
+/*
+ * #%L
+ * ToPIA :: JUnit
+ * $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.reflect.FieldUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.hibernate.cfg.Configuration;
+import org.junit.rules.TestWatcher;
+import org.junit.runner.Description;
+import org.nuiton.topia.AbstractTopiaApplicationContext;
+import org.nuiton.topia.HibernateProvider;
+import org.nuiton.topia.TopiaContextFactory;
+import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.TopiaPersistenceContext;
+
+import java.io.File;
+import java.io.InputStream;
+import java.lang.reflect.Field;
+import java.util.Properties;
+
+/**
+ * Put this class as a Rule in test to obtain a new isolated db for each test.
+ * <p/>
+ * Here is a simple example of usage :
+ * <pre>
+ * public class MyTest {
+ *
+ * \@Rule
+ * public final TopiaDatabase db = new TopiaDatabase();
+ *
+ * \@Test
+ * public void testMethod() throws TopiaException {
+ *
+ * TopiaContext tx = db.beginTransaction();
+ * ...
+ * }
+ * </pre>
+ * The db created will be unique for each test method (and for each build also).
+ * <p/>
+ * You don't need to close any transaction, it will be done for you and the end
+ * of each method test.
+ * <p/>
+ * Created on 11/22/13.
+ *
+ * @author Tony Chemit <chemit(a)codelutin.com>
+ * @since 3.0
+ */
+public abstract class AbstractDatabaseResource<PersistenceContext extends TopiaPersistenceContext, ApplicationContext extends AbstractTopiaApplicationContext<PersistenceContext>> extends TestWatcher {
+
+ /** Logger. */
+ private static final Log log = LogFactory.getLog(AbstractDatabaseResource.class);
+
+ private File testBasedir;
+
+ private Properties dbConfiguration;
+
+ private ApplicationContext applicationContext;
+
+ private Configuration hibernateCfg;
+
+ private final String configurationPath;
+
+ protected abstract ApplicationContext createApplicationContext(Properties dbConfiguration);
+
+ protected abstract String getImplementationClassesAsString();
+
+ public AbstractDatabaseResource(String configurationPath) {
+ this.configurationPath = configurationPath;
+ }
+
+ @Override
+ protected void starting(Description description) {
+
+ // get test directory
+ testBasedir = ConfigurationHelper.getTestSpecificDirectory(
+ description.getTestClass(),
+ description.getMethodName());
+
+ if (log.isDebugEnabled()) {
+ log.debug("testBasedir = " + testBasedir);
+ }
+
+ // create the root context
+ try {
+
+ dbConfiguration = new Properties();
+ InputStream stream =
+ getClass().getResourceAsStream(configurationPath);
+
+ try {
+ dbConfiguration.load(stream);
+ } finally {
+ stream.close();
+ }
+ dbConfiguration.setProperty(
+ TopiaContextFactory.CONFIG_PERSISTENCE_CLASSES,
+ getImplementationClassesAsString());
+
+ // make sure we always use a different directory
+
+ String dbPath = new File(testBasedir, "db").getAbsolutePath();
+
+ if (log.isDebugEnabled()) {
+ log.debug("dbPath = " + dbPath);
+ }
+ dbConfiguration.setProperty(
+ TopiaContextFactory.CONFIG_URL, "jdbc:h2:file:" + dbPath);
+
+ onDbConfigurationCreate(dbConfiguration, testBasedir, dbPath);
+
+ applicationContext = createApplicationContext(dbConfiguration);
+
+ Field field = FieldUtils.getField(AbstractTopiaApplicationContext.class, "hibernateProvider", true);
+ HibernateProvider hibernateProvider = (HibernateProvider) field.get(applicationContext);
+ hibernateCfg = hibernateProvider.getHibernateConfiguration();
+
+ } catch (Exception e) {
+ throw new IllegalStateException(
+ "Could not start db at " + testBasedir, e);
+ }
+ }
+
+ @Override
+ public void finished(Description description) {
+
+ if (applicationContext != null && !applicationContext.isClosed()) {
+ try {
+ applicationContext.closeContext();
+ } catch (TopiaException e) {
+ if (log.isErrorEnabled()) {
+ log.error("Could not close topia root context", e);
+ }
+ }
+ }
+ applicationContext = null;
+ dbConfiguration = null;
+ hibernateCfg = null;
+ }
+
+ public File getTestBasedir() {
+ return testBasedir;
+ }
+
+ public Properties getDbConfiguration() {
+ return dbConfiguration;
+ }
+
+ public ApplicationContext getApplicationContext() {
+ return applicationContext;
+ }
+
+ public Configuration getHibernateCfg() {
+ return hibernateCfg;
+ }
+
+ public PersistenceContext beginTransaction() throws TopiaException {
+ return applicationContext.newPersistenceContext();
+ }
+
+ protected void onDbConfigurationCreate(Properties configuration,
+ File testDir,
+ String dbPath) {
+
+ }
+
+}
\ No newline at end of file
Property changes on: trunk/topia-junit/src/main/java/org/nuiton/topia/junit/AbstractDatabaseResource.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Added: trunk/topia-junit/src/main/java/org/nuiton/topia/junit/ConfigurationHelper.java
===================================================================
--- trunk/topia-junit/src/main/java/org/nuiton/topia/junit/ConfigurationHelper.java (rev 0)
+++ trunk/topia-junit/src/main/java/org/nuiton/topia/junit/ConfigurationHelper.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -0,0 +1,93 @@
+package org.nuiton.topia.junit;
+
+/*
+ * #%L
+ * ToPIA :: JUnit
+ * $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.io.FileUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.util.FileUtil;
+
+import java.io.File;
+import java.io.IOException;
+
+/**
+ * Created on 11/22/13.
+ *
+ * @author Tony Chemit <chemit(a)codelutin.com>
+ * @since 3.0
+ */
+public class ConfigurationHelper {
+
+ /** A time-stamp, allow to make multiple build and keep the tests data. */
+ public static final String TIMESTAMP = String.valueOf(System.nanoTime());
+
+ private static final Log log = LogFactory.getLog(ConfigurationHelper.class);
+
+ public static File getTestWorkdir() {
+ File result;
+ String base = System.getProperty("java.io.tmpdir");
+ if (base == null || base.isEmpty()) {
+ base = new File("").getAbsolutePath();
+ if (log.isWarnEnabled()) {
+ log.warn("'\"java.io.tmpdir\" not defined");
+ }
+ }
+ result = new File(base);
+ if (log.isDebugEnabled()) {
+ log.debug("basedir for test " + result);
+ }
+ return result;
+ }
+
+ public static File getTestBasedir(Class<?> testClass) throws IOException {
+ File dir = getTestWorkdir();
+ File result = new File(dir, testClass.getName());
+ if (result.exists()) {
+
+ // when calling this method (always in a BeforeClass method), we wants
+ // to clean the directory, this is a new build
+ FileUtils.deleteDirectory(result);
+ }
+
+ // always create the directory
+ FileUtil.createDirectoryIfNecessary(result);
+ return result;
+ }
+
+ public static File getTestSpecificDirectory(Class<?> testClassName,
+ String methodName) {
+
+ File tempDirFile = getTestWorkdir();
+
+ // create the directory to store database data
+ String dataBasePath = testClassName.getName()
+ + File.separator // a directory with the test class name
+ + methodName// a sub-directory with the method name
+ + '_'
+ + TIMESTAMP; // and a timestamp
+ File databaseFile = new File(tempDirFile, dataBasePath);
+ return databaseFile;
+ }
+}
Property changes on: trunk/topia-junit/src/main/java/org/nuiton/topia/junit/ConfigurationHelper.java
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision HeadURL
Added: svn:eol-style
+ native
Modified: trunk/topia-service-replication/pom.xml
===================================================================
--- trunk/topia-service-replication/pom.xml 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-service-replication/pom.xml 2013-11-22 20:03:11 UTC (rev 2885)
@@ -50,13 +50,19 @@
<dependency>
<groupId>${project.groupId}</groupId>
- <artifactId>topia-persistence</artifactId>
+ <artifactId>topia-junit</artifactId>
<version>${project.version}</version>
<scope>test</scope>
- <classifier>tests</classifier>
</dependency>
<dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>topia-it</artifactId>
+ <version>${project.version}</version>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
</dependency>
Modified: trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationOperationTest.java
===================================================================
--- trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationOperationTest.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationOperationTest.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -27,16 +27,29 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
-import org.junit.*;
-import org.nuiton.topia.TestHelper;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
import org.nuiton.topia.TopiaContext;
import org.nuiton.topia.TopiaContextFactory;
-import org.nuiton.topia.TopiaTestDAOHelper.TopiaTestEntityEnum;
import org.nuiton.topia.framework.TopiaContextImplementor;
+import org.nuiton.topia.it.TopiaConfigurationHelper;
+import org.nuiton.topia.it.legacy.TopiaTestDAOHelper.TopiaTestEntityEnum;
+import org.nuiton.topia.it.legacy.test.entities.Person;
+import org.nuiton.topia.it.legacy.test.entities.PersonImpl;
+import org.nuiton.topia.it.legacy.test.entities.Pet;
+import org.nuiton.topia.it.legacy.test.entities.PetImpl;
+import org.nuiton.topia.it.legacy.test.entities.Race;
+import org.nuiton.topia.it.legacy.test.entities.RaceImpl;
import org.nuiton.topia.persistence.TopiaEntityEnum;
import org.nuiton.topia.replication.model.ReplicationOperationPhase;
-import org.nuiton.topia.replication.operation.*;
-import org.nuiton.topia.test.entities.*;
+import org.nuiton.topia.replication.operation.DettachAssociation;
+import org.nuiton.topia.replication.operation.Duplicate;
+import org.nuiton.topia.replication.operation.FakeOperation;
+import org.nuiton.topia.replication.operation.UncreatableOperation;
+import org.nuiton.topia.replication.operation.UnregistredOperation;
import java.io.File;
import java.io.IOException;
@@ -77,7 +90,7 @@
@BeforeClass
public static void beforeClass() throws IOException {
- tesDir = TestHelper.getTestBasedir(TopiaReplicationOperationTest.class);
+ tesDir = TopiaConfigurationHelper.getTestBasedir(TopiaReplicationOperationTest.class);
}
@@ -302,7 +315,7 @@
protected Properties getH2Properties(String dbName) throws IOException {
- Properties config = TestHelper.initTopiaContextConfiguration(tesDir, dbName);
+ Properties config = TopiaConfigurationHelper.initTopiaContextConfiguration(tesDir, dbName);
// config.setProperty("hibernate.show_sql", "false");
// config.setProperty("hibernate.hbm2ddl.auto", "create");
Modified: trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplAllTest.java
===================================================================
--- trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplAllTest.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplAllTest.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -32,25 +32,26 @@
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
-import org.nuiton.topia.TestHelper;
import org.nuiton.topia.TopiaContext;
import org.nuiton.topia.TopiaContextFactory;
import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.TopiaTestDAOHelper.TopiaTestEntityEnum;
import org.nuiton.topia.framework.TopiaContextImplementor;
+import org.nuiton.topia.it.TopiaConfigurationHelper;
+import org.nuiton.topia.it.legacy.test.entities.Person;
+import org.nuiton.topia.it.legacy.test.entities.PersonImpl;
+import org.nuiton.topia.it.legacy.test.entities.Pet;
+import org.nuiton.topia.it.legacy.test.entities.PetImpl;
+import org.nuiton.topia.it.legacy.test.entities.Race;
+import org.nuiton.topia.it.legacy.test.entities.RaceImpl;
import org.nuiton.topia.persistence.TopiaEntity;
import org.nuiton.topia.persistence.TopiaEntityEnum;
-import org.nuiton.topia.test.entities.Person;
-import org.nuiton.topia.test.entities.PersonImpl;
-import org.nuiton.topia.test.entities.Pet;
-import org.nuiton.topia.test.entities.PetImpl;
-import org.nuiton.topia.test.entities.Race;
-import org.nuiton.topia.test.entities.RaceImpl;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
+import static org.nuiton.topia.it.legacy.TopiaTestDAOHelper.TopiaTestEntityEnum;
+
/**
* TopiaReplicationServiceImplTest on model TopiaTest
* <p/>
@@ -85,9 +86,9 @@
@BeforeClass
public static void beforeClass() throws IOException {
- tesDir = TestHelper.getTestBasedir(TopiaReplicationServiceImplAllTest.class);
+ tesDir = TopiaConfigurationHelper.getTestBasedir(TopiaReplicationServiceImplAllTest.class);
}
-
+
@AfterClass
public static void after() throws Exception {
AbstractTopiaReplicationServiceTest.after();
@@ -274,7 +275,7 @@
protected Properties getH2Properties(String dbName) throws IOException {
- Properties config = TestHelper.initTopiaContextConfiguration(tesDir, dbName);
+ Properties config = TopiaConfigurationHelper.initTopiaContextConfiguration(tesDir, dbName);
// config.setProperty("hibernate.show_sql", "false");
// config.setProperty("hibernate.hbm2ddl.auto", "create");
Modified: trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplTest.java
===================================================================
--- trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplTest.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplTest.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -32,12 +32,17 @@
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
-import org.nuiton.topia.TestHelper;
import org.nuiton.topia.TopiaContext;
import org.nuiton.topia.TopiaContextFactory;
import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.TopiaTestDAOHelper.TopiaTestEntityEnum;
import org.nuiton.topia.framework.TopiaContextImplementor;
+import org.nuiton.topia.it.TopiaConfigurationHelper;
+import org.nuiton.topia.it.legacy.test.entities.Person;
+import org.nuiton.topia.it.legacy.test.entities.PersonImpl;
+import org.nuiton.topia.it.legacy.test.entities.Pet;
+import org.nuiton.topia.it.legacy.test.entities.PetImpl;
+import org.nuiton.topia.it.legacy.test.entities.Race;
+import org.nuiton.topia.it.legacy.test.entities.RaceImpl;
import org.nuiton.topia.persistence.TopiaEntityEnum;
import org.nuiton.topia.persistence.util.TopiaEntityIdsMap;
import org.nuiton.topia.replication.model.ReplicationModel;
@@ -46,17 +51,13 @@
import org.nuiton.topia.replication.operation.FakeOperation;
import org.nuiton.topia.replication.operation.UncreatableOperation;
import org.nuiton.topia.replication.operation.UnregistredOperation;
-import org.nuiton.topia.test.entities.Person;
-import org.nuiton.topia.test.entities.PersonImpl;
-import org.nuiton.topia.test.entities.Pet;
-import org.nuiton.topia.test.entities.PetImpl;
-import org.nuiton.topia.test.entities.Race;
-import org.nuiton.topia.test.entities.RaceImpl;
import java.io.File;
import java.io.IOException;
import java.util.Properties;
+import static org.nuiton.topia.it.legacy.TopiaTestDAOHelper.TopiaTestEntityEnum;
+
/**
* TopiaReplicationServiceImplTest on model TopiaTest
* <p/>
@@ -85,7 +86,7 @@
@BeforeClass
public static void beforeClass() throws IOException {
- tesDir = TestHelper.getTestBasedir(
+ tesDir = TopiaConfigurationHelper.getTestBasedir(
TopiaReplicationServiceImplTest.class);
}
@@ -436,7 +437,7 @@
protected Properties getH2Properties(String dbName) throws IOException {
- Properties config = TestHelper.initTopiaContextConfiguration(tesDir, dbName);
+ Properties config = TopiaConfigurationHelper.initTopiaContextConfiguration(tesDir, dbName);
// config.setProperty("hibernate.show_sql", "false");
// config.setProperty("hibernate.hbm2ddl.auto", "create");
Property changes on: trunk/topia-templates/LICENSE.txt
___________________________________________________________________
Modified: svn:keywords
- Author Date Id Revision
+ Author Date Id Revision HeadURL
Property changes on: trunk/topia-templates/README.txt
___________________________________________________________________
Modified: svn:keywords
- Author Date Id Revision
+ Author Date Id Revision HeadURL
Modified: trunk/topia-templates/pom.xml
===================================================================
--- trunk/topia-templates/pom.xml 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-templates/pom.xml 2013-11-22 20:03:11 UTC (rev 2885)
@@ -4,7 +4,7 @@
ToPIA :: Persistence
$Id$
- $HeadURL: http://svn.nuiton.org/svn/topia/trunk/topia-persistence/pom.xml $
+ $HeadURL$
%%
Copyright (C) 2004 - 2010 CodeLutin
%%
Property changes on: trunk/topia-templates/pom.xml
___________________________________________________________________
Modified: svn:keywords
- Author Date Id Revision
+ Author Date Id Revision HeadURL
Modified: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/ApplicationContextTransformer.java
===================================================================
--- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/ApplicationContextTransformer.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/ApplicationContextTransformer.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -1,5 +1,29 @@
package org.nuiton.topia.templates;
+/*
+ * #%L
+ * ToPIA :: Templates
+ * $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%
+ */
+
/*{generator option: parentheses = false}*/
/*{generator option: writeString = +}*/
Modified: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/BinderHelperTransformer.java
===================================================================
--- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/BinderHelperTransformer.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/BinderHelperTransformer.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -1,5 +1,29 @@
package org.nuiton.topia.templates;
+/*
+ * #%L
+ * ToPIA :: Templates
+ * $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.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
Modified: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/DAOHelperTransformer.java
===================================================================
--- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/DAOHelperTransformer.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/DAOHelperTransformer.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -1,5 +1,29 @@
package org.nuiton.topia.templates;
+/*
+ * #%L
+ * ToPIA :: Templates
+ * $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.ArrayUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
Modified: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/DTOTransformer.java
===================================================================
--- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/DTOTransformer.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/DTOTransformer.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -1,5 +1,29 @@
package org.nuiton.topia.templates;
+/*
+ * #%L
+ * ToPIA :: Templates
+ * $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.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.logging.Log;
Modified: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityDTOTransformer.java
===================================================================
--- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityDTOTransformer.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityDTOTransformer.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -1,6 +1,30 @@
package org.nuiton.topia.templates;
+/*
+ * #%L
+ * ToPIA :: Templates
+ * $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.apache.commons.lang3.builder.ToStringBuilder;
import org.nuiton.eugene.GeneratorUtil;
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-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityDaoTransformer.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -1,5 +1,29 @@
package org.nuiton.topia.templates;
+/*
+ * #%L
+ * ToPIA :: Templates
+ * $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%
+ */
+
/*{generator option: parentheses = false}*/
/*{generator option: writeString = +}*/
Modified: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityHibernateMappingGenerator.java
===================================================================
--- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityHibernateMappingGenerator.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityHibernateMappingGenerator.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -13,6 +13,30 @@
package org.nuiton.topia.templates;
+/*
+ * #%L
+ * ToPIA :: Templates
+ * $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.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
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-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityTransformer.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -1,5 +1,29 @@
package org.nuiton.topia.templates;
+/*
+ * #%L
+ * ToPIA :: Templates
+ * $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.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.logging.Log;
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-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/PersistenceContextTransformer.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -1,5 +1,29 @@
package org.nuiton.topia.templates;
+/*
+ * #%L
+ * ToPIA :: Templates
+ * $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%
+ */
+
/*{generator option: parentheses = false}*/
/*{generator option: writeString = +}*/
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-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaGeneratorUtil.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -1,5 +1,29 @@
package org.nuiton.topia.templates;
+/*
+ * #%L
+ * ToPIA :: Templates
+ * $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.lang3.StringUtils;
Modified: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaJavaValidator.java
===================================================================
--- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaJavaValidator.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaJavaValidator.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -1,5 +1,29 @@
package org.nuiton.topia.templates;
+/*
+ * #%L
+ * ToPIA :: Templates
+ * $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.eugene.models.object.ObjectModel;
import org.nuiton.eugene.models.object.ObjectModelAttribute;
Modified: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaMetaTransformer.java
===================================================================
--- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaMetaTransformer.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaMetaTransformer.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -1,5 +1,29 @@
package org.nuiton.topia.templates;
+/*
+ * #%L
+ * ToPIA :: Templates
+ * $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.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.nuiton.eugene.AbstractMetaTransformer;
Modified: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaRelationValidator.java
===================================================================
--- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaRelationValidator.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaRelationValidator.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -12,6 +12,30 @@
package org.nuiton.topia.templates;
+/*
+ * #%L
+ * ToPIA :: Templates
+ * $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.eugene.models.object.ObjectModel;
import org.nuiton.eugene.models.object.ObjectModelAttribute;
import org.nuiton.eugene.models.object.validator.ObjectModelValidator;
Modified: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaStereoTypes.java
===================================================================
--- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaStereoTypes.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaStereoTypes.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -1,5 +1,29 @@
package org.nuiton.topia.templates;
+/*
+ * #%L
+ * ToPIA :: Templates
+ * $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.eugene.EugeneStereoTypes;
import org.nuiton.eugene.models.object.ObjectModelAttribute;
import org.nuiton.eugene.models.object.ObjectModelClassifier;
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-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaTagValues.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -1,5 +1,29 @@
package org.nuiton.topia.templates;
+/*
+ * #%L
+ * ToPIA :: Templates
+ * $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.eugene.EugeneTagValues;
import org.nuiton.eugene.models.object.ObjectModel;
import org.nuiton.eugene.models.object.ObjectModelAttribute;
Modified: trunk/topia-templates/src/test/java/org/nuiton/topia/templates/TopiaGeneratorUtilTest.java
===================================================================
--- trunk/topia-templates/src/test/java/org/nuiton/topia/templates/TopiaGeneratorUtilTest.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-templates/src/test/java/org/nuiton/topia/templates/TopiaGeneratorUtilTest.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -1,5 +1,29 @@
package org.nuiton.topia.templates;
+/*
+ * #%L
+ * ToPIA :: Templates
+ * $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.junit.Test;
import static org.junit.Assert.assertEquals;
Modified: trunk/topia-templates/src/test/java/org/nuiton/topia/templates/TopiaModelPropertiesProviderTest.java
===================================================================
--- trunk/topia-templates/src/test/java/org/nuiton/topia/templates/TopiaModelPropertiesProviderTest.java 2013-11-22 18:03:47 UTC (rev 2884)
+++ trunk/topia-templates/src/test/java/org/nuiton/topia/templates/TopiaModelPropertiesProviderTest.java 2013-11-22 20:03:11 UTC (rev 2885)
@@ -1,5 +1,29 @@
package org.nuiton.topia.templates;
+/*
+ * #%L
+ * ToPIA :: Templates
+ * $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.junit.Assert;
import org.junit.Before;
import org.junit.Test;
1
0
Nov. 22, 2013
Author: tchemit
Date: 2013-11-22 19:03:47 +0100 (Fri, 22 Nov 2013)
New Revision: 2884
Url: http://nuiton.org/projects/topia/repository/revisions/2884
Log:
refs #299: Refactor modules
Added:
trunk/topia-it/
trunk/topia-it/LICENSE.txt
trunk/topia-it/README.txt
trunk/topia-it/pom.xml
trunk/topia-it/src/
trunk/topia-it/src/main/
trunk/topia-it/src/main/java/
trunk/topia-it/src/main/java/org/
trunk/topia-it/src/main/java/org/nuiton/
trunk/topia-it/src/main/java/org/nuiton/topia/
trunk/topia-it/src/main/java/org/nuiton/topia/it/
trunk/topia-it/src/main/xmi/
trunk/topia-it/src/test/
trunk/topia-it/src/test/java/
trunk/topia-it/src/test/java/org/
trunk/topia-it/src/test/java/org/nuiton/
trunk/topia-it/src/test/java/org/nuiton/topia/
trunk/topia-it/src/test/java/org/nuiton/topia/it/
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/AbstractEmployeTopiaDao.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/AbstractPersonneTopiaDao.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/EmployeTopiaDao.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/EmployeeDao.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/GeneratedEmployeeTopiaDao.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/GeneratedPersonneTopiaDao.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/PersonneDao.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/PersonneTopiaDao.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TestHelper.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaContextFactoryTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaDatabase.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaJpaSupportTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/EntityStateTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaConnectionProviderHardCoded.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaConnectionProviderTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextImplTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextReplicateTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaUtilTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/generator/
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/generator/TopiaTestCase.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/EntityVisitorExportXmlTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/ExportXMLVisitor.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/HqlAndParametersBuilderTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/NaturalIdTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/TopiaDAOTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/CollectorTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/EntityOperatorTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityBinderTest.java
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/TopiaEntityRefTester.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityRefTesterTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/ano1882/
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/ano1882/DAOAbstractTransformerTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/evo1912/
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/evo1912/EntityDTOTransformerTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/AbstractExtraDAOEntityTopiaDao.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/EnumTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/Gender.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/Title.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/beangen/
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/beangen/RoueImpl.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/AbstractContact2TopiaDao.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/DeleteEntityTest.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Abstract.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Impl.hbm.xml
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Impl.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/package-info.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/FakeService.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/TestService.java
trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/package-info.java
trunk/topia-it/src/test/resources/
trunk/topia-it/src/test/resources/TopiaConnectionProviderHardcoded.properties
trunk/topia-it/src/test/resources/TopiaContextImpl.properties
trunk/topia-it/src/test/resources/log4j.properties
trunk/topia-junit/
trunk/topia-junit/LICENSE.txt
trunk/topia-junit/README.txt
trunk/topia-junit/pom.xml
trunk/topia-junit/src/
trunk/topia-junit/src/main/
trunk/topia-junit/src/main/java/
trunk/topia-junit/src/main/java/org/
trunk/topia-junit/src/main/java/org/nuiton/
trunk/topia-junit/src/main/java/org/nuiton/topia/
trunk/topia-junit/src/main/java/org/nuiton/topia/junit/
trunk/topia-templates/
trunk/topia-templates/LICENSE.txt
trunk/topia-templates/README.txt
trunk/topia-templates/pom.xml
trunk/topia-templates/src/
trunk/topia-templates/src/main/
trunk/topia-templates/src/main/java/
trunk/topia-templates/src/main/java/org/
trunk/topia-templates/src/main/java/org/nuiton/
trunk/topia-templates/src/main/java/org/nuiton/topia/
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/ApplicationContextTransformer.java
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/BinderHelperTransformer.java
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/DAOHelperTransformer.java
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/DTOTransformer.java
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityDTOTransformer.java
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityDaoTransformer.java
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityHibernateMappingGenerator.java
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityTransformer.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/TopiaJavaValidator.java
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaMetaTransformer.java
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaRelationValidator.java
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaStereoTypes.java
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaTagValues.java
trunk/topia-templates/src/main/java/org/nuiton/topia/templates/package-info.java
trunk/topia-templates/src/main/resources/
trunk/topia-templates/src/main/resources/META-INF.services/
trunk/topia-templates/src/main/resources/META-INF.services/org.nuiton.eugene.ModelPropertiesUtil$ModelPropertiesProvider
trunk/topia-templates/src/test/
trunk/topia-templates/src/test/java/
trunk/topia-templates/src/test/java/org/
trunk/topia-templates/src/test/java/org/nuiton/
trunk/topia-templates/src/test/java/org/nuiton/topia/
trunk/topia-templates/src/test/java/org/nuiton/topia/templates/
trunk/topia-templates/src/test/java/org/nuiton/topia/templates/TopiaGeneratorUtilTest.java
trunk/topia-templates/src/test/java/org/nuiton/topia/templates/TopiaModelPropertiesProviderTest.java
Removed:
trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/ApplicationContextTransformer.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/BinderHelperTransformer.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DAOHelperTransformer.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DTOTransformer.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityDTOTransformer.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityDaoTransformer.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityHibernateMappingGenerator.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityTransformer.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/PersistenceContextTransformer.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaGeneratorUtil.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaJavaValidator.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaMetaTransformer.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaRelationValidator.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaStereoTypes.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaTagValues.java
trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/package-info.java
trunk/topia-persistence/src/main/resources/META-INF/services/org.nuiton.eugene.ModelPropertiesUtil$ModelPropertiesProvider
trunk/topia-persistence/src/test/java/org/nuiton/topia/AbstractEmployeTopiaDao.java
trunk/topia-persistence/src/test/java/org/nuiton/topia/AbstractPersonneTopiaDao.java
trunk/topia-persistence/src/test/java/org/nuiton/topia/EmployeTopiaDao.java
trunk/topia-persistence/src/test/java/org/nuiton/topia/EmployeeDao.java
trunk/topia-persistence/src/test/java/org/nuiton/topia/GeneratedEmployeeTopiaDao.java
trunk/topia-persistence/src/test/java/org/nuiton/topia/GeneratedPersonneTopiaDao.java
trunk/topia-persistence/src/test/java/org/nuiton/topia/PersonneDao.java
trunk/topia-persistence/src/test/java/org/nuiton/topia/PersonneTopiaDao.java
trunk/topia-persistence/src/test/java/org/nuiton/topia/TestHelper.java
trunk/topia-persistence/src/test/java/org/nuiton/topia/TopiaContextFactoryTest.java
trunk/topia-persistence/src/test/java/org/nuiton/topia/TopiaDatabase.java
trunk/topia-persistence/src/test/java/org/nuiton/topia/TopiaJpaSupportTest.java
trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/EntityStateTest.java
trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaConnectionProviderHardCoded.java
trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaConnectionProviderTest.java
trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaContextImplTest.java
trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaContextReplicateTest.java
trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaUtilTest.java
trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/TopiaGeneratorUtilTest.java
trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/TopiaModelPropertiesProviderTest.java
trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/TopiaTestCase.java
trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/EntityVisitorExportXmlTest.java
trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/ExportXMLVisitor.java
trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/HqlAndParametersBuilderTest.java
trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/NaturalIdTest.java
trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/TopiaDAOTest.java
trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/CollectorTest.java
trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/EntityOperatorTest.java
trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityBinderTest.java
trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityHelperTest.java
trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTester.java
trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTesterTest.java
trunk/topia-persistence/src/test/java/org/nuiton/topia/test/ano1882/DAOAbstractTransformerTest.java
trunk/topia-persistence/src/test/java/org/nuiton/topia/test/evo1912/EntityDTOTransformerTest.java
trunk/topia-persistence/src/test/java/org/nuiton/topiatest/AbstractExtraDAOEntityTopiaDao.java
trunk/topia-persistence/src/test/java/org/nuiton/topiatest/EnumTest.java
trunk/topia-persistence/src/test/java/org/nuiton/topiatest/Gender.java
trunk/topia-persistence/src/test/java/org/nuiton/topiatest/Title.java
trunk/topia-persistence/src/test/java/org/nuiton/topiatest/beangen/RoueImpl.java
trunk/topia-persistence/src/test/java/org/nuiton/topiatest/deletetest/AbstractContact2TopiaDao.java
trunk/topia-persistence/src/test/java/org/nuiton/topiatest/deletetest/DeleteEntityTest.java
trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1.java
trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1Abstract.java
trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1Impl.hbm.xml
trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1Impl.java
trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/package-info.java
trunk/topia-persistence/src/test/java/org/nuiton/topiatest/service/FakeService.java
trunk/topia-persistence/src/test/java/org/nuiton/topiatest/service/TestService.java
trunk/topia-persistence/src/test/java/org/nuiton/topiatest/service/package-info.java
trunk/topia-persistence/src/test/resources/TopiaConnectionProviderHardcoded.properties
trunk/topia-persistence/src/test/resources/TopiaContextImpl.properties
trunk/topia-persistence/src/test/resources/log4j.properties
trunk/topia-persistence/src/test/xmi/
Modified:
trunk/pom.xml
trunk/topia-it/src/main/xmi/topiatest.zargo
trunk/topia-persistence/pom.xml
trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaEntity.java
Modified: trunk/pom.xml
===================================================================
--- trunk/pom.xml 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/pom.xml 2013-11-22 18:03:47 UTC (rev 2884)
@@ -202,6 +202,9 @@
<modules>
<module>topia-persistence</module>
+ <module>topia-junit</module>
+ <module>topia-templates</module>
+ <module>topia-it</module>
<module>topia-service-replication</module>
<module>topia-service-migration</module>
</modules>
Property changes on: trunk/topia-it
___________________________________________________________________
Added: svn:ignore
+ target
.idea
*.ipr
*.iws
*.iml
Property changes on: trunk/topia-it/LICENSE.txt
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision
Added: svn:eol-style
+ native
Property changes on: trunk/topia-it/README.txt
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision
Added: svn:eol-style
+ native
Added: trunk/topia-it/pom.xml
===================================================================
--- trunk/topia-it/pom.xml (rev 0)
+++ trunk/topia-it/pom.xml 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,129 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ #%L
+ ToPIA :: Persistence
+
+ $Id$
+ $HeadURL: http://svn.nuiton.org/svn/topia/trunk/topia-persistence/pom.xml $
+ %%
+ 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-it</artifactId>
+ <packaging>jar</packaging>
+
+ <name>ToPIA :: IT</name>
+ <description>Integration tests</description>
+
+ <dependencies>
+
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>topia-persistence</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>topia-junit</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-log4j12</artifactId>
+ </dependency>
+
+ <!-- BD H2 for testing -->
+ <dependency>
+ <groupId>com.h2database</groupId>
+ <artifactId>h2</artifactId>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-core</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>log4j</groupId>
+ <artifactId>log4j</artifactId>
+ <scope>test</scope>
+ </dependency>
+
+ </dependencies>
+
+ <build>
+
+ <plugins>
+
+ <plugin>
+ <groupId>org.nuiton.eugene</groupId>
+ <artifactId>eugene-maven-plugin</artifactId>
+ <configuration>
+
+ </configuration>
+ <executions>
+ <execution>
+ <id>Model Generator</id>
+ <phase>generate-sources</phase>
+ <configuration>
+ <templates>
+ org.nuiton.eugene.java.JavaInterfaceTransformer,
+ org.nuiton.eugene.java.JavaBeanTransformer,
+ org.nuiton.topia.templates.TopiaMetaTransformer,
+ org.nuiton.topia.templates.EntityDTOTransformer,
+ org.nuiton.topia.templates.BinderHelperTransformer
+ </templates>
+ <fullPackagePath>org.nuiton.topia</fullPackagePath>
+ <defaultPackage>org.nuiton.topia</defaultPackage>
+ </configuration>
+ <goals>
+ <goal>generate</goal>
+ </goals>
+ </execution>
+ </executions>
+ <dependencies>
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>topia-templates</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ </dependencies>
+ </plugin>
+
+ </plugins>
+ </build>
+
+</project>
Property changes on: trunk/topia-it/pom.xml
___________________________________________________________________
Added: svn:mime-type
+ text/xml
Added: svn:keywords
+ Author Date Id Revision
Added: svn:eol-style
+ native
Property changes on: trunk/topia-it/src/main/java/org
___________________________________________________________________
Added: svn:ignore
+ target
*.ipr
*.iws
*.iml
.idea
Modified: trunk/topia-it/src/main/xmi/topiatest.zargo
===================================================================
(Binary files differ)
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/AbstractEmployeTopiaDao.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/AbstractEmployeTopiaDao.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/AbstractEmployeTopiaDao.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/AbstractEmployeTopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,33 @@
+package org.nuiton.topia.it.legacy;
+
+/*
+ * #%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.nuiton.topiatest.Employe;
+
+/**
+ * @author Arnaud Thimel <thimel(a)codelutin.com>
+ */
+public abstract class AbstractEmployeTopiaDao<E extends Employe> extends GeneratedEmployeeTopiaDao<E> {
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/AbstractPersonneTopiaDao.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/AbstractPersonneTopiaDao.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/AbstractPersonneTopiaDao.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/AbstractPersonneTopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,34 @@
+package org.nuiton.topia.it.legacy;
+
+/*
+ * #%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.nuiton.topiatest.Personne;
+
+/**
+ * @author Arnaud Thimel <thimel(a)codelutin.com>
+ */
+public abstract class AbstractPersonneTopiaDao<E extends Personne> extends GeneratedPersonneTopiaDao<E> {
+
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/EmployeTopiaDao.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/EmployeTopiaDao.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/EmployeTopiaDao.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/EmployeTopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,42 @@
+package org.nuiton.topia.it.legacy;
+
+/*
+ * #%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.util.List;
+
+import org.nuiton.topiatest.Employe;
+import org.nuiton.topiatest.Personne;
+
+/**
+ * @author Arnaud Thimel <thimel(a)codelutin.com>
+ */
+public class EmployeTopiaDao extends AbstractEmployeTopiaDao<Employe> {
+
+ @Override
+ public List<Personne> findAllPersonnesByXAndY(int x, int y) {
+ return null;
+ }
+
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/EmployeeDao.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/EmployeeDao.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/EmployeeDao.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/EmployeeDao.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,31 @@
+package org.nuiton.topia.it.legacy;
+
+/*
+ * #%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%
+ */
+
+/**
+ * @author Arnaud Thimel <thimel(a)codelutin.com>
+ */
+public interface EmployeeDao {
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/GeneratedEmployeeTopiaDao.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/GeneratedEmployeeTopiaDao.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/GeneratedEmployeeTopiaDao.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/GeneratedEmployeeTopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,33 @@
+package org.nuiton.topia.it.legacy;
+
+/*
+ * #%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.nuiton.topiatest.Employe;
+
+/**
+ * @author Arnaud Thimel <thimel(a)codelutin.com>
+ */
+public abstract class GeneratedEmployeeTopiaDao<E extends Employe> extends AbstractPersonneTopiaDao<E> {
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/GeneratedPersonneTopiaDao.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/GeneratedPersonneTopiaDao.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/GeneratedPersonneTopiaDao.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/GeneratedPersonneTopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,60 @@
+package org.nuiton.topia.it.legacy;
+
+/*
+ * #%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.util.List;
+import java.util.Map;
+
+import org.nuiton.topia.persistence.AbstractTopiaDao;
+import org.nuiton.topia.persistence.TopiaEntity;
+import org.nuiton.topia.persistence.TopiaEntityEnum;
+import org.nuiton.topiatest.Personne;
+
+/**
+ * @author Arnaud Thimel <thimel(a)codelutin.com>
+ */
+public abstract class GeneratedPersonneTopiaDao<E extends Personne> extends AbstractTopiaDao<E> implements PersonneDao {
+
+ @Override
+ public TopiaEntityEnum getTopiaEntityEnum() {
+ return null;
+ }
+
+ @Override
+ public <R extends TopiaEntity> List<R> findUsages(Class<R> type, E entity) throws TopiaException {
+ return null;
+ }
+
+ @Override
+ public Map<Class<? extends TopiaEntity>, List<? extends TopiaEntity>> findAllUsages(E entity) throws TopiaException {
+ return null;
+ }
+
+ @Override
+ public Class<E> getEntityClass() {
+ return null;
+ }
+
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/PersonneDao.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/PersonneDao.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/PersonneDao.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/PersonneDao.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,38 @@
+package org.nuiton.topia.it.legacy;
+
+/*
+ * #%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.util.List;
+
+import org.nuiton.topiatest.Personne;
+
+/**
+ * @author Arnaud Thimel <thimel(a)codelutin.com>
+ */
+public interface PersonneDao {
+
+ List<Personne> findAllPersonnesByXAndY(int x, int y);
+
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/PersonneTopiaDao.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/PersonneTopiaDao.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/PersonneTopiaDao.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/PersonneTopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,41 @@
+package org.nuiton.topia.it.legacy;
+
+/*
+ * #%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.util.List;
+
+import org.nuiton.topiatest.Personne;
+
+/**
+ * @author Arnaud Thimel <thimel(a)codelutin.com>
+ */
+public class PersonneTopiaDao extends AbstractPersonneTopiaDao<Personne> {
+
+ @Override
+ public List<Personne> findAllPersonnesByXAndY(int x, int y) {
+ return null;
+ }
+
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TestHelper.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/TestHelper.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TestHelper.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TestHelper.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,160 @@
+/*
+ * #%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%
+ */
+package org.nuiton.topia.it.legacy;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.hibernate.cfg.Environment;
+import org.junit.Ignore;
+import org.nuiton.util.FileUtil;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Properties;
+
+/**
+ * Helper for all topia tests.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.5
+ */
+@Ignore
+// this is not a test :)
+public class TestHelper {
+
+ private static final Log log = LogFactory.getLog(TestHelper.class);
+
+ protected static File testBasedir;
+
+ protected static File targetdir;
+
+ protected static File dirDatabase;
+
+ public static final String DEFAULT_CONFIGURATION_LOCATION = "/TopiaContextImpl.properties";
+
+ public static File getTestWorkdir() {
+ if (testBasedir == null) {
+ String base = System.getProperty("java.io.tmpdir");
+ if (base == null || base.isEmpty()) {
+ base = new File("").getAbsolutePath();
+ }
+ testBasedir = new File(base);
+ log.info("basedir for test " + testBasedir);
+ }
+ return testBasedir;
+ }
+
+ public static File getTestBasedir(Class<?> testClass) throws IOException {
+ File dir = getTestWorkdir();
+ File result = new File(dir, testClass.getName());
+ if (result.exists()) {
+
+ // when calling this method (always in a BeforeClass method), we wants
+ // to clean the directory, this is a new build
+ FileUtils.deleteDirectory(result);
+ }
+
+ // always create the directory
+ FileUtil.createDirectoryIfNecessary(result);
+ return result;
+ }
+
+ public static TopiaContext initTopiaContext(File testDirectory,
+ String dbname)
+ throws IOException, TopiaNotFoundException {
+
+
+ TopiaContext topiaContext = initTopiaContext(
+ testDirectory,
+ DEFAULT_CONFIGURATION_LOCATION,
+ dbname
+ );
+ return topiaContext;
+ }
+
+ public static TopiaContext initTopiaContext(File testDirectory,
+ String dbPropertiesPath,
+ String dbname)
+ throws IOException, TopiaNotFoundException {
+
+ Properties configuration = initTopiaContextConfiguration(
+ testDirectory,
+ dbPropertiesPath,
+ dbname);
+ return TopiaContextFactory.getContext(configuration);
+ }
+
+ public static Properties initTopiaContextConfiguration(File testDirectory,
+ String dbPropertiesPath,
+ String dbname)
+ throws IOException {
+
+ Properties configuration = loadHibernateConfiguration(dbPropertiesPath);
+
+ // make sure we always use a different directory
+
+ String dbPath = getDbName(testDirectory, dbname);
+
+ if (log.isInfoEnabled()) {
+ log.info("dbPath = " + dbPath);
+ }
+ configuration.setProperty(
+ Environment.URL,
+// "hibernate.connection.url",
+ "jdbc:h2:file:" + dbPath);
+
+ return configuration;
+ }
+
+ public static Properties loadHibernateConfiguration(String dbPropertiesPath) throws IOException {
+ InputStream stream = TestHelper.class.getResourceAsStream(dbPropertiesPath);
+
+ Properties configuration = new Properties();
+
+ configuration.load(stream);
+ configuration.setProperty(
+ TopiaContextFactory.CONFIG_PERSISTENCE_CLASSES,
+ TopiaTestDAOHelper.getImplementationClassesAsString());
+ return configuration;
+ }
+
+ public static String getDbName(File testDirectory, String dbname) {
+ return new File(testDirectory,
+ dbname + '_' + System.nanoTime()).getAbsolutePath();
+ }
+
+ public static Properties initTopiaContextConfiguration(File testDirectory,
+ String dbname)
+ throws IOException {
+
+ return initTopiaContextConfiguration(
+ testDirectory,
+ DEFAULT_CONFIGURATION_LOCATION,
+ dbname
+ );
+ }
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaContextFactoryTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/TopiaContextFactoryTest.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaContextFactoryTest.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaContextFactoryTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,189 @@
+/*
+ * #%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%
+ */
+package org.nuiton.topia.it.legacy;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.nuiton.topia.framework.AbstractTopiaContext;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.List;
+import java.util.Properties;
+
+/**
+ * Created: 8 mai 2010
+ *
+ * @author fdesbois <fdesbois(a)codelutin.com>
+ * @version $Id$
+ */
+public class TopiaContextFactoryTest {
+
+ private static final Log log =
+ LogFactory.getLog(TopiaContextFactoryTest.class);
+
+ protected static File testBasedir;
+
+ protected Properties properties;
+
+ @BeforeClass
+ public static void init() throws IOException {
+
+ testBasedir = TopiaDatabase.getTestSpecificDirectory(TopiaContextFactoryTest.class, "dummy");
+
+ }
+
+ @Before
+ public void setUp() throws Exception {
+ properties = new Properties();
+ properties.setProperty("prop1", "value1");
+ properties.setProperty("prop2", "value2");
+ TopiaContextFactory.contextCache.clear();
+ }
+
+ @Test
+ public void testGetContextOpened() throws Exception {
+ log.debug("## testGetContextOpened");
+
+ /** PREPARE DATA **/
+ String databaseName = "h2data-testGetContextByPropertie";
+ File dbDirectory = new File(testBasedir, databaseName);
+ String url = "jdbc:h2:file:" + dbDirectory;
+ properties.setProperty("hibernate.connection.url", url);
+
+ AbstractTopiaContext test = new AbstractTopiaContext(properties);
+ TopiaContextFactory.contextCache.put(properties, test);
+
+ /** EXEC METHOD **/
+ List<String> result = TopiaContextFactory.getContextOpened();
+ Assert.assertEquals(1, result.size());
+ Assert.assertEquals(url, result.get(0));
+ }
+
+ @Test
+ public void testRemoveContext() throws Exception {
+ log.debug("## testRemoveContext");
+
+ /** PREPARE DATA **/
+ AbstractTopiaContext test = new AbstractTopiaContext(properties);
+ TopiaContextFactory.contextCache.put(properties, test);
+
+ /** EXEC METHOD **/
+ TopiaContextFactory.removeContext(test);
+ Assert.assertEquals(0, TopiaContextFactory.contextCache.size());
+ }
+
+ //@Test
+
+ public void testGetContext() throws Exception {
+ // TODO-fdesbois-20100508 : only used TopiaUtil.getProperties, need tests for this method
+ }
+
+ @Test
+ public void testGetContextByProperties() throws Exception {
+ log.debug("## testGetContextByProperties");
+
+ /** PREPARE DATA **/
+ Properties propertiesParent = new Properties(properties);
+ propertiesParent.setProperty("prop3", "value3");
+
+ Properties propertiesAll = new Properties();
+ propertiesAll.setProperty("prop1", "value1");
+ propertiesAll.setProperty("prop2", "value2");
+ propertiesAll.setProperty("prop3", "value3");
+
+ /** EXEC METHOD **/
+
+ log.info("test 0 : add null properties");
+ try {
+ TopiaContextFactory.getContext(null);
+ } catch (Exception eee) {
+ Assert.assertEquals(NullPointerException.class, eee.getClass());
+ }
+
+ log.info("test 1 : add new properties, will instantiate a new" +
+ " TopiaContext");
+ TopiaContext test1 = TopiaContextFactory.getContext(propertiesParent);
+ Assert.assertNotNull(test1);
+ Assert.assertEquals(1, TopiaContextFactory.contextCache.size());
+
+ log.info("test 2 : with same properties, will retrieve existing" +
+ " TopiaContext");
+ TopiaContext test2 = TopiaContextFactory.getContext(propertiesParent);
+ Assert.assertEquals(test1, test2);
+ Assert.assertEquals(1, TopiaContextFactory.contextCache.size());
+
+ log.info("test 3 : use other properties, will instantiate a different" +
+ "TopiaContext");
+ TopiaContext test3 = TopiaContextFactory.getContext(properties);
+ log.debug("cache size : " + TopiaContextFactory.contextCache.size());
+ log.debug("result : " + test1);
+ log.debug("result3 : " + test3);
+ Assert.assertNotSame(test1, test3);
+ Assert.assertEquals(2, TopiaContextFactory.contextCache.size());
+
+ log.info("test 4 : use other properties but equivalent to existing " +
+ "TopiaContext");
+ // Test flating of properties
+ TopiaContext test4 = TopiaContextFactory.getContext(propertiesAll);
+ Assert.assertEquals(test1, test4);
+ Assert.assertEquals(2, TopiaContextFactory.contextCache.size());
+
+ log.info("test5a : reinstantiate new TopiaContext after one is closed.");
+ // TEST
+ // Strange behavior the closed flag of context stay true if
+ // hibernateFactory is not loaded from real properties
+// test1.closeContext();
+// Assert.assertTrue(test1.isClosed());
+
+ // Add properties for Hibernate to have real opened topiaContext
+ String databaseName = "h2data-testGetContextByPropertie";
+ File f = new File(testBasedir, databaseName);
+
+ properties.setProperty("hibernate.connection.username", "sa");
+ properties.setProperty("hibernate.connection.password", "");
+ properties.setProperty("hibernate.connection.driver_class", "org.h2.Driver");
+ properties.setProperty("hibernate.connection.url",
+ "jdbc:h2:file:" + f.getAbsolutePath());
+
+
+ TopiaContext test5 = TopiaContextFactory.getContext(properties);
+ Assert.assertNotSame(test1, test5);
+ Assert.assertEquals(3, TopiaContextFactory.contextCache.size());
+
+ log.info("test5b : beginTransaction to properly close the context");
+ test5.beginTransaction();
+
+ test5.closeContext();
+
+ TopiaContext result = TopiaContextFactory.getContext(properties);
+ Assert.assertNotSame(test5, result);
+ Assert.assertEquals(3, TopiaContextFactory.contextCache.size());
+ }
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaDatabase.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/TopiaDatabase.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaDatabase.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaDatabase.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,210 @@
+/*
+ * #%L
+ * ToPIA :: Persistence
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2004 - 2012 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%
+ */
+package org.nuiton.topia.it.legacy;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.hibernate.cfg.Configuration;
+import org.junit.rules.TestWatcher;
+import org.junit.runner.Description;
+import org.nuiton.topia.HibernateProvider;
+import org.nuiton.topia.TopiaContextFactory;
+import org.nuiton.topia.TopiaException;
+
+import java.io.File;
+import java.io.InputStream;
+import java.util.Properties;
+
+/**
+ * Put this class as a Rule in test to obtain a new isolated db for each test.
+ * <p/>
+ * Here is a simple example of usage :
+ * <pre>
+ * public class MyTest {
+ *
+ * \@Rule
+ * public final TopiaDatabase db = new TopiaDatabase();
+ *
+ * \@Test
+ * public void testMethod() throws TopiaException {
+ *
+ * TopiaContext tx = db.beginTransaction();
+ * ...
+ * }
+ * </pre>
+ * The db created will be unique for each test method (and for each build also).
+ * <p/>
+ * You don't need to close any transaction, it will be done for you and the end
+ * of each method test.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.6.8
+ */
+public class TopiaDatabase extends TestWatcher {
+
+ /** Logger. */
+ private static final Log log = LogFactory.getLog(TopiaDatabase.class);
+
+ /** A time-stamp, allow to make multiple build and keep the tests data. */
+ public static final String TIMESTAMP = String.valueOf(System.nanoTime());
+
+ private File testBasedir;
+
+ private Properties dbConfiguration;
+
+ private TopiaTestTopiaApplicationContext applicationContext;
+
+ private Configuration hibernateCfg;
+
+ private final String configurationPath;
+
+ public TopiaDatabase() {
+ this(TestHelper.DEFAULT_CONFIGURATION_LOCATION);
+ }
+
+ public TopiaDatabase(String configurationPath) {
+ this.configurationPath = configurationPath;
+ }
+
+ @Override
+ protected void starting(Description description) {
+
+ // get test directory
+ testBasedir = getTestSpecificDirectory(
+ description.getTestClass(),
+ description.getMethodName());
+
+ if (log.isDebugEnabled()) {
+ log.debug("testBasedir = " + testBasedir);
+ }
+
+ // create the root context
+ try {
+
+ dbConfiguration = new Properties();
+ InputStream stream =
+ getClass().getResourceAsStream(configurationPath);
+
+ try {
+ dbConfiguration.load(stream);
+ } finally {
+ stream.close();
+ }
+ dbConfiguration.setProperty(
+ TopiaContextFactory.CONFIG_PERSISTENCE_CLASSES,
+ TopiaTestDAOHelper.getImplementationClassesAsString());
+
+ // make sure we always use a different directory
+
+ String dbPath = new File(testBasedir, "db").getAbsolutePath();
+
+ if (log.isDebugEnabled()) {
+ log.debug("dbPath = " + dbPath);
+ }
+ dbConfiguration.setProperty(
+ TopiaContextFactory.CONFIG_URL, "jdbc:h2:file:" + dbPath);
+
+ onDbConfigurationCreate(dbConfiguration, testBasedir, dbPath);
+
+// rootCtxt = TopiaContextFactory.getContext(dbConfiguration);
+ applicationContext = new TopiaTestTopiaApplicationContext(dbConfiguration) {
+ @Override
+ protected HibernateProvider getHibernateProvider() {
+ HibernateProvider provider = super.getHibernateProvider();
+ hibernateCfg = provider.getHibernateConfiguration();
+ return provider;
+ }
+ };
+ } catch (Exception e) {
+ throw new IllegalStateException(
+ "Could not start db at " + testBasedir, e);
+ }
+ }
+
+ @Override
+ public void finished(Description description) {
+
+ if (applicationContext != null && !applicationContext.isClosed()) {
+ try {
+ applicationContext.closeContext();
+ } catch (TopiaException e) {
+ if (log.isErrorEnabled()) {
+ log.error("Could not close topia root context", e);
+ }
+ }
+ }
+ applicationContext = null;
+ dbConfiguration = null;
+ }
+
+ public File getTestBasedir() {
+ return testBasedir;
+ }
+
+ public Properties getDbConfiguration() {
+ return dbConfiguration;
+ }
+
+ public TopiaTestTopiaApplicationContext getApplicationContext() {
+ return applicationContext;
+ }
+
+ public Configuration getHibernateCfg() {
+ return hibernateCfg;
+ }
+
+ public TopiaTestTopiaPersistenceContext beginTransaction() throws TopiaException {
+ return applicationContext.newPersistenceContext();
+ }
+
+ protected void onDbConfigurationCreate(Properties configuration,
+ File testDir,
+ String dbPath) {
+
+ }
+
+ public static File getTestSpecificDirectory(Class<?> testClassName, String methodName) {
+ // Trying to look for the temporary folder to store data for the test
+ String tempDirPath = System.getProperty("java.io.tmpdir");
+ if (tempDirPath == null) {
+ // can this really occur ?
+ tempDirPath = "";
+ if (log.isWarnEnabled()) {
+ log.warn("'\"java.io.tmpdir\" not defined");
+ }
+ }
+ File tempDirFile = new File(tempDirPath);
+
+ // create the directory to store database data
+ String dataBasePath = testClassName.getName()
+ + File.separator // a directory with the test class name
+ + methodName// a sub-directory with the method name
+ + '_'
+ + TIMESTAMP; // and a timestamp
+ File databaseFile = new File(tempDirFile, dataBasePath);
+ return databaseFile;
+ }
+}
+
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaJpaSupportTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/TopiaJpaSupportTest.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaJpaSupportTest.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaJpaSupportTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,161 @@
+/*
+ * #%L
+ * ToPIA :: Persistence :: Test Compatibility Kit
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2004 - 2012 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%
+ */
+package org.nuiton.topia.it.legacy;
+
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.nuiton.topiatest.Address;
+import org.nuiton.topiatest.AddressTopiaDao;
+import org.nuiton.topiatest.Gender;
+import org.nuiton.topiatest.Personne;
+import org.nuiton.topiatest.PersonneTopiaDao;
+
+import java.util.List;
+
+/**
+ * Tests the TopiaContext#find|findAll|findUnique methods
+ *
+ * @author Arnaud Thimel <thimel(a)codelutin.com>
+ */
+public class TopiaJpaSupportTest {
+
+ @Rule
+ public final TopiaDatabase db = new TopiaDatabase();
+
+ protected TopiaTestTopiaPersistenceContext persistenceContext;
+ protected TopiaJpaSupport jpaSupport;
+ protected AddressTopiaDao addressDAO;
+ protected PersonneTopiaDao personneDAO;
+ protected Address address;
+
+ @Before
+ public void createCompanies() throws TopiaException {
+ persistenceContext = db.beginTransaction();
+ jpaSupport = persistenceContext.jpaSupport;
+
+ personneDAO = persistenceContext.getPersonneDao();
+ addressDAO = persistenceContext.getAddressDao();
+
+ address = addressDAO.create(
+ Address.PROPERTY_ADRESS, "17 rue de la Pote Gellée, 44200 NANTES");
+
+ personneDAO.create(
+ Personne.PROPERTY_NAME, "Arnaud",
+ Personne.PROPERTY_GENDER, Gender.MALE);
+ personneDAO.create(
+ Personne.PROPERTY_NAME, "Charlotte",
+ Personne.PROPERTY_GENDER, Gender.FEMALE);
+ personneDAO.create(
+ Personne.PROPERTY_NAME, "Hortense",
+ Personne.PROPERTY_GENDER, Gender.FEMALE);
+ persistenceContext.commitTransaction();
+ }
+
+ @Test
+ public void testFindDAO() throws TopiaException {
+ Assert.assertEquals(3, personneDAO.count());
+
+ Assert.assertEquals(2, personneDAO.findAllByGender(Gender.FEMALE).size());
+ Assert.assertNotNull(personneDAO.findByGender(Gender.FEMALE));
+ Assert.assertNotNull(personneDAO.findByGender(Gender.MALE));
+ Assert.assertNull(personneDAO.findByGender(null));
+
+ Assert.assertEquals(0, personneDAO.findAllByName("nobody").size());
+ }
+
+ @Test
+ public void testFindAll() throws TopiaException {
+ Assert.assertEquals(3, personneDAO.count());
+
+ String query = "from " + Personne.class.getName() +
+ " where " + Personne.PROPERTY_GENDER + "=:g";
+
+ List females = jpaSupport.findAll(query, "g", Gender.FEMALE);
+ Assert.assertEquals(2, females.size());
+
+ List males = jpaSupport.findAll(query, "g", Gender.MALE);
+ Assert.assertEquals(1, males.size());
+
+ List all = jpaSupport.findAll("from " + Personne.class.getName());
+ Assert.assertEquals(3, all.size());
+
+ List none = jpaSupport.findAll("from " + Personne.class.getName() +
+ " where " + Personne.PROPERTY_NAME + "=:pax", "pax", "nobody");
+ Assert.assertEquals(0, none.size());
+ }
+
+ @Test
+ public void testFind() throws TopiaException {
+ Assert.assertEquals(3, personneDAO.count());
+
+ String query = "from " + Personne.class.getName() +
+ " where " + Personne.PROPERTY_GENDER + "=:g";
+
+ List females = jpaSupport.find(query, 0, 100, "g", Gender.FEMALE);
+ Assert.assertEquals(2, females.size());
+
+ females = jpaSupport.find(query, 0, 0, "g", Gender.FEMALE);
+ Assert.assertEquals(1, females.size());
+ Personne charlotte = (Personne)females.get(0);
+
+ females = jpaSupport.find(query, 1, 1, "g", Gender.FEMALE);
+ Assert.assertEquals(1, females.size());
+ Personne hortense = (Personne)females.get(0);
+
+ Assert.assertFalse(hortense.equals(charlotte));
+
+ // endIndex = -1 not supported in ToPIA 2.6, wait for 3.0
+// females = context.find(query, 0, -1, "g", Gender.FEMALE);
+// Assert.assertEquals(2, females.size());
+ }
+
+ @Test
+ public void testFindUnique() throws TopiaException {
+ Assert.assertEquals(3, personneDAO.count());
+
+ String query = "from " + Personne.class.getName() +
+ " where " + Personne.PROPERTY_GENDER + "=:g";
+
+ Object male = jpaSupport.findUnique(query, "g", Gender.MALE);
+ Assert.assertNotNull(male);
+
+ Object none = jpaSupport.findUnique("from " + Personne.class.getName() +
+ " where " + Personne.PROPERTY_NAME + "=:pax", "pax", "nobody");
+ Assert.assertNull(none);
+ }
+
+ @Test(expected = TopiaException.class)
+ public void testFindUniqueOutOfBounds() throws TopiaException {
+ Assert.assertEquals(3, personneDAO.count());
+
+ String query = "from " + Personne.class.getName() +
+ " where " + Personne.PROPERTY_GENDER + "=:g";
+
+ Object female = jpaSupport.findUnique(query, "g", Gender.FEMALE);
+ Assert.assertNotNull(female);
+ }
+
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/EntityStateTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/EntityStateTest.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/EntityStateTest.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/EntityStateTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,97 @@
+/*
+ * #%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%
+ */
+
+package org.nuiton.topia.it.legacy.framework;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.nuiton.topia.framework.EntityState;
+
+/**
+ * EntityStateTest.java
+ * <p/>
+ * Created: 22 nov. 06 12:15:11
+ *
+ * @author poussin <poussin(a)codelutin.com>
+ * @version $Revision$
+ * <p/>
+ * Last update: $Date$
+ * by : $Author$
+ */
+public class EntityStateTest {
+
+ /**
+ * Test les changements d'etat de {@link EntityState}.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void testState() throws Exception {
+ EntityState state = new EntityState();
+
+ state.addLoad();
+ Assert.assertTrue(state.isLoad());
+ Assert.assertFalse(state.isRead());
+ Assert.assertFalse(state.isCreate());
+ Assert.assertFalse(state.isUpdate());
+ Assert.assertFalse(state.isDelete());
+
+ state.addRead();
+ Assert.assertTrue(state.isLoad());
+ Assert.assertTrue(state.isRead());
+ Assert.assertFalse(state.isCreate());
+ Assert.assertFalse(state.isUpdate());
+ Assert.assertFalse(state.isDelete());
+
+ //state.addRead();
+ state.addCreate();
+ Assert.assertTrue(state.isLoad());
+ Assert.assertTrue(state.isRead());
+ Assert.assertTrue(state.isCreate());
+ Assert.assertFalse(state.isUpdate());
+ Assert.assertFalse(state.isDelete());
+
+ state.addUpdate();
+ Assert.assertTrue(state.isLoad());
+ Assert.assertTrue(state.isRead());
+ Assert.assertTrue(state.isCreate());
+ Assert.assertTrue(state.isUpdate());
+ Assert.assertFalse(state.isDelete());
+
+ state.addDelete();
+ Assert.assertTrue(state.isLoad());
+ Assert.assertTrue(state.isRead());
+ Assert.assertTrue(state.isCreate());
+ Assert.assertTrue(state.isUpdate());
+ Assert.assertTrue(state.isDelete());
+
+ state = new EntityState();
+ state.addDelete();
+ Assert.assertFalse(state.isRead());
+ Assert.assertFalse(state.isCreate());
+ Assert.assertFalse(state.isUpdate());
+ Assert.assertTrue(state.isDelete());
+ }
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaConnectionProviderHardCoded.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaConnectionProviderHardCoded.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaConnectionProviderHardCoded.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaConnectionProviderHardCoded.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,210 @@
+/*
+ * #%L
+ * ToPIA :: Persistence
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2004 - 2011 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%
+ */
+package org.nuiton.topia.it.legacy.framework;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Properties;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.hibernate.HibernateException;
+import org.hibernate.cfg.Environment;
+import org.hibernate.internal.util.ReflectHelper;
+import org.hibernate.internal.util.config.ConfigurationHelper;
+import org.hibernate.service.jdbc.connections.internal.ConnectionProviderInitiator;
+import org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl;
+
+/**
+ * Customized connection provider.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.5.3
+ */
+public class TopiaConnectionProviderHardCoded extends DriverManagerConnectionProviderImpl {
+
+ private String url;
+
+ private Properties connectionProps;
+
+ private Integer isolation;
+
+ private final ArrayList pool = new ArrayList();
+
+ private int poolSize;
+
+ private int checkedOut = 0;
+
+ private boolean autocommit;
+
+ /** Logger. */
+ private static final Log log =
+ LogFactory.getLog(TopiaConnectionProviderHardCoded.class);
+
+ @Override
+ public void configure(Map configurationValues) throws HibernateException {
+ String driverClass = (String)configurationValues.get(Environment.DRIVER);
+
+ poolSize = ConfigurationHelper.getInt(Environment.POOL_SIZE, configurationValues, 20); //default pool size 20
+ log.info("Using Hibernate built-in connection pool (not for production use!)");
+ log.info("Hibernate connection pool size: " + poolSize);
+
+ autocommit = ConfigurationHelper.getBoolean(Environment.AUTOCOMMIT, configurationValues);
+ log.info("autocommit mode: " + autocommit);
+
+ isolation = ConfigurationHelper.getInteger(Environment.ISOLATION, configurationValues);
+ if (isolation != null)
+ log.info("JDBC isolation level: " + Environment.isolationLevelToString(isolation));
+
+ if (driverClass == null) {
+ log.warn("no JDBC Driver class was specified by property " + Environment.DRIVER);
+ } else {
+ try {
+ // trying via forName() first to be as close to DriverManager's semantics
+ Class.forName(driverClass);
+ } catch (ClassNotFoundException cnfe) {
+ try {
+ ReflectHelper.classForName(driverClass);
+ } catch (ClassNotFoundException e) {
+ String msg = "JDBC Driver class not found: " + driverClass;
+ log.error(msg, e);
+ throw new HibernateException(msg, e);
+ }
+ }
+ }
+
+ // use a dummy directory to make sure only the connection provider knows
+ // the real directory where db is and then make sure hibernate always
+ // use the connection provider...
+ String directory =
+ (String)configurationValues.get(TopiaConnectionProviderTest.TEST_URL);
+
+ url = directory;
+// url = props.getProperty(Environment.URL);
+
+// if (url == null) {
+// String msg = "JDBC URL was not specified by property " + Environment.URL;
+// log.error(msg);
+// throw new HibernateException(msg);
+// }
+
+ connectionProps = ConnectionProviderInitiator.getConnectionProperties(configurationValues);
+
+ log.info("using driver: " + driverClass + " at URL: " + url);
+ // if debug level is enabled, then log the password, otherwise mask it
+ if (log.isDebugEnabled()) {
+ log.info("connection properties: " + connectionProps);
+ } else if (log.isInfoEnabled()) {
+ log.info("connection properties: " + ConfigurationHelper.maskOut(connectionProps, "password"));
+ }
+ }
+
+ @Override
+ public Connection getConnection() throws SQLException {
+ if (log.isTraceEnabled())
+ log.trace("total checked-out connections: " + checkedOut);
+
+ synchronized (pool) {
+ if (!pool.isEmpty()) {
+ int last = pool.size() - 1;
+ if (log.isTraceEnabled()) {
+ log.trace("using pooled JDBC connection, pool size: " + last);
+ }
+ checkedOut++;
+ Connection pooled = (Connection) pool.remove(last);
+ if (isolation != null)
+ pooled.setTransactionIsolation(isolation.intValue());
+ if (pooled.getAutoCommit() != autocommit)
+ pooled.setAutoCommit(autocommit);
+ return pooled;
+ }
+ }
+
+ log.debug("opening new JDBC connection");
+ Connection conn = DriverManager.getConnection(url, connectionProps);
+ if (isolation != null) conn.setTransactionIsolation(isolation);
+ if (conn.getAutoCommit() != autocommit) conn.setAutoCommit(autocommit);
+
+ if (log.isDebugEnabled()) {
+ log.debug("created connection to: " + url + ", Isolation Level: " + conn.getTransactionIsolation());
+ }
+// if ( log.isTraceEnabled() )
+ checkedOut++;
+
+ return conn;
+ }
+
+ @Override
+ public void closeConnection(Connection conn) throws SQLException {
+// if ( log.isDebugEnabled() )
+ checkedOut--;
+
+ synchronized (pool) {
+ int currentSize = pool.size();
+ if (currentSize < poolSize) {
+ if (log.isTraceEnabled()) {
+ log.trace("returning connection to pool, pool size: " + (currentSize + 1));
+ }
+ pool.add(conn);
+ return;
+ }
+ }
+
+ log.debug("closing JDBC connection");
+
+ conn.close();
+ }
+
+ @Override
+ protected void finalize() throws Throwable {
+ super.finalize();
+ close();
+ }
+
+ public void close() {
+
+ log.info("cleaning up connection pool: " + url);
+
+ Iterator iter = pool.iterator();
+ while (iter.hasNext()) {
+ try {
+ ((Connection) iter.next()).close();
+ } catch (SQLException sqle) {
+ log.warn("problem closing pooled connection", sqle);
+ }
+ }
+ pool.clear();
+
+ }
+
+ @Override
+ public boolean supportsAggressiveRelease() {
+ return false;
+ }
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaConnectionProviderTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaConnectionProviderTest.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaConnectionProviderTest.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaConnectionProviderTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,142 @@
+/*
+ * #%L
+ * ToPIA :: Persistence
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2004 - 2011 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%
+ */
+package org.nuiton.topia.it.legacy.framework;
+
+import org.junit.Assert;
+import org.junit.Rule;
+import org.junit.Test;
+import org.nuiton.topia.TopiaContextFactory;
+import org.nuiton.topia.TopiaDatabase;
+import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.TopiaTestDAOHelper;
+import org.nuiton.topia.TopiaTestTopiaPersistenceContext;
+import org.nuiton.topia.framework.TopiaConnectionProvider;
+import org.nuiton.topia.test.entities.Person;
+import org.nuiton.topia.test.entities.PersonDAO;
+import org.nuiton.topia.test.entities.PersonTopiaDao;
+import org.nuiton.topiatest.Personne;
+
+import java.io.File;
+import java.util.Locale;
+import java.util.Properties;
+
+import static org.junit.Assert.assertNotNull;
+
+/**
+ * To test the {@link TopiaConnectionProvider} and make sure all connections
+ * are done from here...
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.5.3
+ */
+public class TopiaConnectionProviderTest {
+
+// private static final Log log =
+// LogFactory.getLog(TopiaConnectionProviderTest.class);
+
+ public static final String TEST_URL = "testURL";
+
+ @Rule
+ public final TopiaDatabase db =
+ new TopiaDatabase("/TopiaConnectionProviderHardcoded.properties") {
+
+ @Override
+ protected void onDbConfigurationCreate(Properties configuration,
+ File testdir,
+ String dbPath) {
+
+ Assert.assertFalse(testdir.exists());
+
+ String dbPathFake = new File(testdir, "fake" + File.separator + "db").getAbsolutePath();
+
+ Assert.assertFalse(new File(dbPathFake).getParentFile().exists());
+
+ configuration.setProperty("dbPath", dbPath);
+ configuration.setProperty("dbPathFake", dbPathFake);
+
+ // give the path where connection provider will create db
+ configuration.setProperty(TEST_URL,
+ "jdbc:h2:file:" + dbPath);
+
+ // give a fake db path (we will make sure it is never create after hibernate usage).
+ configuration.setProperty(TopiaContextFactory.CONFIG_URL,
+ "jdbc:h2:file:" + dbPathFake);
+ }
+ };
+
+ @Test
+ public void testWithHardcoded() throws Exception {
+
+// Properties dbProperties = TestHelper.loadHibernateConfiguration(
+// "/TopiaConnectionProviderHardcoded.properties");
+//
+// File directory = new File(TestHelper.getDbName(testBasedir, "testWithHardcoded"));
+
+ String dbPath = (String) db.getDbConfiguration().get("dbPath");
+ String dbPathFake = (String) db.getDbConfiguration().get("dbPathFake");
+
+// new File(directory, "real" + File.separator + "db").getAbsolutePath();
+// Assert.assertFalse(new File(dbPath).getParentFile().exists());
+
+// String dbPathFake = new File(directory, "fake" + File.separator + "db").getAbsolutePath();
+
+// Assert.assertFalse(new File(dbPathFake).getParentFile().exists());
+
+// // give the path where connection provider will create db
+// dbProperties.setProperty(TEST_URL, "jdbc:h2:file:" + dbPath);
+//
+// // give a fake db path (we will make sure it is never create after hibernate usage).
+// dbProperties.setProperty(Environment.URL, "jdbc:h2:file:" + dbPathFake);
+//
+// root = TopiaContextFactory.getContext(dbProperties);
+
+ Locale.setDefault(Locale.FRANCE);
+
+ doStuffOnDb();
+
+ // the db file must have been created
+ Assert.assertTrue(new File(dbPath).getParentFile().exists());
+
+ // make sure the fake db path was never used
+ Assert.assertFalse(new File(dbPathFake).getParentFile().exists());
+ }
+
+ private void doStuffOnDb() throws TopiaException {
+ TopiaTestTopiaPersistenceContext transaction = db.beginTransaction();
+
+ try {
+ PersonDAO dao = TopiaTestDAOHelper.getPersonDAO(transaction);
+
+ Person personne = dao.create(Personne.PROPERTY_NAME, "Jack Bauer");
+ transaction.commitTransaction();
+ String idPersonne = personne.getTopiaId();
+ assertNotNull(idPersonne);
+
+ transaction.commitTransaction();
+ } finally {
+ transaction.closeContext();
+ }
+ }
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextImplTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaContextImplTest.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextImplTest.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextImplTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,552 @@
+/*
+ * #%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%
+ */
+package org.nuiton.topia.it.legacy.framework;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.h2.Driver;
+import org.hibernate.cfg.Configuration;
+import org.hibernate.mapping.PersistentClass;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.nuiton.topia.TopiaContextFactory;
+import org.nuiton.topia.TopiaDatabase;
+import org.nuiton.topia.TopiaNotFoundException;
+import org.nuiton.topia.framework.AbstractTopiaContext;
+import org.nuiton.topia.framework.TopiaContextImplementor;
+import org.nuiton.topia.framework.TopiaService;
+import org.nuiton.topiatest.persistence.Entity1;
+import org.nuiton.topia.it.legacy.topiatest.persistence.Entity1Impl;
+import org.nuiton.topiatest.service.FakeService;
+import org.nuiton.topiatest.service.TestService;
+
+import java.io.File;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+
+/**
+ * Created: 10 mai 2010
+ *
+ * @author fdesbois <fdesbois(a)codelutin.com>
+ * @version $Id$
+ */
+public class TopiaContextImplTest {
+
+ private static final Log log =
+ LogFactory.getLog(TopiaContextImplTest.class);
+
+ protected Properties properties = new Properties();
+
+ static File testBasedir;
+
+ @BeforeClass
+ public static void setUpClass() throws Exception {
+
+ testBasedir = TopiaDatabase.getTestSpecificDirectory(TopiaContextImplTest.class, "dummy");
+ }
+
+ @Before
+ public void setUp() throws Exception {
+ properties.clear();
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ }
+
+ @Test
+ public void testLoadServices() throws Exception {
+ if (log.isDebugEnabled()) {
+ log.debug("## testLoadServices");
+ }
+
+ /** PREPARE DATA **/
+ properties.setProperty("topia.service.test",
+ TestService.class.getName());
+
+ AbstractTopiaContext context = new AbstractTopiaContext();
+
+ /** EXEC METHOD **/
+ if (log.isInfoEnabled()) {
+ log.info("test 1 : load a simple TestService from properties");
+ }
+ Map<String, TopiaService> results = context.loadServices(properties);
+ Assert.assertEquals(1, results.size());
+ Assert.assertTrue(results.containsKey("test"));
+ TopiaService service = results.get("test");
+ Assert.assertEquals(TestService.class, service.getClass());
+
+ if (log.isInfoEnabled()) {
+ log.info("test 2 : load with wrong key : will display a WARN");
+ }
+ properties.clear();
+
+ properties.setProperty("topia.service.fake",
+ TestService.class.getName());
+
+ results = context.loadServices(properties);
+ Assert.assertEquals(0, results.size());
+ Assert.assertFalse(results.containsKey("fake"));
+
+ if (log.isInfoEnabled()) {
+ log.info("test 3 : load with fake service name : will display an ERROR");
+ }
+ properties.clear();
+
+ properties.setProperty("topia.service.test", "FAKE");
+
+ results = context.loadServices(properties);
+ Assert.assertEquals(0, results.size());
+ Assert.assertFalse(results.containsKey("test"));
+ }
+
+ @Test
+ public void testGetServices() throws Exception {
+ if (log.isDebugEnabled()) {
+ log.debug("## testGetServices");
+ }
+
+ /** PREPARE DATA **/
+ properties.setProperty("topia.service.test",
+ TestService.class.getName());
+
+ // Calling the constructor with properties will load the services
+ AbstractTopiaContext context = new AbstractTopiaContext(properties);
+
+ // Instantiate a child context and set its parent
+ AbstractTopiaContext child = new AbstractTopiaContext(context);
+
+ /** EXEC METHOD **/
+ if (log.isInfoEnabled()) {
+ log.info("test 1 : with child context");
+ }
+ Map<String, TopiaService> test1 = child.getServices();
+ Assert.assertEquals(1, test1.size());
+ Assert.assertTrue(test1.containsKey("test"));
+
+ if (log.isInfoEnabled()) {
+ log.info("test 2 : test serviceEnabled method");
+ }
+ boolean test2 = child.serviceEnabled("test");
+ Assert.assertTrue(test2);
+
+ if (log.isInfoEnabled()) {
+ log.info("test 3 : test getService method");
+ }
+ TopiaService test3 = child.getService("test");
+ Assert.assertEquals(TestService.class, test3.getClass());
+
+ if (log.isInfoEnabled()) {
+ log.info("test 4 : test serviceEnabled from class TestService");
+ }
+ boolean test4 = child.serviceEnabled(TestService.class);
+ Assert.assertTrue(test4);
+
+ if (log.isInfoEnabled()) {
+ log.info("test 5 : test getService from class TestService");
+ }
+ TestService test5 = child.getService(TestService.class);
+ Assert.assertNotNull(test5);
+
+ if (log.isInfoEnabled()) {
+ log.info("test 6 : test serviceEnabled error with class FakeService");
+ }
+ // FakeService doesn't contains property SERVICE_NAME used by
+ // serviceEnabled method
+ // Even it's properly loaded the serviceEnabled method will return false
+ properties.clear();
+ properties.setProperty("topia.service.fake",
+ FakeService.class.getName());
+ AbstractTopiaContext otherContext = new AbstractTopiaContext(properties);
+
+ boolean test6 = otherContext.serviceEnabled(FakeService.class);
+ Assert.assertFalse(test6);
+
+ if (log.isInfoEnabled()) {
+ log.info("test 7 : test getService with error TopiaNotFoundException" +
+ " : service not loaded");
+ }
+ // TestService is not loaded in otherContext
+ try {
+ TestService test7 = otherContext.getService(TestService.class);
+ Assert.fail();
+ } catch (TopiaNotFoundException eee) {
+ //log.error(eee.getClass().getSimpleName() + " : " + eee.getMessage());
+ //Assert.assertEquals(TopiaNotFoundException.class, eee.getClass());
+ } catch (Exception e) {
+ Assert.fail();
+ }
+ }
+
+ @Test
+ public void testContextHierarchy() throws Exception {
+ if (log.isDebugEnabled()) {
+ log.debug("## testContextHierarchy");
+ }
+
+ /** PREPARE DATA **/
+ AbstractTopiaContext context = new AbstractTopiaContext(properties);
+
+ /** EXEC METHODS **/
+ if (log.isInfoEnabled()) {
+ log.info("test 1 : constructor with parent context");
+ }
+ AbstractTopiaContext test1 = new AbstractTopiaContext(context);
+ Assert.assertEquals(context, test1.parentContext);
+
+ if (log.isInfoEnabled()) {
+ log.info("test 2 : addChildContext");
+ }
+ AbstractTopiaContext test2 = new AbstractTopiaContext(properties);
+ AbstractTopiaContext child2 = new AbstractTopiaContext();
+ test2.addChildContext(child2);
+ Assert.assertEquals(1, test2.childContext.size());
+
+ if (log.isInfoEnabled()) {
+ log.info("test 3 : removeChildContext");
+ }
+ AbstractTopiaContext test3 = new AbstractTopiaContext(properties);
+ AbstractTopiaContext child3 = new AbstractTopiaContext(test3);
+ test3.childContext.add(child3);
+ test3.removeChildContext(child3);
+ Assert.assertEquals(0, test3.childContext.size());
+
+ // No remove if context is closed
+ test3.childContext.add(child3);
+ test3.closed = true;
+ test3.removeChildContext(child3);
+ Assert.assertEquals(1, test3.childContext.size());
+
+ if (log.isInfoEnabled()) {
+ log.info("test 4 : getRootContext");
+ }
+ TopiaContextImplementor test4 = child3.getRootContext();
+ Assert.assertEquals(test3, test4);
+
+ // Note : existing test is already done for concurrency problem on
+ // getChildContext(). Go to : http://www.nuiton.org/repositories/browse/sandbox/testTopiaPostgresError/tr…
+ }
+//
+// @Test
+// public void testCreateSchema() throws Exception {
+// }
+//
+// @Test
+// public void testShowCreateSchema() throws Exception {
+// }
+//
+// @Test
+// public void testUpdateSchema() throws Exception {
+// }
+//
+// @Test
+// public void testGetHibernate() throws Exception {
+// }
+//
+
+ @Test
+ public void testGetHibernateFactory() throws Exception {
+ if (log.isDebugEnabled()) {
+ log.debug("## testGetHibernateFactory");
+ }
+
+ /** PREPARE DATA **/
+ AbstractTopiaContext context = new AbstractTopiaContext();
+ context.services = new HashMap<String, TopiaService>();
+
+ String basedir = System.getenv("basedir");
+ if (basedir == null) {
+
+ // says basedir is where we start tests.
+ basedir = new File("").getAbsolutePath();
+ }
+
+ if (log.isDebugEnabled()) {
+ log.debug("baseDir : " + basedir);
+ }
+ File persistenceDir = new File(basedir,
+ "target" + File.separator +
+ "test-classes" + File.separator +
+ "org" + File.separator +
+ "nuiton" + File.separator +
+ "topiatest" + File.separator +
+ "persistence");
+ if (log.isDebugEnabled()) {
+ log.debug("persistenceDir : " + persistenceDir);
+ }
+ File resourcesDir = new File(basedir,
+ "target" + File.separator +
+ "test-classes");
+
+ /** EXEC METHOD **/
+ if (log.isInfoEnabled()) {
+ log.info("test 1 : load mappings from directory");
+ }
+
+ properties.setProperty(TopiaContextFactory.CONFIG_PERSISTENCE_DIRECTORIES,
+ persistenceDir.getAbsolutePath());
+ context.config = properties;
+
+ Configuration test1 = context.getHibernateConfiguration();
+ PersistentClass persistentClass =
+ test1.getClassMapping(Entity1Impl.class.getName());
+ Assert.assertNotNull(persistentClass);
+ Assert.assertEquals(Entity1.class, persistentClass.getProxyInterface());
+
+// for (Iterator<RootClass> it = test1.getClassMappings(); it.hasNext();) {
+// RootClass o = it.next();
+// log.debug("entity : " + o.getEntityName());
+// }
+
+ if (log.isInfoEnabled()) {
+ log.info("test 2 : load mappings for all entities");
+ }
+ //reset from previous test
+ context = new AbstractTopiaContext();
+ context.services = new HashMap<String, TopiaService>();
+ properties.clear();
+
+ // use property TOPIA_PERSISTENCE_CLASSES
+ properties.setProperty(TopiaContextFactory.CONFIG_PERSISTENCE_CLASSES,
+ Entity1Impl.class.getName());
+ context.config = properties;
+
+ Configuration test2 = context.getHibernateConfiguration();
+ persistentClass = test2.getClassMapping(Entity1Impl.class.getName());
+ Assert.assertNotNull(persistentClass);
+ Assert.assertEquals(Entity1.class, persistentClass.getProxyInterface());
+
+ if (log.isInfoEnabled()) {
+ log.info("test 3 : add properties from file");
+ }
+ //reset from previous test
+ context = new AbstractTopiaContext();
+ context.services = new HashMap<String, TopiaService>();
+ properties.clear();
+
+ // use property TOPIA_PERSISTENCE_PROPERTIES_FILE to add default
+ // properties from file
+ properties.setProperty(TopiaContextFactory.CONFIG_PERSISTENCE_PROPERTIES_FILE,
+ resourcesDir + File.separator + "TopiaContextImpl.properties");
+ context.config = properties;
+
+ Configuration test3 = context.getHibernateConfiguration();
+ Assert.assertEquals(
+ test3.getProperty("hibernate.connection.driver_class"),
+ Driver.class.getName());
+
+ // Note : maybe add a test to load classes from services
+ }
+
+// @Test
+// public void replicateEntity() throws Exception {
+//
+// Properties configSource = TestHelper.initTopiaContextConfiguration(
+// testBasedir,
+// "/TopiaContextImpl.properties",
+// "replicateSource");
+//
+// Properties configTarget = TestHelper.initTopiaContextConfiguration(
+// testBasedir,
+// "/TopiaContextImpl.properties",
+// "replicateTarget");
+//
+//
+// TopiaContext contextSource = null;
+// TopiaContext contextTarget = null;
+//
+// try {
+// contextSource = TopiaContextFactory.getContext(configSource);
+// contextTarget = TopiaContextFactory.getContext(configTarget);
+//
+// TopiaContext txSource;
+// TopiaContext txTarget;
+// PersonDAO daoSource, daoTarget;
+// PetDAO petDAOSource, petDAOTarget;
+// Person personSource, personTarget;
+// Pet petSource, petTarget;
+//
+// txSource = contextSource.beginTransaction();
+// daoSource = TopiaTestDAOHelper.getPersonDAO(txSource);
+// petDAOSource = TopiaTestDAOHelper.getPetDAO(txSource);
+//
+// personSource = daoSource.create(Person.PROPERTY_FIRSTNAME, " firstName",
+// Person.PROPERTY_NAME, " name"
+// );
+//
+// petSource = petDAOSource.create(Pet.PROPERTY_NAME, "name",
+// Pet.PROPERTY_TYPE, "type",
+// Pet.PROPERTY_PERSON, personSource
+// );
+//
+// personSource.addPet(petSource);
+//
+// txSource.commitTransaction();
+//
+// daoSource = TopiaTestDAOHelper.getPersonDAO(txSource);
+//
+// personSource = daoSource.findByTopiaId(personSource.getTopiaId());
+// Assert.assertNotNull(personSource);
+//
+// petSource = petDAOSource.findByTopiaId(petSource.getTopiaId());
+// Assert.assertNotNull(petSource);
+// Assert.assertEquals(1, personSource.sizePet());
+// Assert.assertEquals(petSource, personSource.getPet().iterator().next());
+//
+// txTarget = contextTarget.beginTransaction();
+//
+// txSource.replicateEntity(txTarget, petSource);
+// txSource.replicateEntity(txTarget, personSource);
+//
+// txTarget.commitTransaction();
+//
+// daoTarget = TopiaTestDAOHelper.getPersonDAO(txTarget);
+// petDAOTarget = TopiaTestDAOHelper.getPetDAO(txTarget);
+//
+// personTarget = daoTarget.findByTopiaId(personSource.getTopiaId());
+// Assert.assertNotNull(personTarget);
+// Assert.assertEquals(personSource, personTarget);
+// Assert.assertEquals(1, personTarget.sizePet());
+//
+// petTarget = petDAOTarget.findByTopiaId(petSource.getTopiaId());
+// Assert.assertNotNull(petTarget);
+// Assert.assertEquals(petSource, petTarget);
+//
+// Assert.assertEquals(petTarget, personTarget.getPet().iterator().next());
+//
+//
+// } finally {
+// closeDb(contextSource);
+// closeDb(contextTarget);
+// }
+//
+// }
+//
+// protected static void closeDb(TopiaContext contextSource) {
+// if (contextSource != null && !contextSource.isClosed())
+// try {
+// contextSource.clear(false);
+// } catch (TopiaException e) {
+// if (log.isErrorEnabled()) {
+// log.error("Could not close db " + contextSource, e);
+// }
+// }
+// }
+
+
+//
+// @Test
+// public void testGetHibernateConfiguration() throws Exception {
+// }
+//
+// @Test
+// public void testGetDAO() throws Exception {
+// }
+//
+// @Test
+// public void testBeginTransaction() throws Exception {
+// }
+//
+// @Test
+// public void testCommitTransaction() throws Exception {
+// }
+//
+// @Test
+// public void testRollbackTransaction() throws Exception {
+// }
+//
+// @Test
+// public void testCloseContext() throws Exception {
+// }
+//
+// @Test
+// public void testIsClosed() throws Exception {
+// }
+//
+// @Test
+// public void testFindByTopiaId() throws Exception {
+// }
+//
+// @Test
+// public void testFind() throws Exception {
+// }
+//
+// @Test
+// public void testFind2() throws Exception {
+// }
+//
+// @Test
+// public void testExecute() throws Exception {
+// }
+//
+// @Test
+// public void testAdd() throws Exception {
+// }
+//
+// @Test
+// public void testImportXML() throws Exception {
+// }
+//
+// @Test
+// public void testExportXML() throws Exception {
+// }
+//
+//
+// @Test
+// public void testReplicateEntity() throws Exception {
+// }
+//
+// @Test
+// public void testReplicateEntities() throws Exception {
+// }
+//
+// @Test
+// public void testGetFiresSupport() throws Exception {
+// }
+//
+// @Test
+// public void testBackup() throws Exception {
+// }
+//
+// @Test
+// public void testRestore() throws Exception {
+// }
+//
+// @Test
+// public void testClear() throws Exception {
+// }
+//
+// @Test
+// public void testGetPersistenceClasses() throws Exception {
+// }
+//
+// @Test
+// public void testIsSchemaExist() throws Exception {
+// }
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextReplicateTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaContextReplicateTest.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextReplicateTest.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextReplicateTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,155 @@
+/*
+ * #%L
+ * ToPIA :: Persistence
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2004 - 2012 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%
+ */
+package org.nuiton.topia.it.legacy.framework;
+
+import org.junit.Assert;
+import org.junit.Rule;
+import org.junit.Test;
+import org.nuiton.topia.TopiaContextFactory;
+import org.nuiton.topia.TopiaDatabase;
+import org.nuiton.topia.TopiaTestDAOHelper;
+import org.nuiton.topia.TopiaTestTopiaPersistenceContext;
+import org.nuiton.topia.test.entities.Person;
+import org.nuiton.topia.test.entities.PersonDAO;
+import org.nuiton.topia.test.entities.Pet;
+import org.nuiton.topia.test.entities.PetDAO;
+
+import java.io.File;
+import java.util.Properties;
+
+/**
+ * To test replication sugin TopiaContext.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.6.8
+ */
+public class TopiaContextReplicateTest {
+
+ @Rule
+ public final TopiaDatabase dbSource =
+ new TopiaDatabase() {
+
+ @Override
+ protected void onDbConfigurationCreate(Properties configuration, File testDir, String dbPath) {
+ configuration.setProperty(
+ TopiaContextFactory.CONFIG_URL, "jdbc:h2:file:" + dbPath + "-source");
+
+ }
+ };
+
+ @Rule
+ public final TopiaDatabase dbTarget =
+ new TopiaDatabase() {
+
+ @Override
+ protected void onDbConfigurationCreate(Properties configuration, File testDir, String dbPath) {
+ configuration.setProperty(
+ TopiaContextFactory.CONFIG_URL, "jdbc:h2:file:" + dbPath + "-target");
+
+ }
+ };
+
+ @Test
+ public void replicateEntity() throws Exception {
+//
+// Properties configSource = TestHelper.initTopiaContextConfiguration(
+// testBasedir,
+// "/TopiaContextImpl.properties",
+// "replicateSource");
+//
+// Properties configTarget = TestHelper.initTopiaContextConfiguration(
+// testBasedir,
+// "/TopiaContextImpl.properties",
+// "replicateTarget");
+//
+
+
+// try {
+// contextSource = TopiaContextFactory.getContext(configSource);
+// contextTarget = TopiaContextFactory.getContext(configTarget);
+
+ TopiaTestTopiaPersistenceContext txSource;
+ TopiaTestTopiaPersistenceContext txTarget;
+ PersonDAO daoSource, daoTarget;
+ PetDAO petDAOSource, petDAOTarget;
+ Person personSource, personTarget;
+ Pet petSource, petTarget;
+
+ txSource = dbSource.beginTransaction();
+ daoSource = TopiaTestDAOHelper.getPersonDAO(txSource);
+ petDAOSource = TopiaTestDAOHelper.getPetDAO(txSource);
+
+ personSource = daoSource.create(Person.PROPERTY_FIRSTNAME, " firstName",
+ Person.PROPERTY_NAME, " name"
+ );
+
+ petSource = petDAOSource.create(Pet.PROPERTY_NAME, "name",
+ Pet.PROPERTY_TYPE, "type",
+ Pet.PROPERTY_PERSON, personSource
+ );
+
+ personSource.addPet(petSource);
+
+ txSource.commitTransaction();
+
+ daoSource = TopiaTestDAOHelper.getPersonDAO(txSource);
+
+ personSource = daoSource.findByTopiaId(personSource.getTopiaId());
+ Assert.assertNotNull(personSource);
+
+ petSource = petDAOSource.findByTopiaId(petSource.getTopiaId());
+ Assert.assertNotNull(petSource);
+ Assert.assertEquals(1, personSource.sizePet());
+ Assert.assertEquals(petSource, personSource.getPet().iterator().next());
+
+ txTarget = dbTarget.beginTransaction();
+
+ txSource.replicateEntity(txTarget, petSource);
+ txSource.replicateEntity(txTarget, personSource);
+
+ txTarget.commitTransaction();
+
+ daoTarget = TopiaTestDAOHelper.getPersonDAO(txTarget);
+ petDAOTarget = TopiaTestDAOHelper.getPetDAO(txTarget);
+
+ personTarget = daoTarget.findByTopiaId(personSource.getTopiaId());
+ Assert.assertNotNull(personTarget);
+ Assert.assertEquals(personSource, personTarget);
+ Assert.assertEquals(1, personTarget.sizePet());
+
+ petTarget = petDAOTarget.findByTopiaId(petSource.getTopiaId());
+ Assert.assertNotNull(petTarget);
+ Assert.assertEquals(petSource, petTarget);
+
+ Assert.assertEquals(petTarget, personTarget.getPet().iterator().next());
+
+
+// } finally {
+// closeDb(contextSource);
+// closeDb(contextTarget);
+// }
+
+ }
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaUtilTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaUtilTest.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaUtilTest.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaUtilTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,114 @@
+/*
+ * #%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%
+ */
+
+package org.nuiton.topia.it.legacy.framework;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.hibernate.cfg.Configuration;
+import org.junit.Rule;
+import org.junit.Test;
+import org.nuiton.topia.TopiaDatabase;
+import org.nuiton.topia.framework.TopiaUtil;
+import org.nuiton.topia.test.entities.PersonImpl;
+import org.nuiton.topiatest.Personne;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+/**
+ * Test pour les methodes de {@link TopiaUtil}.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @version $Revision$
+ * <p/>
+ * Last update: $Date$
+ * by : $Author$
+ */
+public class TopiaUtilTest {
+
+ protected static final String PERSON_ID = "org.nuiton.topiatest.Personne#1226701039001#0.6502325993664224";
+
+ protected static final String PERSON_ID2 = "org.nuiton.topiatest.Personne#1226701039001#0.6502325993664999";
+
+ @Rule
+ public final TopiaDatabase db = new TopiaDatabase();
+
+ @Test
+ public void testGetTopiaIdPattern() throws Exception {
+ String expected;
+ String actual;
+
+ expected = "org\\.nuiton\\.topiatest\\.Personne#(?:\\d+?)#(?:\\d+)\\.(?:\\d+)";
+ actual = TopiaUtil.getTopiaIdPattern(Personne.class);
+ assertEquals(expected, actual);
+ }
+
+ @Test
+ public void testGetTopiaPattern() throws Exception {
+ String expected;
+ Pattern pattern;
+
+ expected = "(\\d+)-(org\\.nuiton\\.topiatest\\.Personne#(?:\\d+?)#(?:\\d+)\\.(?:\\d+))-(org\\.nuiton\\.topiatest\\.Personne#(?:\\d+?)#(?:\\d+)\\.(?:\\d+))(.*)";
+ pattern = TopiaUtil.getTopiaPattern("(\\d+)-%1$s-%1$s(.*)", Personne.class);
+ assertEquals(expected, pattern.toString());
+
+ String expression = 123 + "-" + PERSON_ID + "-" + PERSON_ID2 + "-afterall";
+
+ Matcher matcher = pattern.matcher(expression);
+
+ assertTrue(matcher.matches());
+
+ assertTrue(matcher.matches());
+ assertEquals(4, matcher.groupCount());
+ assertEquals("123", matcher.group(1));
+ assertEquals(PERSON_ID, matcher.group(2));
+ assertEquals(PERSON_ID2, matcher.group(3));
+ assertEquals("-afterall", matcher.group(4));
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testIsSchemaExistFailed() throws Exception {
+ TopiaUtil.isSchemaExist(db.getHibernateCfg(), "fake");
+ }
+
+ @Test
+ public void testIsSchemaExist() throws Exception {
+
+ String personClassName = PersonImpl.class.getName();
+ Configuration hibernateCfg = db.getHibernateCfg();
+
+ // First, test before DB is created, the table should not exist
+ assertFalse(TopiaUtil.isSchemaExist(hibernateCfg, personClassName));
+
+ // Create schema
+ db.getApplicationContext().createSchema();
+
+ // Now table should exist
+ assertTrue(TopiaUtil.isSchemaExist(hibernateCfg, personClassName));
+ }
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/generator/TopiaTestCase.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/TopiaTestCase.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/generator/TopiaTestCase.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/generator/TopiaTestCase.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,170 @@
+/*
+ * #%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%
+ */
+
+package org.nuiton.topia.it.legacy.generator;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.junit.Assert;
+import org.junit.Rule;
+import org.junit.Test;
+import org.nuiton.topia.TopiaDatabase;
+import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.TopiaTestDAOHelper;
+import org.nuiton.topia.TopiaTestTopiaPersistenceContext;
+import org.nuiton.topiatest.Company;
+import org.nuiton.topiatest.CompanyDAO;
+import org.nuiton.topiatest.Department;
+import org.nuiton.topiatest.DepartmentDAO;
+
+/**
+ * TopiaTestCase.
+ *
+ * @author chatellier
+ * @version $Revision$
+ * <p/>
+ * Last update : $Date$
+ * By : $Author$
+ */
+public class TopiaTestCase {
+
+ /** Logger */
+ private final static Log log = LogFactory.getLog(TopiaTestCase.class);
+
+ @Rule
+ public final TopiaDatabase db = new TopiaDatabase();
+
+// /** Proprietes */
+// protected static Properties config;
+//
+// /** TopiaContext */
+// protected static TopiaContext context;
+
+// /**
+// * Init les proprietes de connection a la base
+// *
+// * @throws IOException for any IO error while getting configuration.
+// */
+// @BeforeClass
+// public static void init() throws IOException {
+//
+// File testBasedir = TestHelper.getTestBasedir(TopiaTestCase.class);
+//
+// config = TestHelper.initTopiaContextConfiguration(
+// testBasedir,
+// "/TopiaContextImpl.properties",
+// "TopiaTestCaseDb");
+//// config = new Properties();
+//// config.setProperty("topia.persistence.classes", TopiaTestDAOHelper.getImplementationClassesAsString());
+////
+//// config.setProperty(Environment.USER, "sa");
+//// config.setProperty(Environment.PASS, "");
+//// config.setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");
+//// config.setProperty(Environment.DIALECT, "org.hibernate.dialect.H2Dialect");
+//// config.setProperty(Environment.DRIVER, "org.h2.Driver");
+//// config.setProperty(Environment.URL, "jdbc:h2:file:" + testBasedir + "/db/data_" + System.currentTimeMillis());
+// }
+//
+// @AfterClass
+// public static void after() throws TopiaException {
+// // destroy database
+// context.clear(false);
+// }
+
+// /** Create base with schema created. */
+// @Before
+// public void setUp() {
+//
+// if (log.isDebugEnabled()) {
+// log.debug("Junit beforeTest");
+// }
+//
+// try {
+// context = TopiaContextFactory.getContext(config);
+//
+// try {
+// context.createSchema();
+// } catch (TopiaException e) {
+// log.error("Erreur à la creation du schema", e);
+// }
+// } catch (TopiaNotFoundException e) {
+// log.error("Erreur à la creation du topia context", e);
+// }
+// }
+
+ @Test
+ public void testCompositeAssociations() throws TopiaException {
+ if (log.isDebugEnabled()) {
+ log.debug("Junit Test testCompositeAssociations");
+ }
+
+// try {
+ TopiaTestTopiaPersistenceContext newContext = db.beginTransaction();
+
+ CompanyDAO companyDAO = newContext.getCompanyDao();
+ DepartmentDAO departmentDAO = newContext.getDepartmentDao();
+
+ Company company = companyDAO.create();
+ company.setName("Ma société");
+
+
+ Department dep1 = departmentDAO.create();
+ dep1.setName("Departement 1");
+ Department dep2 = departmentDAO.create();
+ dep2.setName("Departement 2");
+ Department dep3 = departmentDAO.create();
+ dep3.setName("Departement 3");
+ Department dep4 = departmentDAO.create();
+ dep4.setName("Departement 7");
+
+ departmentDAO.update(dep1);
+ departmentDAO.update(dep2);
+ departmentDAO.update(dep3);
+ departmentDAO.update(dep4);
+
+ company.addDepartment(dep1);
+ company.addDepartment(dep2);
+ company.addDepartment(dep3);
+ company.addDepartment(dep4);
+
+ companyDAO.update(company);
+ newContext.commitTransaction();
+
+ newContext = db.beginTransaction();
+
+ companyDAO = TopiaTestDAOHelper.getCompanyDAO(newContext);
+
+ company = companyDAO.findByTopiaId(company.getTopiaId());
+
+ Assert.assertEquals(company.getName(), "Ma société");
+ Assert.assertEquals(company.getDepartment().size(), 4);
+
+ newContext.commitTransaction();
+// newContext.closeContext();
+// } catch (TopiaException e) {
+// log.error("Erreur pendant le test testCompositeAssociations", e);
+// }
+ }
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/EntityVisitorExportXmlTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/EntityVisitorExportXmlTest.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/EntityVisitorExportXmlTest.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/EntityVisitorExportXmlTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,131 @@
+/*
+ * #%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%
+ */
+
+package org.nuiton.topia.persistence;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.nuiton.topia.TopiaDatabase;
+import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.TopiaTestTopiaPersistenceContext;
+import org.nuiton.topiatest.Address;
+import org.nuiton.topiatest.AddressTopiaDao;
+import org.nuiton.topiatest.Company;
+import org.nuiton.topiatest.CompanyTopiaDao;
+import org.nuiton.topiatest.Department;
+import org.nuiton.topiatest.DepartmentTopiaDao;
+import org.nuiton.topiatest.Employe;
+import org.nuiton.topiatest.EmployeTopiaDao;
+
+/**
+ * Test de visitor.
+ *
+ * @author chatellier
+ * @version $Revision$
+ * <p/>
+ * Last update : $Date$
+ * By : $Author$
+ */
+public class EntityVisitorExportXmlTest {
+
+ private static final Log log =
+ LogFactory.getLog(EntityVisitorExportXmlTest.class);
+
+ @Rule
+ public final TopiaDatabase db = new TopiaDatabase();
+
+ /**
+ * Prepare test.
+ * <p/>
+ * Add all tests commons data
+ *
+ * @throws TopiaException if could not create datas
+ */
+ @Before
+ public void setUp() throws TopiaException {
+
+ TopiaTestTopiaPersistenceContext newContext = db.beginTransaction();
+ try {
+ // company
+ CompanyTopiaDao companyDAO = newContext.getCompanyDao();
+ Company clCompany = companyDAO.create(Company.PROPERTY_NAME, "CodeLutin");
+
+ // employe
+ EmployeTopiaDao employeDAO = newContext.getEmployeDao();
+ Employe empl1 = employeDAO.create(Employe.PROPERTY_NAME, "boss", Employe.PROPERTY_SALARY, 30000);
+
+ AddressTopiaDao adressDAO = newContext.getAddressDao();
+ Address addr1 = adressDAO.create(Address.PROPERTY_CITY, "Nantes", Address.PROPERTY_ADRESS, "12 Avenue Jules Vernes");
+ empl1.setAddress(addr1);
+
+ Employe empl2 = employeDAO.create(Employe.PROPERTY_NAME, "boss2", Employe.PROPERTY_SALARY, 29000);
+ Address addr2 = adressDAO.create(Address.PROPERTY_CITY, "Nantes", Address.PROPERTY_ADRESS, "12 Avenue Jules Vernes");
+ empl2.setAddress(addr2);
+
+ // departement
+ DepartmentTopiaDao departmentDAO = newContext.getDepartmentDao();
+ Department depComm = departmentDAO.create(Department.PROPERTY_NAME, "Commercial");
+ depComm.setLeader(empl1);
+
+ Department depDev = departmentDAO.create(Department.PROPERTY_NAME, "Dev");
+ depDev.setLeader(empl2);
+ clCompany.addDepartment(depComm);
+ clCompany.addDepartment(depDev);
+
+ newContext.commitTransaction();
+ } finally {
+
+ newContext.closeContext();
+ }
+ }
+
+
+ /**
+ * Test l'export XML via un visiteur.
+ * <p/>
+ * Parcourt en profondeur.
+ *
+ * @throws TopiaException
+ */
+ @Test
+ public void testExportXMLDepth() throws TopiaException {
+
+ TopiaTestTopiaPersistenceContext context = db.beginTransaction();
+
+ CompanyTopiaDao companyDAO = context.getCompanyDao();
+ Company clCompany = companyDAO.findByName("CodeLutin");
+
+ EntityVisitor delegateVisitor = new ExportXMLVisitor();
+ EntityVisitor visitor = new DepthEntityVisitor(delegateVisitor);
+ clCompany.accept(visitor);
+
+ if (log.isInfoEnabled()) {
+ log.info("Export XML = \n" + delegateVisitor.toString());
+ }
+ }
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/ExportXMLVisitor.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/ExportXMLVisitor.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/ExportXMLVisitor.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/ExportXMLVisitor.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,107 @@
+/*
+ * #%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%
+ */
+
+package org.nuiton.topia.persistence;
+
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.junit.Ignore;
+
+/**
+ * Visitor pour export xml.
+ *
+ * @author chatellier
+ * @version $Revision$
+ * <p/>
+ * Last update : $Date$
+ * By : $Author$
+ */
+@Ignore
+public class ExportXMLVisitor implements EntityVisitor {
+
+ /** log. */
+ private static Log log = LogFactory.getLog(ExportXMLVisitor.class);
+
+ protected StringBuffer buffer;
+
+ public ExportXMLVisitor() {
+ buffer = new StringBuffer();
+ }
+
+ @Override
+ public void start(TopiaEntity e) {
+ if (log.isDebugEnabled()) {
+ log.debug("start : " + e);
+ }
+
+ buffer.append("<").append(e.getClass().getName());
+ buffer.append(" topiaId=\"").append(e.getTopiaId()).append("\"");
+ buffer.append(" topiaCreateDate=\"").append(e.getTopiaCreateDate()).append("\"");
+ buffer.append(" topiaVersion=\"").append(e.getTopiaVersion()).append("\"");
+ buffer.append(">\n");
+ }
+
+ @Override
+ public void visit(TopiaEntity e, String name, Class<?> type, Object value) {
+ if (log.isDebugEnabled()) {
+ log.debug("visit : " + e);
+ }
+
+ buffer.append("<").append(type.getName()).append(">").append(value).append("</").append(type.getName()).append(">\n");
+ }
+
+ @Override
+ public void visit(TopiaEntity e, String name, Class<?> collectionType, Class<?> type,
+ Object value) {
+ }
+
+ @Override
+ public void visit(TopiaEntity e, String name, Class<?> collectionType, Class<?> type, int index, Object value) {
+ visit(e, name, type, value);
+ }
+
+ @Override
+ public void end(TopiaEntity e) {
+ if (log.isDebugEnabled()) {
+ log.debug("end : " + e);
+ }
+
+ buffer.append("</").append(e.getClass().getName()).append(">\n");
+ }
+
+ @Override
+ public String toString() {
+ String content = buffer.toString();
+ return content;
+ }
+
+ @Override
+ public void clear() {
+ // do nothing
+ }
+
+
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/HqlAndParametersBuilderTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/HqlAndParametersBuilderTest.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/HqlAndParametersBuilderTest.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/HqlAndParametersBuilderTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,118 @@
+package org.nuiton.topia.it.legacy.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.Lists;
+import org.junit.Assert;
+import org.junit.Test;
+import org.nuiton.topia.persistence.HqlAndParametersBuilder;
+import org.nuiton.topia.persistence.TopiaEntity;
+
+import java.util.Collection;
+
+public class HqlAndParametersBuilderTest {
+
+ protected HqlAndParametersBuilder hqlAndParametersBuilder =
+ new HqlAndParametersBuilder(TopiaEntity.class);
+
+ protected static final Collection<String> SOME_VALUES =
+ Lists.newArrayList("value1", "value2", "value3");
+
+ protected static final Collection<String> SOME_VALUES_WITH_NULL =
+ Lists.newArrayList("value1", "value2", null, "value3");
+
+ @Test
+ public void testFindAvailableHqlParameterName() {
+
+ String availableHqlParameterName1 = hqlAndParametersBuilder.putHqlParameterWithAvailableName("survey.topiaId", "topiaId1");
+ String availableHqlParameterName2 = hqlAndParametersBuilder.putHqlParameterWithAvailableName("survey.topiaId", "topiaId1");
+
+ Assert.assertNotEquals(availableHqlParameterName1, availableHqlParameterName2);
+ Assert.assertFalse(availableHqlParameterName1.contains("."));
+ Assert.assertFalse(availableHqlParameterName2.contains("."));
+
+ }
+
+ @Test
+ public void testEqualsNull() {
+
+ hqlAndParametersBuilder.addEquals("myProp", null);
+
+ String actualHql = hqlAndParametersBuilder.getHql();
+
+ Assert.assertFalse(actualHql.contains("myProp = null"));
+ Assert.assertTrue(actualHql.contains("myProp is null"));
+
+ }
+
+ @Test
+ public void testAddInWithNull() {
+
+ hqlAndParametersBuilder.addIn("myProp", SOME_VALUES_WITH_NULL);
+
+ String actualHql = hqlAndParametersBuilder.getHql();
+
+ Assert.assertTrue(actualHql.contains("myProp is null or topiaEntity_.myProp in ("));
+ Assert.assertEquals(
+ SOME_VALUES_WITH_NULL.size() - 1, // there should be as many argument as in collection minus 1 because null is removed
+ hqlAndParametersBuilder.getHqlParameters().size());
+
+ }
+
+ @Test
+ public void testAddNotEqualsToValue() {
+
+ hqlAndParametersBuilder.addNotEquals("myProp", "value");
+
+ String actualHql = hqlAndParametersBuilder.getHql();
+
+ Assert.assertTrue(actualHql.contains("myProp != "));
+ Assert.assertFalse(actualHql.contains("myProp = "));
+
+ }
+
+ @Test
+ public void testAddNotEqualsToNull() {
+
+ hqlAndParametersBuilder.addNotEquals("myProp", null);
+
+ String actualHql = hqlAndParametersBuilder.getHql();
+
+ Assert.assertTrue(actualHql.contains("myProp is not null"));
+
+ }
+
+ @Test
+ public void testAddNotInWithNull() {
+
+ hqlAndParametersBuilder.addNotIn("myProp", SOME_VALUES_WITH_NULL);
+
+ String actualHql = hqlAndParametersBuilder.getHql();
+
+ Assert.assertTrue(actualHql.contains("myProp is not null and "));
+
+ }
+
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/NaturalIdTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/NaturalIdTest.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/NaturalIdTest.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/NaturalIdTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,185 @@
+/*
+ * #%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%
+ */
+
+package org.nuiton.topia.persistence;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.hibernate.PropertyValueException;
+import org.junit.Assert;
+import org.junit.Rule;
+import org.junit.Test;
+import org.nuiton.topia.TopiaDatabase;
+import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.TopiaTestDAOHelper;
+import org.nuiton.topia.TopiaTestTopiaPersistenceContext;
+import org.nuiton.topiatest.NaturalizedEntity;
+import org.nuiton.topiatest.NaturalizedEntityDAO;
+
+/**
+ * NaturalIdTest
+ * <p/>
+ * Created: 18 févr. 2010
+ *
+ * @author fdesbois
+ * @version $Revision$
+ * <p/>
+ * Mise a jour: $Date$
+ * par : $Author$
+ */
+public class NaturalIdTest {
+
+ private static final Log log = LogFactory.getLog(NaturalIdTest.class);
+
+ @Rule
+ public final TopiaDatabase db = new TopiaDatabase();
+
+ @Test
+ public void testCreateSucessfull() throws Exception {
+ log.debug("Test naturalId : create succesfull");
+ TopiaTestTopiaPersistenceContext persistenceContext = db.beginTransaction();
+
+ NaturalizedEntityDAO dao =
+ persistenceContext.getNaturalizedEntityDao();
+
+ // No exception will be thrown with the two properties
+ dao.createByNaturalId(5, "str");
+ persistenceContext.commitTransaction();
+
+ // No exception will only the need property
+ dao.createByNotNull(3);
+ persistenceContext.commitTransaction();
+
+ // No exception will only the need property
+ dao.create(NaturalizedEntity.PROPERTY_NATURAL_ID_NOT_NULL, 3);
+ persistenceContext.commitTransaction();
+ }
+
+ @Test
+ public void testCreateFailed() throws Exception {
+ log.debug("Test naturalId : create failed");
+ TopiaTestTopiaPersistenceContext persistenceContext = db.beginTransaction();
+
+ NaturalizedEntityDAO dao =
+ persistenceContext.getNaturalizedEntityDao();
+
+ // Exception will be throw
+ try {
+ dao.create();
+ persistenceContext.commitTransaction();
+
+ // Note : this is possible to create an empty entity if the type
+ // is primitive like 'int' which have a default value of '0'
+ } catch (TopiaException eee) {
+ Assert.assertNotNull(eee.getCause());
+ Assert.assertTrue(eee.getCause() instanceof PropertyValueException);
+ Assert.assertEquals("naturalIdNotNull", ((PropertyValueException)eee.getCause()).getPropertyName());
+ }
+// catch (PropertyValueException eee) {
+// Assert.assertEquals("naturalIdNotNull", eee.getPropertyName());
+// }
+ }
+
+ @Test
+ public void testUpdateFailed() throws Exception {
+ log.debug("Test naturalId : update failed");
+
+ TopiaTestTopiaPersistenceContext persistenceContext = db.beginTransaction();
+
+ NaturalizedEntityDAO dao =
+ persistenceContext.getNaturalizedEntityDao();
+
+ NaturalizedEntity entity =
+ dao.createByNaturalId(5, "str");
+ persistenceContext.commitTransaction();
+
+ // Exception will be throw : not allowed to modify a naturalId property
+ try {
+ entity.setNaturalIdNotNull(8);
+ persistenceContext.commitTransaction();
+ } catch (TopiaException eee) {
+ Assert.assertEquals("org.hibernate.HibernateException",
+ eee.getCause().getClass().getName());
+ }
+ }
+
+ @Test
+ public void testFindByNaturalId() throws Exception {
+ log.debug("Test naturalId : findByNaturalId");
+ TopiaTestTopiaPersistenceContext persistenceContext = db.beginTransaction();
+
+
+ NaturalizedEntityDAO dao =
+ persistenceContext.getNaturalizedEntityDao();
+
+ NaturalizedEntity entity =
+ dao.createByNaturalId(5, "str");
+ persistenceContext.commitTransaction();
+
+ NaturalizedEntity result = dao.findByNaturalId(5, "str");
+
+ Assert.assertEquals(entity, result);
+ }
+
+ @Test
+ public void testExistNaturalId() throws Exception {
+ log.debug("Test naturalId : existNaturalId");
+ TopiaTestTopiaPersistenceContext persistenceContext = db.beginTransaction();
+
+
+ NaturalizedEntityDAO dao =
+ persistenceContext.getNaturalizedEntityDao();
+
+ dao.createByNaturalId(5, "str");
+ persistenceContext.commitTransaction();
+
+ boolean result = dao.existByNaturalId(5, "str");
+
+ Assert.assertTrue(result);
+
+ // not find with only one correct property
+ result = dao.existByNaturalId(8, "str");
+
+ Assert.assertFalse(result);
+ }
+
+ @Test
+ public void testNaturalIdAreGeneralized() throws Exception {
+
+ // test that natural ids are generalized
+ String[] generalizedNaturalizedNaturalIds = TopiaTestDAOHelper.TopiaTestEntityEnum.GeneralizedNaturalizedEntity.getNaturalIds();
+ String[] naturalizedNaturalIds = TopiaTestDAOHelper.TopiaTestEntityEnum.NaturalizedEntity.getNaturalIds();
+ Assert.assertArrayEquals(generalizedNaturalizedNaturalIds, naturalizedNaturalIds);
+ }
+
+ @Test
+ public void testNotNullsAreGeneralized() throws Exception {
+
+ // test that not nulls are generalized
+ String[] generalizedNaturalizedNotNulls = TopiaTestDAOHelper.TopiaTestEntityEnum.GeneralizedNaturalizedEntity.getNotNulls();
+ String[] naturalizedNotNulls = TopiaTestDAOHelper.TopiaTestEntityEnum.NaturalizedEntity.getNotNulls();
+ Assert.assertArrayEquals(generalizedNaturalizedNotNulls, naturalizedNotNulls);
+ }
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/TopiaDAOTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/TopiaDAOTest.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/TopiaDAOTest.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/TopiaDAOTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,201 @@
+/*
+ * #%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 org.hamcrest.CoreMatchers;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.nuiton.topia.TopiaDatabase;
+import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.TopiaTestTopiaPersistenceContext;
+import org.nuiton.topia.test.entities.Person;
+import org.nuiton.topia.test.entities.PersonDAO;
+
+import com.google.common.collect.Lists;
+
+/**
+ * Test on {@link TopiaDAO}.
+ * <p/>
+ * Last update : $Date$
+ * By : $Author$
+ *
+ * @author chatellier
+ * @version $Revision$
+ */
+public class TopiaDAOTest {
+
+ @Rule
+ public final TopiaDatabase db = new TopiaDatabase();
+
+ protected TopiaTestTopiaPersistenceContext context;
+
+ protected PersonDAO 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.commitTransaction();
+
+ // 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.rollbackTransaction();
+
+ // meme test apres roolback
+ Person person3 = createPerson("tata");
+ allPerson = dao.findAll();
+ Assert.assertEquals(2, allPerson.size());
+ Assert.assertThat(allPerson, CoreMatchers.hasItem(person3));
+
+ context.commitTransaction();
+ }
+
+ @Test
+ public void findAllLazyByQuery() throws TopiaException {
+
+ Assert.assertEquals(dao.count(), 0);
+
+ createPersons(101);
+
+ Iterable<Person> allByLazy = dao.findAllLazyByQuery(
+ 100,
+ "FROM " + dao.getTopiaEntityEnum().getImplementationFQN() + " ORDER BY id");
+
+ List<Person> actual = Lists.newArrayList();
+
+ for (Person person : allByLazy) {
+ actual.add(person);
+ }
+ Assert.assertEquals(dao.count(), actual.size());
+
+ allByLazy = dao.findAllLazyByQuery(
+ 54,
+ "FROM " + dao.getTopiaEntityEnum().getImplementationFQN() + " ORDER BY id");
+
+ actual = Lists.newArrayList();
+
+ for (Person person : allByLazy) {
+ actual.add(person);
+ }
+ Assert.assertEquals(dao.count(), actual.size());
+
+ allByLazy = dao.findAllLazyByQuery(
+ 49,
+ "FROM " + dao.getTopiaEntityEnum().getImplementationFQN() + " ORDER BY id");
+
+ actual = Lists.newArrayList();
+
+ for (Person person : allByLazy) {
+ actual.add(person);
+ }
+ Assert.assertEquals(dao.count(), actual.size());
+
+ allByLazy = dao.findAllLazyByQuery(
+ 101,
+ "FROM " + dao.getTopiaEntityEnum().getImplementationFQN() + " ORDER BY id");
+
+ actual = Lists.newArrayList();
+
+ for (Person person : allByLazy) {
+ actual.add(person);
+ }
+ Assert.assertEquals(dao.count(), actual.size());
+
+ allByLazy = dao.findAllLazyByQuery(
+ 102,
+ "FROM " + dao.getTopiaEntityEnum().getImplementationFQN() + " ORDER BY id");
+
+ 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.commitTransaction();
+ }
+
+ protected Person createPerson(String name) throws TopiaException {
+ return dao.create(Person.PROPERTY_NAME, name);
+ }
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/CollectorTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/CollectorTest.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/CollectorTest.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/CollectorTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,124 @@
+/*
+ * #%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%
+ */
+
+package org.nuiton.topia.persistence.util;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.TopiaTestDAOHelper;
+import org.nuiton.topia.persistence.TopiaEntity;
+import org.nuiton.topia.persistence.TopiaEntityEnum;
+import org.nuiton.topiatest.Company;
+import org.nuiton.topiatest.CompanyImpl;
+import org.nuiton.topiatest.Department;
+import org.nuiton.topiatest.DepartmentImpl;
+import org.nuiton.topiatest.EmployeImpl;
+
+/** @author tchemit <chemit(a)codelutin.com> */
+public class CollectorTest {
+
+
+ private static Log log = LogFactory.getLog(CollectorTest.class);
+
+
+ static TopiaEntityEnum[] contracts;
+
+ @BeforeClass
+ public static void setUpClass() throws Exception {
+ contracts = TopiaTestDAOHelper.getContracts();
+ }
+
+ @AfterClass
+ public static void tearDownClass() throws Exception {
+ contracts = null;
+ }
+
+ @Test
+ public void testCollector() throws Exception {
+
+ Collector<Integer> detector = new Collector<Integer>(contracts) {
+
+ int hits;
+
+ @Override
+ protected void beforeAll(CollectorVisitor visitor, TopiaEntity... entities) {
+ super.beforeAll(visitor, entities);
+ hits = 0;
+ }
+
+ @Override
+ protected Integer afterAll(CollectorVisitor visitor, TopiaEntity... entities) {
+ return hits;
+ }
+
+ @Override
+ protected void onStarted(TopiaEntity e, boolean enter) {
+ super.onStarted(e, enter);
+ int level = stackSize();
+ log.info(String.format("(%1$2d) %2$" + level * 2 + "s %3$s", level, ">>", getStack()));
+
+ hits++;
+ }
+
+ @Override
+ protected void onEnded(TopiaEntity e, boolean enter) {
+ super.onEnded(e, enter);
+ int level = stackSize() + 1;
+ log.info(String.format("(%1$2d) %2$" + level * 2 + "s %3$s", level, "<<", getStack()));
+ }
+ };
+
+ Company company = new CompanyImpl();
+ EmployeImpl employe = new EmployeImpl();
+ Department department = new DepartmentImpl();
+
+ detect(detector, 1, company);
+
+ company.addEmploye(employe);
+ detect(detector, 2, company);
+
+ company.addDepartment(department);
+ detect(detector, 3, company);
+
+ company.removeEmploye(employe);
+ detect(detector, 2, company);
+
+ company.removeDepartment(department);
+ detect(detector, 1, company);
+ }
+
+ protected void detect(Collector<Integer> detector,
+ int expectedResult,
+ TopiaEntity... entities) throws TopiaException {
+ Integer result = detector.detect(entities);
+ Assert.assertNotNull(result);
+ Assert.assertEquals(expectedResult, result.intValue());
+ }
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/EntityOperatorTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/EntityOperatorTest.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/EntityOperatorTest.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/EntityOperatorTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,238 @@
+/*
+ * #%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%
+ */
+
+package org.nuiton.topia.persistence.util;
+
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.nuiton.topia.TopiaTestDAOHelper;
+import org.nuiton.topiatest.Company;
+import org.nuiton.topiatest.CompanyImpl;
+import org.nuiton.topiatest.Department;
+import org.nuiton.topiatest.DepartmentImpl;
+import org.nuiton.topiatest.Employe;
+import org.nuiton.topiatest.EmployeImpl;
+import org.nuiton.topiatest.Personne;
+import org.nuiton.topiatest.PersonneImpl;
+
+import java.util.Collection;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+/** @author tchemit <chemit(a)codelutin.com> */
+public class EntityOperatorTest {
+
+ public EntityOperatorTest() {
+ }
+
+ static EntityOperator<Company> operationC;
+
+ static EntityOperator<Employe> operationE;
+
+ static EntityOperator<Personne> operationP;
+
+ static EntityOperator<Department> operationD;
+
+ Company c;
+
+ Department d;
+
+ Employe e;
+
+ Personne p;
+
+ @BeforeClass
+ public static void setUpClass() throws Exception {
+ operationC = TopiaTestDAOHelper.getOperator(Company.class);
+ operationE = TopiaTestDAOHelper.getOperator(Employe.class);
+ operationP = TopiaTestDAOHelper.getOperator(Personne.class);
+ operationD = TopiaTestDAOHelper.getOperator(Department.class);
+ }
+
+ @AfterClass
+ public static void tearDownClass() throws Throwable {
+ operationC.finalize();
+ operationE.finalize();
+ operationP.finalize();
+ operationD.finalize();
+ }
+
+ @Before
+ public void setUp() {
+ c = new CompanyImpl();
+ d = new DepartmentImpl();
+ e = new EmployeImpl();
+ p = new PersonneImpl();
+ }
+
+ @After
+ public void tearDown() {
+ c = null;
+ d = null;
+ e = null;
+ p = null;
+ }
+
+ /** Test of newOperator method, of class EntityOperator. */
+ @Test
+ public void testGet() {
+
+ Object actual;
+ String name;
+
+ e.setName(name = "name");
+ actual = operationE.get(Employe.PROPERTY_NAME, e);
+ assertEquals(name, actual);
+
+ actual = operationP.get(Employe.PROPERTY_NAME, e);
+ assertEquals(name, actual);
+
+ actual = operationD.get(Department.PROPERTY_COMPANY, d);
+ assertNull(actual);
+
+ d.setCompany(c);
+ actual = operationD.get(Department.PROPERTY_COMPANY, d);
+ assertNotNull(actual);
+ assertEquals(c, actual);
+
+ actual = operationC.get(Company.PROPERTY_DEPARTMENT, c);
+ assertNull(actual);
+
+ c.addDepartment(d);
+ actual = operationC.get(Company.PROPERTY_DEPARTMENT, c);
+ assertNotNull(actual);
+ assertFalse(((Collection<?>) actual).isEmpty());
+ }
+
+ /** Test of set method, of class EntityOperator. */
+ @Test
+ public void testSet() {
+
+ String name;
+
+ operationE.set(Employe.PROPERTY_NAME, e, name = "name");
+ assertEquals(name, e.getName());
+
+ operationP.set(Employe.PROPERTY_NAME, e, name = "name2");
+ assertEquals(name, e.getName());
+ }
+
+ /** Test of getChild method, of class EntityOperator. */
+ @Test
+ public void testGetChild() {
+ Object actual;
+ String topiaId;
+
+ topiaId = "0";
+
+ actual = operationC.get(Company.PROPERTY_DEPARTMENT, c);
+ assertNull(actual);
+
+ actual = operationC.getChild(Company.PROPERTY_DEPARTMENT, c, topiaId);
+ assertNull(actual);
+
+ c.addDepartment(d);
+
+ actual = operationC.get(Company.PROPERTY_DEPARTMENT, c);
+ assertNotNull(actual);
+ assertFalse(((Collection<?>) actual).isEmpty());
+
+ actual = operationC.getChild(Company.PROPERTY_DEPARTMENT, c, topiaId);
+ assertNull(actual);
+
+ d.setTopiaId(topiaId);
+ actual = operationC.getChild(Company.PROPERTY_DEPARTMENT, c, topiaId);
+ assertNotNull(actual);
+ assertEquals(d, actual);
+
+ }
+
+ /** Test of addChild method, of class EntityOperator. */
+ @Test
+ public void testAddChild() {
+
+ assertTrue(c.isDepartmentEmpty());
+
+ operationC.addChild(Company.PROPERTY_DEPARTMENT, c, d);
+ assertFalse(c.isDepartmentEmpty());
+ assertEquals(d, c.getDepartment().iterator().next());
+ }
+
+ /** Test of isChildEmpty method, of class EntityOperator. */
+ @Test
+ public void testIsChildEmpty() {
+
+ assertTrue(c.isDepartmentEmpty());
+
+ boolean actual = operationC.isChildEmpty(Company.PROPERTY_DEPARTMENT, c);
+ assertTrue(actual);
+
+ c.addDepartment(d);
+
+ actual = operationC.isChildEmpty(Company.PROPERTY_DEPARTMENT, c);
+ assertFalse(actual);
+ }
+
+ /** Test of sizeChild method, of class EntityOperator. */
+ @Test
+ public void testChildSize() {
+
+ assertTrue(c.isDepartmentEmpty());
+
+ int actual = operationC.sizeChild(Company.PROPERTY_DEPARTMENT, c);
+ assertEquals(0, actual);
+
+ c.addDepartment(d);
+
+ actual = operationC.sizeChild(Company.PROPERTY_DEPARTMENT, c);
+ assertEquals(1, actual);
+ c.clearDepartment();
+
+ actual = operationC.sizeChild(Company.PROPERTY_DEPARTMENT, c);
+ assertEquals(0, actual);
+ }
+
+ /** Test of removeChild method, of class EntityOperator. */
+ @Test
+ public void testRemoveChild() {
+
+ assertTrue(c.isDepartmentEmpty());
+
+ c.addDepartment(d);
+
+ assertFalse(c.isDepartmentEmpty());
+
+ operationC.removeChild(Company.PROPERTY_DEPARTMENT, c, d);
+
+ assertTrue(c.isDepartmentEmpty());
+ }
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityBinderTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityBinderTest.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityBinderTest.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityBinderTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,105 @@
+/*
+ * #%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%
+ */
+
+package org.nuiton.topia.persistence.util;
+
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.nuiton.topia.TopiaTestDAOHelper;
+import org.nuiton.topia.persistence.TopiaEntity;
+import org.nuiton.topia.persistence.TopiaEntityEnum;
+import org.nuiton.topiatest.Company;
+import org.nuiton.util.beans.Binder;
+import org.nuiton.util.beans.BinderFactory;
+import org.nuiton.util.beans.BinderModelBuilder;
+
+public class TopiaEntityBinderTest {
+
+ static TopiaEntityEnum[] contracts;
+
+ @BeforeClass
+ public static void setUpClass() throws Exception {
+ contracts = TopiaTestDAOHelper.getContracts();
+ }
+
+ public static class CompanyDTO {
+
+ protected String name;
+
+ protected int siret;
+
+ protected String id;
+
+ public String getName() {
+ return name;
+ }
+
+ public void setName(String name) {
+ this.name = name;
+ }
+
+ public int getSiret() {
+ return siret;
+ }
+
+ public void setSiret(int siret) {
+ this.siret = siret;
+ }
+
+ public String getTopiaId() {
+ return id;
+ }
+
+ public void setId(String id) {
+ this.id = id;
+ }
+ }
+
+ @Before
+ public void setUp() {
+ BinderFactory.clear();
+ }
+
+ @AfterClass
+ public static void afterClass() {
+ BinderFactory.clear();
+ }
+
+ @Test
+ public void testBinder() {
+
+ BinderModelBuilder<Company, CompanyDTO> builder = BinderModelBuilder.newEmptyBuilder(Company.class, CompanyDTO.class);
+ builder.addSimpleProperties(Company.PROPERTY_NAME, Company.PROPERTY_SIRET);
+ builder.addProperties(TopiaEntity.PROPERTY_TOPIA_ID, "id");
+ BinderFactory.registerBinderModel(builder);
+
+ Binder<Company, CompanyDTO> binder =
+ BinderFactory.newBinder(Company.class, CompanyDTO.class);
+ Assert.assertNotNull(binder);
+ }
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityHelperTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityHelperTest.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityHelperTest.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityHelperTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,282 @@
+/*
+ * #%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%
+ */
+
+package org.nuiton.topia.persistence.util;
+
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.TopiaTestDAOHelper;
+import org.nuiton.topia.persistence.DefaultTopiaIdFactory;
+import org.nuiton.topia.persistence.TopiaEntity;
+import org.nuiton.topia.persistence.TopiaEntityEnum;
+import org.nuiton.topia.persistence.TopiaIdFactory;
+import org.nuiton.topiatest.Company;
+import org.nuiton.topiatest.CompanyImpl;
+import org.nuiton.topiatest.Department;
+import org.nuiton.topiatest.DepartmentImpl;
+import org.nuiton.topiatest.Employe;
+import org.nuiton.topiatest.EmployeAbstract;
+import org.nuiton.topiatest.EmployeImpl;
+import org.nuiton.topiatest.Personne;
+import org.nuiton.topiatest.PersonneAbstract;
+import org.nuiton.topiatest.PersonneImpl;
+
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+/** @author tchemit <chemit(a)codelutin.com> */
+public class TopiaEntityHelperTest {
+
+ protected static TopiaIdFactory topiaIdFactory = new DefaultTopiaIdFactory();
+
+ protected static TopiaEntityEnum[] contracts;
+
+ protected final Set<Class<? extends TopiaEntity>> contractsClass;
+
+ public TopiaEntityHelperTest() {
+ contractsClass = new HashSet<Class<? extends TopiaEntity>>();
+ contractsClass.add(Company.class);
+ contractsClass.add(Employe.class);
+ contractsClass.add(Department.class);
+ }
+
+ @BeforeClass
+ public static void setUpClass() throws Exception {
+ contracts = TopiaTestDAOHelper.getContracts();
+ }
+
+ @AfterClass
+ public static void tearDownClass() throws Exception {
+ contracts = null;
+ }
+
+ /** Test of getContractClass method, of class TopiaEntityHelper. */
+ @Test
+ public void testgetContract() {
+
+ Class<?> result = TopiaEntityHelper.getContractClass(null, Company.class);
+ assertNull(result);
+
+ Class<? extends TopiaEntity> expResult;
+
+ expResult = Employe.class;
+
+ getContractClass(expResult, EmployeImpl.class);
+ getContractClass(expResult, EmployeAbstract.class);
+ getContractClass(expResult, Employe.class);
+
+ expResult = Personne.class;
+
+ getContractClass(expResult, PersonneImpl.class);
+ getContractClass(expResult, PersonneAbstract.class);
+ getContractClass(expResult, Personne.class);
+ }
+
+ /** Test of retainContracts method, of class TopiaEntityHelper. */
+ @Test
+ public void testRetainContracts() {
+ Set<Class<? extends TopiaEntity>> classes = new HashSet<Class<? extends TopiaEntity>>();
+ Set<Class<? extends TopiaEntity>> result = TopiaEntityHelper.retainContracts(contracts, classes);
+
+ assertTrue(result.isEmpty());
+
+ classes.add(PersonneImpl.class);
+ result = TopiaEntityHelper.retainContracts(contracts, classes);
+ assertEquals(1, result.size());
+ assertTrue(result.contains(Personne.class));
+
+ classes.add(PersonneAbstract.class);
+ result = TopiaEntityHelper.retainContracts(contracts, classes);
+ assertEquals(1, result.size());
+ assertTrue(result.contains(Personne.class));
+
+ classes.add(Personne.class);
+ result = TopiaEntityHelper.retainContracts(contracts, classes);
+ assertEquals(1, result.size());
+ assertTrue(result.contains(Personne.class));
+
+ classes.clear();
+ classes.add(EmployeImpl.class);
+ result = TopiaEntityHelper.retainContracts(contracts, classes);
+ assertEquals(1, result.size());
+ assertTrue(result.contains(Employe.class));
+
+ classes.add(PersonneImpl.class);
+ result = TopiaEntityHelper.retainContracts(contracts, classes);
+ assertEquals(2, result.size());
+ assertTrue(result.contains(Personne.class));
+ assertTrue(result.contains(Employe.class));
+
+ }
+
+ /**
+ * Test of detectTypes method, of class TopiaEntityHelper.
+ *
+ * @throws TopiaException
+ */
+ @Test
+ public void testDetectTypes() throws TopiaException {
+ Company company = new CompanyImpl();
+ EmployeImpl employe = new EmployeImpl();
+ Department departmnet = new DepartmentImpl();
+
+ detectTypes(new Class<?>[]{Company.class, Employe.class, Department.class}, company, employe, departmnet);
+
+ company.addEmploye(employe);
+ detectTypes(new Class<?>[]{Company.class, Employe.class}, company);
+
+ company.addDepartment(departmnet);
+ departmnet.setCompany(company);
+ detectTypes(new Class<?>[]{Company.class, Employe.class, Department.class}, company);
+
+ company.removeEmploye(employe);
+ company.removeDepartment(departmnet);
+ detectTypes(new Class<?>[]{Company.class}, company);
+ }
+
+ @Test
+ public void testDetector() throws Exception {
+
+ Company company = new CompanyImpl();
+ company.setTopiaId(topiaIdFactory.newTopiaId(Company.class, company));
+ Employe employe = new EmployeImpl();
+ employe.setTopiaId(topiaIdFactory.newTopiaId(Employe.class, employe));
+ Department department = new DepartmentImpl();
+ department.setTopiaId(topiaIdFactory.newTopiaId(Department.class, department));
+
+ detectEntities(new Class<?>[]{Company.class, Employe.class, Department.class}, new int[]{1, 1, 1}, company, employe, department);
+ detectEntityIds(new Class<?>[]{Company.class, Employe.class, Department.class}, new int[]{1, 1, 1}, company, employe, department);
+
+ company.addEmploye(employe);
+ detectEntities(new Class<?>[]{Company.class, Employe.class}, new int[]{1, 1, 1}, company);
+ detectEntityIds(new Class<?>[]{Company.class, Employe.class}, new int[]{1, 1, 1}, company);
+
+ company.addDepartment(department);
+ department.setCompany(company);
+
+ detectEntities(new Class<?>[]{Company.class, Employe.class, Department.class}, new int[]{1, 1, 1}, company);
+ detectEntityIds(new Class<?>[]{Company.class, Employe.class, Department.class}, new int[]{1, 1, 1}, company);
+
+ company.removeEmploye(employe);
+ company.removeDepartment(department);
+
+
+ detectEntities(new Class<?>[]{Company.class}, new int[]{1}, company);
+ detectEntityIds(new Class<?>[]{Company.class}, new int[]{1}, company);
+
+ detectEntities(new Class<?>[]{Company.class}, new int[]{2}, company, new CompanyImpl());
+ detectEntityIds(new Class<?>[]{Company.class}, new int[]{2}, company, new CompanyImpl());
+
+ department.setCompany(company);
+
+ detectEntities(new Class<?>[]{Company.class, Department.class}, new int[]{1, 1}, department);
+ detectEntityIds(new Class<?>[]{Company.class, Department.class}, new int[]{1, 1}, department);
+
+ //TODO faire des tests avec des entites avec cycles
+ }
+
+ protected void detectEntities(Class<?>[] expected,
+ int[] sizes,
+ TopiaEntity... data) throws TopiaException {
+
+ Map<Class<? extends TopiaEntity>, List<TopiaEntity>> actual = null;
+
+ try {
+ actual = TopiaEntityHelper.detectEntities(contracts, contractsClass, data);
+
+ Assert.assertEquals(expected.length, actual.size());
+ int index = 0;
+ for (Class<?> c : expected) {
+ List<TopiaEntity> value = actual.get(c);
+ int expectedSize = sizes[index++];
+ Assert.assertEquals(expectedSize, value.size());
+ }
+ } finally {
+ if (actual != null) {
+ actual.clear();
+ }
+ }
+ }
+
+ protected void detectEntityIds(Class<?>[] expected,
+ int[] sizes,
+ TopiaEntity... data) throws TopiaException {
+
+ TopiaEntityIdsMap actual = null;
+
+ try {
+ actual = TopiaEntityHelper.detectEntityIds(contracts,
+ contractsClass,
+ data
+ );
+
+ Assert.assertEquals(expected.length, actual.size());
+ int index = 0;
+ for (Class<?> c : expected) {
+ List<String> value = actual.get(c);
+ int expectedSize = sizes[index++];
+ Assert.assertEquals(expectedSize, value.size());
+ }
+ } finally {
+ if (actual != null) {
+ actual.clear();
+ }
+ }
+ }
+
+ protected void detectTypes(Class<?>[] expected, TopiaEntity... data) throws TopiaException {
+ Set<String> fqns = new HashSet<String>(expected.length);
+ Set<Class<? extends TopiaEntity>> actual = null;
+ for (Class<?> c : expected) {
+ fqns.add(c.getName());
+ }
+ try {
+ actual = TopiaEntityHelper.detectTypes(contracts, data);
+ Assert.assertEquals(expected.length, actual.size());
+ for (Class<? extends TopiaEntity> c : actual) {
+ Assert.assertTrue(fqns.contains(c.getName()));
+ }
+ } finally {
+ fqns.clear();
+ if (actual != null) {
+ actual.clear();
+ }
+ }
+ }
+
+ protected void getContractClass(Class<?> expected, Class<? extends TopiaEntity> klass) {
+ Class<?> result = TopiaEntityHelper.getContractClass(contracts, klass);
+ assertEquals(expected, result);
+ }
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityRefTester.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTester.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityRefTester.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityRefTester.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,331 @@
+/*
+ * #%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%
+ */
+
+package org.nuiton.topia.persistence.util;
+
+import org.junit.After;
+import org.junit.Assert;
+import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.persistence.TopiaEntity;
+import org.nuiton.topia.persistence.TopiaEntityEnum;
+
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+import java.util.SortedMap;
+
+import static java.util.Map.Entry;
+
+/**
+ * A abstract class to help testing {@link TopiaEntityRef} as detectes types, or
+ * detects or references.
+ * <p/>
+ * An example of use if given in the test {@link TopiaEntityRefTesterTest}.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.3.1
+ */
+public abstract class TopiaEntityRefTester<T extends TopiaEntityEnum> {
+
+ protected SortedMap<TopiaEntity, List<TopiaEntityRef>> detected;
+
+ protected Iterator<Entry<TopiaEntity, List<TopiaEntityRef>>> itr;
+
+ protected Entry<TopiaEntity, List<TopiaEntityRef>> entry;
+
+ protected List<TopiaEntityRef> refs;
+
+ protected T[] contracts;
+
+ protected int index;
+
+ protected T[] getContracts() {
+ if (contracts == null) {
+ contracts = getContracts0();
+ }
+ return contracts;
+ }
+
+ /** @return all the {@link TopiaEntityEnum} to be used */
+ protected abstract T[] getContracts0();
+
+ @After
+ public void after() {
+ itr = null;
+ entry = null;
+ refs = null;
+ detected = null;
+ index = 0;
+ }
+
+ /**
+ * Creates a new entity with the given {@code topiaId} (will use the {@link
+ * TopiaEntityEnum#getImplementation()} class).
+ *
+ * @param constant the constant defining the entity
+ * @param topiaId the topia to assign
+ * @param <T> the type of entity
+ * @return the new entity
+ * @throws IllegalAccessException if can no access entity constructor
+ * @throws InstantiationException if can no instanciate the entity
+ */
+ protected <T extends TopiaEntity> T newEntity(
+ TopiaEntityEnum constant, String topiaId) throws
+ IllegalAccessException,
+ InstantiationException {
+ Class<? extends TopiaEntity> impl = constant.getImplementation();
+ TopiaEntity topiaEntity = impl.newInstance();
+ topiaEntity.setTopiaId(topiaId);
+ return (T) topiaEntity;
+ }
+
+ /**
+ * Obtain the reference of an association for a given entity.
+ * <p/>
+ * Example, to obtain the Pet 'pudding' on a Person :
+ * <pre>pet[@topiaId='pudding']</pre>
+ * invoke
+ * <pre>getAssociationRef('pet',pet);</pre>
+ *
+ * @param associationName the name of the association
+ * @param e the required entity
+ * @return the reference of the association
+ */
+ protected String getAssociationRef(String associationName, TopiaEntity e) {
+ return getAssociationRef(associationName, e.getTopiaId());
+ }
+
+ /**
+ * Obtain the reference of an association for a given id.
+ * <p/>
+ * Example to obtain the Pet 'pudding' on a Person :
+ * <pre>pet[@topiaId='pudding']</pre>
+ * invoke
+ * <pre>getAssociationRef('pet','pudding');</pre>
+ *
+ * @param associationName the name of the association
+ * @param e the id
+ * @return the reference of the association
+ */
+ protected String getAssociationRef(String associationName, String e) {
+ String s = String.format(
+ TopiaEntityHelper.ASSOCIATION_PATTERN,
+ associationName,
+ e
+ );
+ return s;
+ }
+
+ /**
+ * Obtain the next entry from the iterator.
+ * <p/>
+ * As a side-effect, it will increment the state {@link #index}.
+ */
+ protected void nextEntry() {
+ if (!itr.hasNext()) {
+ throw new IllegalStateException("no more entry to get...");
+ }
+ entry = itr.next();
+ index = 0;
+ }
+
+ /**
+ * Detects the references from the given {@code entity} which have their
+ * topiaId in the given list of {@code ids}.
+ * <p/>
+ * As a side-effect, it will update the states {@code detected} and set the
+ * iterator {@code itr} to the first position on detected entries.
+ *
+ * @param entity the entity to seek
+ * @param nb the required number of entries
+ * @param ids the ids to seek
+ * @throws TopiaException if any pb while visiting entities
+ */
+ protected void detectReferences(
+ TopiaEntity entity, int nb, String... ids) throws TopiaException {
+ detected = TopiaEntityHelper.detectReferences(
+ getContracts(), ids, entity);
+ assertDetected(nb);
+
+ }
+
+ /**
+ * Detects the references from the given {@code entity} which have their
+ * topiaId in the given list of {@code ids}.
+ * <p/>
+ * As a side-effect, it will update the states {@code detected} and set the
+ * iterator {@code itr} to the first position on detected entries.
+ *
+ * @param entity the entity to seek
+ * @param nb the required number of entries
+ * @param ids the ids to seek
+ * @throws TopiaException if any pb while visiting entities
+ */
+ protected void detectReferences(
+ Collection<? extends TopiaEntity> entity,
+ int nb, String... ids) throws TopiaException {
+ detected = TopiaEntityHelper.detectReferences(
+ getContracts(), ids, entity);
+ assertDetected(nb);
+ }
+
+ /**
+ * Detects the type of entities fro the given {@code data}.
+ *
+ * @param expected the array of expected types
+ * @param data the data to seek
+ * @throws TopiaException if any pb while visiting data
+ */
+ protected void detectTypes(Class<?>[] expected,
+ TopiaEntity... data) throws TopiaException {
+ Set<String> fqns = new HashSet<String>(expected.length);
+ Set<Class<? extends TopiaEntity>> actual = null;
+ for (Class<?> c : expected) {
+ fqns.add(c.getName());
+ }
+ try {
+ actual = TopiaEntityHelper.detectTypes(getContracts(), data);
+ Assert.assertEquals(expected.length, actual.size());
+ for (Class<? extends TopiaEntity> c : actual) {
+ Assert.assertTrue(fqns.contains(c.getName()));
+ }
+ } finally {
+ fqns.clear();
+ if (actual != null) {
+ actual.clear();
+ }
+ }
+ }
+
+ /**
+ * Asserts if the given entry definition is equals to the next entry
+ * references on internal state state {@code entry}.
+ *
+ * @param invoker the invoker of the reference
+ * @param invokerProperty the access path of the reference
+ * @param expected the expected topia entities path to access
+ * reference target
+ */
+ protected void assertNextEntityRef(TopiaEntity invoker,
+ String invokerProperty,
+ TopiaEntity... expected) {
+ assertEntityRef(index, invoker, invokerProperty, expected);
+ index++;
+ }
+
+ /**
+ * Asserts if the given entry definition (of an association) is equals to
+ * the next entry reference on internal state {@code entry}.
+ *
+ * @param invoker the invoker of the reference
+ * @param association the association name
+ * @param id the id of the association ( see {@link
+ * #getAssociationRef(String, TopiaEntity)}
+ * @param expected the expected topia entities path to access reference
+ * target
+ */
+ protected void assertNextAssociationEntityRef(TopiaEntity invoker,
+ String association,
+ String id,
+ TopiaEntity... expected) {
+ String invokerProperty = getAssociationRef(association, id);
+ assertNextEntityRef(invoker, invokerProperty, expected);
+ }
+
+ /**
+ * Asserts if the given entry definition is equals to the reference entry at
+ * position {@code index} on internal state {@code entry}.
+ *
+ * @param index the index of the reference to test in {@code
+ * entry}
+ * @param invoker the invoker of the reference
+ * @param invokerProperty the path of the reference
+ * @param expected th expected topia entities path to access
+ * reference target
+ */
+ protected void assertEntityRef(int index,
+ TopiaEntity invoker,
+ String invokerProperty,
+ TopiaEntity... expected) {
+ Assert.assertNotNull(refs);
+ Assert.assertTrue("no index [" + index + "] in refs of size " +
+ refs.size(), index < refs.size());
+ TopiaEntityRef actual = refs.get(index);
+ Assert.assertEquals(actual.getInvoker(), invoker);
+ Assert.assertEquals(actual.getInvokerProperty(), invokerProperty);
+
+ TopiaEntity[] path = actual.getPath();
+ Assert.assertEquals(expected.length, path.length);
+ for (int i = 0; i < expected.length; i++) {
+ Assert.assertEquals(expected[i].getTopiaId(), path[i].getTopiaId());
+ }
+ }
+
+ /**
+ * Asserts if the given {@code expected} entity is equals to the source of
+ * the internal state {@code entry}.
+ *
+ * @param expected the required source of the entry
+ * @param nbPath the expected number of references of the given entry
+ */
+ protected void assertCurrentEntry(TopiaEntity expected,
+ int nbPath) {
+ assertEntry(expected, nbPath, entry);
+ }
+
+ /**
+ * Asserts if the given {@code entry} has a good source and a good number of
+ * references.
+ *
+ * @param expected the expected entry source
+ * @param nbPath the expected number of reference of the entry
+ * @param entry the entry to test
+ */
+ private void assertEntry(TopiaEntity expected,
+ int nbPath,
+ Entry<TopiaEntity, List<TopiaEntityRef>> entry) {
+ Assert.assertNotNull(entry);
+ Assert.assertEquals(expected, entry.getKey());
+ refs = entry.getValue();
+ Assert.assertEquals(nbPath, refs.size());
+ }
+
+ /**
+ * Asserts that the number of detected entries (store in internal state
+ * {@code detected}) is ok.
+ * <p/>
+ * As a side-effect, it will reset the internal state {@code itr} on the
+ * first entry of the {@code detected} list.
+ *
+ * @param size the expected number of detected entries
+ */
+ protected void assertDetected(int size) {
+ Assert.assertNotNull(detected);
+ Assert.assertEquals(size, detected.size());
+ itr = detected.entrySet().iterator();
+ }
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityRefTesterTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTesterTest.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityRefTesterTest.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityRefTesterTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,155 @@
+/*
+ * #%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%
+ */
+
+package org.nuiton.topia.persistence.util;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.junit.Test;
+import org.nuiton.topia.TopiaTestDAOHelper.TopiaTestEntityEnum;
+import org.nuiton.topia.test.entities.Person;
+import org.nuiton.topia.test.entities.Pet;
+import org.nuiton.topia.test.entities.Race;
+
+/**
+ * Test the {@link TopiaEntityRefTester} on
+ * <p/>
+ * <ul> <li>{@link Pet}</li> <li>{@link Race}</li> <li>{@link Person}</li>
+ * </ul>
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.3.1
+ */
+public class TopiaEntityRefTesterTest extends TopiaEntityRefTester<TopiaTestEntityEnum> {
+
+ /** Logger */
+ private static final Log log =
+ LogFactory.getLog(TopiaEntityRefTesterTest.class);
+
+ private static final String PET1 = "pet1";
+
+ private static final String PET2 = "pet2";
+
+ private static final String RACE1 = "race1";
+
+ private static final String PERSON1 = "person1";
+
+ @Override
+ protected TopiaTestEntityEnum[] getContracts0() {
+ return new TopiaTestEntityEnum[]{
+ TopiaTestEntityEnum.Pet,
+ TopiaTestEntityEnum.Person,
+ TopiaTestEntityEnum.Race,
+ };
+ }
+
+ @Test
+ public void testNoReferences() throws Exception {
+
+ Pet pet = newEntity(TopiaTestEntityEnum.Pet, PET1);
+
+ detectReferences(pet, 0);
+
+ Race race = newEntity(TopiaTestEntityEnum.Race, RACE1);
+
+ detectReferences(race, 0);
+
+ Person person = newEntity(TopiaTestEntityEnum.Person, PERSON1);
+
+ detectReferences(person, 0);
+
+ }
+
+ @Test
+ public void testReferences() throws Exception {
+
+ Pet pet = newEntity(TopiaTestEntityEnum.Pet, PET1);
+ Race race = newEntity(TopiaTestEntityEnum.Race, RACE1);
+ pet.setRace(race);
+ Person person = newEntity(TopiaTestEntityEnum.Person, PERSON1);
+
+ detectReferences(pet, 1, RACE1);
+
+ nextEntry();
+ assertCurrentEntry(race, 1);
+ assertNextEntityRef(pet, Pet.PROPERTY_RACE, pet, race);
+
+ pet.setPerson(person);
+
+ detectReferences(pet, 2, RACE1, PERSON1);
+
+ nextEntry();
+ assertCurrentEntry(person, 1);
+ assertNextEntityRef(pet, Pet.PROPERTY_PERSON, pet, person);
+
+ nextEntry();
+ assertCurrentEntry(race, 1);
+ assertNextEntityRef(pet, Pet.PROPERTY_RACE, pet, race);
+
+ person.addPet(pet);
+
+ detectReferences(person, 1, PET1);
+
+ nextEntry();
+ assertCurrentEntry(pet, 1);
+ assertNextAssociationEntityRef(person, Person.PROPERTY_PET, PET1, person, pet);
+
+ Pet pet2 = newEntity(TopiaTestEntityEnum.Pet, PET2);
+
+ person.addPet(pet2);
+
+ detectReferences(person, 3, PET1, PET2, RACE1);
+
+ nextEntry();
+ assertCurrentEntry(pet, 1);
+ assertNextAssociationEntityRef(person, Person.PROPERTY_PET, PET1, person, pet);
+
+ nextEntry();
+ assertCurrentEntry(pet2, 1);
+ assertNextAssociationEntityRef(person, Person.PROPERTY_PET, PET2, person, pet2);
+
+ nextEntry();
+ assertCurrentEntry(race, 1);
+ assertNextEntityRef(pet, Pet.PROPERTY_RACE, person, pet, race);
+
+ pet2.setRace(race);
+
+ detectReferences(person, 3, PET1, PET2, RACE1);
+
+ nextEntry();
+ assertCurrentEntry(pet, 1);
+ assertNextAssociationEntityRef(person, Person.PROPERTY_PET, PET1, person, pet);
+
+ nextEntry();
+ assertCurrentEntry(pet2, 1);
+ assertNextAssociationEntityRef(person, Person.PROPERTY_PET, PET2, person, pet2);
+
+ nextEntry();
+ assertCurrentEntry(race, 2);
+ assertNextEntityRef(pet, Pet.PROPERTY_RACE, person, pet, race);
+ assertNextEntityRef(pet2, Pet.PROPERTY_RACE, person, pet2, race);
+
+ }
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/ano1882/DAOAbstractTransformerTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/test/ano1882/DAOAbstractTransformerTest.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/ano1882/DAOAbstractTransformerTest.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/ano1882/DAOAbstractTransformerTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,57 @@
+/*
+ * #%L
+ * ToPIA :: Persistence
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2004 - 2012 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%
+ */
+package org.nuiton.topia.test.ano1882;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.nuiton.topia.TopiaDatabase;
+import org.nuiton.topia.TopiaTestDAOHelper;
+import org.nuiton.topia.TopiaTestTopiaPersistenceContext;
+
+import java.util.Arrays;
+
+public class DAOAbstractTransformerTest {
+
+ @Rule
+ public final TopiaDatabase db = new TopiaDatabase();
+
+ @Test
+ public void testAno1882() throws Exception {
+ TopiaTestTopiaPersistenceContext transaction = db.beginTransaction();
+
+ FrenchCompanyDAO dao = TopiaTestDAOHelper.getFrenchCompanyDAO(transaction);
+ SIRETDAO siretDAO = TopiaTestDAOHelper.getSIRETDAO(transaction);
+ SIRET siret = siretDAO.create();
+ FrenchCompany entity =
+ dao.create(
+ FrenchCompany.PROPERTY_S_IREN, null,
+ FrenchCompany.PROPERTY_SIREN2, null,
+ FrenchCompany.PROPERTY_S_IRET, Arrays.asList(siret),
+ FrenchCompany.PROPERTY_SIRET2, null);
+ transaction.commitTransaction();
+ dao.delete(entity);
+ transaction.commitTransaction();
+ }
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/evo1912/EntityDTOTransformerTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/test/evo1912/EntityDTOTransformerTest.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/evo1912/EntityDTOTransformerTest.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/evo1912/EntityDTOTransformerTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,46 @@
+/*
+ * #%L
+ * ToPIA :: Persistence
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2004 - 2012 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%
+ */
+package org.nuiton.topia.test.evo1912;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.nuiton.topiatest.CompanyDTO;
+
+/** @author ymartel <martel(a)codelutin.com> */
+public class EntityDTOTransformerTest {
+
+ @Test
+ public void testEvo1912() throws Exception {
+ // simply test the getter/setter on id property : with the tagValue, they should be generated
+ CompanyDTO companyDTO = new CompanyDTO();
+ String originalId = companyDTO.getTopiaId();
+ Assert.assertNull(originalId);
+ String wantedId = "mycompany";
+ companyDTO.setTopiaId(wantedId);
+ String updatedId = companyDTO.getTopiaId();
+ Assert.assertEquals(wantedId, updatedId);
+ }
+
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/AbstractExtraDAOEntityTopiaDao.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topiatest/AbstractExtraDAOEntityTopiaDao.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/AbstractExtraDAOEntityTopiaDao.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/AbstractExtraDAOEntityTopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,40 @@
+/*
+ * #%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%
+ */
+package org.nuiton.topiatest;
+
+import org.nuiton.topia.TopiaException;
+
+/**
+ * Created: 26 mai 2010
+ *
+ * @author fdesbois <fdesbois(a)codelutin.com>
+ * @version $Id$
+ */
+public class AbstractExtraDAOEntityTopiaDao<E extends ExtraDAOEntity> extends GeneratedExtraDAOEntityTopiaDao<E> {
+
+ @Override
+ public void extra() throws TopiaException {
+ }
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/EnumTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topiatest/EnumTest.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/EnumTest.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/EnumTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,75 @@
+/*
+ * #%L
+ * ToPIA :: Persistence
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2004 - 2011 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%
+ */
+package org.nuiton.topiatest;
+
+import org.junit.Assert;
+import org.junit.Rule;
+import org.junit.Test;
+import org.nuiton.topia.TopiaDatabase;
+import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.TopiaTestDAOHelper;
+import org.nuiton.topia.TopiaTestTopiaPersistenceContext;
+
+/**
+ * Test the support of possibility to have an attribute of type enumeration
+ * in a entity
+ */
+public class EnumTest {
+
+ @Rule
+ public final TopiaDatabase db = new TopiaDatabase();
+
+ /**
+ * Create an entity having two field of type enumeration. One is stored
+ * using ordinal, the other using the name.
+ * <p/>
+ * The test check that values are stored, and that find methods works
+ *
+ * @throws TopiaException if any exception with db
+ */
+ @Test
+ public void storeEntityWithEnumValue() throws TopiaException {
+ TopiaTestTopiaPersistenceContext transaction = db.beginTransaction();
+
+ PersonneDAO dao = TopiaTestDAOHelper.getPersonneDAO(transaction);
+ Personne personne = new PersonneImpl();
+ personne.setGender(Gender.FEMALE);
+ personne.setOtherGender(Gender.MALE);
+ dao.create(personne);
+ String topiaId = personne.getTopiaId();
+ transaction.commitTransaction();
+ transaction.closeContext();
+
+ transaction = db.beginTransaction();
+ dao = TopiaTestDAOHelper.getPersonneDAO(transaction);
+ dao.findByTopiaId(topiaId);
+ Assert.assertEquals(Gender.FEMALE, personne.getGender());
+ Assert.assertEquals(Gender.MALE, personne.getOtherGender());
+
+ Assert.assertNotNull(dao.findByGender(Gender.FEMALE));
+ Assert.assertNotNull(dao.findByOtherGender(Gender.MALE));
+ transaction.closeContext();
+ }
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/Gender.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topiatest/Gender.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/Gender.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/Gender.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,29 @@
+/*
+ * #%L
+ * ToPIA :: Persistence
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2004 - 2011 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%
+ */
+package org.nuiton.topiatest;
+
+public enum Gender {
+ MALE, FEMALE
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/Title.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topiatest/Title.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/Title.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/Title.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,37 @@
+/*
+ * #%L
+ * ToPIA :: Persistence
+ *
+ * $Id$
+ * $HeadURL$
+ * %%
+ * Copyright (C) 2004 - 2011 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%
+ */
+package org.nuiton.topiatest;
+
+/**
+ * To test http://nuiton.org/issues/1732.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.6.2
+ */
+public enum Title {
+ Mr,
+ Madam,
+ Other
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/beangen/RoueImpl.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topiatest/beangen/RoueImpl.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/beangen/RoueImpl.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/beangen/RoueImpl.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,53 @@
+/*
+ * #%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%
+ */
+
+package org.nuiton.topiatest.beangen;
+
+import org.nuiton.topiatest.Product;
+
+/**
+ * RoueImpl
+ *
+ * Created: 14 janv. 2010
+ *
+ * @author fdesbois
+ * @version $Revision$
+ *
+ * Mise a jour: $Date$
+ * par : $Author$
+ */
+public class RoueImpl extends Roue {
+
+ @Override
+ public void mount() {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public Product getModel(String id) {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/AbstractContact2TopiaDao.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topiatest/deletetest/AbstractContact2TopiaDao.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/AbstractContact2TopiaDao.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/AbstractContact2TopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,51 @@
+/*
+ * #%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%
+ */
+
+package org.nuiton.topiatest.deletetest;
+
+
+import org.nuiton.topia.TopiaException;
+import org.nuiton.topiatest.Company;
+import org.nuiton.topiatest.Employe;
+
+import java.util.Set;
+import java.util.TreeSet;
+
+/**
+ *
+ * @author desbois
+ */
+public class AbstractContact2TopiaDao<E extends Contact2> extends GeneratedContact2TopiaDao<E> {
+
+ @Override
+ public Set<Contact2> findAllByCompany(Company company) throws TopiaException {
+ Set<Contact2> contacts = new TreeSet<Contact2>();
+ for (Employe e : company.getEmploye()) {
+ contacts.addAll(e.getContacts());
+ }
+ return contacts;
+ }
+
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/DeleteEntityTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topiatest/deletetest/DeleteEntityTest.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/DeleteEntityTest.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/DeleteEntityTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,206 @@
+/*
+ * #%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%
+ */
+
+
+/**
+ * DeleteEntityTest.java
+ *
+ * Created: 4 juin 2009
+ *
+ * @author Florian Desbois <fdesbois(a)codelutin.com>
+ * @version $Revision$
+ *
+ * Mise a jour: $Date$
+ * par : $Author$
+ */
+
+package org.nuiton.topiatest.deletetest;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.junit.Assert;
+import org.junit.Rule;
+import org.junit.Test;
+import org.nuiton.topia.TopiaDatabase;
+import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.TopiaTestDAOHelper;
+import org.nuiton.topia.TopiaTestTopiaPersistenceContext;
+import org.nuiton.topiatest.Gender;
+import org.nuiton.topiatest.Personne;
+import org.nuiton.topiatest.PersonneDAO;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+
+/**
+ * Deleting tests with DAO and Entities generated with ToPIA (diagram
+ * delete-test in topiatest.zargo). Different case of deleting, with inheritance
+ * or NMultiplicity relationship between two entities, or both. Initiate from an
+ * issue with DAOAbstractGenerator delete method generation. Tests with H2
+ * Database. Configuration in src/test/resources/TopiaContextImpl.properties
+ */
+public class DeleteEntityTest {
+
+ private static final Log log = LogFactory.getLog(DeleteEntityTest.class);
+
+ @Rule
+ public final TopiaDatabase db = new TopiaDatabase();
+
+ /**
+ * Test for deleting entities with inheritance. Delete from the DAO linked
+ * with the subclass entity and from the DAO linked with the superclass
+ * entity. In the test model, the two entities have NMultiplicity
+ * relationship without association class entity.
+ *
+ * @throws TopiaException if any exception while manipulating db
+ */
+ @Test
+ public void testDeleteEntityWithInheritance() throws TopiaException {
+ log.debug("START TEST : testDeleteEntityWithInheritance");
+
+ TopiaTestTopiaPersistenceContext transaction = db.beginTransaction();
+
+ log.debug("DAO : PersonneDAO");
+ PersonneDAO dao = TopiaTestDAOHelper.getPersonneDAO(transaction);
+
+ log.debug("CREATE PERSONNE : Bob Marley");
+ Personne personne = dao.create(Personne.PROPERTY_NAME, "Bob Marley");
+ transaction.commitTransaction();
+ String idPersonne = personne.getTopiaId();
+ assertNotNull(idPersonne);
+ log.debug("ENTITY PERSONNE SAVED !");
+
+ log.debug("DELETE PERSONNE");
+ dao.delete(personne);
+ transaction.commitTransaction();
+ Personne res = dao.forTopiaIdEquals(idPersonne).findAnyOrNull();
+ assertNull(res);
+ log.debug("ENTITY PERSONNE DELETED !");
+
+ log.debug("CREATE PERSONNE : Ziggy Marley");
+ Personne personne2 = dao.create(Personne.PROPERTY_NAME, "Ziggy Marley");
+ transaction.commitTransaction();
+ String idPersonne2 = personne2.getTopiaId();
+ assertNotNull(idPersonne2);
+ log.debug("ENTITY PERSONNE SAVED !");
+
+ log.debug("DAO parent (abstract) : PartyDAO");
+ Party2DAO dao2 = TopiaTestDAOHelper.getParty2DAO(transaction);
+
+ log.debug("DELETE PERSONNE with PartyDAO");
+ dao2.delete(personne2);
+ transaction.commitTransaction();
+ Party2 res2 = dao2.forTopiaIdEquals(idPersonne2).findAnyOrNull();
+ assertNull(res2);
+ log.debug("ENTITY PERSONNE DELETED !");
+
+
+ }
+
+ /**
+ * Test for deleting entities with NMultiplicity relation without
+ * association class entity. Test DAO generation for deleting references
+ * between two entities with NMultiplicity relation. In the test model, the
+ * two entities have both inheritance.
+ *
+ * @throws TopiaException if any exception while manipulating db
+ */
+ @Test
+ public void testDeleteEntityWithManyToManyRelation() throws TopiaException {
+ log.debug("START TEST : testDeleteEntityWithManyToManyRelation");
+
+ TopiaTestTopiaPersistenceContext transaction = db.beginTransaction();
+
+ PersonneDAO dao = TopiaTestDAOHelper.getPersonneDAO(transaction);
+
+ log.debug("CREATE PERSONNE : Bob Marley");
+ Personne personne = dao.create(Personne.PROPERTY_NAME, "Bob Marley");
+ transaction.commitTransaction();
+ String idPersonne = personne.getTopiaId();
+ assertNotNull(idPersonne);
+ log.debug("ENTITY PERSONNE SAVED !");
+
+ Contact2DAO contactDAO = TopiaTestDAOHelper.getContact2DAO(transaction);
+
+ log.debug("CREATE CONTACT : jaja(a)codelutin.com");
+ Contact2 contact = contactDAO.create(Contact2.PROPERTY_CONTACT_VALUE, "jaja(a)codelutin.com");
+ transaction.commitTransaction();
+ String idContact = contact.getTopiaId();
+ assertNotNull(idContact);
+ log.debug("ENTITY CONTACT SAVED !");
+
+ log.debug("ADD CONTACT TO PERSONNE");
+ personne.addContacts(contact);
+ transaction.commitTransaction();
+ assertEquals(1, personne.getContacts().size());
+ log.debug("CONTACT ADDED !");
+
+ log.debug("DELETE PERSONNE");
+ dao.delete(personne);
+ transaction.commitTransaction();
+ Personne res = dao.forTopiaIdEquals(idPersonne).findAnyOrNull();
+ assertNull(res);
+ log.debug("ENTITY PERSONNE DELETED !");
+
+ assertEquals(0, contact.getParty2().size());
+
+ log.debug("DELETE CONTACT");
+ contactDAO.delete(contact);
+ transaction.commitTransaction();
+ Contact2 res2 = contactDAO.forTopiaIdEquals(idContact).findAnyOrNull();
+ assertNull(res2);
+ log.debug("ENTITY PERSONNE DELETED !");
+
+ }
+
+ /**
+ * Test than deleting entities will modify isPersisted() result
+ */
+ @Test
+ public void testIsPersisted() {
+ log.debug("START TEST : testIsPersisted");
+
+ TopiaTestTopiaPersistenceContext transaction = db.beginTransaction();
+
+ PersonneDAO dao = TopiaTestDAOHelper.getPersonneDAO(transaction);
+
+ Personne person = dao.newInstance();
+ Assert.assertNull(person.getTopiaId());
+
+ person.setName("Arno");
+ person.setGender(Gender.MALE);
+ Assert.assertFalse(person.isPersisted());
+
+ Personne person2 = dao.create(person);
+ Assert.assertTrue(person.isPersisted());
+ Assert.assertTrue(person2.isPersisted());
+
+ dao.delete(person2);
+ Assert.assertFalse(person.isPersisted());
+ Assert.assertFalse(person2.isPersisted());
+ }
+
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,49 @@
+/*
+ * #%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%
+ */
+package org.nuiton.topia.it.legacy.topiatest.persistence;
+
+import org.nuiton.topia.persistence.TopiaEntity;
+
+/**
+ * Created: 11 mai 2010
+ *
+ * @author fdesbois <fdesbois(a)codelutin.com>
+ * @version $Id$
+ */
+public interface Entity1 extends TopiaEntity {
+
+ String ATTR_1 = "attr1";
+
+ String ATTR_2 = "attr2";
+
+ String getAttr1();
+
+ void setAttr1(String attr1);
+
+ String getAttr2();
+
+ void setAttr2(String attr2);
+
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Abstract.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1Abstract.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Abstract.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Abstract.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,83 @@
+/*
+ * #%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%
+ */
+package org.nuiton.topia.it.legacy.topiatest.persistence;
+
+import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.persistence.EntityVisitor;
+import org.nuiton.topia.persistence.TopiaEntityAbstract;
+
+/**
+ * Created: 11 mai 2010
+ *
+ * @author fdesbois <fdesbois(a)codelutin.com>
+ * @version $Id$
+ */
+public abstract class Entity1Abstract extends TopiaEntityAbstract
+ implements Entity1 {
+
+ protected String attr1;
+
+ protected String attr2;
+
+ @Override
+ public String getAttr1() {
+ fireOnPreRead(ATTR_1, attr1);
+ String result = attr1;
+ fireOnPostRead(ATTR_1, attr1);
+ return result;
+ }
+
+ @Override
+ public void setAttr1(String attr1) {
+ String _oldValue = this.attr1;
+ fireOnPreWrite(ATTR_1, _oldValue, attr1);
+ this.attr1 = attr1;
+ fireOnPostWrite(ATTR_1, _oldValue, attr1);
+ }
+
+ @Override
+ public String getAttr2() {
+ fireOnPreRead(ATTR_2, attr2);
+ String result = attr2;
+ fireOnPostRead(ATTR_2, attr2);
+ return result;
+ }
+
+ @Override
+ public void setAttr2(String attr2) {
+ String _oldValue = this.attr2;
+ fireOnPreWrite(ATTR_2, _oldValue, attr2);
+ this.attr2 = attr2;
+ fireOnPostWrite(ATTR_2, _oldValue, attr2);
+ }
+
+ @Override
+ public void accept(EntityVisitor visitor) throws TopiaException {
+ visitor.start(this);
+ visitor.visit(this, ATTR_1, String.class, attr1);
+ visitor.visit(this, ATTR_2, String.class, attr2);
+ visitor.end(this);
+ }
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Impl.hbm.xml (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1Impl.hbm.xml)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Impl.hbm.xml (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Impl.hbm.xml 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,37 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ #%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%
+ -->
+
+<!--<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">-->
+<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
+<hibernate-mapping default-access="field" auto-import="true" package="org.nuiton.topia.it.legacy.topiatest">
+ <class name="org.nuiton.topia.it.legacy.topiatest.persistence.Entity1Impl" table="entity1" node="org.nuiton.topia.it.legacy.topiatest.persistence.Entity1Impl" abstract="false" proxy="org.nuiton.topia.it.legacy.topiatest.persistence.Entity1" >
+ <id name="topiaId" type="string" length="255" node="@topiaId"/>
+ <version name="topiaVersion" type="long" node="@topiaVersion"/>
+ <property name="topiaCreateDate" type="timestamp" node="@topiaCreateDate"/>
+ <property name="attr1" type="java.lang.String" access="field" column="attr1" node="attr1"/>
+ <property name="attr2" type="java.lang.String" access="field" column="attr2" node="attr2"/>
+ </class>
+</hibernate-mapping>
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Impl.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1Impl.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Impl.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Impl.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,37 @@
+/*
+ * #%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%
+ */
+package org.nuiton.topia.it.legacy.topiatest.persistence;
+
+import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.persistence.EntityVisitor;
+
+/**
+ * Created: 11 mai 2010
+ *
+ * @author fdesbois <fdesbois(a)codelutin.com>
+ * @version $Id$
+ */
+public class Entity1Impl extends Entity1Abstract {
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/package-info.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/package-info.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/package-info.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/package-info.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,28 @@
+/*
+ * #%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%
+ */
+/**
+ * Contains persistent entities for Tests.
+ */
+package org.nuiton.topiatest.persistence;
\ No newline at end of file
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/FakeService.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topiatest/service/FakeService.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/FakeService.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/FakeService.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,63 @@
+/*
+ * #%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%
+ */
+package org.nuiton.topia.it.legacy.topiatest.service;
+
+import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.framework.TopiaContextImplTest;
+import org.nuiton.topia.framework.TopiaService;
+
+/**
+ * FakeService which implements {@link TopiaService} to test existing service
+ * from {@link TopiaContextImplTest#testGetServices()}. This fake service
+ * doesn't contains property SERVICE_NAME used by {@link
+ * org.nuiton.topia.framework.AbstractTopiaContext#serviceEnabled(Class)}.
+ * <p/>
+ * Created: 10 mai 2010
+ *
+ * @author fdesbois <fdesbois(a)codelutin.com>
+ * @version $Id$
+ */
+public class FakeService implements TopiaService {
+
+ @Override
+ public String getServiceName() {
+ return "fake";
+ }
+
+ @Override
+ public Class<?>[] getPersistenceClasses() {
+ return new Class<?>[0];
+ }
+
+ @Override
+ public boolean preInit(TopiaContext context) {
+ return true;
+ }
+
+ @Override
+ public boolean postInit(TopiaContext context) {
+ return true;
+ }
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/TestService.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topiatest/service/TestService.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/TestService.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/TestService.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,66 @@
+/*
+ * #%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%
+ */
+package org.nuiton.topia.it.legacy.topiatest.service;
+
+import org.junit.Ignore;
+import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.framework.TopiaContextImplTest;
+import org.nuiton.topia.framework.TopiaService;
+
+/**
+ * TestService which implements {@link TopiaService} to test loading from {@link
+ * TopiaContextImplTest#testLoadServices()}.
+ * <p/>
+ * Created: 10 mai 2010
+ *
+ * @author fdesbois <fdesbois(a)codelutin.com>
+ * @version $Id$
+ */
+@Ignore
+public class TestService implements TopiaService {
+
+ /** Needed field to use {@link TopiaContext#serviceEnabled(Class)} * */
+ public static final String SERVICE_NAME = "test";
+
+ @Override
+ public String getServiceName() {
+ return SERVICE_NAME;
+ }
+
+ @Override
+ public Class<?>[] getPersistenceClasses() {
+ return new Class<?>[0];
+ }
+
+ @Override
+ public boolean preInit(TopiaContext context) {
+ return true;
+ }
+
+ @Override
+ public boolean postInit(TopiaContext context) {
+ return true;
+ }
+}
Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/package-info.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topiatest/service/package-info.java)
===================================================================
--- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/package-info.java (rev 0)
+++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/package-info.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,29 @@
+/*
+ * #%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%
+ */
+/**
+ * This package contains classes which implements {@link
+ * org.nuiton.topia.framework.TopiaService} to test services API.
+ */
+package org.nuiton.topia.it.legacy.topiatest.service;
\ No newline at end of file
Copied: trunk/topia-it/src/test/resources/TopiaConnectionProviderHardcoded.properties (from rev 2882, trunk/topia-persistence/src/test/resources/TopiaConnectionProviderHardcoded.properties)
===================================================================
--- trunk/topia-it/src/test/resources/TopiaConnectionProviderHardcoded.properties (rev 0)
+++ trunk/topia-it/src/test/resources/TopiaConnectionProviderHardcoded.properties 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,35 @@
+###
+# #%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%
+###
+# Proprietes par defaut pour une base de donnees de type H2
+hibernate.hbm2ddl.auto=update
+hibernate.show_sql=false
+
+hibernate.dialect=org.hibernate.dialect.H2Dialect
+hibernate.connection.username=sa
+hibernate.connection.password=
+hibernate.connection.driver_class=org.h2.Driver
+hibernate.connection.provider_class=org.nuiton.topia.it.legacy.framework.TopiaConnectionProviderHardCoded
+# tchemit 2010-11-28 : comment this line, each test must define his own db path
+#hibernate.connection.url=jdbc:h2:file:target/surefire-workdir/h2data
\ No newline at end of file
Copied: trunk/topia-it/src/test/resources/TopiaContextImpl.properties (from rev 2882, trunk/topia-persistence/src/test/resources/TopiaContextImpl.properties)
===================================================================
--- trunk/topia-it/src/test/resources/TopiaContextImpl.properties (rev 0)
+++ trunk/topia-it/src/test/resources/TopiaContextImpl.properties 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,34 @@
+###
+# #%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%
+###
+# Proprietes par defaut pour une base de donnees de type H2
+hibernate.hbm2ddl.auto=update
+hibernate.show_sql=false
+
+hibernate.dialect=org.hibernate.dialect.H2Dialect
+hibernate.connection.username=sa
+hibernate.connection.password=
+hibernate.connection.driver_class=org.h2.Driver
+# tchemit 2010-11-28 : comment this line, each test must define his own db path
+#hibernate.connection.url=jdbc:h2:file:target/surefire-workdir/h2data
\ No newline at end of file
Copied: trunk/topia-it/src/test/resources/log4j.properties (from rev 2882, trunk/topia-persistence/src/test/resources/log4j.properties)
===================================================================
--- trunk/topia-it/src/test/resources/log4j.properties (rev 0)
+++ trunk/topia-it/src/test/resources/log4j.properties 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,36 @@
+###
+# #%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%
+###
+#\u00a0This log is used to display trace in generation
+
+# Global logging configuration
+log4j.rootLogger=WARN, stdout
+# Console output...
+log4j.appender.stdout=org.apache.log4j.ConsoleAppender
+log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
+log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) %M - %m%n
+# package level
+log4j.logger.org.nuiton.topia=INFO
+#log4j.logger.org.nuiton.topiatest=DEBUG
+log4j.logger.org.nuiton.topia.persistence.util=INFO
Property changes on: trunk/topia-junit
___________________________________________________________________
Added: svn:ignore
+ target
*.ipr
*.iws
*.iml
.idea
Property changes on: trunk/topia-junit/LICENSE.txt
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision
Added: svn:eol-style
+ native
Property changes on: trunk/topia-junit/README.txt
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision
Added: svn:eol-style
+ native
Added: trunk/topia-junit/pom.xml
===================================================================
--- trunk/topia-junit/pom.xml (rev 0)
+++ trunk/topia-junit/pom.xml 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,112 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ #%L
+ ToPIA :: Persistence
+
+ $Id$
+ $HeadURL: http://svn.nuiton.org/svn/topia/trunk/topia-persistence/pom.xml $
+ %%
+ 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-junit</artifactId>
+ <packaging>jar</packaging>
+
+ <name>ToPIA :: JUnit</name>
+ <description>JUnit</description>
+
+ <dependencies>
+
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>topia-persistence</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.nuiton</groupId>
+ <artifactId>nuiton-utils</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>commons-collections</groupId>
+ <artifactId>commons-collections</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>commons-logging</groupId>
+ <artifactId>commons-logging</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>commons-io</groupId>
+ <artifactId>commons-io</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-lang3</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.hibernate</groupId>
+ <artifactId>hibernate-core</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.hibernate</groupId>
+ <artifactId>hibernate-ehcache</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-log4j12</artifactId>
+ </dependency>
+
+ <!-- BD H2 for testing -->
+ <dependency>
+ <groupId>com.h2database</groupId>
+ <artifactId>h2</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>compile</scope>
+ </dependency>
+
+
+ </dependencies>
+
+ <build>
+
+ <plugins>
+
+ </plugins>
+ </build>
+
+</project>
Property changes on: trunk/topia-junit/pom.xml
___________________________________________________________________
Added: svn:mime-type
+ text/xml
Added: svn:keywords
+ Author Date Id Revision
Added: svn:eol-style
+ native
Modified: trunk/topia-persistence/pom.xml
===================================================================
--- trunk/topia-persistence/pom.xml 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/pom.xml 2013-11-22 18:03:47 UTC (rev 2884)
@@ -64,16 +64,6 @@
</dependency>
<dependency>
- <groupId>org.nuiton.eugene</groupId>
- <artifactId>eugene</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.nuiton.eugene</groupId>
- <artifactId>eugene-java-templates</artifactId>
- </dependency>
-
- <dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
@@ -147,141 +137,12 @@
</dependencies>
<build>
- <testResources>
- <testResource>
- <directory>${maven.gen.dir}/test-java</directory>
- <includes>
- <include>**/*.hbm.xml</include>
- </includes>
- </testResource>
-
- <testResource>
- <directory>${maven.src.dir}/test/resources</directory>
- <includes>
- <include>**/*.properties</include>
- </includes>
- </testResource>
-
- <testResource>
- <directory>${maven.src.dir}/test/java</directory>
- <includes>
- <include>**/*.hbm.xml</include>
- </includes>
- </testResource>
-
- </testResources>
- <plugins>
-
- <plugin>
- <groupId>org.nuiton.processor</groupId>
- <artifactId>processor-maven-plugin</artifactId>
- </plugin>
-
- <!-- expose new plexus components -->
- <plugin>
- <groupId>org.codehaus.plexus</groupId>
- <artifactId>plexus-component-metadata</artifactId>
- <executions>
- <execution>
- <goals>
- <goal>generate-metadata</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
-
- <plugin>
- <groupId>org.nuiton.eugene</groupId>
- <artifactId>eugene-maven-plugin</artifactId>
- <configuration>
-
- </configuration>
- <executions>
- <execution>
- <id>Test Generator</id>
- <phase>generate-test-sources</phase>
- <configuration>
- <testPhase>true</testPhase>
- <templates>
- org.nuiton.topia.generator.TopiaMetaTransformer,
- org.nuiton.eugene.java.JavaInterfaceTransformer,
- org.nuiton.eugene.java.JavaBeanTransformer,
- org.nuiton.topia.generator.EntityDTOTransformer,
- org.nuiton.topia.generator.BinderHelperTransformer
- </templates>
- <fullPackagePath>org.nuiton.topia</fullPackagePath>
- <defaultPackage>org.nuiton.topia</defaultPackage>
- </configuration>
- <goals>
- <goal>generate</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
-
- <!-- expose tests -->
- <plugin>
- <artifactId>maven-jar-plugin</artifactId>
- <executions>
- <execution>
- <id>attach-test</id>
- <goals>
- <goal>test-jar</goal>
- </goals>
- </execution>
- </executions>
-
- </plugin>
- </plugins>
</build>
<profiles>
- <!-- perform only on a release stage when using the maven-release-plugin -->
<profile>
- <id>release-profile</id>
- <activation>
- <property>
- <name>performRelease</name>
- <value>true</value>
- </property>
- </activation>
-
- <build>
- <plugins>
-
- <!-- always expose tests source jar -->
- <plugin>
- <artifactId>maven-source-plugin</artifactId>
- <executions>
- <execution>
- <id>attach-test-sources</id>
- <goals>
- <goal>test-jar</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
-
- <!-- always expose tests javadoc jar -->
- <plugin>
- <artifactId>maven-javadoc-plugin</artifactId>
- <executions>
- <execution>
- <id>attach-test-javadoc</id>
- <goals>
- <goal>test-jar</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
-
- </plugins>
- </build>
- </profile>
-
- <profile>
<id>run-its</id>
<activation>
<property>
@@ -333,12 +194,6 @@
<reporting>
<plugins>
<plugin>
- <groupId>org.codehaus.plexus</groupId>
- <artifactId>plexus-maven-plugin</artifactId>
- <version>${plexusPluginVersion}</version>
- </plugin>
-
- <plugin>
<artifactId>maven-invoker-plugin</artifactId>
<version>${invokerPluginVersion}</version>
</plugin>
Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/ApplicationContextTransformer.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/ApplicationContextTransformer.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/ApplicationContextTransformer.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,294 +0,0 @@
-package org.nuiton.topia.generator;
-
-/*
- * #%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%
- */
-
-/*{generator option: parentheses = false}*/
-
-/*{generator option: writeString = +}*/
-
-import org.nuiton.eugene.java.ObjectModelTransformerToJava;
-import org.nuiton.eugene.models.object.ObjectModel;
-import org.nuiton.eugene.models.object.ObjectModelClass;
-import org.nuiton.eugene.models.object.ObjectModelJavaModifier;
-import org.nuiton.eugene.models.object.ObjectModelOperation;
-import org.nuiton.topia.AbstractTopiaApplicationContext;
-import org.nuiton.topia.persistence.TopiaEntity;
-import org.nuiton.topia.persistence.util.EntityOperator;
-import org.nuiton.topia.persistence.util.EntityOperatorStore;
-
-import java.lang.reflect.Array;
-import java.util.List;
-import java.util.Properties;
-
-/**
- * To generate PersistenceHelper
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.generator.ApplicationContextTransformer"
- * @since 3.0
- */
-public class ApplicationContextTransformer extends ObjectModelTransformerToJava {
-
- @Override
- public void transformFromModel(ObjectModel input) {
-
- String packageName = TopiaGeneratorUtil.getApplicationContextPackage(this, model);
-
- String applicationContextAbstractName = TopiaGeneratorUtil.getApplicationContextAbstractName(model);
-
- String applicationContextConcreteName = TopiaGeneratorUtil.getApplicationContextConcreteName(model);
-
- boolean generateAbstract = !isInClassPath(packageName, applicationContextAbstractName);
-
- boolean generateConcrete = !isInClassPath(packageName, applicationContextConcreteName);
-
-
- if (generateAbstract) {
-
- generateAbstract(packageName,
- applicationContextAbstractName);
- }
-
- if (generateConcrete) {
-
- generateImpl(packageName,
- applicationContextAbstractName,
- applicationContextConcreteName);
- }
-
- }
-
- protected void generateAbstract(String packageName,
- String className) {
-
- // try to find a super class by tag-value
-// String superClass = TopiaGeneratorUtil.getPersistenceContextSuperClassTagValue(model);
- String superClass = null;
-
- if (superClass == null) {
-
- // no super-class, use default one
- superClass = AbstractTopiaApplicationContext.class.getName();
- }
-
- ObjectModelClass output = createAbstractClass(className, packageName);
-
- String persistenceContextConcreteName = TopiaGeneratorUtil.getPersistenceContextConcreteName(model);
- setSuperClass(output, superClass + "<" + persistenceContextConcreteName + ">");
-
- // detect if there is a contract to set on abstract
- String contractName = TopiaGeneratorUtil.getPersistenceContextInterfaceName(model);
-
-// addInterface(output, TopiaPersistenceContext.class);
-
- boolean addPersistenceContextContract = isInClassPath(packageName, contractName);
-
- if (addPersistenceContextContract) {
- addInterface(output, packageName + "." + contractName);
- }
-
- String modelName = model.getName();
- String daoHelperClazzName = modelName + "DAOHelper";
-
- String entityEnumName = modelName + "EntityEnum";
-
- List<ObjectModelClass> entityClasses =
- TopiaGeneratorUtil.getEntityClasses(model, true);
-
- boolean generateOperator =
- TopiaGeneratorUtil.shouldGenerateOperatorForDAOHelper(model);
-
- boolean generateStandaloneEnum =
- TopiaGeneratorUtil.shouldGenerateStandaloneEnumForDAOHelper(model);
-
- if (!generateStandaloneEnum) {
-
- addImport(output, packageName + "." + daoHelperClazzName + "." + entityEnumName);
-
- }
-
- addImport(output, TopiaEntity.class);
- addImport(output, Array.class);
- addImport(output, Array.class);
-
- if (generateOperator) {
- addImport(output, EntityOperator.class);
- addImport(output, EntityOperatorStore.class);
- }
-
- // add public constructor
- ObjectModelOperation constructor = addConstructor(
- output,
- ObjectModelJavaModifier.PUBLIC);
- addParameter(constructor, Properties.class, "properties");
- setOperationBody(constructor, ""
-/*{
- super(properties);
- }*/
- );
-
- constructor = addConstructor(
- output,
- ObjectModelJavaModifier.PUBLIC);
- addParameter(constructor, "java.util.Map<String, String>", "configuration");
- setOperationBody(constructor, ""
-/*{
- super(configuration);
- }*/
- );
-
- ObjectModelOperation op;
-
- // getModelVersion method
- op = addOperation(output, "newPersistenceContext", persistenceContextConcreteName, ObjectModelJavaModifier.PUBLIC);
- addAnnotation(output, op, Override.class);
- setOperationBody(op, ""
-/*{
- <%=persistenceContextConcreteName%> newContext = new <%=persistenceContextConcreteName%>(
- getHibernateProvider(), getTopiaListenableSupport(), getTopiaIdFactory());
- registerPersistenceContext(newContext);
- return newContext;
- }*/
- );
-
- // getModelVersion method
- String modelVersion = model.getVersion();
- op = addOperation(output, "getModelVersion", "String", ObjectModelJavaModifier.PUBLIC);
- setOperationBody(op, ""
-/*{
- return "<%=modelVersion%>";
- }*/
- );
-
- // getModelName method
- op = addOperation(output, "getModelName", "String", ObjectModelJavaModifier.PUBLIC);
- setOperationBody(op, ""
-/*{
- return "<%=modelName%>";
- }*/
- );
-
- // getContractClass method
- op = addOperation(output, "getContractClass", "<T extends TopiaEntity> Class<T>", ObjectModelJavaModifier.PUBLIC);
- addParameter(op, "Class<T>", "klass");
- setOperationBody(op, ""
-/*{
- <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass);
- return (Class<T>) constant.getContract();
- }*/
- );
-
- // getImplementationClass method
- op = addOperation(output, "getImplementationClass", "<T extends TopiaEntity> Class<T>", ObjectModelJavaModifier.PUBLIC);
- addParameter(op, "Class<T>", "klass");
- setOperationBody(op, ""
-/*{
- <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass);
- return (Class<T>) constant.getImplementation();
- }*/
- );
-
- // getContractClasses method
- op = addOperation(output, "getContractClasses", "Class<? extends TopiaEntity>[]", ObjectModelJavaModifier.PUBLIC);
- setOperationBody(op, ""
-/*{
- <%=entityEnumName%>[] values = <%=entityEnumName%>.values();
- Class<? extends TopiaEntity>[] result = (Class<? extends TopiaEntity>[]) Array.newInstance(Class.class, values.length);
- for (int i = 0; i < values.length; i++) {
- result[i] = values[i].getContract();
- }
- return result;
- }*/
- );
-
- // getImplementationClasses method
- op = addOperation(output, "getImplementationClasses", "Class<? extends TopiaEntity>[]", ObjectModelJavaModifier.PUBLIC);
- setOperationBody(op, ""
-/*{
- <%=entityEnumName%>[] values = <%=entityEnumName%>.values();
- Class<? extends TopiaEntity>[] result = (Class<? extends TopiaEntity>[]) Array.newInstance(Class.class, values.length);
- for (int i = 0; i < values.length; i++) {
- result[i] = values[i].getImplementation();
- }
- return result;
- }*/
- );
-
- // getContracts method
- op = addOperation(output, "getContracts", entityEnumName + "[]", ObjectModelJavaModifier.PUBLIC);
- setOperationBody(op, ""
-/*{
- return <%=entityEnumName%>.values();
- }*/
- );
-
- if (generateOperator) {
- // getOperator method
- op = addOperation(output, "getOperator", "<T extends TopiaEntity> EntityOperator<T>", ObjectModelJavaModifier.PUBLIC);
- addParameter(op, "Class<T>", "klass");
- setOperationBody(op, ""
-/*{
- <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass);
- return EntityOperatorStore.getOperator(constant);
- }*/
- );
- }
-
- }
-
- protected ObjectModelClass generateImpl(String packageName,
- String applicationContextAbstractName,
- String applicationContextConcreteName) {
-
- ObjectModelClass output = createClass(applicationContextConcreteName, packageName);
-
- setSuperClass(output, applicationContextAbstractName);
-
- // add public constructor
- ObjectModelOperation constructor = addConstructor(
- output,
- ObjectModelJavaModifier.PUBLIC);
- addParameter(constructor, Properties.class, "properties");
- setOperationBody(constructor, ""
-/*{
- super(properties);
- }*/
- );
-
- constructor = addConstructor(
- output,
- ObjectModelJavaModifier.PUBLIC);
- addParameter(constructor, "java.util.Map<String, String>", "configuration");
- setOperationBody(constructor, ""
-/*{
- super(configuration);
- }*/
- );
-
- return output;
- }
-
-}
Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/BinderHelperTransformer.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/BinderHelperTransformer.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/BinderHelperTransformer.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,274 +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%
- */
-
-package org.nuiton.topia.generator;
-
-import org.apache.commons.collections.CollectionUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.nuiton.eugene.GeneratorUtil;
-import org.nuiton.eugene.java.ObjectModelTransformerToJava;
-import org.nuiton.eugene.models.object.*;
-import org.nuiton.topia.persistence.TopiaEntity;
-import org.nuiton.topia.persistence.util.TopiaEntityBinder;
-import org.nuiton.topia.persistence.util.TopiaEntityHelper;
-import org.nuiton.util.beans.BinderModelBuilder;
-import org.nuiton.util.beans.BinderFactory;
-
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-
-
-/*{generator option: parentheses = false}*/
-/*{generator option: writeString = +}*/
-
-/**
- * A template to generate a helper for {@link TopiaEntityBinder}.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @version $Id$
- * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.generator.BinderHelperTransformer"
- * @since 2.3.1
- */
-public class BinderHelperTransformer extends ObjectModelTransformerToJava {
-
- private static final Log log =
- LogFactory.getLog(BinderHelperTransformer.class);
-
-
- @Override
- public void transformFromModel(ObjectModel model) {
- ObjectModelClass resultClass;
-
- List<ObjectModelClass> classes = TopiaGeneratorUtil.getEntityClasses(model, true);
-
- if (CollectionUtils.isEmpty(classes)) {
-
- // no entity classes, so no generation
- log.warn("No entity to generate, " + getClass().getName() + " is skipped");
- return;
- }
-
- String packageName = getOutputProperties().getProperty(PROP_DEFAULT_PACKAGE);
- String modelName = model.getName();
- String binderHelperClazzName = modelName + "BinderHelper";
- String daoHelperClazzName = modelName + "DAOHelper";
-
- resultClass = createClass(binderHelperClazzName, packageName);
-
- setSuperClass(resultClass, BinderFactory.class);
-
-
- addImport(resultClass, TopiaEntityBinder.class);
- addImport(resultClass, TopiaEntityHelper.class);
- addImport(resultClass, TopiaEntity.class);
- addImport(resultClass, BinderModelBuilder.class);
-
- ObjectModelOperation op;
-
- op = addOperation(resultClass,
- "getTopiaBinder",
- "<E extends TopiaEntity> TopiaEntityBinder<E>",
- ObjectModelJavaModifier.PUBLIC,
- ObjectModelJavaModifier.STATIC);
- addParameter(op, "Class<E>", "entityClass");
- addParameter(op, "String", "contextName");
- setOperationBody(op, ""
-/*{
- return (TopiaEntityBinder<E>) newBinder(entityClass, entityClass, contextName, TopiaEntityBinder.class);
- }*/
- );
-
- op = addOperation(resultClass,
- "getSimpleTopiaBinder",
- "<E extends TopiaEntity> TopiaEntityBinder<E>",
- ObjectModelJavaModifier.PUBLIC,
- ObjectModelJavaModifier.STATIC);
- addParameter(op, "Class<E>", "entityClass");
- setOperationBody(op, ""
-/*{
- return getTopiaBinder(entityClass, "<%=modelName%>");
- }*/
- );
-
- op = addOperation(resultClass,
- "registerTopiaBinder",
- "void",
- ObjectModelJavaModifier.PUBLIC,
- ObjectModelJavaModifier.STATIC);
- addParameter(op, "BinderModelBuilder", "builder");
- addParameter(op, "String", "contextName");
- setOperationBody(op, ""
-/*{
- registerBinderModel(builder, contextName);
- }*/
- );
-
- op = addOperation(resultClass,
- "registerTopiaBinder",
- "<E extends TopiaEntity> TopiaEntityBinder<E>",
- ObjectModelJavaModifier.PUBLIC,
- ObjectModelJavaModifier.STATIC);
- addParameter(op, "Class<E>", "entityClass");
- addParameter(op, "BinderModelBuilder", "builder");
- addParameter(op, "String", "contextName");
- setOperationBody(op, ""
-/*{
- registerBinderModel(builder, contextName);
- return getTopiaBinder(entityClass, contextName);
- }*/
- );
-
- op = addOperation(resultClass,
- "copy",
- "<E extends TopiaEntity> void",
- ObjectModelJavaModifier.PUBLIC,
- ObjectModelJavaModifier.STATIC);
- addParameter(op, "String", "contextName");
- addParameter(op, "E", "source");
- addParameter(op, "E", "target");
- addParameter(op, "boolean", "tech");
- setOperationBody(op, ""
-/*{
- Class<E> entityClass = (Class<E>) TopiaEntityHelper.getContractClass(<%=daoHelperClazzName%>.getContracts(), target.getClass());
- TopiaEntityBinder<E> binder = getTopiaBinder(entityClass, contextName);
- if (binder == null) {
- throw new NullPointerException("could not find a simple topia binder of type : " + target.getClass());
- }
- binder.load(source, target, tech);
- }*/
- );
-
- op = addOperation(resultClass,
- "simpleCopy",
- "<E extends TopiaEntity> void",
- ObjectModelJavaModifier.PUBLIC,
- ObjectModelJavaModifier.STATIC);
- addParameter(op, "E", "source");
- addParameter(op, "E", "target");
- addParameter(op, "boolean", "tech");
- setOperationBody(op, ""
-/*{
- Class<E> entityClass = (Class<E>) TopiaEntityHelper.getContractClass(<%=daoHelperClazzName%>.getContracts(), target.getClass());
- TopiaEntityBinder<E> binder = getSimpleTopiaBinder(entityClass);
- if (binder == null) {
- throw new NullPointerException("could not find a simple topia binder of type : " + target.getClass());
- }
- binder.load(source, target, tech);
- }*/
- );
-
- StringBuilder initCode = new StringBuilder();
-
- for (ObjectModelClass clazz : classes) {
-
- String prefix = getConstantPrefix(clazz, "");
-
- if (StringUtils.isEmpty(prefix)) {
-
- // no specific prefix, so no prefix
- if (log.isWarnEnabled()) {
- log.warn("[" + clazz.getName() + "] Will generate constants with NO prefix, not a good idea...");
- }
- }
-
- setConstantPrefix(prefix);
-
- generateBinder(modelName, clazz, resultClass, initCode);
-
- }
-
- op = addOperation(resultClass, "initBinders", "void", ObjectModelJavaModifier.PROTECTED, ObjectModelJavaModifier.STATIC);
- setOperationBody(op, initCode.toString());
-
- op = addOperation(resultClass, null, (String) null, ObjectModelJavaModifier.STATIC);
- setOperationBody(op, ""
- /*{
- initBinders();
-}*/
- );
- }
-
- protected void generateBinder(String modelName,
- ObjectModelClass clazz,
- ObjectModelClass resultClass,
- StringBuilder initCode) {
-
- List<ObjectModelAttribute> list = new ArrayList<ObjectModelAttribute>();
- for (ObjectModelAttribute attr : clazz.getAttributes()) {
- if (!attr.isNavigable()) {
- continue;
- }
-
- if (GeneratorUtil.isNMultiplicity(attr)) {
- // not dealing with association
- continue;
- }
-
- list.add(attr);
- }
-
- String clazzName = clazz.getName();
-
- if (list.isEmpty()) {
- // no attribute, do nothing
- if (log.isDebugEnabled()) {
- log.debug("no attribute to add in a binder for " + clazzName +
- ", will not generate it.");
- }
- return;
- }
-
- if (log.isDebugEnabled()) {
- log.debug("generate simple binder for " + clazzName);
- }
- addImport(resultClass, clazz);
- initCode.append(""
-/*{
- BinderModelBuilder<<%=clazzName%>, <%=clazzName%>> builder<%=clazzName%> =
- BinderModelBuilder.newEmptyBuilder(<%=clazzName%>.class);
- builder<%=clazzName%>.addSimpleProperties(
-}*/
- );
- Iterator<ObjectModelAttribute> itr = list.iterator();
- while (itr.hasNext()) {
- ObjectModelAttribute attr = itr.next();
- String attrName = attr.getName();
- boolean hasNext = itr.hasNext();
- initCode.append(""
-/*{ <%=clazzName%>.<%=getConstantName(attrName)%><%=(hasNext?",\n":"")%>}*/
- );
- }
- initCode.append(""
-/*{
- );
- registerTopiaBinder(builder<%=clazzName%>, "<%=modelName%>");
- }*/
- );
- }
-}
-
Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DAOHelperTransformer.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DAOHelperTransformer.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DAOHelperTransformer.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,526 +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%
- */
-
-package org.nuiton.topia.generator;
-
-import org.apache.commons.lang3.ArrayUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.nuiton.eugene.java.ObjectModelTransformerToJava;
-import org.nuiton.eugene.models.object.ObjectModel;
-import org.nuiton.eugene.models.object.ObjectModelAttribute;
-import org.nuiton.eugene.models.object.ObjectModelClass;
-import org.nuiton.eugene.models.object.ObjectModelEnumeration;
-import org.nuiton.eugene.models.object.ObjectModelJavaModifier;
-import org.nuiton.eugene.models.object.ObjectModelOperation;
-import org.nuiton.eugene.models.object.ObjectModelType;
-import org.nuiton.eugene.models.object.xml.ObjectModelAttributeImpl;
-import org.nuiton.eugene.models.object.xml.ObjectModelEnumerationImpl;
-import org.nuiton.topia.TopiaContext;
-import org.nuiton.topia.TopiaDaoSupplier;
-import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.persistence.TopiaDAO;
-import org.nuiton.topia.persistence.TopiaEntity;
-import org.nuiton.topia.persistence.TopiaEntityEnum;
-import org.nuiton.topia.persistence.util.EntityOperator;
-import org.nuiton.topia.persistence.util.EntityOperatorStore;
-
-import java.lang.reflect.Array;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Set;
-
-
-/*{generator option: parentheses = false}*/
-
-/*{generator option: writeString = +}*/
-
-/**
- * Created: 13 nov. 2009 09:05:17
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @version $Id$
- * @since 2.3.0
- * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.generator.DAOHelperTransformer"
- */
-public class DAOHelperTransformer extends ObjectModelTransformerToJava {
-
- private static final Log log =
- LogFactory.getLog(DAOHelperTransformer.class);
-
- @Override
- public void transformFromModel(ObjectModel model) {
- String packageName =
- getOutputProperties().getProperty(PROP_DEFAULT_PACKAGE);
- String modelName = model.getName();
- String daoHelperClazzName = modelName + "DAOHelper";
- String entityEnumName = modelName + "EntityEnum";
-
- List<ObjectModelClass> classes =
- TopiaGeneratorUtil.getEntityClasses(model, true);
-
- boolean generateOperator =
- TopiaGeneratorUtil.shouldGenerateOperatorForDAOHelper(model);
-
- boolean generateStandaloneEnum =
- TopiaGeneratorUtil.shouldGenerateStandaloneEnumForDAOHelper(model);
-
- ObjectModelClass daoHelper = createClass(daoHelperClazzName,
- packageName);
-
- ObjectModelEnumeration entityEnum;
-
- if (generateStandaloneEnum) {
- if (log.isDebugEnabled()) {
- log.debug("Will generate standalone " + entityEnumName +
- " in package " + packageName);
- }
- entityEnum = createEnumeration(entityEnumName, packageName);
- addImport(entityEnum, TopiaEntity.class);
- addImport(entityEnum, EntityOperatorStore.class);
- addImport(entityEnum, Arrays.class);
- addImport(entityEnum, ArrayUtils.class);
-
- } else {
- entityEnum = (ObjectModelEnumerationImpl)
- addInnerClassifier(daoHelper,
- ObjectModelType.OBJECT_MODEL_ENUMERATION,
- entityEnumName
- );
- addImport(daoHelper, TopiaEntityEnum.class);
- addImport(daoHelper, EntityOperatorStore.class);
- addImport(daoHelper, Arrays.class);
- addImport(daoHelper, ArrayUtils.class);
- }
-
- // generate DAOHelper
- createDAOHelper(model,
- daoHelper,
- daoHelperClazzName,
- entityEnumName,
- generateOperator,
- classes
- );
-
- // generate TopiaEntityEnum
- createEntityEnum(entityEnum,
- daoHelperClazzName,
- entityEnumName,
- generateOperator,
- generateStandaloneEnum,
- classes
- );
- }
-
- protected void createDAOHelper(ObjectModel model,
- ObjectModelClass daoHelper,
- String daoHelperClazzName,
- String entityEnumName,
- boolean generateOperator,
- List<ObjectModelClass> classes) {
-
- String modelName = model.getName();
- String modelVersion = model.getVersion();
-
- addImport(daoHelper, TopiaDAO.class);
- addImport(daoHelper, TopiaEntity.class);
- addImport(daoHelper, TopiaContext.class);
- addImport(daoHelper, Array.class);
-
- if (generateOperator) {
- addImport(daoHelper,EntityOperator.class);
- addImport(daoHelper, EntityOperatorStore.class);
- }
-
- addAnnotation(daoHelper, daoHelper, Deprecated.class);
-
- // add non public constructor
- ObjectModelOperation constructor =
- addConstructor(daoHelper, ObjectModelJavaModifier.PROTECTED);
- setOperationBody(constructor," ");
-
- ObjectModelOperation op;
-
- // getModelVersion method
- op = addOperation(daoHelper, "getModelVersion", "String", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
- setOperationBody(op, ""
-/*{
- return "<%=modelVersion%>";
- }*/
- );
-
- // getModelName method
- op = addOperation(daoHelper, "getModelName", "String", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
- setOperationBody(op, ""
-/*{
- return "<%=modelName%>";
- }*/
- );
-
-
- for (ObjectModelClass clazz : classes) {
- String clazzName = clazz.getName();
- String daoClazzName = clazzName + "DAO";
-
- // specialized getXXXDao method
- op = addOperation(daoHelper, "get" + daoClazzName, clazz.getPackageName() + '.' + daoClazzName, ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
- addParameter(op, TopiaDaoSupplier.class, "supplier");
- addImport(daoHelper, clazz);
- addException(op, TopiaException.class);
- setOperationBody(op, ""
-/*{
- <%=daoClazzName%> result = supplier.getDao(<%=clazzName%>.class, <%=daoClazzName%>.class);
- return result;
- }*/
- );
-
- }
-
- // obsolete generic getDAO method
- op = addOperation(daoHelper, "getDAO", "<T extends TopiaEntity, D extends TopiaDAO<? super T>> D", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
- addParameter(op, TopiaContext.class, "context");
- addParameter(op, "Class<T>", "klass");
- addException(op, TopiaException.class);
- addAnnotation(daoHelper, op, Deprecated.class);
- setOperationBody(op, ""
-/*{
- D dao = getDao(context, klass);
- return dao;
- }*/
- );
-
- // generic getDao method
- op = addOperation(daoHelper, "getDao", "<T extends TopiaEntity, D extends TopiaDAO<? super T>> D", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
- addParameter(op, TopiaContext.class, "context");
- addParameter(op, "Class<T>", "klass");
- addException(op, TopiaException.class);
- setOperationBody(op, ""
-/*{
- <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass);
- D dao = (D) context.getDao(constant.getContract());
- return dao;
- }*/
- );
-
- op = addOperation(daoHelper, "getDao", "<T extends TopiaEntity, D extends TopiaDAO<? super T>> D", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
- addParameter(op, TopiaContext.class, "context");
- addParameter(op, "T", "entity");
- addException(op, TopiaException.class);
- setOperationBody(op, ""
-/*{
- <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(entity);
- D dao = (D) context.getDao(constant.getContract());
- return dao;
- }*/
- );
-
- // getContractClass method
- op = addOperation(daoHelper, "getContractClass", "<T extends TopiaEntity> Class<T>", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
- addParameter(op, "Class<T>", "klass");
- setOperationBody(op, ""
-/*{
- <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass);
- return (Class<T>) constant.getContract();
- }*/
- );
-
- // getImplementationClass method
- op = addOperation(daoHelper, "getImplementationClass", "<T extends TopiaEntity> Class<T>", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
- addParameter(op, "Class<T>", "klass");
- setOperationBody(op, ""
-/*{
- <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass);
- return (Class<T>) constant.getImplementation();
- }*/
- );
-
- // getContractClasses method
- op = addOperation(daoHelper, "getContractClasses", "Class<? extends TopiaEntity>[]", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
- setOperationBody(op, ""
-/*{
- <%=entityEnumName%>[] values = <%=entityEnumName%>.values();
- Class<? extends TopiaEntity>[] result = (Class<? extends TopiaEntity>[]) Array.newInstance(Class.class, values.length);
- for (int i = 0; i < values.length; i++) {
- result[i] = values[i].getContract();
- }
- return result;
- }*/
- );
-
- // getImplementationClasses method
- op = addOperation(daoHelper, "getImplementationClasses", "Class<? extends TopiaEntity>[]", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
- setOperationBody(op, ""
-/*{
- <%=entityEnumName%>[] values = <%=entityEnumName%>.values();
- Class<? extends TopiaEntity>[] result = (Class<? extends TopiaEntity>[]) Array.newInstance(Class.class, values.length);
- for (int i = 0; i < values.length; i++) {
- result[i] = values[i].getImplementation();
- }
- return result;
- }*/
- );
-
- // getImplementationClassesAsString method
- op = addOperation(daoHelper, "getImplementationClassesAsString", "String", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
- setOperationBody(op, ""
-/*{
- StringBuilder buffer = new StringBuilder();
- for (Class<? extends TopiaEntity> aClass : getImplementationClasses()) {
- buffer.append(',').append(aClass.getName());
- }
- return buffer.substring(1);
- }*/
- );
-
- // getContracts method
- op = addOperation(daoHelper, "getContracts", entityEnumName+"[]", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
- setOperationBody(op, ""
-/*{
- return <%=entityEnumName%>.values();
- }*/
- );
-
- if (generateOperator) {
- // getOperator method
- op = addOperation(daoHelper, "getOperator", "<T extends TopiaEntity> EntityOperator<T>", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
- addParameter(op,"Class<T>","klass");
- setOperationBody(op, ""
-/*{
- <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass);
- return EntityOperatorStore.getOperator(constant);
- }*/
- );
- }
- }
-
- protected void createEntityEnum(ObjectModelEnumeration entityEnum,
- String daoHelperClazzName,
- String entityEnumName,
- boolean generateOperator,
- boolean generateStandaloneEnum,
- List<ObjectModelClass> classes) {
-
- ObjectModelAttributeImpl attr;
- ObjectModelOperation op;
-
- addInterface(entityEnum, TopiaEntityEnum.class);
-
- for (ObjectModelClass clazz : classes) {
- String clazzName = clazz.getName();
-
- boolean withNatural = false;
- boolean withNotNull = false;
- StringBuilder naturalIdsParams = new StringBuilder();
- StringBuilder notNullParams = new StringBuilder();
-
- Set<ObjectModelAttribute> naturalIdsAttributes = TopiaGeneratorUtil.getNaturalIdAttributes(clazz);
- for (ObjectModelAttribute attribute: naturalIdsAttributes) {
- withNatural = true;
- // attribut metier
- naturalIdsParams.append(", \"").append(attribute.getName()).append("\"");
- }
- Set<ObjectModelAttribute> notNullIdsAttributes = TopiaGeneratorUtil.getNotNullAttributes(clazz);
- for (ObjectModelAttribute attribute : notNullIdsAttributes) {
- withNotNull = true;
- // attribut not-null
- notNullParams.append(", \"").append(attribute.getName()).append("\"");
- }
-
- StringBuilder params = new StringBuilder(clazzName + ".class");
- if (withNotNull) {
- params.append(", new String[]{ " + notNullParams.substring(2) + " }");
- } else {
- params.append(", ArrayUtils.EMPTY_STRING_ARRAY");
- }
- if (withNatural) {
- params.append(", ").append(naturalIdsParams.substring(2));
- }
- addLiteral(entityEnum, clazzName + '(' + params.toString() + ')');
-
- if (generateStandaloneEnum) {
- addImport(entityEnum, clazz);
- }
- }
-
- attr = (ObjectModelAttributeImpl) addAttribute(entityEnum, "contract", "Class<? extends TopiaEntity>");
- attr.setDocumentation("The contract of the entity.");
-
- attr = (ObjectModelAttributeImpl) addAttribute(entityEnum, "implementationFQN", "String");
- attr.setDocumentation("The fully qualified name of the implementation of the entity.");
-
- attr = (ObjectModelAttributeImpl) addAttribute(entityEnum, "implementation", "Class<? extends TopiaEntity>");
- attr.setDocumentation("The implementation class of the entity (will be lazy computed at runtime).");
-
- attr = (ObjectModelAttributeImpl) addAttribute(entityEnum, "naturalIds", "String[]");
- attr.setDocumentation("The array of property involved in the natural key of the entity.");
-
- attr = (ObjectModelAttributeImpl) addAttribute(entityEnum, "notNulls", "String[]");
- attr.setDocumentation("The array of not null properties of the entity.");
-
- // constructor
- op = addConstructor(entityEnum, ObjectModelJavaModifier.PACKAGE);
- addParameter(op,"Class<? extends TopiaEntity >","contract");
- addParameter(op,"String[]","notNulls");
- addParameter(op,"String...","naturalIds");
- setOperationBody(op, ""
-/*{
- this.contract = contract;
- this.notNulls = Arrays.copyOf(notNulls, notNulls.length);
- this.naturalIds = naturalIds;
- implementationFQN = contract.getName() + "Impl";
- }*/
- );
-
- // getContract method
- op = addOperation(entityEnum, "getContract", "Class<? extends TopiaEntity>", ObjectModelJavaModifier.PUBLIC);
- addAnnotation(entityEnum,op,Override.class);
- setOperationBody(op, ""
-/*{
- return contract;
- }*/
- );
-
- // getNaturalIds method
- op = addOperation(entityEnum, "getNaturalIds", "String[]", ObjectModelJavaModifier.PUBLIC);
- addAnnotation(entityEnum,op,Override.class);
- setOperationBody(op, ""
-/*{
- return naturalIds;
- }*/
- );
-
- // isUseNaturalIds method
- op = addOperation(entityEnum, "isUseNaturalIds", "boolean", ObjectModelJavaModifier.PUBLIC);
- addAnnotation(entityEnum,op,Override.class);
- setOperationBody(op, ""
-/*{
- return naturalIds.length > 0;
- }*/
- );
-
- // getNotNulls method
- op = addOperation(entityEnum, "getNotNulls", "String[]", ObjectModelJavaModifier.PUBLIC);
- addAnnotation(entityEnum,op,Override.class);
- setOperationBody(op, ""
-/*{
- return notNulls;
- }*/
- );
-
- // isUseNotNulls method
- op = addOperation(entityEnum, "isUseNotNulls", "boolean", ObjectModelJavaModifier.PUBLIC);
- addAnnotation(entityEnum,op,Override.class);
- setOperationBody(op, ""
-/*{
- return notNulls.length > 0;
- }*/
- );
-
- // getImplementationFQN method
- op = addOperation(entityEnum, "getImplementationFQN","String",ObjectModelJavaModifier.PUBLIC);
- addAnnotation(entityEnum, op, Override.class);
- setOperationBody(op, ""
-/*{
- return implementationFQN;
- }*/
- );
-
- // setImplementationFQN method
- op = addOperation(entityEnum, "setImplementationFQN","void",ObjectModelJavaModifier.PUBLIC);
- addAnnotation(entityEnum,op,Override.class);
- addParameter(op,"String","implementationFQN");
- if (generateOperator) {
- setOperationBody(op, ""
-/*{
- this.implementationFQN = implementationFQN;
- implementation = null;
- // reinit the operators store
- EntityOperatorStore.clear();
- }*/
- );
- } else {
- setOperationBody(op, ""
-/*{
- this.implementationFQN = implementationFQN;
- this.implementation = null;
- }*/
- );
- }
-
- // accept method
- op = addOperation(entityEnum, "accept","boolean",ObjectModelJavaModifier.PUBLIC);
- addAnnotation(entityEnum,op,Override.class);
- addParameter(op,"Class<? extends TopiaEntity>","klass");
- setOperationBody(op, ""
-/*{
- return <%=daoHelperClazzName%>.getContractClass(klass) == contract;
- }*/
- );
-
- // getImplementation method
- op = addOperation(entityEnum, "getImplementation","Class<? extends TopiaEntity>",ObjectModelJavaModifier.PUBLIC);
- addAnnotation(entityEnum,op,Override.class);
- addImport(entityEnum, TopiaException.class);
- setOperationBody(op, ""
-/*{
- if (implementation == null) {
- try {
- implementation = (Class<? extends TopiaEntity>) Class.forName(implementationFQN);
- } catch (ClassNotFoundException e) {
- throw new TopiaException("could not find class " + implementationFQN, e);
- }
- }
- return implementation;
- }*/
- );
-
- // valueOf method
- op = addOperation(entityEnum, "valueOf", entityEnumName, ObjectModelJavaModifier.PUBLIC,ObjectModelJavaModifier.STATIC);
- addParameter(op,"TopiaEntity", "entity");
- setOperationBody(op, ""
-/*{
- return valueOf(entity.getClass());
- }*/
- );
-
- // valueOf method
- op = addOperation(entityEnum, "valueOf", entityEnumName, ObjectModelJavaModifier.PUBLIC,ObjectModelJavaModifier.STATIC);
- addParameter(op,"Class<?>", "klass");
- setOperationBody(op, ""
-/*{
- if (klass.isInterface()) {
- return valueOf(klass.getSimpleName());
- }
- for (<%=entityEnumName%> entityEnum : <%=entityEnumName%>.values()) {
- if (entityEnum.getContract().isAssignableFrom(klass)) {
- //todo check it works for inheritance
- return entityEnum;
- }
- }
- throw new IllegalArgumentException("no entity defined for the class " + klass + " in : " + Arrays.toString(<%=entityEnumName%>.values()));
- }*/
- );
- }
-}
Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DTOTransformer.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DTOTransformer.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DTOTransformer.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,462 +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%
- */
-
-package org.nuiton.topia.generator;
-
-import org.apache.commons.lang3.StringUtils;
-import org.apache.commons.lang3.builder.ToStringBuilder;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.nuiton.eugene.GeneratorUtil;
-import org.nuiton.eugene.java.ObjectModelTransformerToJava;
-import org.nuiton.eugene.models.object.*;
-
-import java.beans.PropertyChangeListener;
-import java.beans.PropertyChangeSupport;
-import java.io.Serializable;
-import java.util.Collection;
-import java.util.List;
-
-
-/*{generator option: parentheses = false}*/
-
-/*{generator option: writeString = +}*/
-
-/**
- * Created: 20 déc. 2009
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @version $Id$
- * @since 2.3.0
- * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.generator.DTOTransformer"
- */
-public class DTOTransformer extends ObjectModelTransformerToJava {
-
- /**
- * Logger
- */
- private static final Log log = LogFactory.getLog(DTOTransformer.class);
-
- @Override
- public void transformFromClass(ObjectModelClass clazz) {
- if (!TopiaGeneratorUtil.hasDtoStereotype(clazz)) {
- return;
- }
- String clazzName = clazz.getName();
- ObjectModelClass result;
- result = createClass(clazzName + "DTO", clazz.getPackageName());
- addImport(result, ToStringBuilder.class);
- addImport(result, PropertyChangeListener.class);
-
- setDocumentation(result, "Implantation DTO pour l'entité " + StringUtils.capitalize(clazzName) + ".");
- String extendClass = "";
- for (ObjectModelClass parent : clazz.getSuperclasses()) {
- extendClass = parent.getQualifiedName() + "DTO";
- // no multi-inheritance in java
- break;
- }
- if (extendClass.length() > 0) {
- setSuperClass(result, extendClass);
- }
-
- addInterface(result, Serializable.class);
- for (ObjectModelInterface parentInterface : clazz.getInterfaces()) {
- if (TopiaGeneratorUtil.hasDtoStereotype(parentInterface)) {
- addInterface(result, parentInterface.getName() + "DTO");
- } else {
- addInterface(result, parentInterface.getName());
- }
- }
-
- addAttributes(result, clazz);
-
- addOperations(result, clazz);
- }
-
- protected void addAttributes(ObjectModelClass result, ObjectModelClass clazz) {
-
- String svUID = TopiaGeneratorUtil.findTagValue("dto-serialVersionUID", clazz, model);
- if (StringUtils.isNotEmpty(svUID)) {
- addAttribute(result, "serialVersionUID", long.class, svUID, ObjectModelJavaModifier.FINAL, ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
- }
-
- addAttribute(result, "p", PropertyChangeSupport.class, null, ObjectModelJavaModifier.PROTECTED);
-
-/*
-* Définition des attributs
-*/
- ObjectModelAttribute attr2;
- for (ObjectModelAttribute attr : clazz.getAttributes()) {
- ObjectModelAttribute reverse = attr.getReverseAttribute();
-
- String attributeName;
- String attributeType;
- if (!(attr.isNavigable()
- || attr.hasAssociationClass())) {
- continue;
- }
-
- String attrName = attr.getName();
- String attrVisibility = attr.getVisibility();
- String attrType = attr.getType();
- if (!GeneratorUtil.isNMultiplicity(attr)) {
- if (!attr.hasAssociationClass()) {
- if (isDTO(attrType)) {
- attrType += "DTO";
- }
- attributeType = attrType;
- attributeName = attrName;
- } else {
- String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(attr);
- attributeType = attr.getAssociationClass().getQualifiedName();
- attributeName = GeneratorUtil.toLowerCaseFirstLetter(assocAttrName);
- }
- } else {
- if (!attr.hasAssociationClass()) {
- String nMultType;
- if (attr.isOrdered()) {
- nMultType = List.class.getName() + "<";
- } else {
- nMultType = Collection.class.getName() + "<";
- }
- nMultType += attrType;
- if (isDTO(attrType)) {
- nMultType += "DTO";
- }
- nMultType += ">";
-
- attributeType = nMultType;
- attributeName = attrName;
- } else {
- String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(attr);
- String assocClassFQN = attr.getAssociationClass().getQualifiedName();
- String nMultType;
- if (attr.isOrdered()) {
- nMultType = List.class.getName() + "<";
- } else {
- nMultType = Collection.class.getName() + "<";
- }
- nMultType += assocClassFQN;
- if (isDTO(attrType)) {
- nMultType += "DTO";
- }
- nMultType += ">";
- attributeType = nMultType;
- attributeName = GeneratorUtil.toLowerCaseFirstLetter(assocAttrName);
- }
- }
-
- attr2 = addAttribute(result, attributeName, attributeType, null, ObjectModelJavaModifier.PROTECTED);
-
- if (attr2 != null) {
- if (TopiaGeneratorUtil.hasDocumentation(attr)) {
- setDocumentation(attr2, attr.getDocumentation());
- }
- String annotation = TopiaGeneratorUtil.getAnnotationTagValue(attr);
- if (StringUtils.isNotEmpty(annotation)) {
- addAnnotation(result, attr2, annotation);
- }
- }
- } /* end for*/
-
- //Déclaration des attributs d'une classe d'associations
- if (clazz instanceof ObjectModelAssociationClass) {
- ObjectModelAssociationClass assoc = (ObjectModelAssociationClass) clazz;
- for (ObjectModelAttribute attr : assoc.getParticipantsAttributes()) {
- if (attr != null) {
- String attrName = attr.getName();
- String attrVisibility = attr.getVisibility();
- String attrType = attr.getType();
- if (isDTO(attrType)) {
- attrType += "DTO";
- }
- addAttribute(result, GeneratorUtil.toLowerCaseFirstLetter(attrName), attrType);
- }
- }
- }
-
- }
-
- protected void addOperations(ObjectModelClass result, ObjectModelClass clazz) {
- ObjectModelOperation op;
- op = addOperation(result, "addPropertyChangeListener", "void", ObjectModelJavaModifier.PUBLIC);
- addParameter(op, PropertyChangeListener.class, "listener");
- setOperationBody(op, ""
-/*{
- p.addPropertyChangeListener(listener);
- }*/
- );
-
- op = addOperation(result, "addPropertyChangeListener", "void", ObjectModelJavaModifier.PUBLIC);
- addParameter(op, String.class, "propertyName");
- addParameter(op, PropertyChangeListener.class, "listener");
- setOperationBody(op, ""
-/*{
- p.addPropertyChangeListener(propertyName, listener);
- }*/
- );
-
- op = addOperation(result, "removePropertyChangeListener", "void", ObjectModelJavaModifier.PUBLIC);
- addParameter(op, PropertyChangeListener.class, "listener");
- setOperationBody(op, ""
-/*{
- p.removePropertyChangeListener(listener);
- }*/
- );
-
- op = addOperation(result, "removePropertyChangeListener", "void", ObjectModelJavaModifier.PUBLIC);
- addParameter(op, String.class, "propertyName");
- addParameter(op, PropertyChangeListener.class, "listener");
- setOperationBody(op, ""
-/*{
- p.removePropertyChangeListener(propertyName, listener);
- }*/
- );
- /*
- * Définition des getteurs et setteurs
- */
- for (ObjectModelAttribute attr : clazz.getAttributes()) {
-
- ObjectModelAttribute reverse = attr.getReverseAttribute();
-
-// if (!(attr.isNavigable() || hasUnidirectionalRelationOnAbstractType(reverse, model))) {
- if (!attr.isNavigable()) {
- continue;
- }
-
- String attrName = attr.getName();
- String attrType = attr.getType();
- String attrTypeDTO = attr.getType();
- if (isDTO(attrType)) {
- attrTypeDTO += "DTO";
- }
-
- if (!GeneratorUtil.isNMultiplicity(attr)) {
- if (!attr.hasAssociationClass()) {
- op = addOperation(result, "set" + StringUtils.capitalize(attrName), "void", ObjectModelJavaModifier.PUBLIC);
- addParameter(op, attrTypeDTO, "value");
- setOperationBody(op, ""
-/*{
- <%=attrTypeDTO%> oldValue = this.<%=attrName%>;
- this.<%=attrName%> = value;
- p.firePropertyChange("<%=attrName%>", oldValue, value);
- }*/
- );
-
- op = addOperation(result, "get" + StringUtils.capitalize(attrName), attrTypeDTO, ObjectModelJavaModifier.PUBLIC);
- setOperationBody(op, ""
-/*{
- return <%=attrName%>;
- }*/
- );
-
- } else {
- String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(attr);
- String assocClassFQN = attr.getAssociationClass().getQualifiedName();
- if (log.isTraceEnabled()) {
- log.trace("assocAttrName: " + assocAttrName);
- }
- op = addOperation(result, "set" + StringUtils.capitalize(assocAttrName), "void", ObjectModelJavaModifier.PUBLIC);
- addParameter(op, assocClassFQN + "DTO", "association");
- setOperationBody(op, ""
-/*{
- <%=assocClassFQN%>DTO oldAssocation = this.<%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%>;
- this.<%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%> = association;
- p.firePropertyChange("<%=attrName%>", oldAssocation, assocation);
- }*/
- );
-
- op = addOperation(result, "get" + StringUtils.capitalize(assocAttrName), assocClassFQN + "DTO", ObjectModelJavaModifier.PUBLIC);
- setOperationBody(op, ""
-/*{
- return <%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%>;
- }*/
- );
- }
- } else { //NMultiplicity
- if (!attr.hasAssociationClass()) { //Méthodes remplacées par des accesseurs sur les classes d'assoc
-
- String nMultType;
- if (attr.isOrdered()) {
- nMultType = List.class.getName() + "<" + attrTypeDTO + ">";
- } else {
- nMultType = Collection.class.getName() + "<" + attrTypeDTO + ">";
- }
- op = addOperation(result, "set" + StringUtils.capitalize(attrName), "void", ObjectModelJavaModifier.PUBLIC);
- addParameter(op, nMultType, "values");
- setOperationBody(op, ""
-/*{
- <%=nMultType%> oldValues = this.<%=attrName%>;
- this.<%=attrName%> = values;
- p.firePropertyChange("<%=attrName%>", oldValues, values);
- }*/
- );
-
- op = addOperation(result, "addChild" + StringUtils.capitalize(attrName), attrTypeDTO, ObjectModelJavaModifier.PUBLIC);
- addParameter(op, attrTypeDTO, attrName);
- StringBuilder buffercode = new StringBuilder();
-
- buffercode.append(""
-/*{
- this.<%=attrName%>.add(<%=attrName%>);
- }*/
- );
-
- if (reverse != null && reverse.isNavigable()) {
- String reverseAttrName = reverse.getName();
- buffercode.append(""
-/*{ <%=attrName%>.set<%=StringUtils.capitalize(reverseAttrName)%>(this);
- }*/
- );
- }
- buffercode.append(""
-/*{ return <%=attrName%>;
- }*/
- );
- setOperationBody(op, buffercode.toString());
-
- op = addOperation(result, "removeChild", "void");
- addParameter(op, attrTypeDTO, attrName);
-
- buffercode = new StringBuilder();
- buffercode.append(""
-/*{
- this.<%=attrName%>.remove(<%=attrName%>);
- }*/
- );
-
- if (reverse != null && reverse.isNavigable()) {
- String reverseAttrName = reverse.getName();
- buffercode.append(""
-/*{ <%=attrName%>.set<%=StringUtils.capitalize(reverseAttrName)%>(null);
- }*/
- );
- }
- setOperationBody(op, buffercode.toString());
-
- } else {
- String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(attr);
- String assocClassFQN = attr.getAssociationClass().getQualifiedName();
- String nMultType;
- if (attr.isOrdered()) {
- nMultType = List.class.getName() + "<" + assocClassFQN + "DTO>";
- } else {
- nMultType = Collection.class.getName() + "<" + assocClassFQN + "DTO>";
- }
- if (log.isTraceEnabled()) {
- log.trace("assocAttrName: " + assocAttrName);
- }
- op = addOperation(result, "set" + StringUtils.capitalize(assocAttrName), "void");
- addParameter(op, nMultType, "values");
- setOperationBody(op, ""
-/*{
- <%=nMultType%> oldValues = this.<%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%>;
- this.<%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%> = values;
- p.firePropertyChange("<%=attrName%>", oldValues, values);
- }*/
- );
- }
- if (!attr.hasAssociationClass()) {
- String nMultType;
- if (attr.isOrdered()) {
- nMultType = List.class.getName() + "<" + attrTypeDTO + ">";
- } else {
- nMultType = Collection.class.getName() + "<" + attrTypeDTO + ">";
- }
- op = addOperation(result, "get" + StringUtils.capitalize(attrName), nMultType);
- setOperationBody(op, ""
-/*{
- return this.<%=attrName%>;
- }*/
- );
- } else {
- String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(attr);
- String assocClassFQN = attr.getAssociationClass().getQualifiedName();
- String nMultType;
- if (attr.isOrdered()) {
- nMultType = List.class.getName() + "<" + assocClassFQN + "DTO>";
- } else {
- nMultType = Collection.class.getName() + "<" + assocClassFQN + "DTO>";
- }
- if (log.isTraceEnabled()) {
- log.trace("assocAttrName: " + assocAttrName);
- }
- op = addOperation(result, "get" + StringUtils.capitalize(assocAttrName), nMultType);
- setOperationBody(op, ""
-/*{
- return this.<%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%>;
- }*/
- );
- }
- }
- }
-
- op = addOperation(result, "toString", String.class, ObjectModelJavaModifier.PUBLIC);
- StringBuilder buffer = new StringBuilder();
-
- buffer.append(""
-/*{
- String result = new ToStringBuilder(this).
-}*/
- );
-
- for (Object o : clazz.getAttributes()) {
- ObjectModelAttribute attr = (ObjectModelAttribute) o;
- if (!(attr.isNavigable()
- || attr.hasAssociationClass())) {
- continue;
- }
- //FIXME possibilité de boucles (non directes)
- ObjectModelClass attrEntity = null;
- if (model.hasClass(attr.getType())) {
- attrEntity = model.getClass(attr.getType());
- }
- boolean isDTO = attrEntity != null &&
- TopiaGeneratorUtil.isEntity(attrEntity); //THIMEL : STEREOTYPE ENTITY ???
- ObjectModelAttribute reverse = attr.getReverseAttribute();
- if (isDTO && (reverse == null || !reverse.isNavigable()) && !attr.hasAssociationClass() || !isDTO) {
- String attrName = attr.getName();
- buffer.append(""
-/*{ append("<%=attrName%>", this.<%=attrName%>).
-}*/
- );
- }
- }
- buffer.append(""
-/*{ toString();
- return result;
- }*/
- );
- setOperationBody(op, buffer.toString());
- }
-
- public boolean isDTO(String type) {
- ObjectModelClassifier clazz = model.getClassifier(type);
- return clazz != null && TopiaGeneratorUtil.hasDtoStereotype(clazz);
- }
-
-
-}
-
Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityDTOTransformer.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityDTOTransformer.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityDTOTransformer.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,366 +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%
- */
-
-package org.nuiton.topia.generator;
-
-import org.apache.commons.lang3.StringUtils;
-import org.apache.commons.lang3.builder.ToStringBuilder;
-import org.nuiton.eugene.GeneratorUtil;
-import org.nuiton.eugene.java.ObjectModelTransformerToJava;
-import org.nuiton.eugene.models.object.ObjectModelAssociationClass;
-import org.nuiton.eugene.models.object.ObjectModelAttribute;
-import org.nuiton.eugene.models.object.ObjectModelClass;
-import org.nuiton.eugene.models.object.ObjectModelClassifier;
-import org.nuiton.eugene.models.object.ObjectModelJavaModifier;
-import org.nuiton.eugene.models.object.ObjectModelModifier;
-import org.nuiton.eugene.models.object.ObjectModelOperation;
-
-import java.beans.PropertyChangeListener;
-import java.beans.PropertyChangeSupport;
-import java.io.Serializable;
-
-import static org.nuiton.topia.generator.TopiaGeneratorUtil.hasUnidirectionalRelationOnAbstractType;
-import static org.nuiton.topia.generator.TopiaGeneratorUtil.shouldGenerateDTOTopiaIdTagValue;
-
-
-/*{generator option: parentheses = false}*/
-
-/*{generator option: writeString = +}*/
-
-/**
- * Created: 14 déc. 2009
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @version $Id$
- * @since 2.3.0
- * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.generator.EntityDTOTransformer"
- * @deprecated since 3.0, will not be replaced
- */
-@Deprecated
-public class EntityDTOTransformer extends ObjectModelTransformerToJava {
-
- public boolean isEntity(String type) {
- ObjectModelClassifier clazz = model.getClassifier(type);
- return clazz != null && ! clazz.isEnum()
- && TopiaGeneratorUtil.isEntity(clazz);
- }
-
- @Override
- public void transformFromClass(ObjectModelClass clazz) {
- if (!TopiaGeneratorUtil.isEntity(clazz)) {
- return;
- }
- String clazzName = clazz.getName();
- ObjectModelClass result;
- result = createClass(clazzName + "DTO", clazz.getPackageName());
- addImport(result, ToStringBuilder.class);
- addImport(result, PropertyChangeListener.class);
-
- setDocumentation(result, "Implantation DTO pour l'entité " + StringUtils.capitalize(clazzName) + ".");
- String extendClass = "";
- for (ObjectModelClass parent : clazz.getSuperclasses()) {
- extendClass = parent.getQualifiedName() + "DTO";
- // no multi-inheritance in java
- break;
- }
- if (extendClass.length() > 0) {
- setSuperClass(result, extendClass);
- }
- addInterface(result, Serializable.class);
-
-
- addAttributes(result,clazz);
-
- addOperations(result,clazz);
-
- }
-
- protected void addAttributes(ObjectModelClass result, ObjectModelClass clazz) {
-
- String svUID = TopiaGeneratorUtil.findTagValue("dto-serialVersionUID", clazz, model);
- if (svUID != null) {
- addAttribute(result, "serialVersionUID", "long", svUID, ObjectModelJavaModifier.FINAL, ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
- }
-
- boolean generateDTOId = shouldGenerateDTOTopiaIdTagValue(clazz, model);
- if (generateDTOId) {
- addAttribute(result, "topiaId", "String");
- }
-
- ObjectModelAttribute attr2;
- for (ObjectModelAttribute attr : clazz.getAttributes()) {
- ObjectModelAttribute reverse = attr.getReverseAttribute();
-
- // pour les asso quoi qu'il arrive il faut les lier des 2 cotes
- // pour pouvoir supprimer en cascade l'asso lors de la suppression
- // d'un des cotes
- if (!(attr.isNavigable()
- || hasUnidirectionalRelationOnAbstractType(reverse, model)
- || attr.hasAssociationClass())) {
- continue;
- }
-
- String attrVisibility = attr.getVisibility();
- ObjectModelModifier modifier = ObjectModelJavaModifier.fromVisibility(attrVisibility);
- if (!attr.hasAssociationClass()) {
- String attrType = attr.getType();
- String attrName = attr.getName();
- if (isEntity(attrType)) {
- attrType += "DTO";
- }
- if (!GeneratorUtil.isNMultiplicity(attr)) {
- attr2 = addAttribute(result, attrName, attrType, null, modifier);
- } else {
- attr2 = addAttribute(result, attrName, attrType + "[]", null, modifier);
- }
- } else {
- String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(attr);
- String assocClassFQN = attr.getAssociationClass().getQualifiedName();
- if (!GeneratorUtil.isNMultiplicity(attr)) {
- attr2 = addAttribute(result, GeneratorUtil.toLowerCaseFirstLetter(assocAttrName), assocClassFQN + "DTO", null, modifier);
- } else {
- attr2 = addAttribute(result, GeneratorUtil.toLowerCaseFirstLetter(assocAttrName), assocClassFQN + "DTO[]", null, modifier);
- }
- }
- if (attr2 != null) {
- if (TopiaGeneratorUtil.hasDocumentation(attr)) {
- setDocumentation(attr2, attr.getDocumentation());
- }
-
- String annotation = TopiaGeneratorUtil.getAnnotationTagValue(attr);
- if (!StringUtils.isEmpty(annotation)) {
- addAnnotation(result, attr2, annotation);
- }
- }
- }
-
- //Déclaration des attributs d'une classe d'associations
- if (clazz instanceof ObjectModelAssociationClass) {
- ObjectModelAssociationClass assoc = (ObjectModelAssociationClass) clazz;
- for (ObjectModelAttribute attr : assoc.getParticipantsAttributes()) {
- if (attr != null) {
- String attrVisibility = attr.getVisibility();
- ObjectModelModifier modifier = ObjectModelJavaModifier.fromVisibility(attrVisibility);
- String attrType = attr.getType();
- String attrName = attr.getName();
- if (isEntity(attrType)) {
- attrType += "DTO";
- }
- addAttribute(result, GeneratorUtil.toLowerCaseFirstLetter(attrName), attrType, null, modifier);
- }
- }
- }
-
- addAttribute(result,"p", PropertyChangeSupport.class,"new PropertyChangeSupport(this)",ObjectModelJavaModifier.PROTECTED,ObjectModelJavaModifier.FINAL);
- }
-
- protected void addOperations(ObjectModelClass result,ObjectModelClass clazz) {
-
- boolean generateDTOId = shouldGenerateDTOTopiaIdTagValue(clazz, model);
- ObjectModelOperation op;
- if (generateDTOId) {
- op = addOperation(result, "setTopiaId", "void", ObjectModelJavaModifier.PUBLIC);
- addParameter(op, "String", "topiaId");
- setOperationBody(op, ""
-/*{
- this.topiaId = topiaId;
- }*/
- );
-
- op = addOperation(result, "getTopiaId", "String", ObjectModelJavaModifier.PUBLIC);
- setOperationBody(op, ""
-/*{
- return topiaId;
- }*/
- );
- }
-
- op = addOperation(result, "addPropertyChangeListener", "void");
- addParameter(op,PropertyChangeListener.class,"listener");
- setOperationBody(op,""
-/*{
- p.addPropertyChangeListener(listener);
- }*/
- );
-
- op = addOperation(result, "addPropertyChangeListener", "void");
- addParameter(op, String.class, "propertyName");
- addParameter(op, PropertyChangeListener.class, "listener");
- setOperationBody(op, ""
-/*{
- p.addPropertyChangeListener(propertyName, listener);
- }*/
- );
-
- op = addOperation(result, "removePropertyChangeListener", "void");
- addParameter(op, PropertyChangeListener.class, "listener");
- setOperationBody(op, ""
-/*{
- p.removePropertyChangeListener(listener);
- }*/
- );
-
- op = addOperation(result, "removePropertyChangeListener", "void");
- addParameter(op, String.class, "propertyName");
- addParameter(op, PropertyChangeListener.class, "listener");
- setOperationBody(op, ""
-/*{
- p.removePropertyChangeListener(propertyName, listener);
- }*/
- );
-
- for (ObjectModelAttribute attr : clazz.getAttributes()) {
-
- ObjectModelAttribute reverse = attr.getReverseAttribute();
-
- if (!(attr.isNavigable() || hasUnidirectionalRelationOnAbstractType(reverse, model))) {
- continue;
- }
-
- String attrName = attr.getName();
-
- if (!attr.hasAssociationClass()) {
- String attrType = attr.getType();
- if (isEntity(attrType)) {
- attrType += "DTO";
- }
- String setterName = getJavaBeanMethodName("set", attrName);
- String getterName = getJavaBeanMethodName("get", attrName);
- if (!GeneratorUtil.isNMultiplicity(attr)) {
- op = addOperation(result, setterName, "void", ObjectModelJavaModifier.PUBLIC);
- addParameter(op, attrType, "value");
- setOperationBody(op, ""
-/*{
- <%=attrType%> oldValue = this.<%=attrName%>;
- this.<%=attrName%> = value;
- p.firePropertyChange("<%=attrName%>", oldValue, value);
- }*/
- );
-
- op = addOperation(result, getterName, attrType, ObjectModelJavaModifier.PUBLIC);
- setOperationBody(op, ""
-/*{
- return <%=attrName%>;
- }*/
- );
-
- } else {
-
- op = addOperation(result, setterName, "void", ObjectModelJavaModifier.PUBLIC);
- addParameter(op, attrType+"[]", "values");
- setOperationBody(op, ""
-/*{
- <%=attrType%>[] oldValues = this.<%=attrName%>;
- this.<%=attrName%> = values;
- p.firePropertyChange("<%=attrName%>", oldValues, values);
- }*/
- );
-
- op = addOperation(result, getterName, attrType+"[]", ObjectModelJavaModifier.PUBLIC);
- setOperationBody(op, ""
-/*{
- return <%=attrName%>;
- }*/
- );
- }
- } else {
- String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(attr);
- String propertyName = GeneratorUtil.toLowerCaseFirstLetter(assocAttrName);
- String assocClassFQN = attr.getAssociationClass().getQualifiedName();
- String setterName = getJavaBeanMethodName("set", assocAttrName);
- String getterName = getJavaBeanMethodName("get", assocAttrName);
- if (!GeneratorUtil.isNMultiplicity(attr)) {
- op = addOperation(result, setterName, "void", ObjectModelJavaModifier.PUBLIC);
- addParameter(op, assocClassFQN + "DTO", "association");
- setOperationBody(op, ""
-/*{
- <%=assocClassFQN%>DTO oldAssocation= this.<%=propertyName%>;
- this.<%=propertyName%> = association;
- p.firePropertyChange("<%=attrName%>", oldAssocation, assocation);
- }*/
- );
-
- op = addOperation(result, getterName, assocClassFQN + "DTO", ObjectModelJavaModifier.PUBLIC);
- setOperationBody(op, ""
-/*{
- return <%=propertyName%>;
- }*/
- );
-
- } else {
- op = addOperation(result, setterName, "void", ObjectModelJavaModifier.PUBLIC);
- addParameter(op, assocClassFQN + "DTO[]", "values");
- setOperationBody(op, ""
-/*{
- <%=assocClassFQN%>DTO[] oldValues = this.<%=propertyName%>;
- this.<%=propertyName%> = values;
- p.firePropertyChange("<%=attrName%>", oldValues, values);
- }*/
- );
-
- op = addOperation(result, getterName, assocClassFQN + "DTO[]", ObjectModelJavaModifier.PUBLIC);
- setOperationBody(op, ""
-/*{
- return this.<%=propertyName%>;
- }*/
- );
- }
- }
- }
-
- op = addOperation(result,"toString",String.class, ObjectModelJavaModifier.PUBLIC);
- StringBuilder buffer = new StringBuilder();
-
- buffer.append(""
-/*{
- String result = new ToStringBuilder(this).
-}*/
- );
-
- for (Object o : clazz.getAttributes()) {
- ObjectModelAttribute attr = (ObjectModelAttribute) o;
- //FIXME possibilité de boucles (non directes)
- ObjectModelClass attrEntity = null;
- if (model.hasClass(attr.getType())) {
- attrEntity = model.getClass(attr.getType());
- }
- boolean isEntity = attrEntity != null && TopiaGeneratorUtil.isEntity(attrEntity);
- ObjectModelAttribute reverse = attr.getReverseAttribute();
- if (isEntity && (reverse == null || !reverse.isNavigable()) && !attr.hasAssociationClass() || !isEntity) {
- String attrName = attr.getName();
- buffer.append(""
-/*{ append("<%=attrName%>", this.<%=attrName%>).
-}*/
- );
- }
- }
- buffer.append(""
-/*{ toString();
- return result;
-}*/
- );
- setOperationBody(op, buffer.toString());
- }
-}
Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityDaoTransformer.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityDaoTransformer.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityDaoTransformer.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,1162 +0,0 @@
-/*
- * #%L
- * ToPIA :: Persistence
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2004 - 2011 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%
- */
-package org.nuiton.topia.generator;
-
-/*{generator option: parentheses = false}*/
-/*{generator option: writeString = +}*/
-
-import com.google.common.base.Strings;
-import com.google.common.collect.Sets;
-import org.apache.commons.collections.CollectionUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.nuiton.eugene.GeneratorUtil;
-import org.nuiton.eugene.java.JavaGeneratorUtil;
-import org.nuiton.eugene.java.ObjectModelTransformerToJava;
-import org.nuiton.eugene.models.object.ObjectModel;
-import org.nuiton.eugene.models.object.ObjectModelAssociationClass;
-import org.nuiton.eugene.models.object.ObjectModelAttribute;
-import org.nuiton.eugene.models.object.ObjectModelClass;
-import org.nuiton.eugene.models.object.ObjectModelClassifier;
-import org.nuiton.eugene.models.object.ObjectModelDependency;
-import org.nuiton.eugene.models.object.ObjectModelInterface;
-import org.nuiton.eugene.models.object.ObjectModelJavaModifier;
-import org.nuiton.eugene.models.object.ObjectModelOperation;
-import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.persistence.TopiaEntity;
-import org.nuiton.topia.persistence.TopiaQueryBuilderAddCriteriaOrRunQueryStep;
-
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeMap;
-
-/**
- * To generate all <code>DAO</code> related classes for a given entity.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 2.5.4
- * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.generator.EntityDaoTransformer"
- */
-public class EntityDaoTransformer extends ObjectModelTransformerToJava {
-
- /** Logger. */
- private static final Log log =
- LogFactory.getLog(EntityDaoTransformer.class);
-
- /**
- * map of direct usages (values) for each entity (key).
- * <p/>
- * This map is used to generate the findUsages methods for DAOAbstract.
- */
- protected Map<ObjectModelClass, Set<ObjectModelClass>> usages;
-
- /**
- * All entities fqn of the model (used to detect if an attribute is not
- * an entity).
- */
- protected Set<String> allEntitiesFqn;
-
- /**
- * The class of abstract dao to use.
- * @since 2.5
- */
- protected Class<?> daoImplementation;
-
- protected String entityEnumName;
-
- protected String entityEnumPackage;
-
- /**
- * Map of extra operations for DAO. The key of the map is the qualified
- * name of the entity relative to the DAO.
- */
- protected Map<String, Collection<ObjectModelOperation>> extraOperations =
- new HashMap<String, Collection<ObjectModelOperation>>();
-
- @Override
- public void transformFromModel(ObjectModel model) {
-
- boolean generateStandaloneEnum =
- TopiaGeneratorUtil.shouldGenerateStandaloneEnumForDAOHelper(model);
- String modelName = model.getName();
-
- entityEnumName = modelName + "EntityEnum";
-
- String packageName =
- getOutputProperties().getProperty(PROP_DEFAULT_PACKAGE);
-
- if (generateStandaloneEnum) {
- entityEnumPackage = packageName + "." + entityEnumName;
- } else {
- String daoHelperClazzName = modelName + "DAOHelper";
- entityEnumPackage = packageName + "." + daoHelperClazzName + "." + entityEnumName;
- }
-
- usages = TopiaGeneratorUtil.searchDirectUsages(model);
-
- daoImplementation = TopiaGeneratorUtil.getDAOImplementation(model);
-
-
- // keep all classifiers on the model which are entities
- List<ObjectModelClass> allEntities =
- TopiaGeneratorUtil.getEntityClasses(model, true);
- allEntitiesFqn = new HashSet<String>(allEntities.size());
- for (ObjectModelClass entity : allEntities) {
- String fqn = entity.getQualifiedName();
- allEntitiesFqn.add(fqn);
- Collection<ObjectModelOperation> daoOperations =
- new HashSet<ObjectModelOperation>();
- for (ObjectModelOperation op : entity.getOperations()) {
- if (TopiaGeneratorUtil.hasDaoStereotype(op)) {
- daoOperations.add(op);
- }
- }
-
- if (daoOperations.isEmpty()) {
-
- // found some dao operations
- extraOperations.put(fqn, daoOperations);
- }
- }
- }
-
- @Override
- public void transformFromInterface(ObjectModelInterface interfacez) {
- if (!TopiaGeneratorUtil.hasDaoStereotype(interfacez)) {
- return;
- }
-
- /**
- * EVO #636 : Manage extra operations for DAO from "dao" dependency
- * between an interface with stereotype <<dao>> (dependency client) and
- * a class with stereotype <<entity>> (dependency supplier).
- */
-
- ObjectModelDependency dependency =
- interfacez.getDependency(TopiaGeneratorUtil.DEPENDENCIES_DAO);
-
- if (dependency == null) {
- if (log.isWarnEnabled()) {
- log.warn("Could not find dependency " +
- TopiaGeneratorUtil.DEPENDENCIES_DAO +
- " but DAO stereotype was placed on the interface " +
- interfacez.getName());
- }
- return;
- }
-
- ObjectModelClassifier classifier = dependency.getSupplier();
-
- if (!TopiaGeneratorUtil.isEntity(classifier)) {
-
- // dependency supplier is not an entity...
- if (log.isWarnEnabled()) {
- log.warn("Dependency supplier " +
- classifier.getQualifiedName() +
- " is not an entity.");
- }
- return;
- }
-
- // keep only direct operations
- Collection<ObjectModelOperation> operations =
- interfacez.getOperations();
-
- if (CollectionUtils.isEmpty(operations)) {
-
- // no operations on interface, this is not normal
- if (log.isWarnEnabled()) {
- log.warn("No operation found on interface with DAO " +
- "stereotype "+classifier.getQualifiedName());
- }
- return;
- }
- if (log.isDebugEnabled()) {
- log.debug("add "+operations.size()+" extra operation(s) for DAO");
- }
-
- extraOperations.put(classifier.getQualifiedName(), operations);
- }
-
- @Override
- public void transformFromClass(ObjectModelClass clazz) {
- if (!TopiaGeneratorUtil.isEntity(clazz)) {
- // not an entity
- return;
- }
- String clazzName = clazz.getName();
- String clazzFQN = clazz.getQualifiedName();
-
- if (isGenerateGeneratedDao(clazz)) {
- generateGeneratedDao(clazz, clazzName, clazzFQN);
- }
-
- if (isGenerateAbstractDao(clazz)) {
- generateAbstractDao(clazz, clazzName, clazzFQN);
- }
-
- if (isGenerateLegacyDao(clazz)) {
- generateLegacyDao(clazz, clazzName, clazzFQN);
- }
-
- if (isGenerateConcreteDao(clazz)) {
- generateConcreteDao(clazz, clazzName, clazzFQN);
- }
-
- }
-
- protected boolean isGenerateLegacyDao(ObjectModelClass input) {
-
- String daoLegacyFqn = TopiaGeneratorUtil.getLegacyDaoFqn(input);
-
- if (isInClassPath(daoLegacyFqn)) {
-
- // already in class-path
- return false;
- }
-
- // can safely generate the dao impl
- return true;
- }
-
- protected boolean isGenerateConcreteDao(ObjectModelClass input) {
-
- String daoConcreteFqn = TopiaGeneratorUtil.getConcreteDaoFqn(input);
-
- if (isInClassPath(daoConcreteFqn)) {
-
- // already in class-path
- return false;
- }
-
- // can safely generate the dao impl
- return true;
- }
-
- protected boolean isGenerateGeneratedDao(ObjectModelClass input) {
-
- String daoGeneratedFqn = TopiaGeneratorUtil.getGeneratedDaoFqn(input);
-
- if (isInClassPath(daoGeneratedFqn)) {
-
- // already in class-path
- return false;
- }
-
- // can safely generate the dao impl
- return true;
-
- }
-
- protected boolean isGenerateAbstractDao(ObjectModelClass input) {
-
- String fqn = TopiaGeneratorUtil.getAbstractDaoFqn(input);
-
- if (isInClassPath(fqn)) {
-
- // already in class-path
- return false;
- }
-
- Collection<ObjectModelOperation> moreOperations =
- extraOperations.get(input.getQualifiedName());
-
- if (CollectionUtils.isNotEmpty(moreOperations)) {
-
- // no user operations, can not generate it
- return false;
- }
-
- // can safely generate the dao impl
- return true;
-
- }
-
- protected void generateLegacyDao(ObjectModelClass clazz, String clazzName, String clazzFQN) {
- ObjectModelClass daoClass = createClass(TopiaGeneratorUtil.getLegacyDaoName(clazz), clazz.getPackageName());
- addAnnotation(daoClass, daoClass, Deprecated.class);
- setDocumentation(daoClass, "/**\n" +
- " * Cette classe etend le DAOImpl pour parametrer la classe avec le bon type\n" +
- " * Cette classe est marque finale car l'heritage entre les DAO se fait\n" +
- " * sur les DOAImpl, c-a-d que DAOAbstract peut etendre le DAOImpl\n" +
- " */");
- setSuperClass(daoClass, TopiaGeneratorUtil.getAbstractDaoFqn(clazz) + "<" + clazzName + ">");
- }
-
- protected void generateConcreteDao(ObjectModelClass clazz, String clazzName, String clazzFQN) {
- String concreteDaoName = TopiaGeneratorUtil.getConcreteDaoName(clazz);
- ObjectModelClass daoClass = createClass(concreteDaoName, clazz.getPackageName());
- setDocumentation(daoClass, "/**\n" +
- " * Cette classe etend le DAOImpl pour parametrer la classe avec le bon type\n" +
- " * Cette classe est marque finale car l'heritage entre les DAO se fait\n" +
- " * sur les DOAImpl, c-a-d que DAOAbstract peut etendre le DAOImpl\n" +
- " */");
- // to support legacy dao
- String superclassQualifiedName = TopiaGeneratorUtil.getLegacyDaoFqn(clazz);
- // TODO brendan 04/10/13 above line should be replaced by
-// String superclassQualifiedName = TopiaGeneratorUtil.getAbstractDaoFqn(clazz) + "<" + clazzName + ">";
- setSuperClass(daoClass, superclassQualifiedName);
-
- // TODO AThimel 25/10/13 Remove the next lines in ToPIA 3.1
- // Look for legacy Dao class, then warn user if found in classpath
- String legacyConcreteDaoName = TopiaGeneratorUtil.getLegacyDaoName(clazz);
- warnOnLegacyClassDetected(clazz.getPackageName(), legacyConcreteDaoName, concreteDaoName, null,
- TopiaGeneratorUtil.getAbstractDaoFqn(clazz) + "<" + clazzName + ">");
- }
-
- protected void generateAbstractDao(ObjectModelClass clazz,
- String clazzName,
- String clazzFQN) {
-
- Collection<ObjectModelOperation> moreOperations =
- extraOperations.get(clazz.getQualifiedName());
-
- if (CollectionUtils.isEmpty(moreOperations)) {
-
- // no business Dao found, can safely generate the abstract Dao class
-
- String abstractDaoName = TopiaGeneratorUtil.getAbstractDaoName(clazz);
- String daoGenerics = "<E extends " + clazzName + ">";
- ObjectModelClass abstractDaoClass = createClass(abstractDaoName + daoGenerics, clazz.getPackageName());
- String documentation = String.format("/**%n" +
- " * Implantation du Dao pour l'entité '%s'.%n" +
- " * L'utilisateur peut remplacer cette classe par la sienne en la mettant%n" +
- " * simplement dans ses sources. Cette classe générée sera alors simplement%n" +
- " * ignorée à la génération suivante.%n" +
- " */", clazzName);
- setDocumentation(abstractDaoClass, documentation);
- String superclassQualifiedName = TopiaGeneratorUtil.getGeneratedDaoFqn(clazz) + "<E>";
- setSuperClass(abstractDaoClass, superclassQualifiedName);
-
- // TODO AThimel 25/10/13 Remove the next lines in ToPIA 3.1
- // Look for legacy Dao class, then warn user if found in classpath
- String legacyDaoImplName = TopiaGeneratorUtil.getLegacyDaoName(clazz) + "Impl";
- warnOnLegacyClassDetected(clazz.getPackageName(), legacyDaoImplName, abstractDaoName, daoGenerics,
- superclassQualifiedName);
-
- }
- }
-
- // TODO AThimel 25/10/13 Remove this method in ToPIA 3.1
- protected void warnOnLegacyClassDetected(String packageName,
- String legacyDaoName,
- String daoName,
- String daoGenerics,
- String superclassQualifiedName) {
-
- String legacyDaoFqn = String.format("%s.%s", packageName, legacyDaoName);
-
- // AThimel 25/10/13 Not using isInClassPath(fqn) because this method logs that file won't be generated
- if (log.isWarnEnabled() && getFileInClassPath(legacyDaoFqn) != null) {
- String format = "public class %s%s extends %s {";
- String superclassName = superclassQualifiedName.substring(superclassQualifiedName.lastIndexOf('.') + 1);
- String daoDeclaration = String.format(format, daoName, Strings.nullToEmpty(daoGenerics), superclassName);
- String warnMessage = "Legacy DAO detected : %s !%n" +
- " - You should consider renaming '%s' to '%s'%n" +
- " - Expected class declaration is : %s%n" +
- "%n"; // AThimel 29/10/13 Add a new line for log clearness
- log.warn(String.format(warnMessage, legacyDaoFqn, legacyDaoName, daoName, daoDeclaration));
- }
-
- }
-
- protected void generateGeneratedDao(ObjectModelClass clazz,
- String clazzName,
- String clazzFQN) {
- ObjectModelClass daoAbstractClass = createAbstractClass(TopiaGeneratorUtil.getGeneratedDaoName(clazz) + "<E extends " + clazzName + '>',
- clazz.getPackageName());
-
- // super class
-
- String superClassName = null;
- for (ObjectModelClass parent : clazz.getSuperclasses()) {
- if (TopiaGeneratorUtil.isEntity(parent)) {
- superClassName = TopiaGeneratorUtil.getAbstractDaoFqn(parent) + "<E>";
- // in java no multi-inheritance
- break;
- }
- }
- if (superClassName == null) {
- superClassName = daoImplementation.getName() + "<E>";
- }
- if (log.isDebugEnabled()) {
- log.debug("super class = " + superClassName);
- }
- setSuperClass(daoAbstractClass, superClassName);
-
- String prefix = getConstantPrefix(clazz, "");
- setConstantPrefix(prefix);
-
- // imports
-
- Collection<ObjectModelOperation> daoOperations = getDaoOperations(clazz);
-
- if (TopiaGeneratorUtil.isCollectionNeeded(daoOperations)) {
- addImport(daoAbstractClass, Collection.class);
- }
- if (TopiaGeneratorUtil.isSetNeeded(daoOperations)) {
- addImport(daoAbstractClass, Set.class);
- }
- addImport(daoAbstractClass, List.class);
- addImport(daoAbstractClass, TopiaException.class);
- addImport(daoAbstractClass, TopiaQueryBuilderAddCriteriaOrRunQueryStep.class);
-
- ObjectModelOperation op;
-
- // getEntityClass
-
- op = addOperation(daoAbstractClass,
- "getEntityClass",
- "Class<E>",
- ObjectModelJavaModifier.PUBLIC);
- addAnnotation(daoAbstractClass, op,Override.class);
- setOperationBody(op, ""
-/*{
- return (Class<E>) <%=clazzName%>.class;
- }*/
- );
-
- // getTopiaEntityEnum
- addImport(daoAbstractClass, entityEnumPackage);
- op = addOperation(daoAbstractClass,
- "getTopiaEntityEnum",
- entityEnumName,
- ObjectModelJavaModifier.PUBLIC);
- addAnnotation(daoAbstractClass, op,Override.class);
- setOperationBody(op, ""
-/*{
- return <%=entityEnumName%>.<%=clazzName%>;
- }*/
- );
-
- generateDAOOperations(daoAbstractClass, daoOperations);
-
- generateDelete(clazz, daoAbstractClass);
-
- generateNaturalId(daoAbstractClass, clazz);
-
- generateNotNull(daoAbstractClass, clazz);
-
- for (ObjectModelAttribute attr : clazz.getAttributes()) {
- if (!attr.isNavigable()) {
- continue;
- }
-
- if (!GeneratorUtil.isNMultiplicity(attr)) {
- generateNoNMultiplicity(clazzName, daoAbstractClass, attr, false);
- } else {
- generateNMultiplicity(clazzName, daoAbstractClass, attr);
- }
- }
-
- if (clazz instanceof ObjectModelAssociationClass) {
- ObjectModelAssociationClass assocClass =
- (ObjectModelAssociationClass) clazz;
- for (ObjectModelAttribute attr : assocClass.getParticipantsAttributes()) {
- if (attr != null) {
- if (!GeneratorUtil.isNMultiplicity(attr)) {
- generateNoNMultiplicity(clazzName, daoAbstractClass, attr, true);
- } else {
- generateNMultiplicity(clazzName, daoAbstractClass, attr);
- }
- }
- }
- }
-
- Set<ObjectModelClass> usagesForclass = usages.get(clazz);
- generateFindUsages(clazz, daoAbstractClass, usagesForclass);
- }
-
- protected void generateDelete(ObjectModelClass clazz,
- ObjectModelClass result) {
-
- StringBuilder body = new StringBuilder();
- String modelName = StringUtils.capitalize(model.getName());
- String providerFQN = getOutputProperties().getProperty(
- PROP_DEFAULT_PACKAGE) + '.' + modelName +
- "DAOHelper.getImplementationClass";
-
- for (ObjectModelAttribute attr : clazz.getAttributes()) {
-
- String attrType = GeneratorUtil.getSimpleName(attr.getType());
-
- String reverseAttrName = attr.getReverseAttributeName();
- ObjectModelAttribute reverse = attr.getReverseAttribute();
- if (attr.hasAssociationClass() ||
- reverse == null || !reverse.isNavigable()) {
-
- // never treate a non reverse and navigable attribute
- // never treate an association class attribute
- continue;
- }
-
- // at this point we are sure to have a attribute which is
- // - reverse
- // - navigable
- // - not from an association class
- if (!allEntitiesFqn.contains(attr.getType())) {
-
- // this attribute is not from an entity, don't treate it
- if (log.isDebugEnabled()) {
- log.debug("[" + result.getName() + "] Skip attribute [" +
- attr.getName() + "] with type " + attr.getType());
- }
- continue;
- }
-
- // At this point, the attribute type is a entity
- if (GeneratorUtil.isNMultiplicity(attr) &&
- GeneratorUtil.isNMultiplicity(reverse)) {
- // On doit absolument supprimer pour les relations many-to-many
- // le this de la collection de l'autre cote
-
- String attrDBName = TopiaGeneratorUtil.getDbName(attr);
- String attrClassifierDBName = TopiaGeneratorUtil.getDbName(attr.getClassifier());
- String attrJoinTableName = TopiaGeneratorUtil.getManyToManyTableName(attr);
- String attrReverseDBName = TopiaGeneratorUtil.getReverseDbName(attr);
-
- //FIXME_-FC-20100413 Use a TopiaQuery (use HQLin elements)
-// // Add DAOHelper
-// String daoHelper = modelName + "DAOHelper";
-// String daoHelperFQN = getOutputProperties().
-// getProperty(PROP_DEFAULT_PACKAGE) + '.' + daoHelper;
-// addImport(result, daoHelperFQN);
-//
-// // Add import for TopiaQuery
-// addImport(result, TopiaQuery.class);
-//
-// // Entity DAO and reversePropertyName
-// String entityDAO = attrType + "DAO";
-// String reverseAttrNameProperty =
-// attrType + "." + getConstantName(reverseAttrName);
-//
-//
-// <%=entityDAO%> dao = <%=daoHelper%>.get<%=entityDAO%>(getTopiaContext());
-// TopiaQuery query = dao.createQuery("B").
-// addFrom(entity.getClass(), "A").
-// add("A", entity).
-// addInElements("A", "B." + <%=reverseAttrNameProperty%>);
-//
-// System.out.println("Query : " + query);
-// List<<%=attrType%>> list = dao.findAllByQuery(query);
-
- String removeName = getJavaBeanMethodName("remove", reverseAttrName);
- body.append(""
-/*{
- {
- List<<%=attrType%>> list = topiaHibernateSupport.getHibernateSession().createSQLQuery(
- "SELECT main.topiaid " +
- "from <%=attrClassifierDBName%> main, <%=attrJoinTableName%> secondary " +
- "where main.topiaid=secondary.<%=attrDBName%>" +
- " and secondary.<%=attrReverseDBName%>='" + entity.getTopiaId() + "'")
- .addEntity("main", <%=providerFQN%>(<%=attrType%>.class)).list();
-
- for (<%=attrType%> item : list) {
- item.<%=removeName%>(entity);
- }
- }
-}*/
- );
- } else if (!GeneratorUtil.isNMultiplicity(reverse)) {
- // On doit mettre a null les attributs qui ont cet objet sur les
- // autres entites en one-to-*
- // TODO peut-etre qu'hibernate est capable de faire ca tout seul ?
- // THIMEL: J'ai remplacé reverse.getName() par reverseAttrName sans certitude
- addImport(result, attrType);
- addImport(result, attr.getType() + "TopiaDao"); // AThimel 30/10/13 Not using attrType because we need FQN // Can use TopiaGeneratorUtil.getConcreteDaoFqn(...) ?
- String attrSimpleType = TopiaGeneratorUtil.getClassNameFromQualifiedName(attrType);
- // XXX brendan 04/10/13 do not hard code concrete dao name
- String attrConcreteDaoClassName = attrSimpleType + "TopiaDao";
- String getName = getJavaBeanMethodName("get", reverseAttrName);
- String setName = getJavaBeanMethodName("set", reverseAttrName);
-
- body.append(""
- /*{
- {
- <%=attrConcreteDaoClassName%> dao = topiaDaoSupplier
- .getDao(<%=attrSimpleType%>.class, <%=attrConcreteDaoClassName%>.class);
- List<<%=attrSimpleType%>> list = dao
- .forProperties(<%=attrSimpleType%>.<%=getConstantName(reverseAttrName)%>, entity)
- .findAll();
- for (<%=attrSimpleType%> item : list) {
-
- // sletellier : Set null only if target is concerned by deletion
- if (entity.equals(item.<%=getName%>())) {
- item.<%=setName%>(null);
- }
- }*/
- );
- if (attr.isAggregate()) {
- body.append(""
-/*{
- topiaDaoSupplier.getDao(<%=attrSimpleType%>.class).delete(item);
-}*/
- );
- }
- body.append(""
-/*{
- }
- }
-}*/
- );
-
- }
- }
-
- if (body.length()>0) {
- // something specific was done, need to generate the method
- ObjectModelOperation op;
- op = addOperation(result, "delete", "void", ObjectModelJavaModifier.PUBLIC);
- addAnnotation(result, op,Override.class);
- addParameter(op, "E", "entity");
- body.append(""
-/*{
- super.delete(entity);
- }*/
- );
- setOperationBody(op, body.toString());
- }
-
-
-
- }
-
- protected void generateFindUsages(ObjectModelClass clazz,
- ObjectModelClass result,
- Set<ObjectModelClass> usagesForclass) {
-
- builder.addImport(result, LinkedList.class.getName());
- builder.addImport(result, Map.class.getName());
- builder.addImport(result, HashMap.class.getName());
- builder.addImport(result, TopiaEntity.class.getName());
-
- if (clazz instanceof ObjectModelAssociationClass ||
- usagesForclass.isEmpty()) {
- // not for an association class
- // just let a null method
- ObjectModelOperation operation;
- operation = addOperation(result,
- "findUsages",
- "<U extends TopiaEntity> List<U>",
- ObjectModelJavaModifier.PUBLIC);
-
- addParameter(operation, "Class<U>", "type");
- addParameter(operation, "E", "entity");
- addAnnotation(result, operation, Override.class);
- setOperationBody(operation, ""
-/*{
- return new LinkedList<U>();
- }*/
- );
-
- operation = addOperation(result,
- "findAllUsages",
- "Map<Class<? extends TopiaEntity>, List<? extends TopiaEntity>>",
- ObjectModelJavaModifier.PUBLIC);
-
- addParameter(operation, "E", "entity");
- addAnnotation(result, operation, Override.class);
- setOperationBody(operation, ""
-/*{
- return new HashMap<Class<? extends TopiaEntity>, List<? extends TopiaEntity>>();
- }*/
- );
-
- return;
- }
- List<ObjectModelClass> allEntities;
- Map<String, ObjectModelClass> allEntitiesByFQN;
-
- allEntities = TopiaGeneratorUtil.getEntityClasses(model, true);
- allEntitiesByFQN = new TreeMap<String, ObjectModelClass>();
-
- // prepare usages map and fill allEntitiesByFQN map
- for (ObjectModelClass klass : allEntities) {
- allEntitiesByFQN.put(klass.getQualifiedName(), klass);
- }
-
- ObjectModelOperation operation;
- operation = addOperation(result,
- "findUsages",
- "<U extends TopiaEntity> List<U>",
- ObjectModelJavaModifier.PUBLIC);
-
- addParameter(operation, "Class<U>", "type");
- addParameter(operation, "E", "entity");
- addAnnotation(result, operation, Override.class);
- StringBuilder buffer = new StringBuilder(300);
- buffer.append(""
-/*{
- List<?> result = new LinkedList();
- List tmp;
-}*/
- );
-
- for (ObjectModelClass usageClass : usagesForclass) {
- String usageType = usageClass.getQualifiedName();
- builder.addImport(result, usageType);
- String usageSimpleType =
- TopiaGeneratorUtil.getClassNameFromQualifiedName(usageType);
- String usageSimplePropertyMethod = "findAllBy" + usageSimpleType;
- String usageCollectionPropertyMethod = "findAllContaining" + usageSimpleType;
- for (ObjectModelAttribute attr : usageClass.getAttributes()) {
- if (!attr.isNavigable()) {
- // skip this case
- continue;
- }
- String type;
- String attrName = attr.getName();
- if (attr.hasAssociationClass()) {
- //FIXME-TC20100224 dont known how to do this ?
- continue;
-// type = attr.getAssociationClass().getQualifiedName();
-// //FIXME-TC20100224 : this is crazy ??? must find the good name
-// // Perhaps need to make different cases?
-// attrName = attrName + "_" + TopiaGeneratorUtil.toLowerCaseFirstLetter(attr.getAssociationClass().getName());
- } else {
- type = attr.getType();
- }
- if (!allEntitiesByFQN.containsKey(type)) {
- // not a entity, can skip for this attribute
- continue;
- }
- ObjectModelClass targetEntity = allEntitiesByFQN.get(type);
-// if (!type.equals(clazz.getQualifiedName())) {
- if (!targetEntity.equals(clazz)) {
- // not a good attribute reference
- continue;
- }
- // found something to seek
-
- String methodName;
- if (TopiaGeneratorUtil.isNMultiplicity(attr)) {
- methodName = getJavaBeanMethodName("findAllContains", attrName);
- } else {
- methodName = getJavaBeanMethodName("findAllBy", attrName);
- }
- String daoName = StringUtils.capitalize(usageSimpleType) + "DAO";
-
- builder.addImport(result, usageClass.getPackageName() + '.' + daoName);
-
- buffer.append(""
-/*{
- if (type == <%=usageSimpleType%>.class) {
- <%=daoName%> dao = (<%=daoName%>)
- topiaDaoSupplier.getDao(<%=usageSimpleType%>.class);
- tmp = dao.<%=methodName%>(entity);
- result.addAll(tmp);
- }
-}*/
- );
- }
- }
-
- buffer.append(""
-/*{
- return (List<U>) result;
- }*/
- );
- setOperationBody(operation, buffer.toString());
-
- operation = addOperation(result,
- "findAllUsages",
- "Map<Class<? extends TopiaEntity>, List<? extends TopiaEntity>>",
- ObjectModelJavaModifier.PUBLIC);
-
- addParameter(operation, "E", "entity");
- addAnnotation(result, operation, Override.class);
-
- buffer = new StringBuilder(300);
- buffer.append(""
-/*{
- Map<Class<? extends TopiaEntity>,List<? extends TopiaEntity>> result;
- result = new HashMap<Class<? extends TopiaEntity>, List<? extends TopiaEntity>>(<%=usagesForclass.size()%>);
-
- List<? extends TopiaEntity> list;
-}*/
- );
- for (ObjectModelClass usageClass : usagesForclass) {
-
- String fqn = usageClass.getName();
- buffer.append(""
-/*{
- list = findUsages(<%=fqn%>.class, entity);
- if (!list.isEmpty()) {
- result.put(<%=fqn%>.class, list);
- }
-}*/
- );
-
- }
- buffer.append(""
-/*{
- return result;
- }*/
- );
-
- setOperationBody(operation, buffer.toString());
- }
-
- /**
- * Generation of DAO operations signatures from class. These operations are
- * abstract and identified by <<dao>> stereotype in the model. The
- * developper must defined these methods in the DAOImpl associated to this
- * DAOAbstract.
- *
- * @param result clazz where to add operations
- * @param operations operations to generate
- * @deprecated will be removed ASAP in topia 3.0
- */
- @Deprecated
- protected void generateDAOOperations(ObjectModelClass result,
- Collection<ObjectModelOperation>
- operations) {
- if (CollectionUtils.isEmpty(operations)) {
-
- // no extra operations to generate
- return;
- }
-
- for (ObjectModelOperation op : operations) {
-
- Set<String> exceptions = op.getExceptions();
- cloneOperation(op,
- result,
- true,
- ObjectModelJavaModifier.ABSTRACT,
- ObjectModelJavaModifier.fromVisibility(op.getVisibility())
- );
- }
- }
-
-
- protected void generateNoNMultiplicity(String clazzName,
- ObjectModelClass result,
- ObjectModelAttribute attr,
- boolean isAssoc) {
- String attrName = attr.getName();
- String attrType = attr.getType();
- String propertyName = clazzName + "." + getConstantName(attrName);
-
- String attrTypeForGeneric;
- if (JavaGeneratorUtil.isPrimitiveType(attrType)) {
- attrTypeForGeneric = TopiaGeneratorUtil.getClassForPrimitiveType(attr);
- } else {
- attrTypeForGeneric = attrType;
- }
-
- if (!isAssoc && attr.hasAssociationClass()) {
- String assocClassName = attr.getAssociationClass().getName();
- String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(attr);
- // It is about transitivity : use the property to access the
- // associationClass + '.' + the property to access the expected
- // attribute
- // <class>.<attrAssoc> + '.' + <assocClass>.<attr>
- propertyName =
- clazzName + '.' + getConstantName(assocAttrName) +
- " + '.' + " +
- assocClassName + '.' + getConstantName(attrName);
- }
-
- ObjectModelOperation op;
- op = addOperation(result,
- getJavaBeanMethodName("for", attrName, "In"),
- "TopiaQueryBuilderAddCriteriaOrRunQueryStep<E>",
- ObjectModelJavaModifier.PUBLIC);
- addParameter(op, "Iterable<" + attrTypeForGeneric + ">", "v");
- setOperationBody(op, ""
-/*{
- TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> result = forIn(<%=propertyName%>, (Iterable) v);
- return result;
- }*/
- );
-
- op = addOperation(result,
- getJavaBeanMethodName("for", attrName, "Equals"),
- "TopiaQueryBuilderAddCriteriaOrRunQueryStep<E>",
- ObjectModelJavaModifier.PUBLIC);
- addParameter(op, attrType, "v");
- setOperationBody(op, ""
-/*{
- TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> result = forEquals(<%=propertyName%>, v);
- return result;
- }*/
- );
-
- String methodToDelegateName = op.getName();
-
- op = addOperation(result,
- getJavaBeanMethodName("findBy", attrName),
- "E",
- ObjectModelJavaModifier.PUBLIC);
- addParameter(op, attrType, "v");
- setOperationBody(op, ""
-/*{
- return <%=methodToDelegateName%>(v).findAnyOrNull();
- }*/
- );
-
- addAnnotation(result, op, Deprecated.class);
-
- op = addOperation(result,
- getJavaBeanMethodName("findAllBy", attrName),
- "List<E>",
- ObjectModelJavaModifier.PUBLIC);
- addParameter(op, attrType, "v");
- setOperationBody(op, ""
-/*{
- return <%=methodToDelegateName%>(v).findAll();
- }*/
- );
-
- addAnnotation(result, op, Deprecated.class);
-
- if (!isAssoc && attr.hasAssociationClass()) {
- String assocClassName = attr.getAssociationClass().getName();
- String assocClassFQN = attr.getAssociationClass().getQualifiedName();
- String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(attr);
- String assocPropertyConstantName = getConstantName(assocAttrName);
- op = addOperation(result,
- getJavaBeanMethodName("findBy", assocClassName),
- "E",
- ObjectModelJavaModifier.PUBLIC);
- addParameter(op, assocClassFQN, "value");
- setOperationBody(op, ""
-/*{
- E result = findByProperty(<%=clazzName + "." + assocPropertyConstantName%>, value);
- return result;
- }*/
- );
-
- op = addOperation(result,
- getJavaBeanMethodName("findAllBy", assocClassName),
- "List<E>",
- ObjectModelJavaModifier.PUBLIC);
- addParameter(op, assocClassFQN, "value");
- setOperationBody(op, ""
-/*{
- List<E> result = findAllByProperty(<%=clazzName + "." + assocPropertyConstantName%>, value);
- return result;
- }*/
- );
- }
- }
-
- protected void generateNMultiplicity(String clazzName,
- ObjectModelClass result,
- ObjectModelAttribute attr) {
- String attrName = attr.getName();
- String attrType = attr.getType();
- if (attr.hasAssociationClass()) {
- // do nothing for association class, too complex...
- return;
- }
- ObjectModelOperation op;
-
- op = addOperation(result,
- getJavaBeanMethodName("for", attrName, "Contains"),
- "TopiaQueryBuilderAddCriteriaOrRunQueryStep<E>",
- ObjectModelJavaModifier.PUBLIC);
- addParameter(op, attrType, "v");
- setOperationBody(op, ""
-/*{
- return forContains(<%=clazzName + "." + getConstantName(attrName)%>, v);
- }*/
- );
-
- String methodToDelegateName = op.getName();
-
- op = addOperation(result,
- getJavaBeanMethodName("findContains", attrName),
- "E",
- ObjectModelJavaModifier.PUBLIC);
- addParameter(op, attrType, "v");
- setOperationBody(op, ""
-/*{
- return <%=methodToDelegateName%>(v).findAnyOrNull();
- }*/
- );
-
- addAnnotation(result, op, Deprecated.class);
-
- op = addOperation(result,
- getJavaBeanMethodName("findAllContains", attrName),
- "List<E>",
- ObjectModelJavaModifier.PUBLIC);
- addParameter(op, attrType, "v");
- setOperationBody(op, ""
-/*{
- return <%=methodToDelegateName%>(v).findAll();
- }*/
- );
-
- addAnnotation(result, op, Deprecated.class);
-
- }
-
-
- /**
- * Obtain business operations of the DAO.
- *
- * This operations can not be generated, but must be written by developper.
- *
- * @param clazz the clazz to test.
- * @return collections of extra operations, or empty collection if none found.
- * @deprecated Dao operation will not be generated anymore in a very close future
- */
- @Deprecated
- public Collection<ObjectModelOperation> getDaoOperations(
- ObjectModelClass clazz) {
-
-// // Note : this collection will contains extra operations for DAO.
-// // Overriding existing generated methods is not managed yet
-// Collection<ObjectModelOperation> results =
-// new ArrayList<ObjectModelOperation>();
-
-// // This code will be deprecated
-// for (ObjectModelOperation op : clazz.getOperations()) {
-// if (TopiaGeneratorUtil.hasDaoStereotype(op)) {
-// results.add(op);
-// }
-// }
-
- Collection<ObjectModelOperation> extra =
- extraOperations.get(clazz.getQualifiedName());
- if (extra != null && !extra.isEmpty() && log.isWarnEnabled()) {
- log.warn("Dao contract in model will not be supported in topia 3.0");
- }
- return extra;
-// if (extra != null) {
-// for (ObjectModelOperation op : extra) {
-// results.add(op);
-// }
-// }
-
-// return results;
- }
-
- private void generateNaturalId(ObjectModelClass result,
- ObjectModelClass clazz) {
- Set<ObjectModelAttribute> props =
- TopiaGeneratorUtil.getNaturalIdAttributes(clazz);
-
- if (!props.isEmpty()) {
-
- if (log.isDebugEnabled()) {
- log.debug("generateNaturalId for " + props);
- }
- ObjectModelOperation findByNaturalId = addOperation(result,
- "findByNaturalId", "E", ObjectModelJavaModifier.PUBLIC);
-
- ObjectModelOperation existByNaturalId = addOperation(result,
- "existByNaturalId", "boolean", ObjectModelJavaModifier.PUBLIC);
-
- ObjectModelOperation createByNaturalId = addOperation(result,
- "createByNaturalId", "E", ObjectModelJavaModifier.PUBLIC);
-
- Set<String> properties = Sets.newLinkedHashSet();
- String clazzName = clazz.getName();
-
- for (ObjectModelAttribute attr : props) {
-
- String propName = attr.getName();
- String type = attr.getType();
-
- addParameter(findByNaturalId, type, propName);
- addParameter(existByNaturalId, type, propName);
- addParameter(createByNaturalId, type, propName);
-
- String property = clazzName + '.' + getConstantName(propName) + ", " + propName;
- properties.add(property);
-
- }
-
- String arguments = StringUtils.join(properties, ", ");
-
- setOperationBody(findByNaturalId, ""
-/*{
- return forProperties(<%=arguments%>).findUnique();
- }*/
- );
-
- setOperationBody(existByNaturalId, ""
-/*{
- return forProperties(<%=arguments%>).exists();
- }*/
- );
-
- setOperationBody(createByNaturalId, ""
-/*{
- return create(<%=arguments%>);
- }*/
- );
- }
- }
-
- protected void generateNotNull(ObjectModelClass result,
- ObjectModelClass clazz) {
-
- Set<ObjectModelAttribute> props =
- TopiaGeneratorUtil.getNotNullAttributes(clazz);
-
- if (!props.isEmpty()) {
-
- if (log.isDebugEnabled()) {
- log.debug("generateNotNull for " + props);
- }
-
- ObjectModelOperation createByNotNull = addOperation(result,
- "createByNotNull", "E", ObjectModelJavaModifier.PUBLIC);
-
- String createProperties = "";
-// String params = "";
- String clazzName = clazz.getName();
- for (ObjectModelAttribute attr : props) {
- String propName = attr.getName();
- // add property as param in both methods
- addParameter(createByNotNull, attr.getType(), propName);
-
- createProperties +=
- ", " + clazzName + '.' + getConstantName(propName) +
- ", " + propName;
- //params += ", " + propName;
- }
- createProperties = createProperties.substring(2);
- //params = params.substring(2);
-
- setOperationBody(createByNotNull, ""
-/*{
- return create(<%=createProperties%>);
- }*/
- );
- }
- }
-}
Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityHibernateMappingGenerator.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityHibernateMappingGenerator.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityHibernateMappingGenerator.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,768 +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%
- */
-
-/*{generator option: parentheses = true}*/
-/*{generator option: writeString = output.write}*/
-
-/* *
-* EntityHibernateMappingGenerator.java
-*
-* Created: 12 déc. 2005
-*
-* @author Arnaud Thimel <thimel(a)codelutin.com>
-* @version $Revision$
-*
-*/
-
-package org.nuiton.topia.generator;
-
-import org.apache.commons.lang3.BooleanUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.nuiton.eugene.models.object.ObjectModelAssociationClass;
-import org.nuiton.eugene.models.object.ObjectModelAttribute;
-import org.nuiton.eugene.models.object.ObjectModelClass;
-import org.nuiton.eugene.models.object.ObjectModelGenerator;
-
-import java.beans.Introspector;
-import java.io.File;
-import java.io.IOException;
-import java.io.Writer;
-import java.sql.Types;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.TreeMap;
-
-import static org.nuiton.topia.generator.TopiaGeneratorUtil.hasUnidirectionalRelationOnAbstractType;
-
-/**
- *
- * @author poussin <poussin(a)codelutin.com>
- * @version $Id$
- * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.generator.EntityHibernateMappingGenerator"
- */
-public class EntityHibernateMappingGenerator extends ObjectModelGenerator {
-
- /**
- * Logger.
- */
- private static final Log log = LogFactory
- .getLog(EntityHibernateMappingGenerator.class);
-
- private static final String HIBERNATE_ATTRIBUTE_DEFAULT = "default";
-
- private static final String HIBERNATE_ATTRIBUTE_SQL_TYPE = "sql-type";
-
- private static final String HIBERNATE_ATTRIBUTE_NAME = "name";
-
- private Map<String, String[]> columnNamesMap = new HashMap<String, String[]>();
-
- public static final String HIBERNATE_ATTRIBUTE_LAZY = "lazy";
-
- public static final String HIBERNATE_ATTRIBUTE_FETCH = "fetch";
-
- public static final String HIBERNATE_ATTRIBUTE_NOT_NULL = "not-null";
-
- public static final String HIBERNATE_ATTRIBUTE_SCHEMA = "schema";
-
- public static final String HIBERNATE_ATTRIBUTE_INDEX = "index";
-
- public static final String HIBERNATE_ATTRIBUTE_UNIQUE = "unique";
-
- public static final String HIBERNATE_ATTRIBUTE_LENGTH = "length";
-
- public static final String HIBERNATE_ATTRIBUTE_ORDER_BY = "order-by";
-
- @Override
- public String getFilenameForClass(ObjectModelClass clazz) {
- String DOName = TopiaGeneratorUtil.getDOType(clazz, model);
- return DOName.replace('.', File.separatorChar) + ".hbm.xml";
- }
-
- @Override
- public void generateFromClass(Writer output,
- ObjectModelClass input) throws IOException {
- String persistenceType = TopiaGeneratorUtil.getPersistenceType(input);
- if (!TopiaGeneratorUtil.isEntity(input) &&
- TopiaGeneratorUtil.PERSISTENCE_TYPE_HIBERNATE.equals(persistenceType)) {
- return;
- }
-/*{<?xml version="1.0" encoding="UTF-8"?>
-<hibernate-mapping xmlns="http://www.hibernate.org/xsd/hibernate-mapping"
- xsi:schemaLocation="http://www.hibernate.org/xsd/hibernate-mapping classpath://org/hibernate/hibernate-mapping-4.0.xsd"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- default-access="field" auto-import="true" package="<%=input.getPackageName()%>">
-}*/
- boolean haveSuper = input.getSuperclasses().size() > 0;
- // la liste des attributs faisant parti de la clef metier
- List<ObjectModelAttribute> naturalAttributes = new ArrayList<ObjectModelAttribute>();
- // la liste des autres attributs
- List<ObjectModelAttribute> noneNaturalAttributes = new ArrayList<ObjectModelAttribute>();
-
- String clazzDOType = TopiaGeneratorUtil.getDOType(input, model);
- String tableName = TopiaGeneratorUtil.getDbName(input);
- String isAbstract = BooleanUtils.toStringTrueFalse(input.isAbstract());
- String clazzFQN = input.getQualifiedName();
-
- String optionalAttributes = "";
- String schema = TopiaGeneratorUtil.getDbSchemaNameTagValue(input, model);
- if (schema != null) {
- optionalAttributes += "schema=\"" + schema + "\" ";
- }
-
- //On précise au proxy de quelle interface hérite l'objet
- String proxyTagValue = TopiaGeneratorUtil.getProxyInterfaceTagValue(input, model);
- if (StringUtils.isEmpty(proxyTagValue) || !proxyTagValue.equals("none")) {
- optionalAttributes += "proxy=\"" + clazzFQN + "\" ";
- }
-
- String inheritanceStrategy = null;
- if (haveSuper) {
- ObjectModelClass superClass = input.getSuperclasses().iterator().next();
- String superClassname = superClass.getQualifiedName();
- if (log.isDebugEnabled()) {
- log.debug("superClass for " + input.getQualifiedName() + " is " + superClassname);
- }
- String superClassDOType = TopiaGeneratorUtil.getDOType(superClassname, model);
- inheritanceStrategy = TopiaGeneratorUtil.getInheritanceStrategyTagValue(superClass);
- if ("joined-subclass".equals(inheritanceStrategy) || "union-subclass".equals(inheritanceStrategy)) {
- optionalAttributes += "table=\"" + tableName + "\"";
- }
- if ("subclass".equals(inheritanceStrategy)) {
- optionalAttributes += "discriminator-value=\"" + clazzDOType + "\"";
- }
-/*{ <<%=inheritanceStrategy%> name="<%=clazzDOType%>" extends="<%=superClassDOType%>" node="<%=clazzDOType%>" abstract="<%=isAbstract%>" <%=optionalAttributes%>>
-}*/
- if ("joined-subclass".equals(inheritanceStrategy)) {
-/*{ <key column="topiaId" />
-}*/
- }
- // FIXME mieux gerer le cas haveSuper
- noneNaturalAttributes.addAll(input.getAttributes());
- } else {
-/*{ <class name="<%=clazzDOType%>" table="<%=tableName%>" node="<%=clazzDOType%>" abstract="<%=isAbstract%>" <%=optionalAttributes%>>
- <id name="topiaId" type="string" length="255" node="@topiaId"/>
-}*/
- // cas où on defini la super class, il faut un discriminator seulement dans le cas de
- // la strategy subclass
- String currentInheritanceStrategy = TopiaGeneratorUtil.getInheritanceStrategyTagValue(input);
- if ("subclass".equals(currentInheritanceStrategy)) {
-/*{ <discriminator column="topiaDiscriminator" type="string" />
-}*/
- }
-
- // on detecte les attributs des clef metiers
- for (ObjectModelAttribute attr : input.getAttributes()) {
- if (TopiaGeneratorUtil.isNaturalId(attr)) {
- // attribut metier
- naturalAttributes.add(attr);
- } else {
- // attribut normal
- noneNaturalAttributes.add(attr);
- }
- }
- if (!naturalAttributes.isEmpty()) {
- // generation de la clef metier
- boolean mutable = TopiaGeneratorUtil.isNaturalIdMutable(input);
- String mutableStr = mutable ? " mutable=\"true\"" : "";
- if (log.isDebugEnabled()) {
- log.debug("natural-id detected for class " + input.getName() + " (" + mutableStr + ") attributes : " + naturalAttributes);
- }
-/*{ <natural-id<%=mutableStr%>>
-}*/
- generateAttributes(output, input, naturalAttributes, " ");
-/*{ </natural-id>
-}*/
- }
-/*{ <version name="topiaVersion" type="long" node="@topiaVersion"/>
- <property name="topiaCreateDate" type="timestamp" node="@topiaCreateDate"/>
-}*/
- }
-
- generateAttributes(output, input, noneNaturalAttributes, "");
-
- if (haveSuper) {
-/*{ </<%=inheritanceStrategy%>>
-}*/
- } else {
-/*{ </class>
-}*/
- }
-
- generateDatabaseObjects(output, input, naturalAttributes);
- generateDatabaseObjects(output, input, noneNaturalAttributes);
-
-/*{</hibernate-mapping>
-}*/
- }
-
- protected void generateDatabaseObjects(Writer output,
- ObjectModelClass clazz,
- List<ObjectModelAttribute> attributes) throws IOException {
-
- for (ObjectModelAttribute attribute : attributes) {
- if (!attribute.isNavigable() ||
- attribute.hasAssociationClass() ||
- !TopiaGeneratorUtil.isNMultiplicity(attribute) ||
- attribute.getClassifier() == null ||
- !TopiaGeneratorUtil.isEntity(attribute.getClassifier())
- ) {
-
- // skip for this case (not a nm-multiplicity attribute)
- continue;
- }
-
- String indexForeignKeys =
- TopiaGeneratorUtil.getIndexForeignKeys(attribute, model);
-
- if (StringUtils.isEmpty(indexForeignKeys) || !Boolean.valueOf(indexForeignKeys)) {
-
- // no index to put of the attribute.
- continue;
- }
-
- // add database-object to create and drop index
-
- String tableName;
- String indexName = "idx_" + clazz.getName() + "_" + attribute.getName();
- String propertyName;
-
-
- if (TopiaGeneratorUtil.isNMultiplicity(attribute.getReverseMaxMultiplicity())) {
-
- // many to many
- tableName = TopiaGeneratorUtil.getManyToManyTableName(attribute);
- propertyName = TopiaGeneratorUtil.getDbName(attribute.getReverseAttribute());
- } else {
-
- // one to many
- tableName =TopiaGeneratorUtil.getDbName(attribute.getClassifier());
- propertyName = TopiaGeneratorUtil.getDbName(attribute.getReverseAttribute());
- }
-
- // add schema if exist (http://nuiton.org/issues/2052)
- String schema = TopiaGeneratorUtil.getDbSchemaNameTagValue(clazz, model);
- if (StringUtils.isNotEmpty(schema)) {
- tableName = schema + "." + tableName;
- }
-/*{ <database-object>
- <create>CREATE INDEX <%=indexName%> ON <%=tableName%>(<%=propertyName%>)</create>
- <drop>DROP INDEX <%=indexName%></drop>
- </database-object>
-}*/
-
- }
- }
- protected void generateAttributes(Writer output,
- ObjectModelClass clazz,
- List<ObjectModelAttribute> attributes,
- String prefix) throws IOException {
- for (ObjectModelAttribute attr : attributes) {
- ObjectModelAttribute reverse = attr.getReverseAttribute();
-
- // pour les asso quoi qu'il arrive il faut les lier des 2 cotes
- // pour pouvoir supprimer en cascade l'asso lors de la suppression
- // d'un des cotes
- if (attr.isNavigable()
- || hasUnidirectionalRelationOnAbstractType(reverse, model)
- || attr.hasAssociationClass()) {
- if (!TopiaGeneratorUtil.isNMultiplicity(attr)) {
- if (attr.getClassifier() != null && TopiaGeneratorUtil.isEntity(attr.getClassifier())) {
- if (TopiaGeneratorUtil.isNMultiplicity(attr.getReverseMaxMultiplicity()) && !attr.hasAssociationClass()) {
- generateHibernateManyToOne(output, attr, prefix);
- } else {
- generateHibernateOneToOne(output, attr, prefix);
- }
- } else {
- generateHibernateProperty(output, attr, prefix);
- }
- } else {
- if (attr.getClassifier() != null && TopiaGeneratorUtil.isEntity(attr.getClassifier())) {
- if (TopiaGeneratorUtil.isNMultiplicity(attr.getReverseMaxMultiplicity()) && !attr.hasAssociationClass()) {
- generateHibernateManyToMany(output, attr, prefix);
- } else {
- generateHibernateOneToMany(output, attr, prefix);
- }
- } else {
- generateHibernateMany(output, attr, prefix);
- }
- }
- }
- }
-
- //Attributs pour les classes d'association
- if (clazz instanceof ObjectModelAssociationClass) {
- ObjectModelAssociationClass assoc = (ObjectModelAssociationClass)clazz;
- for (ObjectModelAttribute attr : assoc.getParticipantsAttributes()) {
- if (attr != null) {
-
-// Note(poussin) pour moi quoi qu'il arrive sur la classe d'association il faut
-// un many-to-one, sinon on a des problemes.
-// if ((!attr.getReverseAttribute().isNavigable()) || !Util.isNMultiplicity(attr.getReverseAttribute())) {
-// / *{ <one-to-one name="<%=getName(attr, true)%>" class="<%=getType(attr, true)%>"<%=(TopiaGeneratorUtil.notEmpty(attr.getTagValue(TopiaGeneratorUtil.TAG_LENGTH))?(" length=\"" + attr.getTagValue(TopiaGeneratorUtil.TAG_LENGTH) + "\""):"")%><%=(attr.isComposite()?" cascade=\"delete\"":"")%>/>
-// } */
-// } else {
- String notNull = " " + generateFromTagValue(HIBERNATE_ATTRIBUTE_NOT_NULL, TopiaGeneratorUtil.getNotNullTagValue(attr));
- String attrName = getName(attr, true);
- String attrType = getType(attr, true);
- String lazy = generateFromTagValue(HIBERNATE_ATTRIBUTE_LAZY, TopiaGeneratorUtil.getLazyTagValue(attr));
- String attrColumn = TopiaGeneratorUtil.getDbName(attr);
-/*{<%=prefix%> <many-to-one name="<%=attrName%>" class="<%=attrType%>" <%=lazy%>column="<%=attrColumn%>" node="<%=attrName%>/@topiaId" <%=notNull%>/>
-}*/
-// }
- //Ne sert plus grâce à l'utilisation de la navigabilité
-// if (!attr.getReverseAttribute().isNavigable()) {
-// String type = TopiaGeneratorUtil.getDOType(((ObjectModelClassifier)attr.getDeclaringElement()).getQualifiedName(), model);
-// String name = Util.toLowerCaseFirstLetter(attr.getDeclaringElement().getName());
-// if (log.isTraceEnabled()) {log.trace("reverse: " + type + " " + name);}
-// if (!Util.isNMultiplicity(attr)) {
-//{<!-- <one-to-one name="<%=name%>" class="<%=type%>"/>
-//}
-// } else {
-//{ <many-to-one name="<%=name%>" class="<%=type%>" column="<%=name.toLowerCase()%>"/> -->
-//}
-// }
-// }
- }
- }
- }
- }
-
- protected String getName(ObjectModelAttribute attr) {
- return getName(attr, false);
- }
-
- protected String getName(ObjectModelAttribute attr, boolean isAssoc) {
- String result = Introspector.decapitalize(attr.getName());
- if (attr.hasAssociationClass() && !isAssoc) {
- result = TopiaGeneratorUtil.getAssocAttrName(attr);
- }
- return result;
- }
-
- protected String getType(ObjectModelAttribute attr) {
- return getType(attr, false);
- }
-
- protected String getType(ObjectModelAttribute attr, boolean isAssoc) {
- String type = attr.getType();
- String attrType = TopiaGeneratorUtil.getTypeTagValue(attr);
- if (StringUtils.isNotEmpty(attrType)) {
-
- // tag value detected of the attribute
- type = attrType;
- } else {
-
- String modelType = model.getTagValue(type);
- if (StringUtils.isNotEmpty(modelType)) {
-
- // tag value detected of the model
-
- //TODO tchemit 20100507 Explain What todes it do ? Dont understand the story of columnNamesMap
- int bracketIndex = modelType.indexOf('(');
- if (bracketIndex != -1) {
- type = modelType.substring(0, bracketIndex);
- int bracketEndIndex = modelType.indexOf(')', bracketIndex + 1);
- String colmunList;
- if (bracketEndIndex != -1) {
- colmunList = modelType.substring(bracketIndex + 1, bracketEndIndex);
- } else {
- colmunList = modelType.substring(bracketIndex);
- }
- columnNamesMap.put(type, colmunList.split(","));
- } else {
- type = modelType;
- }
- }
- }
- if (attr.hasAssociationClass() && !isAssoc) {
- type = attr.getAssociationClass().getQualifiedName();
- }
- return TopiaGeneratorUtil.getDOType(type, model);
- }
-
- protected void generateHibernateProperty(Writer output,
- ObjectModelAttribute attr,
- String prefix) throws IOException {
- String attrType = getType(attr);
-
- String accessField = "field";
- String tagValue = TopiaGeneratorUtil.getAccessTagValue(attr);
- if (StringUtils.isNotEmpty(tagValue)) {
- accessField = tagValue;
- }
- String attrName = attr.getName();
- String declaringElementDBName = TopiaGeneratorUtil.getDbName(attr.getDeclaringElement());
- String tableName = declaringElementDBName + "_" + attrName;
-
- boolean attrIsEnumeration = attr.getClassifier() != null
- && attr.getClassifier().isEnum();
-
- if (attrType.trim().endsWith("[]")) {
- attrType = attrType.trim().substring(0, attrType.trim().length()-2);
-
- String optionalAttributes = "";
- String schema = TopiaGeneratorUtil.getDbSchemaNameTagValue(attr, model);
- if (schema != null) {
- optionalAttributes += generateFromTagValue(HIBERNATE_ATTRIBUTE_SCHEMA, schema);
-// optionalAttributes += "schema=\"" + schema + "\" ";
- }
-
- if (TopiaGeneratorUtil.hasIndexedStereotype(attr)) {
- String indexName = tableName + "_idx";
- optionalAttributes += generateFromTagValue(HIBERNATE_ATTRIBUTE_INDEX, indexName);
-// optionalAttributes += "index=\"" + indexName + "\" ";
- }
-
-/*{<%=prefix%> <primitive-array name="<%=attrName%>" table="<%=tableName%>" access="<%=accessField%>" <%=optionalAttributes%>>
-<%=prefix%> <key column="<%=declaringElementDBName%>"/>
-<%=prefix%> <list-index column="<%=attrName%>_idx"/>
-<%=prefix%> <element type="<%=attrType%>"/>
-<%=prefix%> </primitive-array>
-}*/
- } else {
- String optionalAttributes = "";
- if (TopiaGeneratorUtil.hasIndexedStereotype(attr)) {
- String indexName = tableName + "_idx";
- optionalAttributes += generateFromTagValue(HIBERNATE_ATTRIBUTE_INDEX, indexName);
-// optionalAttributes += "index=\"" + indexName + "\"";
- }
-
- if (TopiaGeneratorUtil.hasUniqueStereotype(attr)) {
- // the trim method is called on optionalAttributes after this set to suppress unusual space if no index is set on this attribute
- optionalAttributes += generateFromTagValue(HIBERNATE_ATTRIBUTE_UNIQUE, "true");
-// optionalAttributes += " unique=\"true\"";
- }
- optionalAttributes += generateFromTagValue(HIBERNATE_ATTRIBUTE_NOT_NULL, TopiaGeneratorUtil.getNotNullTagValue(attr));
-/*{<%=prefix%> <property name="<%=attrName%>" access="<%=accessField%>"}*/
- if ( ! attrIsEnumeration) {
-/*{ type="<%=attrType%>"}*/
- }
- optionalAttributes = optionalAttributes.trim();
- String[] columnNames = columnNamesMap.get(attrType);
-
- // contains all required attributes for a column node
- Map<String,String> columnAttributes = new TreeMap<String, String>();
- if (StringUtils.isNotEmpty(attr.getDefaultValue())) {
- //TC-20100129 with a default value we must use the column child tag
-
- String defaultValue = attr.getDefaultValue().trim();
- columnAttributes.put(HIBERNATE_ATTRIBUTE_DEFAULT, defaultValue);
- }
- String sqlType = TopiaGeneratorUtil.getSqlTypeTagValue(attr);
- if (!StringUtils.isEmpty(sqlType)) {
-
- // an specific sql type was specified for the attribute, use it
- columnAttributes.put(HIBERNATE_ATTRIBUTE_SQL_TYPE, sqlType);
- }
-
- // add length attribute if required
- String lengthTagValue = TopiaGeneratorUtil.getLengthTagValue(attr);
- if (!StringUtils.isEmpty(lengthTagValue)) {
-
- optionalAttributes += generateFromTagValue(HIBERNATE_ATTRIBUTE_LENGTH, lengthTagValue);
- }
-
- optionalAttributes = optionalAttributes.trim();
- if (StringUtils.isNotEmpty(optionalAttributes)) {
- optionalAttributes = " " + optionalAttributes;
- }
-
- // to know if specific column name mapping is given
- boolean noSpecifiedColumn = columnNames == null || columnNames.length == 0;
-
- if (noSpecifiedColumn) {
-
- String attrColumn = TopiaGeneratorUtil.getDbName(attr);
-
- if (columnAttributes.isEmpty()) {
-
- // simple case with no column node to generate
-
-/*{ column="<%=attrColumn%>" node="<%=attrName%>"<%=optionalAttributes%>}*/
- if (attrIsEnumeration) {
-/*{>
-<%=prefix%> <type name="org.hibernate.type.EnumType">
-<%=prefix%> <param name="<%=org.hibernate.type.EnumType.ENUM%>"><%=attrType%></param>}*/
-
- // if the user tuned the model to use name instead of
- // ordinal to store the values, we must add a clause
- boolean useEnumerationName = TopiaGeneratorUtil.hasUseEnumerationNameTagValue(attr, model);
- if (useEnumerationName) {
- String enumSQLType = String.valueOf(Types.VARCHAR);
-/*{
-<%=prefix%> <!-- using name instead of ordinal to store enumeration value -->
-<%=prefix%> <param name="<%=org.hibernate.type.EnumType.TYPE%>"><%=enumSQLType%></param>}*/
- }
-
-/*{
-<%=prefix%> </type>
-<%=prefix%> </property>
-}*/
- } else {
-/*{/>
-}*/
- }
- } else {
-
- // there is some attributes to write for the column node
-
- columnAttributes.put(HIBERNATE_ATTRIBUTE_NAME, attrColumn);
-
- String columnAttributesAsString ="";
- for (Map.Entry<String, String> entry :
- columnAttributes.entrySet()) {
- String name = entry.getKey();
- String value = entry.getValue();
- columnAttributesAsString += generateFromTagValue(name, value, null);
- }
- columnAttributesAsString = " " + columnAttributesAsString.trim();
-/*{<%=optionalAttributes%>>
-<%=prefix%> <column<%=columnAttributesAsString%>/>
-<%=prefix%> </property>
-}*/
- }
- } else {
-
- // there is a colum name mapping specified, must use it
- //FIXME tchemit 2010-12-29 Really don't know how to apply columnAttributes for multi-columns...
-/*{<%=optionalAttributes%>>
-}*/
- for (String columnName : columnNames) {
- columnName = attrName + "_" + columnName.trim();
-/*{<%=prefix%> <column name="<%=columnName%>"/>
-}*/
- }
-/*{<%=prefix%> </property>
-}*/
- }
- }
- }
-
- protected void generateHibernateOneToOne(Writer output,
- ObjectModelAttribute attr,
- String prefix) throws IOException {
-// boolean accessField = hasUnidirectionalRelationOnAbstractType(attr.getReverseAttribute(), model);
-/// *{ <one-to-one name="<%=getName(attr)%>" class="<%=getType(attr)%>"<%=(TopiaGeneratorUtil.notEmpty(attr.getTagValue(TopiaGeneratorUtil.TAG_LENGTH))?(" length=\"" + attr.getTagValue(TopiaGeneratorUtil.TAG_LENGTH) + "\""):"")%><%=((attr.isComposite() || attr.hasAssociationClass())?" cascade=\"delete\"":"")%><%=((accessField)?" access=\"field\"":"")%> node="<%=getName(attr)%>/@topiaId" />
-//} */
-
- // for hibernate many-to-one with unique="true" => one-to-one
- // but if it is one-to-zero-or-one unique contraints is violated
- // with null values
- boolean unique = TopiaGeneratorUtil.isOneMultiplicity(attr);
- generateHibernateManyToOne(output, attr, unique, prefix);
-
- }
-
- protected void generateHibernateOneToMany(Writer output,
- ObjectModelAttribute attr,
- String prefix) throws IOException {
- boolean needsIndex = TopiaGeneratorUtil.hasIndexedStereotype(attr);
- boolean isInverse = attr.getReverseAttribute().isNavigable();
- isInverse |= hasUnidirectionalRelationOnAbstractType(attr, model);
-
- String attrName = getName(attr); // ???
- String attrType = getType(attr);
- String reverseAttrDBName = TopiaGeneratorUtil.getReverseDbName(attr);
- String orderBy = generateFromTagValue(HIBERNATE_ATTRIBUTE_ORDER_BY, TopiaGeneratorUtil.getOrderByTagValue(attr));
-
- String cascade = "";
- if (attr.isComposite() || attr.hasAssociationClass()) {
- cascade += "cascade=\"all,delete-orphan\" ";
- }
-
- String lazy = generateFromTagValue(HIBERNATE_ATTRIBUTE_LAZY, TopiaGeneratorUtil.getLazyTagValue(attr), "true");
-
- String fetch = generateFromTagValue(HIBERNATE_ATTRIBUTE_FETCH, TopiaGeneratorUtil.getFetchTagValue(attr));
-
- String collType = TopiaGeneratorUtil.getNMultiplicityHibernateType(attr);
- String inverse = "";
- if (isInverse) {
- inverse = "inverse=\"true\" ";
- }
- if (needsIndex) {
-/*{<%=prefix%> <<%=collType%> name="<%=attrName%>" <%=inverse%><%=lazy%><%=cascade%>node="<%=attrName%>">
-<%=prefix%> <key column="<%=reverseAttrDBName%>"/>
-<%=prefix%> <list-index column="<%=reverseAttrDBName%>_idx"/>
-<%=prefix%> <one-to-many class="<%=attrType%>" node="topiaId"/>
-<%=prefix%> </<%=collType%>>
-}*/
- }else {
-/*{<%=prefix%> <<%=collType%> name="<%=attrName%>" <%=inverse%><%=orderBy%><%=fetch%><%=lazy%><%=cascade%>node="<%=attrName%>">
-<%=prefix%> <key column="<%=reverseAttrDBName%>"/>
-<%=prefix%> <one-to-many class="<%=attrType%>" node="topiaId"/>
-<%=prefix%> </<%=collType%>>
-}*/
- }
- }
-
- private String generateFromTagValue(String attributeName, String tagValue) {
- return generateFromTagValue(attributeName, tagValue, null);
- }
-
- /**
- * Generate hibernate xml attribute with a final space.
- * @param attributeName
- * @param tagValue
- * @param defaultValue
- * @return
- */
- private String generateFromTagValue(String attributeName, String tagValue, String defaultValue) {
- String result = "";
- if (StringUtils.isNotEmpty(tagValue)) {
- result+= attributeName + "=\"" + tagValue+"\" ";
- } else if (defaultValue != null) {
- result+= attributeName + "=\"" + defaultValue +"\" ";
- }
-// if (attr.hasTagValue(tagName) || defaultValue != null) {
-// result+= attributeName + "=\"";
-// if (attr.hasTagValue(tagName)) {
-// result += attr.getTagValue(tagName);
-// } else {
-// result += defaultValue;
-// }
-// result += "\" ";
-// }
- return result;
- }
-
- protected void generateHibernateMany(Writer output,
- ObjectModelAttribute attr,
- String prefix) throws IOException {
- boolean needsIndex = TopiaGeneratorUtil.hasIndexedStereotype(attr);
- String attrName = getName(attr);
- String attrType = getType(attr);
- String collType = TopiaGeneratorUtil.getNMultiplicityHibernateType(attr);
- String lazy = generateFromTagValue(HIBERNATE_ATTRIBUTE_LAZY, TopiaGeneratorUtil.getLazyTagValue(attr));
- String attrColumn = TopiaGeneratorUtil.getDbName(attr);
-
-/*{<%=prefix%> <<%=collType%> name="<%=attrName%>" <%=lazy%>node="<%=attrName%>">
-<%=prefix%> <key column="OWNER"/>
-}*/
- if (needsIndex) {
-/*{<%=prefix%> <list-index/>
-}*/
- }
-/*{<%=prefix%> <element type="<%=attrType%>" column="<%=attrColumn%>" node="id"/>
-<%=prefix%> </<%=collType%>>
-}*/
- }
-
- protected void generateHibernateManyToOne(Writer output,
- ObjectModelAttribute attr,
- String prefix) throws IOException {
- generateHibernateManyToOne(output, attr, false, prefix);
- }
-
- protected void generateHibernateManyToOne(Writer output,
- ObjectModelAttribute attr,
- boolean isUnique,
- String prefix) throws IOException {
- String attrName = getName(attr);
- String attrType = getType(attr);
- String attrColumn = TopiaGeneratorUtil.getDbName(attr);
-/*{<%=prefix%> <many-to-one name="<%=attrName%>" class="<%=attrType%>" column="<%=attrColumn%>" }*/
- if (attr.isComposite() || attr.hasAssociationClass()) {
-/*{cascade="delete" }*/
- }
- // Pour le test suivant, on verifie d'abord que l'attribut a un reverse.
- // S'il n'en a pas, cela signifie qu'il ne s'agit pas d'un entite
- // (au sens stereotype entity), donc a donc pas besoin de faire un access=field.
- if (attr.getReverseAttribute() != null && hasUnidirectionalRelationOnAbstractType(attr.getReverseAttribute(), model)) {
-/*{access="field" }*/
- }
- // vérifier si le tag lazy est defini par defaut dans le fichier de proprietes
- String lazy = generateFromTagValue(HIBERNATE_ATTRIBUTE_LAZY, TopiaGeneratorUtil.getLazyTagValue(attr));
-/*{<%=lazy%>}*/
- String notNull = generateFromTagValue(HIBERNATE_ATTRIBUTE_NOT_NULL, TopiaGeneratorUtil.getNotNullTagValue(attr));
-/*{<%=notNull%>}*/
- if (isUnique) {
-/*{unique="true" }*/
- }
-/*{node="<%=attrName%>/@topiaId"}*/
-
-/*{/>
-}*/
- }
-
- protected void generateHibernateManyToMany(Writer output,
- ObjectModelAttribute attr,
- String prefix) throws IOException {
- // On ne met le inverse="true" uniquement pour un seul coté de la relation.
- // Dans le cas contraire, les modifications dans la relation ne seront
- // pas sauvegardées. Ceci n'est vrai que si les deux coté sont navigable
- boolean isInverse = attr.isNavigable() && attr.getReverseAttribute().isNavigable();
- //isInverse |= !Util.isFirstAttribute(attr);
- //isInverse = false; // 20070117 poussin: pour du many, jamais de inverse
-
- // Modification FD-2010-04-01 :
- // Le tagvalue "inverse" permet de spécifier qui possède le
- // inverse="true". Il est impératif de l'utiliser sur les deux
- // extrémités pour ne pas avoir de surprise.
- String inverseValue = TopiaGeneratorUtil.getInverseTagValue(attr);
- if (StringUtils.isNotEmpty(inverseValue)) {
- isInverse &= Boolean.parseBoolean(inverseValue);
- // Si aucun tagvalue n'est défini, le choix est arbitraire : le
- // premier attribut dans l'ordre alphabétique sera choisi pour porter le
- // inverse="true"
- } else {
- isInverse &= TopiaGeneratorUtil.isFirstAttribute(attr);
- }
-
- boolean needsIndex = TopiaGeneratorUtil.hasIndexedStereotype(attr);
- String cascade = "";
- if (attr.isComposite() || attr.hasAssociationClass()) {
- cascade = " cascade=\"delete,delete-orphan\"";
- }
-
- String attrType = getType(attr);
- String attrName = getName(attr);
- String attrColumn = TopiaGeneratorUtil.getDbName(attr);
- String lazy = generateFromTagValue(HIBERNATE_ATTRIBUTE_LAZY, TopiaGeneratorUtil.getLazyTagValue(attr), "true");
- String orderBy = generateFromTagValue(HIBERNATE_ATTRIBUTE_ORDER_BY, TopiaGeneratorUtil.getOrderByTagValue(attr));
- String collType = TopiaGeneratorUtil.getNMultiplicityHibernateType(attr);
- String tableName = TopiaGeneratorUtil.getManyToManyTableName(attr);
- String inverse = "";
- if (isInverse) {
- inverse = "inverse=\"true\" ";
- }
- String reverseAttrDBName = TopiaGeneratorUtil.getReverseDbName(attr);
-
-/*{<%=prefix%> <<%=collType%> name="<%=attrName%>" table="<%=tableName%>" <%=inverse%><%=lazy%><%=cascade%> node="<%=attrName%>">
-<%=prefix%> <key column="<%=reverseAttrDBName%>"/>
-}*/
- if (needsIndex) {
-/*{<%=prefix%> <list-index column="<%=reverseAttrDBName%>_idx"/>
-}*/
- }
-/*{<%=prefix%> <many-to-many class="<%=attrType%>" column="<%=attrColumn%>" <%=orderBy%>node="topiaId"/>
-<%=prefix%> </<%=collType%>>
-}*/
- }
-
-} //EntityHibernateMappingGenerator
Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityTransformer.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityTransformer.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityTransformer.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,1654 +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%
- */
-package org.nuiton.topia.generator;
-
-import org.apache.commons.lang3.StringUtils;
-import org.apache.commons.lang3.builder.ToStringBuilder;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.nuiton.eugene.EugeneTagValues;
-import org.nuiton.eugene.java.ObjectModelTransformerToJava;
-import org.nuiton.eugene.models.object.ObjectModelAssociationClass;
-import org.nuiton.eugene.models.object.ObjectModelAttribute;
-import org.nuiton.eugene.models.object.ObjectModelClass;
-import org.nuiton.eugene.models.object.ObjectModelClassifier;
-import org.nuiton.eugene.models.object.ObjectModelInterface;
-import org.nuiton.eugene.models.object.ObjectModelJavaModifier;
-import org.nuiton.eugene.models.object.ObjectModelModifier;
-import org.nuiton.eugene.models.object.ObjectModelOperation;
-import org.nuiton.eugene.models.object.ObjectModelParameter;
-import org.nuiton.topia.TopiaDaoSupplier;
-import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.persistence.EntityVisitor;
-import org.nuiton.topia.persistence.TopiaEntity;
-import org.nuiton.topia.persistence.TopiaEntityAbstract;
-import org.nuiton.topia.persistence.TopiaEntityContextable;
-import org.nuiton.topia.persistence.util.TopiaEntityHelper;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Set;
-
-import static org.nuiton.topia.generator.TopiaGeneratorUtil.hasUnidirectionalRelationOnAbstractType;
-
-
-
-/*{generator option: parentheses = false}*/
-/*{generator option: writeString = +}*/
-
-/**
- * A template to generate all the {@link TopiaEntity} api for all classifier
- * with a {@code entity} stereotype.
- *
- * For example, given a {@code House} entity, it will generates :
- * <ul>
- * <li>{@code House} : contract of entity</li>
- * <li>{@code AbstractHouse} : default abstract implementation of entity</li>
- * <li>{@code HouseImpl} : default impl of abstract entity</li>
- * </ul>
- *
- * <b>Note: </b> The impl will ony be generated in these cases :
- * <ul>
- * <li>There is no abstract method</li>
- * <li>There is no already defined such class in class-path</li>
- * </ul>
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 2.3.4
- * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.generator.EntityTransformer"
- */
-public class EntityTransformer extends ObjectModelTransformerToJava {
-
- /** Logger */
- private static final Log log = LogFactory.getLog(EntityTransformer.class);
-
- protected ObjectModelInterface outputInterface;
-
- protected ObjectModelClass outputAbstract;
-
- protected ObjectModelClass outputImpl;
-
- private boolean associationClass;
-
- protected boolean generateInterface;
-
- protected boolean generateAbstract;
-
- protected boolean generateImpl;
-
- protected boolean generateBooleanGetMethods;
-
- protected void clean() {
- outputInterface = null;
- outputAbstract = null;
- outputImpl = null;
- }
-
- @Override
- public void transformFromClass(ObjectModelClass input) {
-
- if (!TopiaGeneratorUtil.isEntity(input)) {
-
- // not an entity, skip class.
- return;
- }
-
- if (log.isDebugEnabled()) {
- log.debug("for entity : " + input.getQualifiedName());
- log.debug("Will use classLoader " + getClassLoader());
- }
-
- // fix once for all the constant prefix to use
- String prefix = getConstantPrefix(input, "");
- if (StringUtils.isEmpty(prefix)) {
-
- // no specific prefix, so no prefix
- if (log.isWarnEnabled()) {
- log.warn("[" + input.getName() + "] Will generate constants with NO prefix, not a good idea... \n" +
- "Use '" + EugeneTagValues.TAG_CONSTANT_PREFIX +
- "' tagvalue in your xmi properties. For example " +
- "for all the model : model.tagvalue." + EugeneTagValues.TAG_CONSTANT_PREFIX + "=PROPERTY_");
- }
- }
- setConstantPrefix(prefix);
-
- generateInterface = isGenerateInterface(input);
- generateAbstract = isGenerateAbstract(input);
- generateImpl = isGenerateImpl(input);
-
- generateBooleanGetMethods = TopiaGeneratorUtil.isDoNotGenerateBooleanGetMethods(model, input);
-
- if (generateInterface) {
-
- // Create Entity Interface and its header
- createEntityInterface(input);
- }
-
- if (generateAbstract) {
-
- // Create Entity Abstract class and its header
- createEntityAbstractClass(input);
- }
-
- // Generate i18n block
- String i18nPrefix = TopiaGeneratorUtil.getI18nPrefixTagValue(input, model);
- if (!StringUtils.isEmpty(i18nPrefix)) {
- generateI18nBlock(input, outputAbstract, i18nPrefix);
- }
-
- // Create accept operation, will be updated during property generation
- createAcceptOperation();
-
- // Add constant, attribute and operations for each property
- generateProperties(input.getAttributes());
-
- // Case of association class : properties from participants/extremities
- // of the association class.
- if (input instanceof ObjectModelAssociationClass) {
- ObjectModelAssociationClass association =
- (ObjectModelAssociationClass)input;
- associationClass = true;
- generateProperties(association.getParticipantsAttributes());
- associationClass = false;
- }
-
- closeAcceptOperation();
-
- // Add extra constants (from uml dependency)
- generateExtraConstants(input);
-
- // Add extra operations (defined on the entity)
- generateExtraOperations(input);
-
- // Implement aggregate and composite operations
- generateAggregateOperation(input);
- generateCompositeOperation(input);
-
- // Implement toString operation
- if (TopiaGeneratorUtil.generateToString(input, model)) {
- generateToStringOperation(input);
- }
-
- // Generate serialVersionUID on abstract class
- generateSerialVersionUID(input, outputAbstract);
-
- // Generate Entity Implementation class
- if (generateImpl) {
- generateImpl(input);
- generateSerialVersionUID(input, outputImpl);
- }
-
-
-
- // Clean data output after transformation
- clean();
- }
-
- protected void generateSerialVersionUID(ObjectModelClass input,
- ObjectModelClass ouput) {
-
- // serialVersionUID
- String svUID = TopiaGeneratorUtil.findTagValue(TopiaGeneratorUtil.SERIAL_VERSION_UID,
- input,
- model
- );
- if (svUID == null) {
-
- // use a default one
- svUID = TopiaGeneratorUtil.generateSerialVersionUID(ouput) + "L";
- }
- addConstant(ouput, TopiaGeneratorUtil.SERIAL_VERSION_UID, long.class, svUID,
- ObjectModelJavaModifier.PRIVATE);
- }
-
- protected void createEntityInterface(ObjectModelClass input) {
-
- outputInterface = createInterface(input.getName(),
- input.getPackageName());
-
- // Documentation
- if (TopiaGeneratorUtil.hasDocumentation(input)) {
- setDocumentation(outputInterface, input.getDocumentation());
- }
-
- if (log.isTraceEnabled()) {
- log.trace("Will add interfaces on " +
- outputInterface.getQualifiedName());
- }
-
- List<String> interfaceAlreadyDone = new LinkedList<String> ();
- // Extends
- for (ObjectModelClassifier parent : input.getInterfaces()) {
- addInterface(interfaceAlreadyDone, outputInterface, parent);
- }
-
- // Extends from inheritance
- boolean needTopiaEntity = true;
- for (ObjectModelClassifier parent : input.getSuperclasses()) {
- if (TopiaGeneratorUtil.isEntity(parent)) {
- addInterface(interfaceAlreadyDone, outputInterface, parent);
- needTopiaEntity = false;
- break;
- }
- }
-
- // Extends TopiaEntity (only if hasn't parent entity)
- if (needTopiaEntity) {
-
- Class<?> interfaze = TopiaEntity.class;
-
- if (TopiaGeneratorUtil.isContextable(input)) {
- interfaze = TopiaEntityContextable.class;
- }
-
- addInterface(interfaceAlreadyDone,
- outputInterface,
- interfaze);
-
- } else if (TopiaGeneratorUtil.isContextable(input)) {
- // Even if there is no need to implement TopiaEntity, it might be
- // necessary to implement TopiaEntityContextable
- addInterface(interfaceAlreadyDone,
- outputInterface,
- TopiaEntityContextable.class);
- }
- }
-
- protected void createEntityAbstractClass(ObjectModelClass input) {
-
- outputAbstract = createAbstractClass(input.getName() + "Abstract",
- input.getPackageName());
-
- // Documentation
- StringBuilder doc = new StringBuilder();
- doc.append("Implantation POJO pour l'entité {@link ");
- doc.append(StringUtils.capitalize(outputInterface.getName()));
- doc.append("}\n");
-
- String dbName = TopiaGeneratorUtil.getDbName(input);
- if (dbName != null) {
- doc.append("<p>Nom de l'entité en BD : ");
- doc.append(dbName);
- doc.append(".</p>");
- }
-
- setDocumentation(outputAbstract, doc.toString());
-
- // Implements
- addInterface(outputAbstract, outputInterface.getName());
-
- // Extends
- for (ObjectModelClass parent : input.getSuperclasses()) {
- //tchemit-2011-09-12 What ever abstract or not, we alwyas use an Impl, moreover use the util method instead
- String extendClass = TopiaGeneratorUtil.getDOType(parent, model);
-// String extendClass = parent.getQualifiedName();
-// //Si une des classes parentes définies des méthodes abstraites, son
-// // impl ne sera pas créé
-// boolean abstractParent = TopiaGeneratorUtil.shouldBeAbstract(parent);
-// if (TopiaGeneratorUtil.isEntity(parent)) {
-// if (abstractParent) {
-// extendClass += "Abstract";
-// } else {
-// extendClass += "Impl";
-// }
-// }
- setSuperClass(outputAbstract, extendClass);
- }
-
- // Extends TopiaEntityAbstract (only if hasn't parent entity)
- if (outputAbstract.getSuperclasses().isEmpty()) {
- setSuperClass(outputAbstract, TopiaEntityAbstract.class);
- }
-
- addContextableMethods(input, outputAbstract);
- }
-
- /**
- * Ajout les methodes necessaire à l'interface {@link TopiaEntityContextable}
- * si le tagValue {@link TopiaTagValues#TAG_CONTEXTABLE} est renseigné.
- * @param input
- * @param outputAbstract
- */
- protected void addContextableMethods(ObjectModelClass input,
- ObjectModelClass outputAbstract) {
-
- if (TopiaGeneratorUtil.isContextable(input)) {
-
- addImport(outputAbstract, TopiaDaoSupplier.class);
-
- // topiaContext attribute
- ObjectModelAttribute topiaContextAttribute = addAttribute(
- outputAbstract, "topiaDaoSupplier", TopiaDaoSupplier.class, null,
- ObjectModelJavaModifier.PROTECTED, ObjectModelJavaModifier.TRANSIENT);
- setDocumentation(topiaContextAttribute,
- "TopiaDAO instance associated with the current \n" +
- "instance. For internal usage only");
-
- ObjectModelOperation op = addOperation(outputAbstract,
- "getTopiaDAOSupplier", TopiaDaoSupplier.class,
- ObjectModelJavaModifier.PUBLIC);
- setDocumentation(op,"@since 3.0");
- addAnnotation(outputAbstract, op, Override.class);
- setOperationBody(op, ""
-/*{
- return topiaDaoSupplier;
- }*/
- );
-
- op = addOperation(outputAbstract,
- "setTopiaDAOSupplier", "void",
- ObjectModelJavaModifier.PUBLIC);
- addException(op, TopiaException.class);
- addParameter(op, TopiaDaoSupplier.class, "topiaDaoSupplier");
- setDocumentation(op,
-// "@param context The context to set.\n" +
-// "@throws TopiaException if trying to replace a context\n" +
- "@since 3.0");
- addAnnotation(outputAbstract, op, Override.class);
- setOperationBody(op, ""
-/*{
- if (this.topiaDaoSupplier == null) {
- this.topiaDaoSupplier = topiaDaoSupplier;
-// } else {
-// throw new TopiaException("TopiaContext replacement is forbidden");
- }
- }*/
- );
-
- op = addOperation(outputAbstract, "update", "void",
- ObjectModelJavaModifier.PUBLIC);
- addException(op, TopiaException.class);
-// setDocumentation(op,"@since 2.5.3");
- addAnnotation(outputAbstract, op, Override.class);
- setOperationBody(op, ""
-/*{
- getTopiaDAOSupplier().getDao(<%=input.getName()%>.class).update(this);
- }*/
- );
-
- op = addOperation(outputAbstract, "delete", "void", ObjectModelJavaModifier.PUBLIC);
- addException(op, TopiaException.class);
-// setDocumentation(op,"@since 2.5.3");
- addAnnotation(outputAbstract, op, Override.class);
- setOperationBody(op, ""
-/*{
- getTopiaDAOSupplier().getDao(<%=input.getName()%>.class).delete(this);
- }*/
- );
- }
- }
-
- protected boolean isGenerateInterface(ObjectModelClass input) {
-
- boolean alreadyInClassPath = !isInClassPath(input);
- return alreadyInClassPath;
- }
-
- protected boolean isGenerateAbstract(ObjectModelClass input) {
-
- String fqn = input.getQualifiedName() + " Abstract";
- boolean alreadyInClassPath = !isInClassPath(fqn);
- return alreadyInClassPath;
- }
-
- protected boolean isGenerateImpl(ObjectModelClass input) {
-
- Collection<ObjectModelOperation> operations = input.getOperations();
- String fqn = input.getQualifiedName() + "Impl";
-
- boolean alreadyInClassPath = isInClassPath(fqn);
- if (alreadyInClassPath) {
-
- return false;
- }
-
- // On ne génère pas le impl si l'entité a des opérations
- if (!operations.isEmpty()) {
-
- log.info("Will not generate [" + fqn + "], there is some operations to manually implement");
- return false;
- }
-
- //De même, on ne génère pas le impl si il y a des opérations venant des
- // superclasses non implémentées
- for (ObjectModelOperation otherOp : input.getAllOtherOperations(false)) {
- if (otherOp.isAbstract()) {
- log.info("Will not generate [" + fqn + "], there is an abstract operation [" + otherOp.getName() + "] in allOtherOperations.");
- return false;
- }
- }
-
- return true;
- }
-
- protected void generateImpl(ObjectModelClass input) {
-
- String implName = input.getName() + "Impl";
- String packageName = input.getPackageName();
- if (isVerbose()) {
- log.info("Will generate [" + implName + "]");
- }
-
- if (isAbstract(input)) {
- outputImpl = createAbstractClass(implName, packageName);
- } else {
- outputImpl = createClass(implName, packageName);
- }
-
- setDocumentation(outputImpl, "Implantation des operations pour l'entité " +
- input.getName() + ".");
- setSuperClass(outputImpl, input.getQualifiedName() + "Abstract");
- }
-
- /**
- * Generate extra constants if {@code input} has dependencies on
- * enum used as constant injector.
- *
- * @param input Entity class to treate
- */
- protected void generateExtraConstants(ObjectModelClass input) {
- Set<String> constants = addConstantsFromDependency(input, outputInterface);
-
- if (log.isDebugEnabled()) {
- log.debug("Add constants from dependency : " + constants);
- }
- }
-
- protected void generateExtraOperations(ObjectModelClass input) {
- for (ObjectModelOperation operation : input.getOperations()) {
-
- String opName = operation.getName();
- String opType = operation.getReturnType();
- ObjectModelModifier visibility =
- ObjectModelJavaModifier.fromVisibility(operation.getVisibility());
-
- if (log.isDebugEnabled()) {
- log.debug("Extra operation for : " + input.getQualifiedName() +
- " - method : " + opName +
- " - returnType : " + opType +
- " - visibility : " + visibility);
- }
-
- // Deprecated from 2.3.4
- // Pas de génération des signatures de méthodes pour celles à intégrer au DAO de l'entité
- if (TopiaGeneratorUtil.hasDaoStereotype(operation)) {
- return;
-
- // Generate entity methods which have not a public visibility.
- // Only in abstract entity class as abstract operation.
- } else if (!visibility.equals(ObjectModelJavaModifier.PUBLIC)) {
- addOperation(outputAbstract, opName, opType, visibility,
- ObjectModelJavaModifier.ABSTRACT);
-
- // Other operations, only in entity interface, implementations
- // need to be done in implementation class created by developper
- } else {
- cloneOperationSignature(operation, outputInterface, true);
- }
- }
- }
-
- /**
- * Generate properties from {@code attributes}. Generate
- * constant, attribute and operations for each property.
- *
- * @param attributes Input attributes
- */
- protected void generateProperties(Collection<ObjectModelAttribute> attributes) {
- for (ObjectModelAttribute attribute : attributes) {
-
- if (!associationClass) {
-
- // FIXME-fdesbois-2010-06-25 : Strange behavior to keep those links, will break hibernate, may be a problem in mapping
- if (!attribute.isNavigable() && attribute.hasAssociationClass()) {
- generatePropertyConstant(attribute);
-
- generatePropertyAttribute(attribute);
-
- updateAcceptOperation(attribute);
- }
-
- if (!attribute.isNavigable() &&
- !TopiaGeneratorUtil.hasUnidirectionalRelationOnAbstractType(
- attribute.getReverseAttribute(), model)) {
- continue;
- }
- }
-
- // constant
- generatePropertyConstant(attribute);
-
- // attribute
- generatePropertyAttribute(attribute);
-
- // operations
- generatePropertyOperations(attribute);
-
- // update accept body
- updateAcceptOperation(attribute);
- }
- }
-
- // -------------------------------------------------------------------------
- // Generate for property
- // -------------------------------------------------------------------------
-
- /**
- * Generate constant in interface for {@code attribute}.
- *
- * @param attribute Input attribute to treate
- * @see #getPropertyName(ObjectModelAttribute)
- */
- protected void generatePropertyConstant(ObjectModelAttribute attribute) {
- String attrName = getPropertyName(attribute);
-
- if (log.isDebugEnabled()) {
- log.debug("Generate constant for property : " + attrName);
- }
-
- addAttribute(outputInterface, getConstantName(attrName), String.class,
- "\"" + attrName + "\"");
- }
-
- protected void generatePropertyAttribute(ObjectModelAttribute attribute) {
-
- String attrName = getPropertyName(attribute);
- String attrType = getPropertyType(attribute);
- String collectionType = getCollectionType(attribute);
-
- if (collectionType != null) {
- attrType = collectionType + "<" + attrType + ">";
- }
-
- //String attrVisibility = attr.getVisibility();
-
- // Declaration
- ObjectModelAttribute property =
- addAttribute(outputAbstract, attrName, attrType, null,
- //ObjectModelJavaModifier.toValue(attrVisibility),
- ObjectModelJavaModifier.PROTECTED
- );
-
- // Documentation
- StringBuilder buffer = new StringBuilder();
- if (TopiaGeneratorUtil.hasDocumentation(attribute)) {
- String attrDocumentation = attribute.getDocumentation();
- buffer.append(attrDocumentation).append('\n');
- }
-
- String dbName = TopiaGeneratorUtil.getDbName(attribute);
- if (!StringUtils.isEmpty(dbName)) {
- buffer.append("Nom de l'attribut en BD : ").append(dbName).append('\n');
- }
- setDocumentation(property, buffer.toString());
-
- // Annotation
- String annotation = TopiaGeneratorUtil.getAnnotationTagValue(attribute);
- if (!StringUtils.isEmpty(annotation)) {
- //FIXME Make annotation works...
- //TODO tchemit 20100513 Test it still works
- addAnnotation(outputAbstract, property, annotation);
- }
- }
-
- /**
- * Generation operations for {@code attributes}.
- * One method exists for each operation to generate. Methods starting
- * with 'addSingle' is for maxMultiplicity attribute = 1 and for collection
- * case, methods start with 'addMultiple'. Other case are take care in each
- * method (association class, reverse, entity reference, ...).
- *
- * @param attribute Input attribute to treate
- * @see #addSingleGetOperation(ObjectModelAttribute, String, String)
- * @see #addSingleSetOperation(ObjectModelAttribute)
- * @see #addMultipleAddOperation(ObjectModelAttribute, String)
- * @see #addMultipleAddAllOperation(ObjectModelAttribute, String)
- * @see #addMultipleSetOperation(ObjectModelAttribute, String, String)
- * @see #addMultipleRemoveOperation(ObjectModelAttribute)
- * @see #addMultipleClearOperation(ObjectModelAttribute, String, String)
- * @see #addMultipleGetOperation(ObjectModelAttribute, String)
- * @see #addMultipleGetTopiaIdOperation(ObjectModelAttribute)
- * @see #addMultipleGetOperationFromEntity(ObjectModelAttribute)
- * @see #addMultipleSizeOperation(ObjectModelAttribute)
- * @see #addMultipleIsEmptyOperation(ObjectModelAttribute)
- */
- protected void generatePropertyOperations(ObjectModelAttribute attribute) {
-
- if (attribute.getMaxMultiplicity() == 1 || associationClass) {
-
- // setXXX
- addSingleSetOperation(attribute);
-
- boolean booleanProperty =
- TopiaGeneratorUtil.isBooleanPrimitive(attribute);
-
- String attrType = getPropertyType(attribute);
-
- if (booleanProperty) {
-
- // isXXX
- addSingleGetOperation(
- attribute,
- attrType,
- TopiaGeneratorUtil.OPERATION_GETTER_BOOLEAN_PREFIX);
- }
-
- if (!booleanProperty || generateBooleanGetMethods) {
-
- // getXXX
- addSingleGetOperation(
- attribute,
- attrType,
- TopiaGeneratorUtil.OPERATION_GETTER_DEFAULT_PREFIX);
- }
-
- } else {
-
- // List, Set or Collection ?
- String collectionInterface =
- TopiaGeneratorUtil.getNMultiplicityInterfaceType(attribute);
- String collectionImpl =
- TopiaGeneratorUtil.getNMultiplicityObjectType(attribute);
-
- addImport(outputInterface, collectionInterface);
- addImport(outputAbstract, collectionInterface);
- addImport(outputAbstract, collectionImpl);
-
- collectionInterface =
- TopiaGeneratorUtil.getSimpleName(collectionInterface);
- collectionImpl =
- TopiaGeneratorUtil.getSimpleName(collectionImpl);
-
- // addXXX
- addMultipleAddOperation(attribute, collectionImpl);
-
- // addAllXXX
- addMultipleAddAllOperation(attribute, collectionInterface);
-
- // setXXX
- addMultipleSetOperation(attribute, collectionInterface, collectionImpl);
-
- // removeXXX
- addMultipleRemoveOperation(attribute);
-
- // clearXXX
- addMultipleClearOperation(attribute, collectionInterface, collectionImpl);
-
- // getXXX
- addMultipleGetOperation(attribute, collectionInterface);
-
- if (TopiaGeneratorUtil.isEntity(attribute, model)) {
-
- // getXXXByTopiaId
- addMultipleGetTopiaIdOperation(attribute);
- }
-
- if (attribute.hasAssociationClass()) {
- // getXXX with entity parameter
- addMultipleGetOperationFromEntity(attribute);
- }
-
- // sizeXXX
- addMultipleSizeOperation(attribute);
-
- // isXXXEmpty
- addMultipleIsEmptyOperation(attribute);
- }
- }
-
- protected void addSingleSetOperation(ObjectModelAttribute attribute) {
-
- String attrName = getPropertyName(attribute);
- String attrType = getPropertyType(attribute);
-
- if (log.isDebugEnabled()) {
- log.debug("Generate single 'set' operation for property : " + attrName +
- " [" + attrType + "]");
- }
-
- // Interface operation
- ObjectModelOperation interfaceOperation =
- createPropertySetterSignature(outputInterface, attrType, attrName,
- "");
-
- // Implementation
- ObjectModelOperation implOperation = createImplOperation(interfaceOperation);
-
- attrType = TopiaGeneratorUtil.getSimpleName(attrType);
-
- String constantName = getConstantName(attrName);
-
- setOperationBody(implOperation, ""
-/*{
- <%=attrType%> oldValue = this.<%=attrName%>;
- fireOnPreWrite(<%=constantName%>, oldValue, <%=attrName%>);
- this.<%=attrName%> = <%=attrName%>;
- fireOnPostWrite(<%=constantName%>, oldValue, <%=attrName%>);
- }*/
- );
- }
-
- /**
- * Add getter for simple property (neither association nor multiple).
- * Will add two different operations for boolean case ('is' method and
- * 'get' method). This method add the operation in both {@code
- * outputAbstract} and {@code outputInterface}.
- *
- * @param attribute ObjectModelAttribute for getter operation
- * @param attrType type of the attribute
- * @param operationPrefix Operation prefix : 'get' by default, if prefix
- * is null
- */
- protected void addSingleGetOperation(ObjectModelAttribute attribute,
- String attrType,
- String operationPrefix) {
-
- String attrName = getPropertyName(attribute);
-
- if (log.isDebugEnabled()) {
- log.debug("Generate single '" + operationPrefix + "' operation for property : "
- + attrName + " [" + attrType + "]");
- }
-
- String constantName = getConstantName(attrName);
-
- // Interface operation
- ObjectModelOperation interfaceOperation =
- addOperation(outputInterface, getJavaBeanMethodName(operationPrefix, attrName),
- attrType, ObjectModelJavaModifier.PACKAGE);
-
- // Implementation
- ObjectModelOperation implOperation =
- createImplOperation(interfaceOperation);
-
- attrType = TopiaGeneratorUtil.getSimpleName(attrType);
-
- setOperationBody(implOperation, ""
-/*{
- fireOnPreRead(<%=constantName%>, <%=attrName%>);
- <%=attrType%> result = this.<%=attrName%>;
- fireOnPostRead(<%=constantName%>, <%=attrName%>);
- return result;
- }*/
- );
- }
-
- protected void addMultipleAddOperation(ObjectModelAttribute attribute,
- String collectionImpl) {
-
- String attrName = getPropertyName(attribute);
- String attrType = getPropertyType(attribute);
- ObjectModelAttribute reverse = attribute.getReverseAttribute();
-
- if (log.isDebugEnabled()) {
- log.debug("Generate multiple 'add' operation for property : " + attrName +
- " [" + attrType + "]");
- }
-
- String constantName = getConstantName(attrName);
-
- // Interface operation
- ObjectModelOperation interfaceOperation =
- addOperation(outputInterface, getJavaBeanMethodName("add", attrName),
- void.class, ObjectModelJavaModifier.PACKAGE);
- ObjectModelParameter param =
- addParameter(interfaceOperation, attrType, attrName);
-
- // Implementation
- ObjectModelOperation implOperation = createImplOperation(interfaceOperation);
-
- attrType = TopiaGeneratorUtil.getSimpleName(attrType);
-
- StringBuilder body = new StringBuilder();
-
- body.append(""
-/*{
- fireOnPreWrite(<%=constantName%>, null, <%=attrName%>);
- if (this.<%=attrName%> == null) {
- this.<%=attrName%> = new <%=collectionImpl%><<%=attrType%>>();
- }
-}*/
- );
-
- if (reverse != null && (reverse.isNavigable() ||
- hasUnidirectionalRelationOnAbstractType(attribute, model))) {
- String getterName = getJavaBeanMethodName("get", reverse.getName());
- String setterName = getJavaBeanMethodName("set", reverse.getName());
-
- String reverseAttrType = TopiaGeneratorUtil.getSimpleName(reverse.getType());
-
- if (!TopiaGeneratorUtil.isNMultiplicity(reverse)) {
- body.append(""
-/*{
- <%=attrName%>.<%=setterName%>(this);
-}*/
- );
- // Don't manage reverse attribute add if attribute has associationClass
- } else if (!attribute.hasAssociationClass()) {
- body.append(""
-/*{
- if (<%=attrName%>.<%=getterName%>() == null) {
- <%=attrName%>.<%=setterName%>(new <%=collectionImpl%><<%=reverseAttrType%>>());
- }
- <%=attrName%>.<%=getterName%>().add(this);
-}*/
- );
- }
- }
- body.append(""
-/*{
- this.<%=attrName%>.add(<%=attrName%>);
- fireOnPostWrite(<%=constantName%>, this.<%=attrName%>.size(), null, <%=attrName%>);
- }*/
- );
- setOperationBody(implOperation, body.toString());
- }
-
- protected void addMultipleAddAllOperation(ObjectModelAttribute attribute,
- String collectionInterface) {
-
- String attrName = getPropertyName(attribute);
- String attrType = getPropertyType(attribute);
-
- if (log.isDebugEnabled()) {
- log.debug("Generate multiple 'addAll' operation for property : " + attrName +
- " [" + attrType + "]");
- }
-
- // Interface operation
- ObjectModelOperation interfaceOperation =
- addOperation(outputInterface, getJavaBeanMethodName("addAll", attrName),
- void.class, ObjectModelJavaModifier.PACKAGE);
- ObjectModelParameter param =
- addParameter(interfaceOperation, collectionInterface + "<" + attrType + ">", attrName);
-
- // Implementation
- ObjectModelOperation implOperation =
- createImplOperation(interfaceOperation);
-
- attrType = TopiaGeneratorUtil.getSimpleName(attrType);
- String addMethodName = getJavaBeanMethodName("add", attrName);
- setOperationBody(implOperation, ""
-/*{
- if (<%=attrName%> == null) {
- return;
- }
- for (<%=attrType%> item : <%=attrName%>) {
- <%=addMethodName%>(item);
- }
- }*/
- );
- }
-
- protected void addMultipleSetOperation(ObjectModelAttribute attribute,
- String collectionInterface,
- String collectionImpl) {
-
- String attrName = getPropertyName(attribute);
- String referenceType = getPropertyType(attribute);
- String attrType = collectionInterface + "<" + referenceType + ">";
- String constantName = getConstantName(attrName);
-
- if (log.isDebugEnabled()) {
- log.debug("Generate multiple 'set' operation for property : " + attrName +
- " [" + attrType + "]");
- }
-
- // Interface operation
- ObjectModelOperation interfaceOperation =
- createPropertySetterSignature(outputInterface, attrType, attrName,
- "");
-
- ObjectModelOperation implOperation = createImplOperation(interfaceOperation);
-
- attrType = TopiaGeneratorUtil.getSimpleName(attrType);
- referenceType = TopiaGeneratorUtil.getSimpleName(referenceType);
-
- // Force fire for collection
- setOperationBody(implOperation, ""
-/*{
- // Copy elements to keep data for fire with new reference
- <%=attrType%> oldValue = this.<%=attrName%> != null ? new <%=collectionImpl%><<%=referenceType%>>(this.<%=attrName%>) : null;
- fireOnPreWrite(<%=constantName%>, oldValue, <%=attrName%>);
- this.<%=attrName%> = <%=attrName%>;
- fireOnPostWrite(<%=constantName%>, oldValue, <%=attrName%>);
- }*/
- );
- }
-
- protected void addMultipleRemoveOperation(ObjectModelAttribute attribute) {
-
- String attrName = getPropertyName(attribute);
- String attrType = getPropertyType(attribute);
- ObjectModelAttribute reverse = attribute.getReverseAttribute();
- String constantName = getConstantName(attrName);
-
- if (log.isDebugEnabled()) {
- log.debug("Generate 'remove' operation for property : " + attrName +
- " [" + attrType + "]");
- }
-
- // Interface operation
- ObjectModelOperation interfaceOperation =
- addOperation(outputInterface, getJavaBeanMethodName("remove" , attrName),
- void.class, ObjectModelJavaModifier.PACKAGE);
- ObjectModelParameter param =
- addParameter(interfaceOperation, attrType, attrName);
-
- // Implementation
- ObjectModelOperation implOperation = createImplOperation(interfaceOperation);
-
- attrType = TopiaGeneratorUtil.getSimpleName(attrType);
-
- StringBuilder body = new StringBuilder();
-
- body.append(""
-/*{
- fireOnPreWrite(<%=constantName%>, <%=attrName%>, null);
- if (this.<%=attrName%> == null || !this.<%=attrName%>.remove(<%=attrName%>)) {
- throw new IllegalArgumentException("List does not contain given element");
- }
-}*/
- );
-
- if (reverse != null && (reverse.isNavigable() ||
- hasUnidirectionalRelationOnAbstractType(attribute, model))) {
- String getterName = getJavaBeanMethodName("get", reverse.getName());
- String setterName = getJavaBeanMethodName("set", reverse.getName());
- if (!TopiaGeneratorUtil.isNMultiplicity(reverse)) {
- body.append(""
-/*{
- <%=attrName%>.<%=setterName%>(null);
-}*/
- );
- // Don't manage reverse attribute remove if attribute has associationClass
- } else if (!attribute.hasAssociationClass()) {
- body.append(""
-/*{
- <%=attrName%>.<%=getterName%>().remove(this);
-}*/
- );
- }
- }
- body.append(""
-/*{
- fireOnPostWrite(<%=constantName%>, this.<%=attrName%>.size() + 1, <%=attrName%>, null);
- }*/
- );
- setOperationBody(implOperation, body.toString());
- }
-
- protected void addMultipleClearOperation(ObjectModelAttribute attribute,
- String collectionInterface,
- String collectionImpl) {
-
- String attrName = getPropertyName(attribute);
- String attrType = getPropertyType(attribute);
- ObjectModelAttribute reverse = attribute.getReverseAttribute();
- String constantName = getConstantName(attrName);
-
- if (log.isDebugEnabled()) {
- log.debug("Generate multiple 'clear' operation for property : " + attrName +
- " [" + attrType + "]");
- }
-
- // Interface operation
- ObjectModelOperation interfaceOperation =
- addOperation(outputInterface, getJavaBeanMethodName("clear" , attrName),
- void.class, ObjectModelJavaModifier.PACKAGE);
-
- // Implementation
- ObjectModelOperation implOperation = createImplOperation(interfaceOperation);
-
- attrType = TopiaGeneratorUtil.getSimpleName(attrType);
-
- StringBuilder body = new StringBuilder(""
-/*{
- if (this.<%=attrName%> == null) {
- return;
- }
-}*/
- );
-
- if (reverse != null && (reverse.isNavigable() ||
- hasUnidirectionalRelationOnAbstractType(attribute, model))) {
- String getterName = getJavaBeanMethodName("get", reverse.getName());
- String setterName = getJavaBeanMethodName("set", reverse.getName());
- body.append(""
-/*{ for (<%=attrType%> item : this.<%=attrName%>) {
-}*/
- );
- if (!TopiaGeneratorUtil.isNMultiplicity(reverse)) {
- body.append(""
-/*{ item.<%=setterName%>(null);
-}*/
- );
- // Don't manage reverse attribute remove if attribute has associationClass
- } else if (!attribute.hasAssociationClass()) {
- body.append(""
-/*{ item.<%=getterName%>().remove(this);
-}*/
- );
- }
- body.append(""
-/*{ }
-}*/
- );
- }
- body.append(""
-/*{ <%=collectionInterface%><<%=attrType%>> oldValue = new <%=collectionImpl%><<%=attrType%>>(this.<%=attrName%>);
- fireOnPreWrite(<%=constantName%>, oldValue, this.<%=attrName%>);
- this.<%=attrName%>.clear();
- fireOnPostWrite(<%=constantName%>, oldValue, this.<%=attrName%>);
- }*/
- );
- setOperationBody(implOperation, body.toString());
- }
-
- protected void addMultipleGetOperation(ObjectModelAttribute attribute,
- String collectionInterface) {
-
- String attrName = getPropertyName(attribute);
- String attrType = collectionInterface + "<" + getPropertyType(attribute) + ">";
-
- if (log.isDebugEnabled()) {
- log.debug("Generate multiple 'get' operation for property : " + attrName +
- " [" + attrType + "]");
- }
-
- // Interface operation
- ObjectModelOperation interfaceOperation =
- addOperation(outputInterface, getJavaBeanMethodName("get" , attrName),
- attrType, ObjectModelJavaModifier.PACKAGE);
-
- // Implementation
- ObjectModelOperation implOperation = createImplOperation(interfaceOperation);
-
- setOperationBody(implOperation, ""
-/*{
- return <%=attrName%>;
- }*/
- );
- }
-
- protected void addMultipleGetTopiaIdOperation(ObjectModelAttribute attribute) {
-
- String attrName = getPropertyName(attribute);
- String attrType = getPropertyType(attribute);
-
- if (log.isDebugEnabled()) {
- log.debug("Generate multiple 'getByTopiaId' operation for property : " + attrName +
- " [" + attrType + "]");
- }
-
- // Interface operation
- ObjectModelOperation interfaceOperation =
- addOperation(outputInterface, getJavaBeanMethodName("get", attrName) + "ByTopiaId",
- attrType, ObjectModelJavaModifier.PACKAGE);
- ObjectModelParameter param =
- addParameter(interfaceOperation, String.class, "topiaId");
-
- // Implementation
- ObjectModelOperation implOperation =
- createImplOperation(interfaceOperation);
-
- addImport(outputAbstract, TopiaEntityHelper.class);
-
- setOperationBody(implOperation, ""
-/*{
- return TopiaEntityHelper.getEntityByTopiaId(<%=attrName%>, topiaId);
- }*/
- );
- }
-
- protected void addMultipleGetOperationFromEntity(ObjectModelAttribute attribute) {
-
- // reference to the real attribute name
- String referenceName = attribute.getName();
- String referenceType = attribute.getType();
-
- String referenceGetterName = getJavaBeanMethodName("get", referenceName);
- // association attribute name
- String attrName = getPropertyName(attribute);
- String attrType = getPropertyType(attribute);
-
- if (log.isDebugEnabled()) {
- log.debug("Generate multiple 'getFromEntity' operation for property : " + attrName +
- " [" + attrType + "]");
- }
-
- // Interface operation
- ObjectModelOperation interfaceOperation =
- addOperation(outputInterface,
- getJavaBeanMethodName("get", attrName), attrType);
-
- addParameter(interfaceOperation, referenceType, referenceName);
-
- // Implementation
- ObjectModelOperation implOperation = createImplOperation(interfaceOperation);
-
- attrType = TopiaGeneratorUtil.getSimpleName(attrType);
-
- setOperationBody(implOperation, ""
-/*{
- if (<%=referenceName%> == null || this.<%=attrName%> == null) {
- return null;
- }
- for (<%=attrType%> item : this.<%=attrName%>) {
- if (<%=referenceName%>.equals(item.<%=referenceGetterName%>())) {
- return item;
- }
- }
- return null;
- }*/
- );
- }
-
- protected void addMultipleSizeOperation(ObjectModelAttribute attribute) {
-
- String attrName = getPropertyName(attribute);
-
- if (log.isDebugEnabled()) {
- log.debug("Generate multiple 'size' operation for property : " + attrName);
- }
-
- // Interface operation
- ObjectModelOperation interfaceOperation =
- addOperation(outputInterface, getJavaBeanMethodName("size", attrName),
- int.class, ObjectModelJavaModifier.PACKAGE);
-
- // Implementation
- ObjectModelOperation implOperation = createImplOperation(interfaceOperation);
-
- setOperationBody(implOperation, ""
-/*{
- if (<%=attrName%> == null) {
- return 0;
- }
- return <%=attrName%>.size();
- }*/
- );
- }
-
- protected void addMultipleIsEmptyOperation(ObjectModelAttribute attribute) {
-
- String attrName = getPropertyName(attribute);
-
- if (log.isDebugEnabled()) {
- log.debug("Generate multiple 'isEmpty' operation for property : " + attrName);
- }
-
- String sizeMethodName = getJavaBeanMethodName("size", attrName);
- // Interface operation
- ObjectModelOperation interfaceOperation =
- addOperation(outputInterface, getJavaBeanMethodName("is", attrName)+ "Empty",
- boolean.class, ObjectModelJavaModifier.PACKAGE);
-
- // Implementation
- ObjectModelOperation implOperation = createImplOperation(interfaceOperation);
-
- setOperationBody(implOperation, ""
-/*{
- int size = <%=sizeMethodName%>();
- return size == 0;
- }*/
- );
- }
-
- // -------------------------------------------------------------------------
- // Generate util operations
- // -------------------------------------------------------------------------
-
- private ObjectModelOperation acceptOperation;
-
- private StringBuilder acceptOperationBody;
-
- protected void createAcceptOperation() {
-
- // Declaration
- acceptOperation = addOperation(outputAbstract, "accept", void.class);
- addAnnotation(outputAbstract, acceptOperation , Override.class);
- ObjectModelParameter param =
- addParameter(acceptOperation, EntityVisitor.class, "visitor");
-
- addException(acceptOperation, TopiaException.class);
-
- // Body init
- acceptOperationBody = new StringBuilder(""
-/*{
- visitor.start(this);
-}*/
- );
- }
-
- protected void updateAcceptOperation(ObjectModelAttribute attribute) {
- String attrName =
- TopiaGeneratorUtil.getSimpleName(getPropertyName(attribute));
- String attrType =
- TopiaGeneratorUtil.getSimpleName(getPropertyType(attribute));
- String collectionType = getCollectionType(attribute);
- String constantName = getConstantName(attrName);
- if (collectionType != null) {
- collectionType = TopiaGeneratorUtil.getSimpleName(collectionType);
- acceptOperationBody.append(""
-/*{ visitor.visit(this, <%=constantName%>, <%=collectionType%>.class, <%=attrType%>.class, <%=attrName%>);
-}*/
- );
- } else {
- acceptOperationBody.append(""
-/*{ visitor.visit(this, <%=constantName%>, <%=attrType%>.class, <%=attrName%>);
-}*/
- );
- }
- }
-
- protected void closeAcceptOperation() {
- acceptOperationBody.append(""
-/*{ visitor.end(this);
- }*/
- );
- setOperationBody(acceptOperation, acceptOperationBody.length() == 0 ?
- " " : acceptOperationBody.toString());
- }
-
- protected void generateToStringOperation(ObjectModelClass input) {
-
- if (log.isDebugEnabled()) {
- log.debug("generate toString method for entity " +
- outputInterface.getQualifiedName());
- }
- ObjectModelOperation operation =
- addOperation(outputAbstract, "toString", String.class);
-
- addAnnotation(outputAbstract, operation, Override.class);
-
- addImport(outputAbstract, ToStringBuilder.class);
-
- StringBuilder body = new StringBuilder(""
-/*{
- String result = new ToStringBuilder(this).
-}*/
- );
- for (ObjectModelAttribute attr : input.getAttributes()) {
-
- //FIXME possibilité de boucles (non directes)
-
- ObjectModelClass attrEntity = null;
-
- if (model.hasClass(attr.getType())) {
- attrEntity = model.getClass(attr.getType());
- }
-
- boolean isEntity = attrEntity != null &&
- TopiaGeneratorUtil.isEntity(attrEntity);
-
- ObjectModelAttribute reverse = attr.getReverseAttribute();
- if (isEntity && (reverse == null || !reverse.isNavigable())
- && !attr.hasAssociationClass() || !isEntity) {
- String attrName = attr.getName();
- String constantName = getConstantName(attrName);
- body.append(""
-/*{ append(<%=constantName%>, this.<%=attrName%>).
-}*/
- );
- }
- }
- body.append(""
-/*{ toString();
- return result;
- }*/
- );
- setOperationBody(operation, body.length() == 0 ? " " : body.toString());
-
- }
-
- protected void generateCompositeOperation(ObjectModelClass input) {
-
- ObjectModelOperation operation =
- addOperation(outputAbstract, "getComposite",
- List.class.getName() + '<' + TopiaEntity.class.getName() + '>');
-
- addException(operation, TopiaException.class);
- addAnnotation(outputAbstract, operation, Override.class);
-
- StringBuilder body;
- if (!TopiaGeneratorUtil.isContextable(input)) {
- body = new StringBuilder(""
-/*{
- throw new UnsupportedOperationException("Since ToPIA 3.0, 'getComposite' is only available for contextable entities");
- }*/
- );
- } else {
- addImport(outputAbstract, ArrayList.class);
- addImport(outputAbstract, List.class);
-
- body = new StringBuilder(""
-/*{
- List<TopiaEntity> tmp = new ArrayList<TopiaEntity>();
-
- // pour tous les attributs rechecher les composites et les class d'asso
- // on les ajoute dans tmp
-}*/
- );
- for (ObjectModelAttribute attr : input.getAttributes()) {
-
- if (attr.referenceClassifier() &&
- TopiaGeneratorUtil.isEntity(attr.getClassifier())) {
-
- if (attr.isComposite()) {
- String attrName = attr.getName();
- String getterName = getJavaBeanMethodName("get", attrName);
- if (TopiaGeneratorUtil.isNMultiplicity(attr)) {
- body.append(""
-/*{ if (<%=getterName%>() != null) {
- tmp.addAll(<%=getterName%>());
- }
-}*/
- );
- } else {
- body.append(""
-/*{ tmp.add(<%=getterName%>());
-}*/
- );
- }
- } else if (attr.hasAssociationClass()) {
- String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(
- attr);
- String assocClassFQN = TopiaGeneratorUtil.getSimpleName(
- attr.getAssociationClass().getQualifiedName());
- String ref = "this." + TopiaGeneratorUtil.toLowerCaseFirstLetter(
- assocAttrName);
- if (!TopiaGeneratorUtil.isNMultiplicity(attr)) {
- body.append(""
-/*{
- if (<%=ref%> != null) {
- tmp.add(<%=ref%>);
- }
-}*/
- );
- } else {
- ObjectModelAttribute reverse = attr.getReverseAttribute();
- String reverseAttrName = reverse.getName();
- // On utilise pas l'attribut car il est potentiellement
- // pas a jour, car pour les asso avec cardinalité
- // personne ne fait de add. Ce qui est normal, mais
- // pour pouvoir faire tout de meme des delete en cascade
- // sur les asso, le champs est dans le mapping
- // hibernate et donc il le faut aussi dans la classe
- // sinon hibernate rale lorsqu'il charge l'objet
- // if (<%=ref%> != null) {
- // tmp.addAll(<%=ref%>);
- // }
-
- body.append(""
-/*{
- {
- org.nuiton.topia.persistence.TopiaDAO<<%=assocClassFQN%>> dao = getTopiaContext().getDao(<%=assocClassFQN%>.class);
- List<<%=assocClassFQN%>> findAllByProperties = dao.findAllByProperties("<%=reverseAttrName%>", this);
- if (findAllByProperties != null) {
- tmp.addAll(findAllByProperties);
- }
- }
-}*/
- );
- }
- }
- }
- }
- body.append(""
-/*{
- // on refait un tour sur chaque entity de tmp pour recuperer leur
- // composite
- List<TopiaEntity> result = new ArrayList<TopiaEntity>();
- for (TopiaEntity entity : tmp) {
- if (entity != null) {
- result.add(entity);
- result.addAll(entity.getComposite());
- }
- }
- return result;
- }*/
- );
- }
-
- setOperationBody(operation, body.length() == 0 ? " " : body.toString());
- }
-
- protected void generateAggregateOperation(ObjectModelClass input) {
-
- ObjectModelOperation operation =
- addOperation(outputAbstract, "getAggregate",
- List.class.getName() + '<' + TopiaEntity.class.getName() + '>');
-
- addException(operation, TopiaException.class);
- addAnnotation(outputAbstract, operation, Override.class);
-
-
- StringBuilder body = new StringBuilder();
- if (!TopiaGeneratorUtil.isContextable(input)) {
- body = new StringBuilder(""
-/*{
- throw new UnsupportedOperationException("Since ToPIA 3.0, 'getComposite' is only available for contextable entities");
- }*/
- );
- } else {
-
- addImport(outputAbstract, ArrayList.class);
- addImport(outputAbstract, List.class);
- body .append(""
-/*{
- List<TopiaEntity> tmp = new ArrayList<TopiaEntity>();
-
- // pour tous les attributs rechecher les composites et les class d'asso
- // on les ajoute dans tmp
-}*/
- );
- for (ObjectModelAttribute attr : input.getAttributes()) {
-
- if (attr.referenceClassifier() &&
- TopiaGeneratorUtil.isEntity(attr.getClassifier()) &&
- attr.isAggregate()) {
-
- String attrName = attr.getName();
- String getterName = getJavaBeanMethodName("get", attrName);
- if (TopiaGeneratorUtil.isNMultiplicity(attr)) {
- body.append(""
-/*{ tmp.addAll(<%=getterName%>());
-}*/
- );
- } else {
- body.append(""
-/*{ tmp.add(<%=getterName%>());
-}*/
- );
- }
- }
- }
- body.append(""
-/*{
- // on refait un tour sur chaque entity de tmp pour recuperer leur
- // composite
- List<TopiaEntity> result = new ArrayList<TopiaEntity>();
- for (TopiaEntity entity : tmp) {
- result.add(entity);
- result.addAll(entity.getAggregate());
- }
- return result;
- }*/
- );
- }
- setOperationBody(operation, body.length() == 0 ? " " : body.toString());
- }
-
- // -------------------------------------------------------------------------
- // Helpers
- // -------------------------------------------------------------------------
-
- protected boolean isAbstract(ObjectModelClass clazz) {
- if (clazz.isAbstract()) {
- return true;
- }
-
- //Une classe peut être abstraite si elle a des méthodes définies dans
- // ses superinterface et non implantées dans ses superclasses
- Collection<ObjectModelOperation> allInterfaceOperations =
- clazz.getAllInterfaceOperations(true);
- allInterfaceOperations.removeAll(clazz.getAllOtherOperations(true));
- for (ObjectModelOperation op : allInterfaceOperations) {
- boolean implementationFound = false;
- for (ObjectModelClass superClazz : clazz.getSuperclasses()) {
- for (ObjectModelOperation matchingOp :
- superClazz.getOperations(op.getName())) {
- implementationFound = op.equals(matchingOp) &&
- !matchingOp.isAbstract();
- if (implementationFound) {
- break;
- }
- }
- if (implementationFound) {
- break;
- }
- }
- if (!implementationFound) {
- if (log.isDebugEnabled()) {
- log.debug(clazz.getName() + " : abstract operation " + op);
- }
- return true;
- }
- }
- return false;
- }
-
- protected String getCollectionType(ObjectModelAttribute attribute) {
- String result = null;
- if (!associationClass && TopiaGeneratorUtil.isNMultiplicity(attribute)) {
- result = TopiaGeneratorUtil.getNMultiplicityInterfaceType(attribute);
- }
- return result;
- }
-
- protected String getPropertyName(ObjectModelAttribute attribute) {
- String propertyName = attribute.getName();
- if (!associationClass && attribute.hasAssociationClass()) {
- propertyName = TopiaGeneratorUtil.getAssocAttrName(attribute);
- }
- return propertyName;
- }
-
- protected String getPropertyType(ObjectModelAttribute attribute) {
- String propertyType = attribute.getType();
- if (!associationClass && attribute.hasAssociationClass()) {
- propertyType = attribute.getAssociationClass().getQualifiedName();
- }
- return propertyType;
- }
-
- protected ObjectModelOperation createImplOperation(ObjectModelOperation interfaceOperation) {
- ObjectModelOperation implOperation =
- cloneOperationSignature(interfaceOperation, outputAbstract, false);
- addAnnotation(outputAbstract, implOperation, Override.class);
- return implOperation;
- }
-
- /**
- * TODO-fdesbois-2010-06-25 : This method can be put in JavaBuilder or ObjectModelTransformerToJava
- *
- * This method create an set operation in {@code classifier} with
- * {@code propertyType} as return type and {@code propertyName} used for
- * operation name ('set[propertyName]'). {@code operationDocument} can
- * also be added to the operation created. Only signature with default
- * visibility will be added.
- *
- * @param classifier Classifier where the operation will be added
- * @param propertyType Type of the property (better if qualified name)
- * @param propertyName Name of the property to set
- * @param operationDocumentation Documentation for the operation
- * @return the created operation
- */
- protected ObjectModelOperation createPropertySetterSignature(ObjectModelClassifier classifier,
- String propertyType,
- String propertyName,
- String operationDocumentation) {
- // Operation
- ObjectModelOperation operation =
- addOperation(classifier,
- getJavaBeanMethodName("set", propertyName), void.class);
-
- ObjectModelParameter param =
- addParameter(operation, propertyType, propertyName);
-
- // Documentation
- if (StringUtils.isNotEmpty(operationDocumentation)) {
- setDocumentation(operation, operationDocumentation);
- setDocumentation(param, "La valeur de l'attribut à positionner.");
- }
-
- return operation;
- }
-
- protected void addInterface(List<String> interfaceAlreadyDone,
- ObjectModelClassifier output,
- ObjectModelClassifier interfaze) {
- String qualifiedName = interfaze.getQualifiedName();
- if (!interfaceAlreadyDone.contains(qualifiedName)) {
-
- interfaceAlreadyDone.add(qualifiedName);
-
- if (output != null) {
-
- // add it to output
- addInterface(output, qualifiedName);
-
- if (log.isTraceEnabled()) {
- log.trace("Add interface " + qualifiedName + " on " +
- output.getQualifiedName());
- }
- } else {
- if (log.isTraceEnabled()) {
- log.trace("Skip included interface " + qualifiedName);
- }
- }
-
- // scan also all interfaces or super-classes of it
- for (ObjectModelClassifier parent : interfaze.getInterfaces()) {
- addInterface(interfaceAlreadyDone, null, parent);
- }
- }
- }
-
- protected void addInterface(List<String> interfaceAlreadyDone,
- ObjectModelClassifier output,
- Class<?> clazz) {
- String qualifiedName = clazz.getName();
- if (!interfaceAlreadyDone.contains(qualifiedName)) {
-
- // add it to output
- addInterface(output, qualifiedName);
-
- }
- }
-}
Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/PersistenceContextTransformer.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/PersistenceContextTransformer.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/PersistenceContextTransformer.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,287 +0,0 @@
-package org.nuiton.topia.generator;
-
-/*
- * #%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%
- */
-
-/*{generator option: parentheses = false}*/
-
-/*{generator option: writeString = +}*/
-
-import org.nuiton.eugene.java.ObjectModelTransformerToJava;
-import org.nuiton.eugene.models.object.ObjectModel;
-import org.nuiton.eugene.models.object.ObjectModelClass;
-import org.nuiton.eugene.models.object.ObjectModelJavaModifier;
-import org.nuiton.eugene.models.object.ObjectModelOperation;
-import org.nuiton.topia.AbstractTopiaPersistenceContext;
-import org.nuiton.topia.HibernateProvider;
-import org.nuiton.topia.TopiaListenableSupport;
-import org.nuiton.topia.persistence.TopiaEntity;
-import org.nuiton.topia.persistence.TopiaIdFactory;
-import org.nuiton.topia.persistence.util.EntityOperator;
-import org.nuiton.topia.persistence.util.EntityOperatorStore;
-
-import java.lang.reflect.Array;
-import java.util.List;
-
-/**
- * To generate PersistenceHelper
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.generator.PersistenceContextTransformer"
- * @since 3.0
- */
-public class PersistenceContextTransformer extends ObjectModelTransformerToJava {
-
- @Override
- public void transformFromModel(ObjectModel input) {
-
- String packageName = TopiaGeneratorUtil.getPersistenceContextPackage(this, model);
-
- String entityAbstractName = TopiaGeneratorUtil.getPersistenceContextAbstractName(model);
-
- String entityConcreteName = TopiaGeneratorUtil.getPersistenceContextConcreteName(model);
-
- boolean generateAbstract = !isInClassPath(packageName, entityAbstractName);
-
- boolean generateConcrete = !isInClassPath(packageName, entityConcreteName);
-
-
- if (generateAbstract) {
-
- generateAbstract(packageName,
- entityAbstractName);
- }
-
- if (generateConcrete) {
-
- generateImpl(packageName,
- entityAbstractName,
- entityConcreteName);
- }
-
- }
-
- protected void generateAbstract(String packageName,
- String className) {
-
- // try to find a super class by tag-value
-// String superClass = TopiaGeneratorUtil.getPersistenceContextSuperClassTagValue(model);
- String superClass = null;
-
- if (superClass == null) {
-
- // no super-class, use default one
- superClass = AbstractTopiaPersistenceContext.class.getName();
- }
-
- ObjectModelClass output = createAbstractClass(className, packageName);
-
- setSuperClass(output, superClass);
-
- // detect if there is a contract to set on abstract
- String contractName = TopiaGeneratorUtil.getPersistenceContextInterfaceName(model);
-
-// addInterface(output, TopiaPersistenceContext.class);
-
- boolean addPersistenceContextContract = isInClassPath(packageName, contractName);
-
- if (addPersistenceContextContract) {
- addInterface(output, packageName + "." + contractName);
- }
-
- String modelName = model.getName();
- String daoHelperClazzName = modelName + "DAOHelper";
-
- String entityEnumName = modelName + "EntityEnum";
-
- List<ObjectModelClass> entityClasses =
- TopiaGeneratorUtil.getEntityClasses(model, true);
-
- boolean generateOperator =
- TopiaGeneratorUtil.shouldGenerateOperatorForDAOHelper(model);
-
- boolean generateStandaloneEnum =
- TopiaGeneratorUtil.shouldGenerateStandaloneEnumForDAOHelper(model);
-
- if (!generateStandaloneEnum) {
-
- addImport(output, packageName + "." + daoHelperClazzName + "." + entityEnumName);
-
- }
-
-// addImport(output, TopiaDAO.class);
- addImport(output, TopiaEntity.class);
-// addImport(output, TopiaContext.class);
- addImport(output, Array.class);
- addImport(output, Array.class);
-
- if (generateOperator) {
- addImport(output, EntityOperator.class);
- addImport(output, EntityOperatorStore.class);
- }
-
- // add public constructor
- ObjectModelOperation constructor = addConstructor(
- output,
- ObjectModelJavaModifier.PUBLIC);
- addParameter(constructor, HibernateProvider.class, "hibernateProvider");
- addParameter(constructor, TopiaListenableSupport.class, "listenableSupport");
- addParameter(constructor, TopiaIdFactory.class, "topiaIdFactory");
- setOperationBody(constructor, ""
-/*{
- super(hibernateProvider, listenableSupport, topiaIdFactory);
- }*/
- );
-
- ObjectModelOperation op;
-
- // getModelVersion method
- String modelVersion = model.getVersion();
- op = addOperation(output, "getModelVersion", "String", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
- setOperationBody(op, ""
-/*{
- return "<%=modelVersion%>";
- }*/
- );
-
- // getModelName method
- op = addOperation(output, "getModelName", "String", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
- setOperationBody(op, ""
-/*{
- return "<%=modelName%>";
- }*/
- );
-
- for (ObjectModelClass clazz : entityClasses) {
- String clazzName = clazz.getName();
-
- // TODO brendan 14/10/13 use method
- String daoContractName = clazzName + "Dao";
- String daoClazzName = TopiaGeneratorUtil.getConcreteDaoName(clazz);
-
- // specialized getXXXDao method
- op = addOperation(output, "get" + daoContractName, clazz.getPackageName() + '.' + daoClazzName);
- addImport(output, clazz);
- setOperationBody(op, ""
-/*{
- <%=daoClazzName%> result = getDao(<%=clazzName%>.class, <%=daoClazzName%>.class);
- return result;
- }*/
- );
-
- }
-
- // getContractClass method
- op = addOperation(output, "getContractClass", "<T extends TopiaEntity> Class<T>", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
- addParameter(op, "Class<T>", "klass");
- setOperationBody(op, ""
-/*{
- <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass);
- return (Class<T>) constant.getContract();
- }*/
- );
-
- // getImplementationClass method
- op = addOperation(output, "getImplementationClass", "<T extends TopiaEntity> Class<T>", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
- addParameter(op, "Class<T>", "klass");
- setOperationBody(op, ""
-/*{
- <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass);
- return (Class<T>) constant.getImplementation();
- }*/
- );
-
- // getContractClasses method
- op = addOperation(output, "getContractClasses", "Class<? extends TopiaEntity>[]", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
- setOperationBody(op, ""
-/*{
- <%=entityEnumName%>[] values = <%=entityEnumName%>.values();
- Class<? extends TopiaEntity>[] result = (Class<? extends TopiaEntity>[]) Array.newInstance(Class.class, values.length);
- for (int i = 0; i < values.length; i++) {
- result[i] = values[i].getContract();
- }
- return result;
- }*/
- );
-
- // getImplementationClasses method
- op = addOperation(output, "getImplementationClasses", "Class<? extends TopiaEntity>[]", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
- setOperationBody(op, ""
-/*{
- <%=entityEnumName%>[] values = <%=entityEnumName%>.values();
- Class<? extends TopiaEntity>[] result = (Class<? extends TopiaEntity>[]) Array.newInstance(Class.class, values.length);
- for (int i = 0; i < values.length; i++) {
- result[i] = values[i].getImplementation();
- }
- return result;
- }*/
- );
-
- // getContracts method
- op = addOperation(output, "getContracts", entityEnumName + "[]", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
- setOperationBody(op, ""
-/*{
- return <%=entityEnumName%>.values();
- }*/
- );
-
- if (generateOperator) {
- // getOperator method
- op = addOperation(output, "getOperator", "<T extends TopiaEntity> EntityOperator<T>", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
- addParameter(op, "Class<T>", "klass");
- setOperationBody(op, ""
-/*{
- <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass);
- return EntityOperatorStore.getOperator(constant);
- }*/
- );
- }
-
- }
-
- protected ObjectModelClass generateImpl(String packageName,
- String entityAbstractName,
- String entityConcreteName) {
-
- ObjectModelClass output = createClass(entityConcreteName, packageName);
-
- setSuperClass(output, entityAbstractName);
-
- ObjectModelOperation constructor = addConstructor(
- output,
- ObjectModelJavaModifier.PUBLIC);
- addParameter(constructor, HibernateProvider.class, "hibernateProvider");
- addParameter(constructor, TopiaListenableSupport.class, "listenableSupport");
- addParameter(constructor, TopiaIdFactory.class, "topiaIdFactory");
- setOperationBody(constructor, ""
-/*{
- super(hibernateProvider, listenableSupport, topiaIdFactory);
- }*/
- );
-
- return output;
- }
-
-}
Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaGeneratorUtil.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaGeneratorUtil.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaGeneratorUtil.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,1712 +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%
- */
-
-package org.nuiton.topia.generator;
-
-import com.google.common.base.Preconditions;
-import org.apache.commons.collections.CollectionUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.nuiton.eugene.AbstractGenerator;
-import org.nuiton.eugene.GeneratorUtil;
-import org.nuiton.eugene.ModelPropertiesUtil;
-import org.nuiton.eugene.java.JavaGeneratorUtil;
-import org.nuiton.eugene.java.ObjectModelTransformerToJava;
-import org.nuiton.eugene.models.object.ObjectModel;
-import org.nuiton.eugene.models.object.ObjectModelAssociationClass;
-import org.nuiton.eugene.models.object.ObjectModelAttribute;
-import org.nuiton.eugene.models.object.ObjectModelClass;
-import org.nuiton.eugene.models.object.ObjectModelClassifier;
-import org.nuiton.eugene.models.object.ObjectModelElement;
-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.TopiaDAOImpl;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.LinkedHashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeMap;
-
-/**
- * Classe regroupant divers méthodes utiles pour la génération des entités
- * <p/>
- * Created: 13 déc. 2005
- *
- * @author Arnaud Thimel <thimel(a)codelutin.com>
- * @author tchemit <tchemit(a)codelutin.com>
- * @author fdesbois <fdesbois(a)codelutin.com>
- * @author chatellier <chatellier(a)codelutin.com>
- * @version $Id$
- */
-public class TopiaGeneratorUtil extends JavaGeneratorUtil {
-
- /** Logger */
- private static final Log log = LogFactory.getLog(TopiaGeneratorUtil.class);
-
- /**
- * dependency to add extra operations for entity dao.
- *
- * @since 2.3.4
- */
- public static final String DEPENDENCIES_DAO = "dao";
-
- /** Type de persistence Hibernate */
- public static final String PERSISTENCE_TYPE_HIBERNATE = "hibernate";
-
- /** Type de persistence LDAP */
- public static final String PERSISTENCE_TYPE_LDAP = "ldap";
-
- /** Type de persistence par défaut (si aucun précisé) */
- public static final String PERSISTENCE_TYPE_DEFAULT = PERSISTENCE_TYPE_HIBERNATE;
-
- /** Propriété des générateurs indiquant le package par défaut */
- public static final String PROPERTY_DEFAULT_PACKAGE = "defaultPackage";
-
- /** Le package par défaut si aucun n'est spécifié */
- public static final String DEFAULT_PACKAGE = "org.codelutin.malo";
-
- /** Stratégie d'heritage par defaut. */
- public static final String DEFAULT_INHERITANCE_STRATEGY = "union-subclass";
-
- /**
- * The Eugene provider of tag values and stereotypes.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @plexus.component role="org.nuiton.eugene.ModelPropertiesUtil$ModelPropertiesProvider" role-hint="topia"
- * @since 2.3
- */
- public static class TopiaModelPropertiesProvider extends ModelPropertiesUtil.ModelPropertiesProvider {
-
- @Override
- public void init() throws IllegalAccessException {
- scanStereotypeClass(TopiaStereoTypes.class);
- scanTagValueClass(TopiaTagValues.class);
- }
- }
-
- /**
- * Renvoie le package par défaut pour le générateur donné
- *
- * @param generator le générateur donné
- * @return le package par défaut du générator donné
- */
- public static String getDefaultPackage(AbstractGenerator<?> generator) {
- String packageName = generator.getProperty(PROPERTY_DEFAULT_PACKAGE);
- if (StringUtils.isBlank(packageName)) {
- packageName = DEFAULT_PACKAGE;
- }
- return packageName;
- }
-
- public static String getApplicationContextPackage(ObjectModelTransformerToJava transformer,
- ObjectModel model) {
-
- String result = transformer.getDefaultPackageName();
-
- return result;
- }
-
- public static String getPersistenceContextPackage(ObjectModelTransformerToJava transformer,
- ObjectModel model) {
-
- String result = transformer.getDefaultPackageName();
-
- return result;
- }
-
- public static String getDaoPackage(ObjectModelTransformerToJava transformer,
- ObjectModel model,
- ObjectModelClassifier input) {
-
- Preconditions.checkState(isEntity(input), "Cant' find dao package name for a none entity " + input);
- String result = input.getPackageName();
- return result;
- }
-
- public static String getApplicationContextInterfaceName(ObjectModel model) {
- return model.getName() + "ApplicationContext";
- }
-
- public static String getApplicationContextAbstractName(ObjectModel model) {
- return "Abstract" + model.getName() + "TopiaApplicationContext";
- }
-
- public static String getApplicationContextConcreteName(ObjectModel model) {
- return model.getName() + "TopiaApplicationContext";
- }
-
- public static String getPersistenceContextAbstractName(ObjectModel model) {
- return "Abstract" + model.getName() + "TopiaPersistenceContext";
- }
-
- public static String getPersistenceContextConcreteName(ObjectModel model) {
- return model.getName() + "TopiaPersistenceContext";
- }
-
- public static String getPersistenceContextInterfaceName(ObjectModel model) {
- return model.getName() + "PersistenceContext";
- }
-
- public static String getEntityAbstractName(ObjectModelClass input) {
- return "AbstractTopia" + input.getName();
- }
-
- public static String getEntityConcreteName(ObjectModelClass input) {
- return input.getName();
- }
-
- public static String getAbstractDaoName(ObjectModelClass input) {
- return "Abstract" + input.getName() + "TopiaDao";
- }
-
- public static String getGeneratedDaoName(ObjectModelClass input) {
- return "Generated" + input.getName() + "TopiaDao";
- }
-
- public static String getConcreteDaoName(ObjectModelClass input) {
- return input.getName() + "TopiaDao";
- }
-
- @Deprecated
- public static String getLegacyDaoName(ObjectModelClass input) {
- return input.getName() + "DAO";
- }
-
- public static String getAbstractDaoFqn(ObjectModelClass input) {
- return input.getPackageName() + "." + getAbstractDaoName(input);
- }
-
- public static String getGeneratedDaoFqn(ObjectModelClass input) {
- return input.getPackageName() + "." + getGeneratedDaoName(input);
- }
-
- public static String getConcreteDaoFqn(ObjectModelClass input) {
- return input.getPackageName() + "." + getConcreteDaoName(input);
- }
-
- @Deprecated
- public static String getLegacyDaoFqn(ObjectModelClass input) {
- return input.getPackageName() + "." + getLegacyDaoName(input);
- }
-
- public static String getEntityPackage(ObjectModelTransformerToJava transformer,
- ObjectModel model,
- ObjectModelClassifier input) {
-
- String result = input.getPackageName();
- return result;
- }
-
- /**
- * Renvoie l'interface DAO associée à la classe passée en paramètre
- *
- * @param clazz la classe à tester
- * @param model le modele utilisé
- * @return l'interface trouvée ou null sinon
- */
- public static ObjectModelInterface getDAOInterface(ObjectModelClass clazz,
- ObjectModel model) {
- for (Object o : model.getInterfaces()) {
- ObjectModelInterface daoInterface = (ObjectModelInterface) o;
- if (daoInterface.getName().equals(clazz.getName() + "DAO")) {
- if (hasDaoStereotype(daoInterface)) {
- return daoInterface;
- }
- }
- }
- return null;
- }
-
- /**
- * Renvoie le type de persistence pour le classifier donné. Si aucun n'est
- * trouvé, le type par défaut est utilisé
- *
- * @param classifier l'élément à tester
- * @return le type de persitence pour l'élément donné.
- * @since 2.5
- */
- public static String getPersistenceType(ObjectModelClassifier classifier) {
- String tag = getPersistenceTypeTagValue(classifier);
- if (StringUtils.isEmpty(tag)) {
- tag = PERSISTENCE_TYPE_DEFAULT;
- }
- return tag;
- }
-
- /**
- * Obtain the reverse db name of an attribute.
- * <p/>
- * If attribute has a specific reverse attribute, use his db name, otherwise
- * suffix the db name of the attribute by {@code _id}.
- *
- * @param attr the attribute to seek
- * @return the value of the reverse name
- * @since 2.5
- */
- public static String getReverseDbName(ObjectModelAttribute attr) {
- if (attr.getReverseAttribute() != null) {
- return getDbName(attr.getReverseAttribute());
- } else {
- return getDbName(attr) + "_id";
- }
- }
-
- /**
- * Renvoie le nom BD de l'élement passé en paramètre. Elle se base sur le
- * tag associé si il existe, sinon sur le nom de l'élément
- *
- * @param element l'élément à tester
- * @return le nom de table
- */
- public static String getDbName(ObjectModelElement element) {
- if (element == null) {
- return null;
- }
- String value = getDbNameTagValue(element);
- if (!StringUtils.isEmpty(value)) {
- return value;
- }
- return toLowerCaseFirstLetter(element.getName());
- }
-
- /**
- * Cherche si le tagvalue {@link TopiaTagValues#TAG_GENERATE_OPERATOR_FOR_DAO_HELPER} a été
- * activé dans le model.
- *
- * @param model le modele utilisé
- * @return {@code true} si le tag value trouvé dans le modèle, {@code false}
- * sinon.
- * @since 2.5
- */
- public static boolean shouldGenerateOperatorForDAOHelper(ObjectModel model) {
- String tagValue = getGenerateOperatorForDAOHelperTagValue(model);
- boolean generate = StringUtils.isNotEmpty(tagValue) &&
- Boolean.valueOf(tagValue);
- return generate;
- }
-
- /**
- * Cherche si le tagvalue {@link TopiaTagValues#TAG_GENERATE_OPERATOR_FOR_DAO_HELPER} a été
- * activé dans le model.
- *
- * @param model le modele utilisé
- * @return {@code true} si le tag value trouvé dans le modèle, {@code false}
- * sinon.
- * @since 2.5
- */
- public static boolean shouldGenerateStandaloneEnumForDAOHelper(ObjectModel model) {
- String tagValue = getGenerateStandaloneEnumForDAOHelperTagValue(model);
- boolean generate = StringUtils.isNotEmpty(tagValue) &&
- Boolean.valueOf(tagValue);
- return generate;
- }
-
- /**
- * Cherche et renvoie la liste des attributs constituant la clef metier
- * d'une classe.
- *
- * @param clazz la classe à tester
- * @return la liste des attributs de la clef métier
- */
- public static Set<ObjectModelAttribute> getNaturalIdAttributes(
- ObjectModelClass clazz) {
-
- // use {@link LinkedHashSet} to keep order and prevent duplicate natural ids found
- Set<ObjectModelAttribute> results =
- new LinkedHashSet<ObjectModelAttribute>();
- for (ObjectModelAttribute attr : clazz.getAttributes()) {
- if (isNaturalId(attr)) {
- results.add(attr);
- }
- }
-
- // sletellier : #2050 Natural id and not null attributes are not propagated on generalized entities (http://nuiton.org/issues/2050)
- Collection<ObjectModelClass> superclasses = clazz.getSuperclasses();
- for (ObjectModelClass superClass : superclasses) {
- Set<ObjectModelAttribute> naturalIdsOfSuperClass = getNaturalIdAttributes(superClass);
- results.addAll(naturalIdsOfSuperClass);
- }
- return results;
- }
-
- /**
- * Cherche et renvoie la liste des attributs qui ne doivent pas etre null dans
- * une classe.
- *
- * @param clazz la classe à tester
- * @return la liste des attributs qui ne doivent pas etre null
- */
- public static Set<ObjectModelAttribute> getNotNullAttributes(
- ObjectModelClass clazz) {
-
- // use {@link LinkedHashSet} to keep order and prevent duplicate not null found
- Set<ObjectModelAttribute> results =
- new LinkedHashSet<ObjectModelAttribute>();
- for (ObjectModelAttribute attr : clazz.getAttributes()) {
- if (isNotNull(attr)) {
- results.add(attr);
- }
- }
-
- Collection<ObjectModelClass> superclasses = clazz.getSuperclasses();
- for (ObjectModelClass superClass : superclasses) {
- Set<ObjectModelAttribute> notNullOfSuperClass = getNotNullAttributes(superClass);
- results.addAll(notNullOfSuperClass);
- }
-
- // Association class participants are obviously not null
- if (clazz instanceof ObjectModelAssociationClass) {
- List<ObjectModelAttribute> participantsAttributes = ((ObjectModelAssociationClass) clazz).getParticipantsAttributes();
- results.addAll(participantsAttributes);
- }
-
- return results;
- }
-
- /**
- * Test if we need to generate {@code toString} method for the given class.
- *
- * @param clazz class to test
- * @param model model
- * @return {@code true} if {@code toString} should be generated.
- * clef métier.
- */
- public static boolean generateToString(ObjectModelClass clazz,
- ObjectModel model) {
- String value = getNotGenerateToStringTagValue(clazz, model);
- return StringUtils.isEmpty(value);
- }
-
-
- /**
- * Cherche et renvoie la liste des attributs constituant la clef metier
- * d'une classe.
- *
- * @param clazz la classe à tester
- * @param model le modele
- * @return la liste des attributs de la clef métier ou null si pas de
- * clef métier.
- */
- public static boolean sortAttribute(ObjectModelClass clazz,
- ObjectModel model) {
- String value = getSortAttributeTagValue(clazz, model);
- return "true".equals(value);
- }
-
- /**
- * Detecte si un attribut fait partie d'une clef metier.
- *
- * @param attribute l'attribut à tester
- * @return {@code true} si l'attribut fait partie d'une clef metier,
- * <code>false</cdoe> sinon.
- */
- public static boolean isNaturalId(ObjectModelAttribute attribute) {
- String value = getNaturalIdTagValue(attribute);
- if (StringUtils.isEmpty(value)) {
- // valeur null, donc pas positionnee
- return false;
- }
- try {
- return Boolean.valueOf(value.trim());
- } catch (Exception e) {
- // on a pas reussi a convertir en boolean.
- //todo peut-être declancher une exception ?
- return false;
- }
- }
-
- /**
- * Detecte si un attribut est marqué comme non null.
- * Les naturalId {@link #isNaturalId} sont not null par défaut
- *
- * @param attribute l'attribut à tester
- * @return {@code true} si l'attribut doit être non null,
- * par défaut pour les naturalId, {@code false} sinon..
- * @since 2.6.9
- */
- public static boolean isNotNull(ObjectModelAttribute attribute) {
- String value = getNotNullTagValue(attribute);
- if (StringUtils.isEmpty(value)) {
- // valeur null, donc pas positionnee
- return isNaturalId(attribute);
- }
- try {
- return Boolean.valueOf(value.trim());
- } catch (Exception e) {
- // on a pas reussi a convertir en boolean.
- //todo peut-être declancher une exception ?
- return false;
- }
- }
-
- public static <Type extends ObjectModelElement> Collection<Type> getElementsWithStereotype(
- Collection<Type> elements, String... stereotypes) {
- Collection<Type> result = new ArrayList<Type>();
- for (Type element : elements) {
- if (hasStereotypes(element, stereotypes)) {
- result.add(element);
- }
- }
- return result;
- }
-
- public static boolean hasStereotypes(ObjectModelElement element,
- String... stereotypes) {
- for (String stereotype : stereotypes) {
- if (!element.hasStereotype(stereotype)) {
- return false;
- }
- }
- return true;
- }
-
- public static String getPrimaryKeyAttributesListDeclaration(
- ObjectModelClass clazz, boolean includeName) {
- String attributes = "";
- Collection<ObjectModelAttribute> attributeCollection;
- attributeCollection = getElementsWithStereotype(clazz.getAttributes(),
- TopiaStereoTypes.STEREOTYPE_PRIMARYKAY);
- for (ObjectModelAttribute attr : attributeCollection) {
- attributes += attr.getType();
- if (includeName) {
- attributes += ' ' + attr.getName();
- }
- attributes += ", ";
- }
- if (attributes.length() > 0) {
- attributes = attributes.substring(0, attributes.length() - 2);
- }
- return attributes;
- }
-
- public static boolean isAssociationClassDoublon(ObjectModelAttribute attr) {
- return attr.getReverseAttribute() != null &&
- attr.getDeclaringElement().equals(
- attr.getReverseAttribute().getDeclaringElement()) &&
- !GeneratorUtil.isFirstAttribute(attr);
- }
-
- public static String getDOType(ObjectModelElement elem, ObjectModel model) {
- String type = elem.getName();
- if (elem instanceof ObjectModelAttribute) {
- type = ((ObjectModelAttribute) elem).getType();
- }
- if (elem instanceof ObjectModelClass) {
- type = ((ObjectModelClass) elem).getQualifiedName();
- }
- return getDOType(type, model);
- }
-
- public static String getDOType(String type, ObjectModel model) {
- if (!model.hasClass(type)) {
- return type;
- }
- ObjectModelClass clazz = model.getClass(type);
- if (isEntity(clazz)) {
- //tchemit-2011-09-12 What ever abstract or not, we always use an Impl
- type += "Impl";
-// if (shouldBeAbstract(clazz)) {
-// type += "Abstract";
-// } else {
-// type += "Impl";
-// }
- }
- return type;
- }
-
- private static final Set<String> numberTypes = new HashSet<String>();
-
- private static final Set<String> textTypes = new HashSet<String>();
-
- private static final Set<String> booleanTypes = new HashSet<String>();
-
- private static final Set<String> primitiveTypes = new HashSet<String>();
-
- private static final Map<String, String> primitiveTypeToClass = new HashMap<String, String>();
-
- private static final String VOID_TYPE = "void";
-
- static {
-
- primitiveTypeToClass.put("byte", "java.lang.Byte");
- primitiveTypeToClass.put("short", "java.lang.Short");
- primitiveTypeToClass.put("int", "java.lang.Integer");
- primitiveTypeToClass.put("long", "java.lang.Long");
- primitiveTypeToClass.put("float", "java.lang.Float");
- primitiveTypeToClass.put("double", "java.lang.Double");
- primitiveTypeToClass.put("char", "java.lang.Char");
- primitiveTypeToClass.put("boolean", "java.lang.Boolean");
-
- numberTypes.add("byte");
- numberTypes.add("java.lang.Byte");
- numberTypes.add("Byte");
- numberTypes.add("short");
- numberTypes.add("java.lang.Short");
- numberTypes.add("Short");
- numberTypes.add("int");
- numberTypes.add("java.lang.Integer");
- numberTypes.add("Integer");
- numberTypes.add("long");
- numberTypes.add("java.lang.Long");
- numberTypes.add("Long");
- numberTypes.add("float");
- numberTypes.add("java.lang.Float");
- numberTypes.add("Float");
- numberTypes.add("double");
- numberTypes.add("java.lang.Double");
- numberTypes.add("Double");
-
- textTypes.add("char");
- textTypes.add("java.lang.Char");
- textTypes.add("Char");
- textTypes.add("java.lang.String");
- textTypes.add("String");
-
- booleanTypes.add("boolean");
- booleanTypes.add("java.lang.Boolean");
- booleanTypes.add("Boolean");
-
- primitiveTypes.addAll(numberTypes);
- primitiveTypes.addAll(textTypes);
- primitiveTypes.addAll(booleanTypes);
- }
-
- public static boolean isNumericType(ObjectModelAttribute attr) {
- return numberTypes.contains(attr.getType());
- }
-
- public static boolean isTextType(ObjectModelAttribute attr) {
- return textTypes.contains(attr.getType());
- }
-
- public static boolean isDateType(ObjectModelAttribute attr) {
- return "java.util.Date".equals(attr.getType());
- }
-
- public static boolean isBooleanType(ObjectModelAttribute attr) {
- return booleanTypes.contains(attr.getType());
- }
-
- public static boolean isPrimitiveType(ObjectModelAttribute attr) {
- return primitiveTypes.contains(attr.getType());
- }
-
- public static String getClassForPrimitiveType(ObjectModelAttribute attr) {
- Preconditions.checkState(isPrimitiveType(attr));
- String className = primitiveTypeToClass.get(attr.getType());
- Preconditions.checkNotNull(className);
- return className;
- }
-
- /**
- * Indique si la classe specifiee n'a aucune ou que des methodes abstraites
- *
- * @param clazz l'instance de ObjectModelClass
- * @return true si la classe n'a que des operations abstraite ou aucune
- * operation
- */
- public static boolean hasNothingOrAbstractMethods(ObjectModelClass clazz) {
- boolean result = true;
- Iterator<?> operations = clazz.getOperations().iterator();
- while (result && operations.hasNext()) {
- ObjectModelOperation op = (ObjectModelOperation) operations.next();
- result = op.isAbstract();
- }
- return result;
- }
-
- /**
- * Indique si la classe specifiee devrait etre abstraite
- *
- * @param clazz l'instance de ObjectModelClass
- * @return true dans ce cas, false sinon
- */
- public static boolean shouldBeAbstract(ObjectModelClass clazz) {
- return clazz != null && clazz.isAbstract() &&
- hasNothingOrAbstractMethods(clazz);
- }
-
- /**
- * <p>
- * Cette méthode permet de détecter si
- * - l'attribut représente une relation 1-n
- * - cette relation est unidirectionnelle
- * - le type de l'attribut représente un entité
- * - cette entité a des sous-classes dans le modèle
- * <p/>
- * Ce cas correspond à une incompatibilité d'Hibernate qui nous oblige a
- * adopter un comportement particulier.
- * </p>
- *
- * @param attr l'attribut a tester
- * @param model le model
- * @return true si et seulement si il s'agit bien de ce type de relation
- */
- public static boolean hasUnidirectionalRelationOnAbstractType(
- ObjectModelAttribute attr, ObjectModel model) {
- ObjectModelAttribute reverse = attr.getReverseAttribute();
- //relation 1-n
- if (reverse != null && isNMultiplicity(attr) &&
- !isNMultiplicity(reverse)) {
- //Pas de navigabilité
- if (!reverse.isNavigable()) {
- //Il s'agit d'une entity
- ObjectModelClass clazz = model.getClass(attr.getType());
- if (clazz != null && isEntity(clazz)) {
- //Cette classe a des sous-classes dans le modèle
- for (ObjectModelClass subClass : model.getClasses()) {
- if (subClass.getSuperclasses().contains(clazz)) {
- return true;
- }
- }
- }
- }
- }
- return false;
- }
-
- /**
- * Renvoie le nom unique de table pour une relation ManyToMany en fonction
- * de l'attribut <code>attr</code>
- * <p/>
- * Plusieurs cas de figure:
- * <li>
- *
- * @param attr l'attribut servant de base au calcul du nom
- * @return le nom de la table
- */
- public static String getManyToManyTableName(ObjectModelAttribute attr) {
- String result;
-
- if (attr.hasAssociationClass()) {
- result = getDbName(attr.getAssociationClass());
- } else {
- String name = attr.getName();
- String revers = attr.getReverseAttributeName();
-
- if (name.compareToIgnoreCase(revers) < 0) {
- result = name + '_' + revers;
- } else {
- result = revers + '_' + name;
- }
- }
- return result.toLowerCase();
- }
-
- /**
- * Renvoie le type d'interface à utiliser en fonction de l'attribut
- *
- * @param attr l'attribut a traiter
- * @return String
- */
- public static String getNMultiplicityInterfaceType(
- ObjectModelAttribute attr) {
- if (hasUniqueStereotype(attr)) {
- return Set.class.getName();
- } else if (JavaGeneratorUtil.hasIndexedStereotype(attr) || attr.isOrdered()) {
- return List.class.getName();
- }
- return Collection.class.getName();
- }
-
- /**
- * Renvoie le type d'objet (instance) à utiliser en fonction de l'attribut
- *
- * @param attr l'attribut a traiter
- * @return String
- */
- public static String getNMultiplicityObjectType(ObjectModelAttribute attr) {
- if (hasUniqueStereotype(attr)) {
- return HashSet.class.getName();
- } else if (JavaGeneratorUtil.hasIndexedStereotype(attr) || attr.isOrdered()) {
- //On considère qu'on ne sait pas traiter vraiment l'attribut "ordered"
- // puisqu'on va conserver l'ordre d'insertion, et non un ordre en
- // fonction d'un élément donné. Donc on renvoi une ArrayList
- return ArrayList.class.getName();
- }
- LinkedList.class.getName();
- return ArrayList.class.getName();
- }
-
- /**
- * Renvoie le type d'interface à utiliser en fonction de l'attribut
- *
- * @param attr l'attribut a traiter
- * @return String
- */
- public static String getNMultiplicityHibernateType(
- ObjectModelAttribute attr) {
- if (hasUniqueStereotype(attr)) {
- return "set";
- } else if (JavaGeneratorUtil.hasIndexedStereotype(attr)) {
- return "list";
- }
- //attr.isOrdered() - On génère le ordered en bag
- return "bag";
- }
-
- /**
- * Obtain the list of entities classes with the possibility to sort the
- * result.
- *
- * @param model the current model to scan
- * @param sort flag to allow sort the result
- * @return the list of filtred classes by their stereotype
- */
- public static List<ObjectModelClass> getEntityClasses(ObjectModel model,
- boolean sort) {
- return getClassesByStereotype(TopiaStereoTypes.STEREOTYPE_ENTITY, model, sort);
- }
-
- /**
- * Obtain the list of classes for a given stereotype with the possibility
- * to sort the result.
- *
- * @param stereotype filter stereotype
- * @param model the current model to scan
- * @param sort flag to allow sort the result
- * @return the list of filtred classes by their stereotype
- */
- public static List<ObjectModelClass> getClassesByStereotype(
- String stereotype, ObjectModel model, boolean sort) {
- List<ObjectModelClass> classes = new ArrayList<ObjectModelClass>();
- for (ObjectModelClass clazz : model.getClasses()) {
- if (clazz.hasStereotype(stereotype)) {
- classes.add(clazz);
- }
- }
- if (sort && !classes.isEmpty()) {
-
- Collections.sort(classes, OBJECT_MODEL_CLASS_COMPARATOR);
- }
- return classes;
- }
-
- static public final Comparator<ObjectModelClass>
- OBJECT_MODEL_CLASS_COMPARATOR =
- new Comparator<ObjectModelClass>() {
-
- @Override
- public int compare(ObjectModelClass o1,
- ObjectModelClass o2) {
- return o1.getQualifiedName().compareTo(
- o2.getQualifiedName());
- }
- };
-
- /**
- * Detecte si la clef metier d'une classe est mutable ou pas.
- * <p/>
- * On respecte la valeur par defaut d'hibernate, à savoir que par default
- * une clef metier est non mutable.
- *
- * @param clazz la classe a tester
- * @return {@code true} si le tag value a ete positionne sur la classe
- * via le tag {@link TopiaTagValues#TAG_NATURAL_ID_MUTABLE}, {@code false}
- * sinon.
- */
- public static boolean isNaturalIdMutable(ObjectModelClass clazz) {
- String value = getNaturalIdMutableTagValue(clazz);
- if (StringUtils.isEmpty(value)) {
- // valeur null, donc par default positionnee
- return false;
- }
- try {
- return Boolean.valueOf(value.trim());
- } catch (Exception e) {
- // on a pas reussi a convertir en boolean.
- //todo peut-être declancher une exception ?
- return false;
- }
- }
-
- /**
- * Retourne true si le tagValue {@link TopiaTagValues#TAG_CONTEXTABLE}
- * à la valeur {@code true}.
- *
- * @param classifier classifier to test
- * @return {@code true} si {@link TopiaTagValues#TAG_CONTEXTABLE} == {@code true}
- */
- public static boolean isContextable(ObjectModelClassifier classifier) {
- boolean result = false;
- String value = classifier.getTagValue(TopiaTagValues.TAG_CONTEXTABLE);
- if (StringUtils.equalsIgnoreCase(value, "true")) {
- result = true;
- }
- return result;
- }
-
- /**
- * Obtain the list of fqn of object involed in the given class.
- *
- * @param aClass the clazz to inspect
- * @param incomingFqns incoming fqns
- * @return the list of fqn of attributes
- */
- public static List<String> getImports(ObjectModelClass aClass,
- String... incomingFqns) {
- Set<String> tmp = new HashSet<String>();
- tmp.addAll(Arrays.asList(incomingFqns));
- getImports(aClass, tmp);
- List<String> result = cleanImports(aClass.getPackageName(), tmp);
- return result;
- }
-
- /**
- * Obtain the list of fqn of object involed in the given interface.
- *
- * @param anInterface the interface to inspect
- * @param incomingFqns incoming fqns
- * @return the list of fqn of attributes
- */
- public static List<String> getImports(ObjectModelInterface anInterface,
- String... incomingFqns) {
- Set<String> tmp = new HashSet<String>();
- tmp.addAll(Arrays.asList(incomingFqns));
- getImports(anInterface, tmp);
- List<String> result = cleanImports(anInterface.getPackageName(), tmp);
- return result;
- }
-
- /**
- * Obtain the list of fqn of object involed in the given class.
- *
- * @param aClass the class to inspect
- * @param fqns where to store found fqns
- */
- protected static void getImports(ObjectModelClass aClass,
- Set<String> fqns) {
- // scan attributes
- for (ObjectModelAttribute attr : aClass.getAttributes()) {
- fqns.add(attr.getType());
- if (isNMultiplicity(attr)) {
- String collectionType = getNMultiplicityInterfaceType(attr);
- fqns.add(collectionType);
- String collectionObject = getNMultiplicityObjectType(attr);
- fqns.add(collectionObject);
- }
- }
- for (ObjectModelAttribute attribute : aClass.getAllOtherAttributes()) {
- fqns.add(attribute.getType());
- }
- // scan associations
- if (aClass instanceof ObjectModelAssociationClass) {
- ObjectModelAssociationClass assoc =
- (ObjectModelAssociationClass) aClass;
- for (ObjectModelAttribute attr :
- assoc.getParticipantsAttributes()) {
- if (attr == null) {
- continue;
- }
- fqns.add(attr.getType());
- if (isNMultiplicity(attr)) {
- String collectionType = getNMultiplicityInterfaceType(attr);
- fqns.add(collectionType);
- String collectionObject = getNMultiplicityObjectType(attr);
- fqns.add(collectionObject);
- }
- }
- }
- // scan operations
- for (ObjectModelOperation operation : aClass.getOperations()) {
- getImports(operation, fqns);
- }
- // scan super interfaces
- for (ObjectModelInterface modelInterface : aClass.getInterfaces()) {
- fqns.add(modelInterface.getQualifiedName());
- getImports(modelInterface, fqns);
- }
- // scan super classes
- for (ObjectModelClass modelClass : aClass.getSuperclasses()) {
- fqns.add(modelClass.getQualifiedName());
- getImports(modelClass);
- }
- }
-
- /**
- * Obtain the list of fqn of object involed in the given interface.
- *
- * @param anInterface the interface to inspect
- * @param fqns where to store found fqns
- */
- protected static void getImports(ObjectModelInterface anInterface,
- Set<String> fqns) {
- // scan operations
- for (ObjectModelOperation operation : anInterface.getOperations()) {
- getImports(operation, fqns);
- }
- // scan super interfaces
- for (ObjectModelInterface modelInterface : anInterface.getInterfaces()) {
- fqns.add(modelInterface.getQualifiedName());
- getImports(modelInterface, fqns);
- }
- }
-
- /**
- * Obtain the fqn's list of all involed type in a givne operation.
- *
- * @param operation operation to inspect
- * @param fqns where to store found fqns
- */
- protected static void getImports(ObjectModelOperation operation,
- Set<String> fqns) {
- String fqn = operation.getReturnType();
- fqns.add(fqn);
- for (ObjectModelParameter parameter : operation.getParameters()) {
- fqns.add(parameter.getType());
- }
- }
-
- /**
- * Clean a set of fqns, transform it into a {@link List} and sort it.
- *
- * @param packageName the current package name
- * @param fqns the dirty set of fqns
- * @return the sorted cleaned list of fqns.
- */
- protected static List<String> cleanImports(String packageName,
- Set<String> fqns) {
- fqns.removeAll(primitiveTypes);
- fqns.remove(VOID_TYPE);
- int packageLength = packageName.length();
- List<String> genericType = new ArrayList<String>();
- for (Iterator<String> it = fqns.iterator(); it.hasNext(); ) {
- String fqn = it.next();
- int lastIndex = fqn.lastIndexOf(".");
- if (lastIndex == packageLength && fqn.startsWith(packageName)) {
- // same package
- it.remove();
- continue;
- }
- int genericIndex = fqn.indexOf('<');
- if (genericIndex != -1) {
- genericType.add(fqn.substring(0, genericIndex));
- it.remove();
- }
- }
- fqns.addAll(genericType);
-
- ArrayList<String> result = new ArrayList<String>(fqns);
- Collections.sort(result);
- return result;
- }
-
- /**
- * Obtain the class to use as abstract dao.
- * <p/>
- * It will look after a tag value {@link TopiaTagValues#TAG_DAO_IMPLEMENTATION} in model
- * and if not found will use the default value which is {@link TopiaDAOImpl}.
- *
- * @param model the model which could contains
- * @return the type of the abstract dao to use
- * @since 2.5
- */
- public static Class<?> getDAOImplementation(ObjectModel model) {
- String daoImpl = getDaoImplementationTagValue(model);
- Class<?> result;
- if (StringUtils.isEmpty(daoImpl)) {
-
- // use the default dao implementation of topia
- result = AbstractTopiaDao.class;
- } else {
- try {
- result = Class.forName(daoImpl);
- } catch (ClassNotFoundException e) {
- String message = "Could not find dao implementation named " + daoImpl;
- log.error(message);
- throw new IllegalStateException(message, e);
- }
- }
- return result;
- }
-
- public static Map<ObjectModelClass, Set<ObjectModelClass>>
- searchDirectUsages(ObjectModel model) {
- List<ObjectModelClass> allEntities;
- Map<String, ObjectModelClass> allEntitiesByFQN;
- Map<ObjectModelClass, Set<ObjectModelClass>> usages;
-
- allEntities = getEntityClasses(model, true);
-
- allEntitiesByFQN = new TreeMap<String, ObjectModelClass>();
- usages = new LinkedHashMap<ObjectModelClass, Set<ObjectModelClass>>();
-
- // prepare usages map and fill allEntitiesByFQN map
- for (ObjectModelClass klass : allEntities) {
- usages.put(klass, new HashSet<ObjectModelClass>());
- allEntitiesByFQN.put(klass.getQualifiedName(), klass);
- }
-
- // first pass to detect direct usages
- for (ObjectModelClass klass : allEntities) {
- searchDirectUsages(klass, allEntitiesByFQN, usages);
- }
- allEntities.clear();
- allEntitiesByFQN.clear();
- return usages;
-
- }
-
- public static void searchDirectUsages(
- ObjectModelClass klass,
- Map<String, ObjectModelClass> allEntitiesByFQN,
- Map<ObjectModelClass, Set<ObjectModelClass>> usages) {
-
- if (log.isDebugEnabled()) {
- log.debug("for entity " + klass.getQualifiedName());
- }
- for (ObjectModelAttribute attr : klass.getAttributes()) {
- if (!attr.isNavigable()) {
- // skip this case
- continue;
- }
- String type;
- if (attr.hasAssociationClass()) {
- type = attr.getAssociationClass().getQualifiedName();
- } else {
- type = attr.getType();
- }
- if (!allEntitiesByFQN.containsKey(type)) {
- // not a entity, can skip for this attribute
- continue;
- }
- if (log.isDebugEnabled()) {
- log.debug(" uses " + type);
- }
- // register the klass as using the targetEntity
- ObjectModelClass targetEntity = allEntitiesByFQN.get(type);
- Set<ObjectModelClass> classes = usages.get(targetEntity);
- classes.add(klass);
- }
- }
-
- public static boolean isImportNeeded(Collection<ObjectModelOperation> operations,
- String importName) {
- if (CollectionUtils.isNotEmpty(operations)) {
- for (ObjectModelOperation op : operations) {
- if (op.getReturnType().contains(importName)) {
- return true;
- }
- for (ObjectModelParameter param : op.getParameters()) {
- if (param.getType().contains(importName)) {
- return true;
- }
- }
- }
- }
- return false;
- }
-
- public static boolean isCollectionNeeded(
- Collection<ObjectModelOperation> operations) {
- return isImportNeeded(operations,
- Collection.class.getSimpleName());
- }
-
- public static boolean isSetNeeded(Collection<ObjectModelOperation> operations) {
- return isImportNeeded(operations,
- Set.class.getSimpleName());
- }
-
- /**
- * Check if the given classifier has the
- * {@link TopiaStereoTypes#STEREOTYPE_ENTITY} stereotype.
- *
- * @param classifier classifier to test
- * @return {@code true} if stereotype was found, {@code false} otherwise
- * @see TopiaStereoTypes#STEREOTYPE_ENTITY
- * @since 2.5
- */
- public static boolean hasEntityStereotype(ObjectModelClassifier classifier) {
- return classifier.hasStereotype(TopiaStereoTypes.STEREOTYPE_ENTITY);
- }
-
- /**
- * Check if the given attribute type is an entity.
- *
- * @param attribute attribute to test
- * @param model model containing the attribute
- * @return {@code true} if type of attribute is an entity,
- * {@code false} otherwise
- * @see TopiaStereoTypes#STEREOTYPE_ENTITY
- * @since 2.7
- */
- public static boolean isEntity(ObjectModelAttribute attribute,
- ObjectModel model) {
- if (isPrimitiveType(attribute)) {
- return false;
- }
- String attributeType = attribute.getType();
- ObjectModelClassifier typeclassifier =
- model.getClassifier(attributeType);
- return typeclassifier != null && isEntity(typeclassifier);
- }
-
- /**
- * Check if the given classifier has the
- * {@link TopiaStereoTypes#STEREOTYPE_ENTITY} and is not an enumeration
- *
- * @param classifier classifier to test
- * @return {@code true} if stereotype was found and classifier is not
- * enumeration, {@code false} otherwise
- * @see TopiaStereoTypes#STEREOTYPE_ENTITY
- * @since 2.5
- */
- public static boolean isEntity(ObjectModelClassifier classifier) {
- return hasEntityStereotype(classifier) && !classifier.isEnum();
- }
-
-
- /**
- * Check if the given attribute has the
- * {@link TopiaStereoTypes#STEREOTYPE_ENTITY} stereotype.
- *
- * @param attribute attribute to test
- * @return {@code true} if stereotype was found, {@code false otherwise}
- * @see TopiaStereoTypes#STEREOTYPE_ENTITY
- * @since 2.5
- */
- public static boolean hasEntityStereotype(ObjectModelAttribute attribute) {
- return attribute.hasStereotype(TopiaStereoTypes.STEREOTYPE_ENTITY);
- }
-
- /**
- * Check if the given classifier has the
- * {@link TopiaStereoTypes#STEREOTYPE_DTO} stereotype.
- *
- * @param classifier classifier to test
- * @return {@code true} if stereotype was found, {@code false otherwise}
- * @see TopiaStereoTypes#STEREOTYPE_DTO
- * @since 2.5
- */
- public static boolean hasDtoStereotype(ObjectModelClassifier classifier) {
- return classifier.hasStereotype(TopiaStereoTypes.STEREOTYPE_DTO);
- }
-
- /**
- * Check if the given classifier has the
- * {@link TopiaStereoTypes#STEREOTYPE_DAO} stereotype.
- *
- * @param classifier classifier to test
- * @return {@code true} if stereotype was found, {@code false otherwise}
- * @see TopiaStereoTypes#STEREOTYPE_DAO
- * @since 2.5
- */
- public static boolean hasDaoStereotype(ObjectModelClassifier classifier) {
- return classifier.hasStereotype(TopiaStereoTypes.STEREOTYPE_DAO);
- }
-
- /**
- * Check if the given operation has the
- * {@link TopiaStereoTypes#STEREOTYPE_DAO} stereotype.
- *
- * @param operation operation to test
- * @return {@code true} if stereotype was found, {@code false otherwise}
- * @see TopiaStereoTypes#STEREOTYPE_DAO
- * @since 2.5
- */
- public static boolean hasDaoStereotype(ObjectModelOperation operation) {
- return operation.hasStereotype(TopiaStereoTypes.STEREOTYPE_DAO);
- }
-
- /**
- * Check if the given attribute has the
- * {@link TopiaStereoTypes#STEREOTYPE_UNIQUE} stereotype.
- *
- * @param attribute attribute to test
- * @return {@code true} if stereotype was found, {@code false otherwise}
- * @see TopiaStereoTypes#STEREOTYPE_UNIQUE
- * @since 2.5
- */
- public static boolean hasUniqueStereotype(ObjectModelAttribute attribute) {
- return attribute.hasStereotype(TopiaStereoTypes.STEREOTYPE_UNIQUE);
- }
-
- /**
- * Check if the given attribute has the
- * {@link TopiaStereoTypes#STEREOTYPE_PRIMARYKAY} stereotype.
- *
- * @param attribute attribute to test
- * @return {@code true} if stereotype was found, {@code false otherwise}
- * @see TopiaStereoTypes#STEREOTYPE_PRIMARYKAY
- * @since 2.5
- */
- public static boolean hasPrimaryKeyStereotype(ObjectModelAttribute attribute) {
- return attribute.hasStereotype(TopiaStereoTypes.STEREOTYPE_PRIMARYKAY);
- }
-
- /**
- * Obtain the value of the {@link TopiaTagValues#TAG_PERSISTENCE_TYPE}
- * tag value on the given classifier.
- *
- * @param classifier classifier to seek
- * @return the none empty value of the found tag value or {@code null} if not found nor empty.
- * @see TopiaTagValues#TAG_PERSISTENCE_TYPE
- * @since 2.5
- */
- public static String getPersistenceTypeTagValue(ObjectModelClassifier classifier) {
- String value = findTagValue(TopiaTagValues.TAG_PERSISTENCE_TYPE, classifier, null);
- return value;
- }
-
- /**
- * Obtain the value of the {@link TopiaTagValues#TAG_INHERITANCE_STRATEGY}
- * tag value on the given classifier.
- *
- * @param classifier classifier to seek
- * @return the none empty value of the found tag value or {@code null} if not found nor empty.
- * @see TopiaTagValues#TAG_INHERITANCE_STRATEGY
- * @since 3.0
- */
- public static String getInheritanceStrategyTagValue(ObjectModelClassifier classifier) {
- String value = findTagValue(TopiaTagValues.TAG_INHERITANCE_STRATEGY, classifier, null);
- if (value == null) {
- value = DEFAULT_INHERITANCE_STRATEGY;
- }
- return value;
- }
-
- /**
- * Obtain the value of the {@link TopiaTagValues#TAG_DB_NAME}
- * tag value on the given classifier.
- *
- * @param element classifier to seek
- * @return the none empty value of the found tag value or {@code null} if not found nor empty.
- * @see TopiaTagValues#TAG_DB_NAME
- * @since 2.5
- */
- public static String getDbNameTagValue(ObjectModelElement element) {
- String value = findTagValue(TopiaTagValues.TAG_DB_NAME, element, null);
- return value;
- }
-
- /**
- * Obtain the value of the {@link TopiaTagValues#TAG_SCHEMA_NAME}
- * tag value on the given classifier.
- *
- * @param classifier classifier to seek
- * @param model model to seek
- * @return the none empty value of the found tag value or {@code null} if not found nor empty.
- * @see TopiaTagValues#TAG_SCHEMA_NAME
- * @since 2.5
- */
- public static String getDbSchemaNameTagValue(ObjectModelClassifier classifier, ObjectModel model) {
- String value = findTagValue(TopiaTagValues.TAG_SCHEMA_NAME, classifier, model);
- return value;
- }
-
- /**
- * Obtain the value of the {@link TopiaTagValues#TAG_SCHEMA_NAME}
- * tag value on the given attribute.
- *
- * @param attribute attribute to seek
- * @param model model to seek
- * @return the none empty value of the found tag value or {@code null} if not found nor empty.
- * @see TopiaTagValues#TAG_SCHEMA_NAME
- * @since 2.5
- */
- public static String getDbSchemaNameTagValue(ObjectModelAttribute attribute, ObjectModel model) {
- String value = findTagValue(TopiaTagValues.TAG_SCHEMA_NAME, attribute, model);
- return value;
- }
-
- /**
- * Obtain the value of the {@link TopiaTagValues#TAG_LENGTH}
- * tag value on the given attribute.
- *
- * @param attribute attribute to seek
- * @return the none empty value of the found tag value or {@code null} if not found nor empty.
- * @see TopiaTagValues#TAG_LENGTH
- * @since 2.5
- */
- public static String getLengthTagValue(ObjectModelAttribute attribute) {
- String value = findTagValue(TopiaTagValues.TAG_LENGTH, attribute, null);
- return value;
- }
-
- /**
- * Obtain the value of the {@link TopiaTagValues#TAG_ANNOTATION}
- * tag value on the given attribute.
- *
- * @param attribute attribute to seek
- * @return the none empty value of the found tag value or {@code null} if not found nor empty.
- * @see TopiaTagValues#TAG_ANNOTATION
- * @since 2.5
- */
- public static String getAnnotationTagValue(ObjectModelAttribute attribute) {
- String value = findTagValue(TopiaTagValues.TAG_ANNOTATION, attribute, null);
- return value;
- }
-
- /**
- * Obtain the value of the {@link TopiaTagValues#TAG_ACCESS}
- * tag value on the given attribute.
- *
- * @param attribute attribute to seek
- * @return the none empty value of the found tag value or {@code null} if not found nor empty.
- * @see TopiaTagValues#TAG_ACCESS
- * @since 2.5
- */
- public static String getAccessTagValue(ObjectModelAttribute attribute) {
- String value = findTagValue(TopiaTagValues.TAG_ACCESS, attribute, null);
- return value;
- }
-
- /**
- * Obtain the value of the {@link TopiaTagValues#TAG_NATURAL_ID}
- * tag value on the given attribute.
- *
- * @param attribute attribute to seek
- * @return the none empty value of the found tag value or {@code null} if not found nor empty.
- * @see TopiaTagValues#TAG_NATURAL_ID
- * @since 2.5
- */
- public static String getNaturalIdTagValue(ObjectModelAttribute attribute) {
- String value = findTagValue(TopiaTagValues.TAG_NATURAL_ID, attribute, null);
- return value;
- }
-
- /**
- * Obtain the value of the {@link TopiaTagValues#TAG_NATURAL_ID_MUTABLE}
- * tag value on the given classifier.
- *
- * @param classifier classifier to seek
- * @return the none empty value of the found tag value or {@code null} if not found nor empty.
- * @see TopiaTagValues#TAG_NATURAL_ID_MUTABLE
- * @since 2.5
- */
- public static String getNaturalIdMutableTagValue(ObjectModelClassifier classifier) {
- String value = findTagValue(TopiaTagValues.TAG_NATURAL_ID_MUTABLE, classifier, null);
- return value;
- }
-
- /**
- * Obtain the value of the {@link TopiaTagValues#TAG_INVERSE}
- * tag value on the given attribute.
- *
- * @param attribute attribute to seek
- * @return the none empty value of the found tag value or {@code null} if not found nor empty.
- * @see TopiaTagValues#TAG_INVERSE
- * @since 2.5
- */
- public static String getInverseTagValue(ObjectModelAttribute attribute) {
- String value = findTagValue(TopiaTagValues.TAG_INVERSE, attribute, null);
- return value;
- }
-
- /**
- * Obtain the value of the {@link TopiaTagValues#TAG_LAZY}
- * tag value on the given attribute.
- *
- * @param attribute attribute to seek
- * @return the none empty value of the found tag value or {@code null} if not found nor empty.
- * @see TopiaTagValues#TAG_LAZY
- * @since 2.5
- */
- public static String getLazyTagValue(ObjectModelAttribute attribute) {
- String value = findTagValue(TopiaTagValues.TAG_LAZY, attribute, null);
- return value;
- }
-
- /**
- * Obtain the value of the {@link TopiaTagValues#TAG_FETCH}
- * tag value on the given attribute.
- *
- * @param attribute attribute to seek
- * @return the none empty value of the found tag value or {@code null} if not found nor empty.
- * @see TopiaTagValues#TAG_FETCH
- * @since 2.5
- */
- public static String getFetchTagValue(ObjectModelAttribute attribute) {
- String value = findTagValue(TopiaTagValues.TAG_FETCH, attribute, null);
- return value;
- }
-
- /**
- * Obtain the value of the {@link TopiaTagValues#TAG_ORDER_BY}
- * tag value on the given attribute.
- *
- * @param attribute attribute to seek
- * @return the none empty value of the found tag value or {@code null} if not found nor empty.
- * @see TopiaTagValues#TAG_ORDER_BY
- * @since 2.5
- */
- public static String getOrderByTagValue(ObjectModelAttribute attribute) {
- String value = findTagValue(TopiaTagValues.TAG_ORDER_BY, attribute, null);
- return value;
- }
-
- /**
- * Obtain the value of the {@link TopiaTagValues#TAG_NOT_NULL}
- * tag value on the given attribute.
- *
- * @param attribute attribute to seek
- * @return the none empty value of the found tag value or {@code null} if not found nor empty.
- * @see TopiaTagValues#TAG_NOT_NULL
- * @since 2.5
- */
- public static String getNotNullTagValue(ObjectModelAttribute attribute) {
- String value = findTagValue(TopiaTagValues.TAG_NOT_NULL, attribute, null);
- return value;
- }
-
- /**
- * Obtain the value of the {@link TopiaTagValues#TAG_PROXY_INTERFACE}
- * tag value on the given classifier.
- *
- * @param classifier classifier to seek
- * @param model model to seek
- * @return the none empty value of the found tag value or {@code null} if not found nor empty.
- * @see TopiaTagValues#TAG_PROXY_INTERFACE
- * @since 2.5
- */
- public static String getProxyInterfaceTagValue(ObjectModelClassifier classifier, ObjectModel model) {
- String value = findTagValue(TopiaTagValues.TAG_PROXY_INTERFACE, classifier, model);
- return value;
- }
-
- /**
- * Tests if the given classifier own at least one security tag value.
- *
- * @param classifier the classifier to test
- * @return {@code true} if there is at least one security tag value on the given class
- * @since 2.5
- */
- public static boolean isClassWithSecurity(ObjectModelClassifier classifier) {
- return StringUtils.isNotEmpty(getSecurityCreateTagValue(classifier)) ||
- StringUtils.isNotEmpty(getSecurityLoadTagValue(classifier)) ||
- StringUtils.isNotEmpty(getSecurityUpdateTagValue(classifier)) ||
- StringUtils.isNotEmpty(getSecurityDeleteTagValue(classifier));
- }
-
- /**
- * Obtain the value of the {@link TopiaTagValues#TAG_SECURITY_CREATE}
- * tag value on the given classifier.
- *
- * @param classifier classifier to seek
- * @return the none empty value of the found tag value or {@code null} if not found nor empty.
- * @see TopiaTagValues#TAG_SECURITY_CREATE
- * @since 2.5
- */
- public static String getSecurityCreateTagValue(ObjectModelClassifier classifier) {
- String value = findTagValue(TopiaTagValues.TAG_SECURITY_CREATE, classifier, null);
- return value;
- }
-
- /**
- * Obtain the value of the {@link TopiaTagValues#TAG_SECURITY_DELETE}
- * tag value on the given classifier.
- *
- * @param classifier classifier to seek
- * @return the none empty value of the found tag value or {@code null} if not found nor empty.
- * @see TopiaTagValues#TAG_SECURITY_DELETE
- * @since 2.5
- */
- public static String getSecurityDeleteTagValue(ObjectModelClassifier classifier) {
- String value = findTagValue(TopiaTagValues.TAG_SECURITY_DELETE, classifier, null);
- return value;
- }
-
- /**
- * Obtain the value of the {@link TopiaTagValues#TAG_SECURITY_LOAD}
- * tag value on the given classifier.
- *
- * @param classifier classifier to seek
- * @return the none empty value of the found tag value or {@code null} if not found nor empty.
- * @see TopiaTagValues#TAG_SECURITY_LOAD
- * @since 2.5
- */
- public static String getSecurityLoadTagValue(ObjectModelClassifier classifier) {
- String value = findTagValue(TopiaTagValues.TAG_SECURITY_LOAD, classifier, null);
- return value;
- }
-
- /**
- * Obtain the value of the {@link TopiaTagValues#TAG_SECURITY_UPDATE}
- * tag value on the given classifier.
- *
- * @param classifier classifier to seek
- * @return the none empty value of the found tag value or {@code null} if not found nor empty.
- * @see TopiaTagValues#TAG_SECURITY_UPDATE
- * @since 2.5
- */
- public static String getSecurityUpdateTagValue(ObjectModelClassifier classifier) {
- String value = findTagValue(TopiaTagValues.TAG_SECURITY_UPDATE, classifier, null);
- return value;
- }
-
- /**
- * Obtain the value of the {@link TopiaTagValues#TAG_NOT_GENERATE_TO_STRING}
- * tag value on the given class.
- *
- * @param clazz class to seek
- * @param model model to seek
- * @return the none empty value of the found tag value or {@code null} if not found nor empty.
- * @see TopiaTagValues#TAG_NOT_GENERATE_TO_STRING
- * @since 2.5
- */
- public static String getNotGenerateToStringTagValue(ObjectModelClassifier clazz, ObjectModel model) {
- String value = findTagValue(TopiaTagValues.TAG_NOT_GENERATE_TO_STRING, clazz, model);
- return value;
- }
-
- /**
- * Obtain the value of the {@link TopiaTagValues#TAG_SORT_ATTRIBUTE}
- * tag value on the given classifier.
- *
- * @param classifier classifier to seek
- * @param model model to seek
- * @return the none empty value of the found tag value or {@code null} if not found nor empty.
- * @see TopiaTagValues#TAG_SORT_ATTRIBUTE
- * @since 2.5
- */
- public static String getSortAttributeTagValue(ObjectModelClassifier classifier, ObjectModel model) {
- String value = findTagValue(TopiaTagValues.TAG_SORT_ATTRIBUTE, classifier, model);
- return value;
- }
-
- /**
- * Obtain the value of the {@link TopiaTagValues#TAG_GENERATE_STANDALONE_ENUM_FOR_DAO_HELPER}
- * tag value on the given model.
- *
- * @param model model to seek
- * @return the none empty value of the found tag value or {@code null} if not found nor empty.
- * @see TopiaTagValues#TAG_GENERATE_STANDALONE_ENUM_FOR_DAO_HELPER
- * @since 2.5
- */
- public static String getGenerateStandaloneEnumForDAOHelperTagValue(ObjectModel model) {
- String value = findTagValue(TopiaTagValues.TAG_GENERATE_STANDALONE_ENUM_FOR_DAO_HELPER, null, model);
- return value;
- }
-
- /* Obtain the value of the {@link TopiaTagValues#TAG_GENERATE_OPERATOR_FOR_DAO_HELPER}
- * tag value on the given model.
- *
- * @param model model to seek
- * @return the none empty value of the found tag value or {@code null} if not found nor empty.
- * @see TopiaTagValues#TAG_GENERATE_OPERATOR_FOR_DAO_HELPER
- * @since 2.5
- */
- public static String getGenerateOperatorForDAOHelperTagValue(ObjectModel model) {
- String value = findTagValue(TopiaTagValues.TAG_GENERATE_OPERATOR_FOR_DAO_HELPER, null, model);
- return value;
- }
-
- /**
- * Obtain the value of the {@link TopiaTagValues#TAG_TYPE}
- * tag value on the given attribute.
- *
- * @param attribute attribute to seek
- * @return the none empty value of the found tag value or {@code null} if not found nor empty.
- * @see TopiaTagValues#TAG_TYPE
- * @since 2.5
- */
- public static String getTypeTagValue(ObjectModelAttribute attribute) {
- String value = findTagValue(TopiaTagValues.TAG_TYPE, attribute, null);
- return value;
- }
-
- /**
- * Obtain the value of the {@link TopiaTagValues#TAG_SQL_TYPE}
- * tag value on the given attribute.
- *
- * @param attribute attribute to seek
- * @return the none empty value of the found tag value or {@code null} if not found nor empty.
- * @see TopiaTagValues#TAG_TYPE
- * @since 2.5
- */
- public static String getSqlTypeTagValue(ObjectModelAttribute attribute) {
- String value = findTagValue(TopiaTagValues.TAG_SQL_TYPE, attribute, null);
- return value;
- }
-
- /**
- * Obtains the value of the {@link TopiaTagValues#TAG_DAO_IMPLEMENTATION}
- * tag value on the given model.
-
- *
- * @param model model to seek
- * @return the none empty value of the found tag value or {@code null} if not found nor empty.
- * @see TopiaTagValues#TAG_DAO_IMPLEMENTATION
- * @since 2.5
- */
- public static String getDaoImplementationTagValue(ObjectModel model) {
- String value = findTagValue(TopiaTagValues.TAG_DAO_IMPLEMENTATION, null, model);
- return value;
- }
-
- /**
- * Obtains the value of the tag value
- * {@link TopiaTagValues#TAG_INDEX_FOREIGN_KEYS} on the model or on the
- * given attribute.
- *
- * @param attribute attribute to test
- * @param model model to test
- * @return none empty value of the found tag value or {@code null} if not found nor empty.
- * @see TopiaTagValues#TAG_INDEX_FOREIGN_KEYS
- * @since 2.6.5
- */
- public static String getIndexForeignKeys(ObjectModelAttribute attribute, ObjectModel model) {
- String value = findTagValue(TopiaTagValues.TAG_INDEX_FOREIGN_KEYS, attribute, model);
- return value;
- }
-
- public static boolean hasUseEnumerationNameTagValue(ObjectModelAttribute attr, ObjectModel model) {
- String value = findTagValue(TopiaTagValues.TAG_USE_ENUMERATION_NAME, attr, model);
- return Boolean.parseBoolean(value);
- }
-
- /**
- * Search if the TagValue {@link TopiaTagValues#TAG_GENERATE_TOPIA_ID_IN_DTO} has been
- * activated in the model.
- *
- * @param classifier classifier to seek
- * @param model model to seek
- * @return the none empty value of the found tag value or {@code null} if not found nor empty.
- * @see TopiaTagValues#TAG_GENERATE_TOPIA_ID_IN_DTO
- * @since 2.6.7
- */
- public static boolean shouldGenerateDTOTopiaIdTagValue(ObjectModelClassifier classifier, ObjectModel model) {
- String tagValue = findTagValue(TopiaTagValues.TAG_GENERATE_TOPIA_ID_IN_DTO, classifier, model);
- boolean generate = StringUtils.isNotEmpty(tagValue) && Boolean.valueOf(tagValue);
- return generate;
- }
-
-} // TopiaGeneratorUtil
-
Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaJavaValidator.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaJavaValidator.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaJavaValidator.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,157 +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%
- */
-
-package org.nuiton.topia.generator;
-
-import org.apache.commons.lang3.StringUtils;
-import org.nuiton.eugene.models.object.ObjectModel;
-import org.nuiton.eugene.models.object.ObjectModelAttribute;
-import org.nuiton.eugene.models.object.ObjectModelClass;
-import org.nuiton.eugene.models.object.ObjectModelOperation;
-import org.nuiton.eugene.models.object.validator.ObjectModelValidator;
-
-import java.util.ArrayList;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-/**
- * Validateur qui valide :
- * - les types des attributs
- * - les nom des attributs
- * - les duplication d'attibuts
- *
- * @author chatellier <chatellier(a)codelutin.com>
- * @version $Id$
- */
-public class TopiaJavaValidator extends ObjectModelValidator {
-
- /**
- * Constructor.
- *
- * @param model model to validate
- */
- public TopiaJavaValidator(ObjectModel model) {
- super(model);
- }
-
- @Override
- protected boolean validateAttribute(ObjectModelAttribute attr) {
-
- boolean isValid = super.validateAttribute(attr);
-
- // type null ou vide
- if (attr.getType() == null || attr.getType().isEmpty()) {
- isValid = false;
-
- addError(attr, "Invalid type \"" + attr.getType() + "\"");
- }
-
- // name = java reserved keywords
- if (!isJavaIdentifier(attr.getName())) {
- isValid = false;
-
- addError(attr, "Attribute name " + attr.getName()
- + " is not valid java identifier");
- }
-
- // test sur les mots réservés ?
-
- return isValid;
-
- }
-
- @Override
- protected boolean validateClass(ObjectModelClass clazz) {
-
- boolean isValid = super.validateClass(clazz);
-
- // test attribute names duplication
- Set<String> attributesName = new HashSet<String>();
- for (ObjectModelAttribute attr : clazz.getAttributes()) {
- if (!attr.isNavigable()) {
-
- // not navigable, so will not use it...
- continue;
- }
- String attrName = attr.getName();
- if (!attributesName.add(attrName)) {
- addError(attr, "Attribute name " + attrName
- + " already exists");
-
- isValid = false;
- }
- }
-
- if (TopiaGeneratorUtil.isEntity(clazz)) {
-
- Set<String> methodsName = new HashSet<String>();
- for (ObjectModelAttribute attr : clazz.getAttributes()) {
-
- String capitalizeAttrName = StringUtils.capitalize(attr.getName());
- methodsName.add(TopiaGeneratorUtil.OPERATION_GETTER_BOOLEAN_PREFIX + capitalizeAttrName);
- methodsName.add(TopiaGeneratorUtil.OPERATION_GETTER_DEFAULT_PREFIX + capitalizeAttrName);
- methodsName.add("set" + capitalizeAttrName);
- }
-
- // test if there is a method an already reserved name
- for (ObjectModelOperation operation : clazz.getOperations()) {
- String operationName = operation.getName();
- if (methodsName.contains(operationName)) {
- addError(operation, "Operation name " + operationName
- + " is already reserved for a getter/setter of an entity attribute");
-
- isValid = false;
- }
- }
- }
-
- return isValid;
- }
-
- @Override
- protected boolean validateModel(ObjectModel model) {
-
- return super.validateModel(model);
- }
-
- /**
- * Returns true if s is a legal Java identifier.
- *
- * @param s string to test
- * @return true if s is a legal Java identifier
- */
- public static boolean isJavaIdentifier(String s) {
- if (s.length() == 0 || !Character.isJavaIdentifierStart(s.charAt(0))) {
- return false;
- }
- for (int i = 1; i < s.length(); i++) {
- if (!Character.isJavaIdentifierPart(s.charAt(i))) {
- return false;
- }
- }
- return true;
- }
-}
Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaMetaTransformer.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaMetaTransformer.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaMetaTransformer.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,132 +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%
- */
-
-package org.nuiton.topia.generator;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.nuiton.eugene.AbstractMetaTransformer;
-import org.nuiton.eugene.models.object.ObjectModel;
-import org.nuiton.eugene.models.object.ObjectModelClass;
-import org.nuiton.eugene.models.object.validator.AttributeNamesValidator;
-import org.nuiton.eugene.models.object.validator.ClassNamesValidator;
-import org.nuiton.eugene.models.object.validator.ObjectModelValidator;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Created: 20 déc. 2009
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @version $Id$
- * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.generator.TopiaMetaTransformer"
- * @since 2.3.0
- */
-public class TopiaMetaTransformer extends AbstractMetaTransformer<ObjectModel> {
-
- /** Logger */
- private static final Log log = LogFactory.getLog(TopiaMetaTransformer.class);
-
- public TopiaMetaTransformer() {
-// super(
-// EntityTransformer.class,
-// DAOTransformer.class,
-// DAOImplTransformer.class,
-// DAOAbstractTransformer.class,
-// DAOHelperTransformer.class,
-// EntityHibernateMappingGenerator.class
-// );
-
- setTemplateTypes(
- ApplicationContextTransformer.class,
- PersistenceContextTransformer.class,
- EntityTransformer.class,
- EntityDaoTransformer.class,
-// DAOTransformer.class,
-// DAOImplTransformer.class,
-// DAOAbstractTransformer.class,
- DAOHelperTransformer.class,
- EntityHibernateMappingGenerator.class
- );
- }
-
- protected boolean validateModel(ObjectModel model) {
- List<ObjectModelValidator> validators = new ArrayList<ObjectModelValidator>();
-
- AttributeNamesValidator attrValidator = new AttributeNamesValidator(
- model);
- attrValidator.addNameAndReason("analyze",
- "Le nom d'attribut \"analyze\" est incompatible avec certains SGBD");
- attrValidator.addNameAndReason("next",
- "Le nom d'attribut \"next\" est incompatible avec HSQL");
- attrValidator.addNameAndReason("value",
- "Le nom d'attribut \"value\" est incompatible avec certains SGBD");
- attrValidator.addNameAndReason("values",
- "Le nom d'attribut \"values\" est incompatible avec certains SGBD");
- attrValidator.addNameAndReason("begin",
- "Le nom d'attribut \"begin\" est incompatible avec certains SGBD");
- attrValidator.addNameAndReason("end",
- "Le nom d'attribut \"end\" est incompatible avec certains SGBD");
- attrValidator.addNameAndReason("authorization",
- "Le nom d'attribut \"authorization\" est incompatible avec certains SGBD");
- attrValidator.addNameAndReason("order",
- "Le nom d'attribut \"order\" est incompatible avec certains SGBD");
- validators.add(attrValidator);
-
- ClassNamesValidator classValidator = new ClassNamesValidator(model);
- classValidator.addNameAndReason("constraint", "Nom de classe incompatible avec certains SGBD");
- classValidator.addNameAndReason("user", "Nom de classe incompatible avec certains SGBD");
- validators.add(classValidator);
-
- validators.add(new TopiaJavaValidator(model));
- validators.add(new TopiaRelationValidator(model));
-
- for (ObjectModelValidator validator : validators) {
- if (!validator.validate()) {
- for (String error : validator.getErrors()) {
- if (log.isWarnEnabled()) {
- log.warn("[VALIDATION] " + error);
- }
- }
- }
- }
-
- // test before all if there is some entities to generate
- List<ObjectModelClass> classes = TopiaGeneratorUtil.getEntityClasses(model, true);
-
- if (classes.isEmpty()) {
- // no entity to generate, can stop safely
- if (log.isWarnEnabled()) {
- log.warn("No entity to generate, " + getClass().getName() +
- " is skipped");
- }
- return false;
- }
- //FIXME-TC20091220 seems we still generate if there is some validation errors ? not very normal
- return true;
- }
-
-}
Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaRelationValidator.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaRelationValidator.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaRelationValidator.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,121 +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%
- */
-
-
-/* *
-* TopiaRelationValidator.java
-*
-* Created: 31 mars 2006
-*
-* @author Arnaud Thimel <thimel(a)codelutin.com>
-* @version $Revision$
-*
-* Mise a jour: $Date$
-* par : $Author$
-*/
-
-package org.nuiton.topia.generator;
-
-import org.nuiton.eugene.models.object.ObjectModel;
-import org.nuiton.eugene.models.object.ObjectModelAttribute;
-import org.nuiton.eugene.models.object.validator.ObjectModelValidator;
-
-/**
- * Validateur pour les relations du modèle.
- * Vérifie que :
- * <ul>
- * <li>Toutes les relations ont au moins une navigabilité</li>
- * <li>Une relation 1-n unidirectionnelle pointant sur une classe ayant des
- * sous-classes dans le modèle est incompatibe avec Hibernate</li>
- * <li>Toutes les relations ont des reverseAttribute</li>
- * </ul>
- *
- * @version $Id$
- */
-public class TopiaRelationValidator extends ObjectModelValidator {
-
- /**
- * Constructeur de TopiaRelationValidator.
- *
- * @param model le modèle à valider
- */
- public TopiaRelationValidator(ObjectModel model) {
- super(model);
- }
-
- /* (non-Javadoc)
- * @see org.nuiton.eugene.models.object.validator.ObjectModelValidator#validateAttribute(org.nuiton.eugene.models.object.ObjectModelAttribute)
- */
- @Override
- protected boolean validateAttribute(ObjectModelAttribute attr) {
- boolean isValid = true;
- ObjectModelAttribute reverse = attr.getReverseAttribute();
-
- /* Relation navigabilité */
- //Pour ne pas avoir de doublons, on ne vérifie que sur le premier
- //attribut par ordre alphabétique
- if (TopiaGeneratorUtil.isFirstAttribute(attr)) {
- if (!attr.isNavigable() && !reverse.isNavigable()) {
- addError(attr, "La relation entre " + "\"" + reverse.getType()
- + "\"[" + attr.getName() + "] et " + "\""
- + attr.getType() + "\"[" + reverse.getName() + "] "
- + "n'est navigable dans aucun sens");
- isValid = false;
- }
- }
-
- /* Relation héritage */
- if (TopiaGeneratorUtil.hasUnidirectionalRelationOnAbstractType(attr, model)) {
- isValid = false;
- addError(
- attr,
- "La relation entre "
- + "\""
- + reverse.getType()
- + "\"["
- + attr.getName()
- + "] et "
- + "\""
- + attr.getType()
- + "\"["
- + reverse.getName()
- + "] "
- + "n'est navigable que dans un sens et "
- + "la classe \""
- + attr.getType()
- + "\" a des sous-classes. "
- + "Des accesseurs doivent donc etre generes pour Hibernate.");
- }
-
- /* Pas d'inverse */
- if (reverse == null && model.hasClass(attr.getType())) {
- isValid = false;
- addError(attr, "Cet attribut n'a pas d'inverse.");
- }
-
- return isValid;
- }
-
-} //TopiaRelationValidator
Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaStereoTypes.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaStereoTypes.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaStereoTypes.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,88 +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%
- */
-package org.nuiton.topia.generator;
-
-import org.nuiton.eugene.EugeneStereoTypes;
-import org.nuiton.eugene.models.object.ObjectModelAttribute;
-import org.nuiton.eugene.models.object.ObjectModelClassifier;
-import org.nuiton.eugene.models.object.ObjectModelOperation;
-
-import static org.nuiton.eugene.ModelPropertiesUtil.StereotypeDefinition;
-
-/**
- * All extra stereotypes usable in topia generators.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 2.5
- */
-public interface TopiaStereoTypes extends EugeneStereoTypes {
-
- /**
- * Stéréotype pour les objets devant être générées sous forme d'entités
- *
- * @see TopiaGeneratorUtil#isEntity(ObjectModelClassifier)
- * @see TopiaGeneratorUtil#hasEntityStereotype(ObjectModelAttribute)
- */
- @StereotypeDefinition(target = {ObjectModelClassifier.class, ObjectModelAttribute.class},
- documentation = "To specify that a class is an Entity")
- String STEREOTYPE_ENTITY = "entity";
-
- /**
- * Stéréotype pour les objets devant être générées sous forme de DTO.
- *
- * @see TopiaGeneratorUtil#hasDtoStereotype(ObjectModelClassifier)
- */
- @StereotypeDefinition(target = ObjectModelClassifier.class,
- documentation = "to specify that a class is a DTO")
- String STEREOTYPE_DTO = "dto";
-
- /**
- * Stéréotype pour les interfaces devant être générées sous forme de DAO.
- *
- * @see TopiaGeneratorUtil#hasDaoStereotype(ObjectModelClassifier)
- * @see TopiaGeneratorUtil#hasDaoStereotype(ObjectModelOperation)
- */
- @StereotypeDefinition(target = {ObjectModelClassifier.class, ObjectModelOperation.class},
- documentation = "To Specify that a classifier or an operation should be generated as (or in) a DAO")
- String STEREOTYPE_DAO = "dao";
-
- /**
- * Stéréotype pour les collections avec unicité.
- *
- * @see TopiaGeneratorUtil#hasUniqueStereotype(ObjectModelAttribute)
- */
- @StereotypeDefinition(target = ObjectModelAttribute.class,
- documentation = "To specify that an attribute is unique (Hibernate mapping)")
- String STEREOTYPE_UNIQUE = "unique";
-
- /**
- * Stéréotype pour les attributs étant des clés primaires.
- *
- * @see TopiaGeneratorUtil#hasPrimaryKeyStereotype(ObjectModelAttribute)
- */
- @StereotypeDefinition(target = ObjectModelAttribute.class,
- documentation = "To specify that an attribute is part of a primary key (Hibernate mapping)")
- String STEREOTYPE_PRIMARYKAY = "primaryKey";
-}
Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaTagValues.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaTagValues.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaTagValues.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,379 +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%
- */
-package org.nuiton.topia.generator;
-
-import org.nuiton.eugene.EugeneTagValues;
-import org.nuiton.eugene.models.object.ObjectModel;
-import org.nuiton.eugene.models.object.ObjectModelAttribute;
-import org.nuiton.eugene.models.object.ObjectModelClass;
-import org.nuiton.eugene.models.object.ObjectModelClassifier;
-import org.nuiton.eugene.models.object.ObjectModelElement;
-import org.nuiton.topia.TopiaContext;
-import org.nuiton.topia.persistence.TopiaEntityContextable;
-import org.nuiton.topia.persistence.TopiaEntityEnum;
-
-import static org.nuiton.eugene.ModelPropertiesUtil.TagValueDefinition;
-
-/**
- * All extra tag values usable in topia generators.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 2.5
- */
-public interface TopiaTagValues extends EugeneTagValues {
-
- /**
- * Tag pour le type de persistence.
- *
- * @see TopiaGeneratorUtil#getPersistenceType(ObjectModelClassifier)
- * @see TopiaGeneratorUtil#getPersistenceTypeTagValue(ObjectModelClassifier)
- * @since 2.5
- */
- @TagValueDefinition(target = {ObjectModelClassifier.class},
- documentation = "")
- String TAG_PERSISTENCE_TYPE = "persistenceType";
-
- /**
- * Tag pour que les entités etendent {@link TopiaEntityContextable} et
- * se fasse injecter le {@link TopiaContext} par rapport aux autres
- * entités qui ne l'ont pas.
- *
- * @since 2.5.3
- */
- @TagValueDefinition(target = {ObjectModelClassifier.class}, documentation = "")
- String TAG_CONTEXTABLE = "contextable";
-
- /**
- * Tag pour le nom du champ / entité en BD.
- *
- * @see TopiaGeneratorUtil#getDbNameTagValue(ObjectModelElement)
- * @see TopiaGeneratorUtil#getDbName(ObjectModelElement)
- * @see TopiaGeneratorUtil#getReverseDbName(ObjectModelAttribute)
- */
- @TagValueDefinition(target = {ObjectModelElement.class},
- documentation = "Sets the database name of an element of the model (a table or a column)")
- String TAG_DB_NAME = "dbName";
-
- /**
- * Tag pour le nom du schema en BD.
- *
- * @see TopiaGeneratorUtil#getDbSchemaNameTagValue(ObjectModelClassifier, ObjectModel)
- * @see TopiaGeneratorUtil#getDbSchemaNameTagValue(ObjectModelAttribute, ObjectModel)
- * @since 2.5
- */
- @TagValueDefinition(target = {ObjectModel.class, ObjectModelClassifier.class, ObjectModelAttribute.class},
- documentation = "Sets the database schema name")
- String TAG_SCHEMA_NAME = "dbSchema";
-
- /**
- * Tag pour la taille du champ en BD.
- *
- * @see TopiaGeneratorUtil#getLengthTagValue(ObjectModelAttribute)
- * @since 2.5
- */
- @TagValueDefinition(target = {ObjectModelAttribute.class},
- documentation = "Sets the length of an attribute in database")
- String TAG_LENGTH = "length";
-
- /**
- * Tag pour ajouter une annotation à un champ.
- *
- * @see TopiaGeneratorUtil#getAnnotationTagValue(ObjectModelAttribute)
- * @since 2.5
- */
- @TagValueDefinition(target = {ObjectModelAttribute.class},
- documentation = "Sets an annotation of an attribute")
- String TAG_ANNOTATION = "annotation";
-
- /**
- * Tag pour specfier le type d'acces a un champ.
- *
- * @see TopiaGeneratorUtil#getAccessTagValue(ObjectModelAttribute)
- * @since 2.5
- */
- @TagValueDefinition(target = {ObjectModelAttribute.class},
- documentation = "Sets the access type of an attribute (Hibernate mapping)")
- String TAG_ACCESS = "access";
-
- /**
- * Tag pour ajouter un attribut dans une clef métier.
- *
- * @see TopiaGeneratorUtil#getNaturalIdTagValue(ObjectModelAttribute)
- * @see TopiaGeneratorUtil#isNaturalId(ObjectModelAttribute)
- * @since 2.5
- */
- @TagValueDefinition(target = {ObjectModelAttribute.class},
- documentation = "Sets an attribute as part of a natural id (Hibernate Mapping)")
- String TAG_NATURAL_ID = "naturalId";
-
- /**
- * Tag pour specifier si une clef metier est mutable.
- *
- * @see TopiaGeneratorUtil#getNaturalIdMutableTagValue(ObjectModelClassifier)
- * @see TopiaGeneratorUtil#isNaturalIdMutable(ObjectModelClass)
- * @since 2.5
- */
- @TagValueDefinition(target = {ObjectModelClassifier.class},
- documentation = "Sets if natural id of a entity is mutable (hibernate mapping)")
- String TAG_NATURAL_ID_MUTABLE = "naturalIdMutable";
-
- /**
- * Tag pour permettre de choisir qui contrôle la relation N-N
- * bidirectionnelle. A utiliser sur les deux extremités de l'association.
- * Mettre inverse=false sur le rôle fils et inverse=true sur le rôle père.
- * Par défaut le inverse=true est placé sur le premier rôle trouvé dans
- * l'ordre alphabétique.
- *
- * @see TopiaGeneratorUtil#getInverseTagValue(ObjectModelAttribute)
- * @since 2.5
- */
- @TagValueDefinition(target = {ObjectModelAttribute.class},
- documentation = "Sets which part of a N-N relation is master (inverse=true) and slave (inverse=false) (must be put on each side on a such relation) (Hibernate mapping)")
- String TAG_INVERSE = "inverse";
-
- /**
- * Tag pour spécifier la caractère lazy d'une association multiple.
- *
- * @see TopiaGeneratorUtil#getLazyTagValue(ObjectModelAttribute)
- * @since 2.5
- */
- @TagValueDefinition(target = {ObjectModelAttribute.class},
- documentation = "Sets if an association should be lazy (Hibernate mapping)")
- String TAG_LAZY = "lazy";
-
- /**
- * Tag pour spécifier la caractère fetch d'une association multiple.
- *
- * @see TopiaGeneratorUtil#getFetchTagValue(ObjectModelAttribute)
- * @since 2.5
- */
- @TagValueDefinition(target = {ObjectModelAttribute.class},
- documentation = "Sets the fetch caracteristic of an attribute (Hibernate mapping)")
- String TAG_FETCH = "fetch";
-
- /**
- * Tag pour spécifier la caractère order-by d'une association multiple.
- *
- * @see TopiaGeneratorUtil#getOrderByTagValue(ObjectModelAttribute)
- * @since 2.5
- */
- @TagValueDefinition(target = {ObjectModelAttribute.class},
- documentation = "Sets the order by propertie of an multiple association (Hibernate mapping)")
- String TAG_ORDER_BY = "orderBy";
-
- /**
- * Tag pour spécifier la caractère not-null d'un attribut.
- *
- * @see TopiaGeneratorUtil#getNotNullTagValue(ObjectModelAttribute)
- * @since 2.5
- */
- @TagValueDefinition(target = {ObjectModelAttribute.class},
- documentation = "Sets if an attribute must be not null (Hibernate mapping)")
- String TAG_NOT_NULL = "notNull";
-
- /**
- * Tag à placer sur un l'attribut d'une entité. Cet attribut est de type
- * énumération : l'ajout de la tagValue indique qu'il faut utiliser le
- * {@code name} de l'énumération et non l'ordinal pour stocker la valeur en
- * base
- */
- @TagValueDefinition(target = {ObjectModelAttribute.class},
- documentation = "'true' if the value of this attribute of type Enumeration should be stored with its name (instead of using ordinal)")
- String TAG_USE_ENUMERATION_NAME = "useEnumerationName";
-
- /**
- * Tag pour configurer l'interface du proxy sur autre chose que l'implementation par defaut.
- * <p/>
- * Par defaut :
- * null > generere le proxy sur l'interface de l'implementation
- * Autre valeur :
- * "none" > laisse la configuration par defaut d'hibernate
- *
- * @see TopiaGeneratorUtil#getPersistenceTypeTagValue(ObjectModelClassifier)
- * @since 2.5
- */
- @TagValueDefinition(target = {ObjectModel.class, ObjectModelClassifier.class},
- documentation = "Configure the proxy interface on something else than the default implementation (null to use our default implementation, none to let hibernate deal it) (Hibernate mapping)")
- String TAG_PROXY_INTERFACE = "hibernateProxyInterface";
-
- /**
- * Tag pour configurer la stategie d'heritage choisie.
- * <p/>
- * Par defaut : union-subclass : Table per class strategy
- * Autre valeur :
- * "subclass" > Single table per class hierarchy strategy
- * "joined-subclass" > Joined subclass strategy
- *
- * @see TopiaGeneratorUtil#getPersistenceTypeTagValue(ObjectModelClassifier)
- * @since 3.0
- */
- @TagValueDefinition(target = {ObjectModel.class, ObjectModelClassifier.class},
- documentation = "Configure the proxy interface on something else than the default implementation (null to use our default implementation, none to let hibernate deal it) (Hibernate mapping)")
- String TAG_INHERITANCE_STRATEGY = "inheritanceStrategy";
-
- /**
- * Tag pour spécifier le permissions à la création.
- *
- * @see TopiaGeneratorUtil#getSecurityCreateTagValue(ObjectModelClassifier)
- * @since 2.5
- */
- @TagValueDefinition(target = {ObjectModelClassifier.class},
- documentation = "Sets the create permission on an entity")
- String TAG_SECURITY_CREATE = "securityCreate";
-
- /**
- * Tag pour spécifier le permissions au chargement.
- *
- * @see TopiaGeneratorUtil#getSecurityLoadTagValue(ObjectModelClassifier)
- * @since 2.5
- */
- @TagValueDefinition(target = {ObjectModelClassifier.class},
- documentation = "Sets the load permission on an entity")
- String TAG_SECURITY_LOAD = "securityLoad";
-
- /**
- * Tag pour spécifier le permissions à la mise à jour.
- *
- * @see TopiaGeneratorUtil#getSecurityUpdateTagValue(ObjectModelClassifier)
- * @since 2.5
- */
- @TagValueDefinition(target = {ObjectModelClassifier.class},
- documentation = "Sets the update permission on an entity")
- String TAG_SECURITY_UPDATE = "securityUpdate";
-
- /**
- * Tag pour spécifier le permissions à la suppression.
- *
- * @see TopiaGeneratorUtil#getSecurityDeleteTagValue(ObjectModelClassifier)
- * @since 2.5
- */
- @TagValueDefinition(target = {ObjectModelClassifier.class},
- documentation = "sets the delete permission on an entity")
- String TAG_SECURITY_DELETE = "securityDelete";
-
- /**
- * Tag pour specifier de ne pas generer la methode toString.
- *
- * @see TopiaGeneratorUtil#getNotGenerateToStringTagValue(ObjectModelClassifier, ObjectModel)
- * @see TopiaGeneratorUtil#generateToString(ObjectModelClass, ObjectModel)
- * @since 2.5
- */
- @TagValueDefinition(target = {ObjectModel.class, ObjectModelClassifier.class},
- documentation = "To not generate the toString method on entities")
- String TAG_NOT_GENERATE_TO_STRING = "notGenerateToString";
-
- /**
- * Tag pour specifier de trier les attributs par nom lors de la generation.
- *
- * @see TopiaGeneratorUtil#getSortAttributeTagValue(ObjectModelClassifier, ObjectModel)
- * @see TopiaGeneratorUtil#sortAttribute(ObjectModelClass, ObjectModel)
- * @since 2.5
- */
- @TagValueDefinition(target = {ObjectModel.class, ObjectModelClassifier.class},
- documentation = "To sort attribute while generation")
- String TAG_SORT_ATTRIBUTE = "sortAttribute";
-
- /**
- * Tag pour specfier si on doit générer la methode getOperator dans les daohelpers.
- *
- * @see TopiaGeneratorUtil#getGenerateOperatorForDAOHelperTagValue(ObjectModel)
- * @see TopiaGeneratorUtil#shouldGenerateOperatorForDAOHelper(ObjectModel)
- * @since 2.5
- */
- @TagValueDefinition(target = {ObjectModel.class},
- documentation = "To generate EntityOperation on generated DAOHelper")
- String TAG_GENERATE_OPERATOR_FOR_DAO_HELPER = "generateOperatorForDAOHelper";
-
- /**
- * Tag pour spécifier si on doit générer le {@link TopiaEntityEnum} en tant qu'inner classe
- * du dao helper ou pas.
- * <p/>
- * <b>Note:</b> Par défaut, on génère en tant qu'inner classe.
- *
- * @see TopiaGeneratorUtil#getGenerateStandaloneEnumForDAOHelperTagValue(ObjectModel)
- * @see TopiaGeneratorUtil#shouldGenerateStandaloneEnumForDAOHelper(ObjectModel)
- * @since 2.5
- */
- @TagValueDefinition(target = {ObjectModel.class},
- documentation = "To generate a standalon EntityEnum outside the DAOHelper")
- String TAG_GENERATE_STANDALONE_ENUM_FOR_DAO_HELPER = "generateStandaloneEnumForDAOHelper";
-
- /**
- * Tag pour spécifier le type d'une propriété dans le mapping hibernate.
- *
- * @see TopiaGeneratorUtil#getTypeTagValue(ObjectModelAttribute)
- * @since 2.5
- */
- @TagValueDefinition(target = {ObjectModelAttribute.class},
- documentation = "Sets the hibernate type of an attribute (Hibernate mapping)")
- String TAG_TYPE = "type";
-
- /**
- * Tag pour spécifier le type sql d'une propriété dans le mapping hibernate.
- *
- * @see TopiaGeneratorUtil#getSqlTypeTagValue(ObjectModelAttribute)
- * @since 2.5
- */
- @TagValueDefinition(target = {ObjectModelAttribute.class},
- documentation = "Sets the sql type of an attribute (Hibernate mapping)")
- String TAG_SQL_TYPE = "sqlType";
-
- /**
- * To specify the abstract dao to use.
- * <p/>
- * If none given, will use the {@code org.nuiton.topia.persistence.TopiaDAOImpl}.
- * <p/>
- * Other value possible is {@code org.nuiton.topia.persistence.TopiaDAOLegacy}
- *
- * @see TopiaGeneratorUtil#getDaoImplementationTagValue(ObjectModel)
- * @since 2.5
- */
- @TagValueDefinition(target = {ObjectModel.class},
- documentation = "Sets the fully qualified name of the DAO implementation to use in generated DAO (default is DAOImpl (base on TopiaQuery))")
- String TAG_DAO_IMPLEMENTATION = "daoImplementation";
-
- /**
- * Stéréotype pour les attributs avec multiplicité nécessitant la création d'un index.
- *
- * @see TopiaGeneratorUtil#getIndexForeignKeys(ObjectModelAttribute, ObjectModel)
- * @since 2.6.5
- */
- @TagValueDefinition(target = {ObjectModel.class, ObjectModelAttribute.class},
- documentation = "Specifies if an nm-multiplicity attribute (or all nm-multiplicity attributes of a given model) needs an index in db (Hibernate mapping)")
- String TAG_INDEX_FOREIGN_KEYS = "indexForeignKeys";
-
- /**
- * Tag to specify if we want to add an "id" property in DTO generated by
- * {@link EntityDTOTransformer}.
- * <p/>
- *
- * @see EntityDTOTransformer
- * @see TopiaGeneratorUtil#shouldGenerateDTOTopiaIdTagValue(ObjectModelClassifier, ObjectModel)
- * @since 2.6.7
- */
- @TagValueDefinition(target = {ObjectModel.class, ObjectModelClassifier.class},
- documentation = "Add a \"id\" property with its getter/setter on a DTO.")
- String TAG_GENERATE_TOPIA_ID_IN_DTO = "generateDTOTopiaId";
-}
Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/package-info.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/package-info.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/package-info.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,118 +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%
- */
-/**
- * TODO-FD20100507 : Need update this javadoc for ToPIA 2.4
- *
- * <h1>Les Générateurs</h1>
- *
- * <h2>TopiaMetaGenerator</h2>
- *
- * <p>TopiaMetaGenerator permet d'enchainer les différents
- * générateurs.</p>
- *
- * <h2>Les DAO</h2>
- *
- * <p>Il il y a trois générateurs pour les DAO</p>
- *
- * <ul>
- * <li>DAOHelperGenerator</li>
- *
- * <li>DAOAbstractGenerator</li>
- *
- * <li>DAOGenerator</li>
- * </ul>
- *
- * <p><b><i>DAOHelperGenerator</i></b> permet de récupérer les DAOs
- * générés spécifiquement pour l'application sans avoir besoin de passer
- * le type de l'entité en paramètre. Cette classe contient donc une
- * methode get par type d'entity qui permet de récupérer le DAO associé.
- * Ces méthodes sont des méthodes statiques et prennent en paramètre un
- * TopiaContext.</p>
- *
- * <p><b><i>DAOAbstractGenerator</i></b> est une classe abstraite même si
- * elle peut implanter toutes les méthodes de l'interface TopiaDAO. De
- * cette façon on oblige l'existance d'une classe concrète qui en hérite
- * soit développé par le développeur soit généré par DAOGenerator.
- * DAOAbstractGenerator contient toutes les méthodes findBy, findAllBy,
- * ... associées aux attributs existants. La classe généré hérite
- * directement ou indirectement de TopiaDAODelegator.</p>
- *
- * <p><b><i>DAOGenerator</i></b> génère une classe vide qui permet au
- * programme de compiler, si le développeur à besoin de méthode find
- * supplémentaire sur son DAO, il lui suffit de d'implanter cette classe
- * dans ses sources, le processus de génération écrasera alors la classe
- * généré par la classe développée spécifiquement.</p>
- *
- * <h2>Les entités</h2>
- *
- * <p>Les entités sont de pure POJO et ne contiennent pas de référence en
- * interne sur le TopiaContext ou le DAO qui les à créée, elle peuvent
- * donc facilement migrer, être utilisé dans différents context, ... le
- * but etant qu'elle reste des classes complètement déconnecté à
- * l'exécution du framework.</p>
- *
- * <p>La seul contrainte est qu'elles implante TopiaEntity</p>
- *
- * <p>Il il y a trois générateurs pour les entités, plus un pour le
- * mapping hibernate</p>
- *
- * <ul>
- * <li>EntityInterfaceGenerator</li>
- *
- * <li>EntityAbstractGenerator</li>
- *
- * <li>EntityImplGenerator</li>
- *
- * <li>EntityHibernateMappingGenerator</li>
- * </ul>
- *
- * <p><b><i>EntityInterfaceGenerator</i></b> génère l'interface de
- * l'entité avec les méthodes d'accès aux attributs et les opérations
- * définis par l'utilisateur dans son diagrammme de classe. Elle implante
- * TopiaEntity</p>
- *
- * <p><b><i>EntityAbstractGenerator</i></b> génère une classe qui
- * implante l'interface de l'entité et étend TopiaEntityAbstract qui
- * implante les méthodes du framework, méthode d'accès aux attributs
- * topiaId, topiaVersion et topiaCreateDate.</p>
- *
- * <p><b><i>EntityImplGenerator</i></b> génère une classe vide qui permet
- * au programme de compiler si l'entité n'a pas d'opération spécifique.
- * Si elle a des opérations spécifiques le développeur doit implanter
- * cette classe dans ses sources et y mettre le code pour les opérations
- * spécifiques, le processus de génération écrasera alors la classe
- * généré par la classe développée spécifiquement.</p>
- *
- * <p><b><i>EntityHibernateMappingGenerator</i></b> génère le fichier de
- * mapping pour entité. L'interface est déclaré dans le mapping et est
- * mappé sur une table préfixé par I. Ensuite le Impl est déclaré en
- * union-subclass de cette interface. On a besoin de l'interface car les
- * méthodes l'utilise dans les signatures de méthode lorsqu'il y a un
- * lien entre deux entités.</p>
- *
- * @author poussin <poussin(a)codelutin.com>
- * @version $Id$
- */
-package org.nuiton.topia.generator;
\ No newline at end of file
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-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaEntity.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -38,9 +38,6 @@
package org.nuiton.topia.persistence;
import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.generator.EntityHibernateMappingGenerator;
-import org.nuiton.topia.generator.EntityTransformer;
-import org.nuiton.topia.generator.TopiaMetaTransformer;
import java.beans.PropertyChangeListener;
import java.beans.VetoableChangeListener;
@@ -49,9 +46,9 @@
import java.util.List;
/**
- * The TopiaEntity is the main interface for each entity generated with {@link
- * TopiaMetaTransformer}. An entity is simply a persistent bean mapped with
- * Hibernate. The manipulation on entities (create, update, delete, find) is
+ * The TopiaEntity is the main interface for each entity generated.
+ * An entity is simply a persistent bean mapped with Hibernate.
+ * The manipulation on entities (create, update, delete, find) is
* made by the DAO associated. The corresponding DAO interface is {@link
* TopiaDAO}.
* <p/>
@@ -61,8 +58,6 @@
* @author poussin <poussin(a)codelutin.com>
* @author fdesbois <fdesbois(a)codelutin.com>
* @version $Id$
- * @see EntityHibernateMappingGenerator
- * @see EntityTransformer
*/
@SearchFields
public interface TopiaEntity extends Serializable {
Deleted: trunk/topia-persistence/src/main/resources/META-INF/services/org.nuiton.eugene.ModelPropertiesUtil$ModelPropertiesProvider
===================================================================
--- trunk/topia-persistence/src/main/resources/META-INF/services/org.nuiton.eugene.ModelPropertiesUtil$ModelPropertiesProvider 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/main/resources/META-INF/services/org.nuiton.eugene.ModelPropertiesUtil$ModelPropertiesProvider 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1 +0,0 @@
-org.nuiton.topia.generator.TopiaGeneratorUtil$TopiaModelPropertiesProvider
\ No newline at end of file
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/AbstractEmployeTopiaDao.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/AbstractEmployeTopiaDao.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/AbstractEmployeTopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,33 +0,0 @@
-package org.nuiton.topia;
-
-/*
- * #%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.nuiton.topiatest.Employe;
-
-/**
- * @author Arnaud Thimel <thimel(a)codelutin.com>
- */
-public abstract class AbstractEmployeTopiaDao<E extends Employe> extends GeneratedEmployeeTopiaDao<E> {
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/AbstractPersonneTopiaDao.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/AbstractPersonneTopiaDao.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/AbstractPersonneTopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,34 +0,0 @@
-package org.nuiton.topia;
-
-/*
- * #%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.nuiton.topiatest.Personne;
-
-/**
- * @author Arnaud Thimel <thimel(a)codelutin.com>
- */
-public abstract class AbstractPersonneTopiaDao<E extends Personne> extends GeneratedPersonneTopiaDao<E> {
-
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/EmployeTopiaDao.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/EmployeTopiaDao.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/EmployeTopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,42 +0,0 @@
-package org.nuiton.topia;
-
-/*
- * #%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.util.List;
-
-import org.nuiton.topiatest.Employe;
-import org.nuiton.topiatest.Personne;
-
-/**
- * @author Arnaud Thimel <thimel(a)codelutin.com>
- */
-public class EmployeTopiaDao extends AbstractEmployeTopiaDao<Employe> {
-
- @Override
- public List<Personne> findAllPersonnesByXAndY(int x, int y) {
- return null;
- }
-
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/EmployeeDao.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/EmployeeDao.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/EmployeeDao.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,31 +0,0 @@
-package org.nuiton.topia;
-
-/*
- * #%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%
- */
-
-/**
- * @author Arnaud Thimel <thimel(a)codelutin.com>
- */
-public interface EmployeeDao {
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/GeneratedEmployeeTopiaDao.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/GeneratedEmployeeTopiaDao.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/GeneratedEmployeeTopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,33 +0,0 @@
-package org.nuiton.topia;
-
-/*
- * #%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.nuiton.topiatest.Employe;
-
-/**
- * @author Arnaud Thimel <thimel(a)codelutin.com>
- */
-public abstract class GeneratedEmployeeTopiaDao<E extends Employe> extends AbstractPersonneTopiaDao<E> {
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/GeneratedPersonneTopiaDao.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/GeneratedPersonneTopiaDao.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/GeneratedPersonneTopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,60 +0,0 @@
-package org.nuiton.topia;
-
-/*
- * #%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.util.List;
-import java.util.Map;
-
-import org.nuiton.topia.persistence.AbstractTopiaDao;
-import org.nuiton.topia.persistence.TopiaEntity;
-import org.nuiton.topia.persistence.TopiaEntityEnum;
-import org.nuiton.topiatest.Personne;
-
-/**
- * @author Arnaud Thimel <thimel(a)codelutin.com>
- */
-public abstract class GeneratedPersonneTopiaDao<E extends Personne> extends AbstractTopiaDao<E> implements PersonneDao {
-
- @Override
- public TopiaEntityEnum getTopiaEntityEnum() {
- return null;
- }
-
- @Override
- public <R extends TopiaEntity> List<R> findUsages(Class<R> type, E entity) throws TopiaException {
- return null;
- }
-
- @Override
- public Map<Class<? extends TopiaEntity>, List<? extends TopiaEntity>> findAllUsages(E entity) throws TopiaException {
- return null;
- }
-
- @Override
- public Class<E> getEntityClass() {
- return null;
- }
-
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/PersonneDao.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/PersonneDao.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/PersonneDao.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,38 +0,0 @@
-package org.nuiton.topia;
-
-/*
- * #%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.util.List;
-
-import org.nuiton.topiatest.Personne;
-
-/**
- * @author Arnaud Thimel <thimel(a)codelutin.com>
- */
-public interface PersonneDao {
-
- List<Personne> findAllPersonnesByXAndY(int x, int y);
-
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/PersonneTopiaDao.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/PersonneTopiaDao.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/PersonneTopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,41 +0,0 @@
-package org.nuiton.topia;
-
-/*
- * #%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.util.List;
-
-import org.nuiton.topiatest.Personne;
-
-/**
- * @author Arnaud Thimel <thimel(a)codelutin.com>
- */
-public class PersonneTopiaDao extends AbstractPersonneTopiaDao<Personne> {
-
- @Override
- public List<Personne> findAllPersonnesByXAndY(int x, int y) {
- return null;
- }
-
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/TestHelper.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/TestHelper.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/TestHelper.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,160 +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%
- */
-package org.nuiton.topia;
-
-import org.apache.commons.io.FileUtils;
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.hibernate.cfg.Environment;
-import org.junit.Ignore;
-import org.nuiton.util.FileUtil;
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Properties;
-
-/**
- * Helper for all topia tests.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 2.5
- */
-@Ignore
-// this is not a test :)
-public class TestHelper {
-
- private static final Log log = LogFactory.getLog(TestHelper.class);
-
- protected static File testBasedir;
-
- protected static File targetdir;
-
- protected static File dirDatabase;
-
- public static final String DEFAULT_CONFIGURATION_LOCATION = "/TopiaContextImpl.properties";
-
- public static File getTestWorkdir() {
- if (testBasedir == null) {
- String base = System.getProperty("java.io.tmpdir");
- if (base == null || base.isEmpty()) {
- base = new File("").getAbsolutePath();
- }
- testBasedir = new File(base);
- log.info("basedir for test " + testBasedir);
- }
- return testBasedir;
- }
-
- public static File getTestBasedir(Class<?> testClass) throws IOException {
- File dir = getTestWorkdir();
- File result = new File(dir, testClass.getName());
- if (result.exists()) {
-
- // when calling this method (always in a BeforeClass method), we wants
- // to clean the directory, this is a new build
- FileUtils.deleteDirectory(result);
- }
-
- // always create the directory
- FileUtil.createDirectoryIfNecessary(result);
- return result;
- }
-
- public static TopiaContext initTopiaContext(File testDirectory,
- String dbname)
- throws IOException, TopiaNotFoundException {
-
-
- TopiaContext topiaContext = initTopiaContext(
- testDirectory,
- DEFAULT_CONFIGURATION_LOCATION,
- dbname
- );
- return topiaContext;
- }
-
- public static TopiaContext initTopiaContext(File testDirectory,
- String dbPropertiesPath,
- String dbname)
- throws IOException, TopiaNotFoundException {
-
- Properties configuration = initTopiaContextConfiguration(
- testDirectory,
- dbPropertiesPath,
- dbname);
- return TopiaContextFactory.getContext(configuration);
- }
-
- public static Properties initTopiaContextConfiguration(File testDirectory,
- String dbPropertiesPath,
- String dbname)
- throws IOException {
-
- Properties configuration = loadHibernateConfiguration(dbPropertiesPath);
-
- // make sure we always use a different directory
-
- String dbPath = getDbName(testDirectory, dbname);
-
- if (log.isInfoEnabled()) {
- log.info("dbPath = " + dbPath);
- }
- configuration.setProperty(
- Environment.URL,
-// "hibernate.connection.url",
- "jdbc:h2:file:" + dbPath);
-
- return configuration;
- }
-
- public static Properties loadHibernateConfiguration(String dbPropertiesPath) throws IOException {
- InputStream stream = TestHelper.class.getResourceAsStream(dbPropertiesPath);
-
- Properties configuration = new Properties();
-
- configuration.load(stream);
- configuration.setProperty(
- TopiaContextFactory.CONFIG_PERSISTENCE_CLASSES,
- TopiaTestDAOHelper.getImplementationClassesAsString());
- return configuration;
- }
-
- public static String getDbName(File testDirectory, String dbname) {
- return new File(testDirectory,
- dbname + '_' + System.nanoTime()).getAbsolutePath();
- }
-
- public static Properties initTopiaContextConfiguration(File testDirectory,
- String dbname)
- throws IOException {
-
- return initTopiaContextConfiguration(
- testDirectory,
- DEFAULT_CONFIGURATION_LOCATION,
- dbname
- );
- }
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/TopiaContextFactoryTest.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/TopiaContextFactoryTest.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/TopiaContextFactoryTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,189 +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%
- */
-package org.nuiton.topia;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.nuiton.topia.framework.AbstractTopiaContext;
-
-import java.io.File;
-import java.io.IOException;
-import java.util.List;
-import java.util.Properties;
-
-/**
- * Created: 8 mai 2010
- *
- * @author fdesbois <fdesbois(a)codelutin.com>
- * @version $Id$
- */
-public class TopiaContextFactoryTest {
-
- private static final Log log =
- LogFactory.getLog(TopiaContextFactoryTest.class);
-
- protected static File testBasedir;
-
- protected Properties properties;
-
- @BeforeClass
- public static void init() throws IOException {
-
- testBasedir = TopiaDatabase.getTestSpecificDirectory(TopiaContextFactoryTest.class, "dummy");
-
- }
-
- @Before
- public void setUp() throws Exception {
- properties = new Properties();
- properties.setProperty("prop1", "value1");
- properties.setProperty("prop2", "value2");
- TopiaContextFactory.contextCache.clear();
- }
-
- @Test
- public void testGetContextOpened() throws Exception {
- log.debug("## testGetContextOpened");
-
- /** PREPARE DATA **/
- String databaseName = "h2data-testGetContextByPropertie";
- File dbDirectory = new File(testBasedir, databaseName);
- String url = "jdbc:h2:file:" + dbDirectory;
- properties.setProperty("hibernate.connection.url", url);
-
- AbstractTopiaContext test = new AbstractTopiaContext(properties);
- TopiaContextFactory.contextCache.put(properties, test);
-
- /** EXEC METHOD **/
- List<String> result = TopiaContextFactory.getContextOpened();
- Assert.assertEquals(1, result.size());
- Assert.assertEquals(url, result.get(0));
- }
-
- @Test
- public void testRemoveContext() throws Exception {
- log.debug("## testRemoveContext");
-
- /** PREPARE DATA **/
- AbstractTopiaContext test = new AbstractTopiaContext(properties);
- TopiaContextFactory.contextCache.put(properties, test);
-
- /** EXEC METHOD **/
- TopiaContextFactory.removeContext(test);
- Assert.assertEquals(0, TopiaContextFactory.contextCache.size());
- }
-
- //@Test
-
- public void testGetContext() throws Exception {
- // TODO-fdesbois-20100508 : only used TopiaUtil.getProperties, need tests for this method
- }
-
- @Test
- public void testGetContextByProperties() throws Exception {
- log.debug("## testGetContextByProperties");
-
- /** PREPARE DATA **/
- Properties propertiesParent = new Properties(properties);
- propertiesParent.setProperty("prop3", "value3");
-
- Properties propertiesAll = new Properties();
- propertiesAll.setProperty("prop1", "value1");
- propertiesAll.setProperty("prop2", "value2");
- propertiesAll.setProperty("prop3", "value3");
-
- /** EXEC METHOD **/
-
- log.info("test 0 : add null properties");
- try {
- TopiaContextFactory.getContext(null);
- } catch (Exception eee) {
- Assert.assertEquals(NullPointerException.class, eee.getClass());
- }
-
- log.info("test 1 : add new properties, will instantiate a new" +
- " TopiaContext");
- TopiaContext test1 = TopiaContextFactory.getContext(propertiesParent);
- Assert.assertNotNull(test1);
- Assert.assertEquals(1, TopiaContextFactory.contextCache.size());
-
- log.info("test 2 : with same properties, will retrieve existing" +
- " TopiaContext");
- TopiaContext test2 = TopiaContextFactory.getContext(propertiesParent);
- Assert.assertEquals(test1, test2);
- Assert.assertEquals(1, TopiaContextFactory.contextCache.size());
-
- log.info("test 3 : use other properties, will instantiate a different" +
- "TopiaContext");
- TopiaContext test3 = TopiaContextFactory.getContext(properties);
- log.debug("cache size : " + TopiaContextFactory.contextCache.size());
- log.debug("result : " + test1);
- log.debug("result3 : " + test3);
- Assert.assertNotSame(test1, test3);
- Assert.assertEquals(2, TopiaContextFactory.contextCache.size());
-
- log.info("test 4 : use other properties but equivalent to existing " +
- "TopiaContext");
- // Test flating of properties
- TopiaContext test4 = TopiaContextFactory.getContext(propertiesAll);
- Assert.assertEquals(test1, test4);
- Assert.assertEquals(2, TopiaContextFactory.contextCache.size());
-
- log.info("test5a : reinstantiate new TopiaContext after one is closed.");
- // TEST
- // Strange behavior the closed flag of context stay true if
- // hibernateFactory is not loaded from real properties
-// test1.closeContext();
-// Assert.assertTrue(test1.isClosed());
-
- // Add properties for Hibernate to have real opened topiaContext
- String databaseName = "h2data-testGetContextByPropertie";
- File f = new File(testBasedir, databaseName);
-
- properties.setProperty("hibernate.connection.username", "sa");
- properties.setProperty("hibernate.connection.password", "");
- properties.setProperty("hibernate.connection.driver_class", "org.h2.Driver");
- properties.setProperty("hibernate.connection.url",
- "jdbc:h2:file:" + f.getAbsolutePath());
-
-
- TopiaContext test5 = TopiaContextFactory.getContext(properties);
- Assert.assertNotSame(test1, test5);
- Assert.assertEquals(3, TopiaContextFactory.contextCache.size());
-
- log.info("test5b : beginTransaction to properly close the context");
- test5.beginTransaction();
-
- test5.closeContext();
-
- TopiaContext result = TopiaContextFactory.getContext(properties);
- Assert.assertNotSame(test5, result);
- Assert.assertEquals(3, TopiaContextFactory.contextCache.size());
- }
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/TopiaDatabase.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/TopiaDatabase.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/TopiaDatabase.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,207 +0,0 @@
-/*
- * #%L
- * ToPIA :: Persistence
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2004 - 2012 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%
- */
-package org.nuiton.topia;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.hibernate.cfg.Configuration;
-import org.junit.rules.TestWatcher;
-import org.junit.runner.Description;
-
-import java.io.File;
-import java.io.InputStream;
-import java.util.Properties;
-
-/**
- * Put this class as a Rule in test to obtain a new isolated db for each test.
- * <p/>
- * Here is a simple example of usage :
- * <pre>
- * public class MyTest {
- *
- * \@Rule
- * public final TopiaDatabase db = new TopiaDatabase();
- *
- * \@Test
- * public void testMethod() throws TopiaException {
- *
- * TopiaContext tx = db.beginTransaction();
- * ...
- * }
- * </pre>
- * The db created will be unique for each test method (and for each build also).
- * <p/>
- * You don't need to close any transaction, it will be done for you and the end
- * of each method test.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 2.6.8
- */
-public class TopiaDatabase extends TestWatcher {
-
- /** Logger. */
- private static final Log log = LogFactory.getLog(TopiaDatabase.class);
-
- /** A time-stamp, allow to make multiple build and keep the tests data. */
- public static final String TIMESTAMP = String.valueOf(System.nanoTime());
-
- private File testBasedir;
-
- private Properties dbConfiguration;
-
- private TopiaTestTopiaApplicationContext applicationContext;
-
- private Configuration hibernateCfg;
-
- private final String configurationPath;
-
- public TopiaDatabase() {
- this(TestHelper.DEFAULT_CONFIGURATION_LOCATION);
- }
-
- public TopiaDatabase(String configurationPath) {
- this.configurationPath = configurationPath;
- }
-
- @Override
- protected void starting(Description description) {
-
- // get test directory
- testBasedir = getTestSpecificDirectory(
- description.getTestClass(),
- description.getMethodName());
-
- if (log.isDebugEnabled()) {
- log.debug("testBasedir = " + testBasedir);
- }
-
- // create the root context
- try {
-
- dbConfiguration = new Properties();
- InputStream stream =
- getClass().getResourceAsStream(configurationPath);
-
- try {
- dbConfiguration.load(stream);
- } finally {
- stream.close();
- }
- dbConfiguration.setProperty(
- TopiaContextFactory.CONFIG_PERSISTENCE_CLASSES,
- TopiaTestDAOHelper.getImplementationClassesAsString());
-
- // make sure we always use a different directory
-
- String dbPath = new File(testBasedir, "db").getAbsolutePath();
-
- if (log.isDebugEnabled()) {
- log.debug("dbPath = " + dbPath);
- }
- dbConfiguration.setProperty(
- TopiaContextFactory.CONFIG_URL, "jdbc:h2:file:" + dbPath);
-
- onDbConfigurationCreate(dbConfiguration, testBasedir, dbPath);
-
-// rootCtxt = TopiaContextFactory.getContext(dbConfiguration);
- applicationContext = new TopiaTestTopiaApplicationContext(dbConfiguration) {
- @Override
- protected HibernateProvider getHibernateProvider() {
- HibernateProvider provider = super.getHibernateProvider();
- hibernateCfg = provider.getHibernateConfiguration();
- return provider;
- }
- };
- } catch (Exception e) {
- throw new IllegalStateException(
- "Could not start db at " + testBasedir, e);
- }
- }
-
- @Override
- public void finished(Description description) {
-
- if (applicationContext != null && !applicationContext.isClosed()) {
- try {
- applicationContext.closeContext();
- } catch (TopiaException e) {
- if (log.isErrorEnabled()) {
- log.error("Could not close topia root context", e);
- }
- }
- }
- applicationContext = null;
- dbConfiguration = null;
- }
-
- public File getTestBasedir() {
- return testBasedir;
- }
-
- public Properties getDbConfiguration() {
- return dbConfiguration;
- }
-
- public TopiaTestTopiaApplicationContext getApplicationContext() {
- return applicationContext;
- }
-
- public Configuration getHibernateCfg() {
- return hibernateCfg;
- }
-
- public TopiaTestTopiaPersistenceContext beginTransaction() throws TopiaException {
- return applicationContext.newPersistenceContext();
- }
-
- protected void onDbConfigurationCreate(Properties configuration,
- File testDir,
- String dbPath) {
-
- }
-
- public static File getTestSpecificDirectory(Class<?> testClassName, String methodName) {
- // Trying to look for the temporary folder to store data for the test
- String tempDirPath = System.getProperty("java.io.tmpdir");
- if (tempDirPath == null) {
- // can this really occur ?
- tempDirPath = "";
- if (log.isWarnEnabled()) {
- log.warn("'\"java.io.tmpdir\" not defined");
- }
- }
- File tempDirFile = new File(tempDirPath);
-
- // create the directory to store database data
- String dataBasePath = testClassName.getName()
- + File.separator // a directory with the test class name
- + methodName// a sub-directory with the method name
- + '_'
- + TIMESTAMP; // and a timestamp
- File databaseFile = new File(tempDirFile, dataBasePath);
- return databaseFile;
- }
-}
-
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/TopiaJpaSupportTest.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/TopiaJpaSupportTest.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/TopiaJpaSupportTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,161 +0,0 @@
-/*
- * #%L
- * ToPIA :: Persistence :: Test Compatibility Kit
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2004 - 2012 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%
- */
-package org.nuiton.topia;
-
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.nuiton.topiatest.Address;
-import org.nuiton.topiatest.AddressTopiaDao;
-import org.nuiton.topiatest.Gender;
-import org.nuiton.topiatest.Personne;
-import org.nuiton.topiatest.PersonneTopiaDao;
-
-import java.util.List;
-
-/**
- * Tests the TopiaContext#find|findAll|findUnique methods
- *
- * @author Arnaud Thimel <thimel(a)codelutin.com>
- */
-public class TopiaJpaSupportTest {
-
- @Rule
- public final TopiaDatabase db = new TopiaDatabase();
-
- protected TopiaTestTopiaPersistenceContext persistenceContext;
- protected TopiaJpaSupport jpaSupport;
- protected AddressTopiaDao addressDAO;
- protected PersonneTopiaDao personneDAO;
- protected Address address;
-
- @Before
- public void createCompanies() throws TopiaException {
- persistenceContext = db.beginTransaction();
- jpaSupport = persistenceContext.jpaSupport;
-
- personneDAO = persistenceContext.getPersonneDao();
- addressDAO = persistenceContext.getAddressDao();
-
- address = addressDAO.create(
- Address.PROPERTY_ADRESS, "17 rue de la Pote Gellée, 44200 NANTES");
-
- personneDAO.create(
- Personne.PROPERTY_NAME, "Arnaud",
- Personne.PROPERTY_GENDER, Gender.MALE);
- personneDAO.create(
- Personne.PROPERTY_NAME, "Charlotte",
- Personne.PROPERTY_GENDER, Gender.FEMALE);
- personneDAO.create(
- Personne.PROPERTY_NAME, "Hortense",
- Personne.PROPERTY_GENDER, Gender.FEMALE);
- persistenceContext.commitTransaction();
- }
-
- @Test
- public void testFindDAO() throws TopiaException {
- Assert.assertEquals(3, personneDAO.count());
-
- Assert.assertEquals(2, personneDAO.findAllByGender(Gender.FEMALE).size());
- Assert.assertNotNull(personneDAO.findByGender(Gender.FEMALE));
- Assert.assertNotNull(personneDAO.findByGender(Gender.MALE));
- Assert.assertNull(personneDAO.findByGender(null));
-
- Assert.assertEquals(0, personneDAO.findAllByName("nobody").size());
- }
-
- @Test
- public void testFindAll() throws TopiaException {
- Assert.assertEquals(3, personneDAO.count());
-
- String query = "from " + Personne.class.getName() +
- " where " + Personne.PROPERTY_GENDER + "=:g";
-
- List females = jpaSupport.findAll(query, "g", Gender.FEMALE);
- Assert.assertEquals(2, females.size());
-
- List males = jpaSupport.findAll(query, "g", Gender.MALE);
- Assert.assertEquals(1, males.size());
-
- List all = jpaSupport.findAll("from " + Personne.class.getName());
- Assert.assertEquals(3, all.size());
-
- List none = jpaSupport.findAll("from " + Personne.class.getName() +
- " where " + Personne.PROPERTY_NAME + "=:pax", "pax", "nobody");
- Assert.assertEquals(0, none.size());
- }
-
- @Test
- public void testFind() throws TopiaException {
- Assert.assertEquals(3, personneDAO.count());
-
- String query = "from " + Personne.class.getName() +
- " where " + Personne.PROPERTY_GENDER + "=:g";
-
- List females = jpaSupport.find(query, 0, 100, "g", Gender.FEMALE);
- Assert.assertEquals(2, females.size());
-
- females = jpaSupport.find(query, 0, 0, "g", Gender.FEMALE);
- Assert.assertEquals(1, females.size());
- Personne charlotte = (Personne)females.get(0);
-
- females = jpaSupport.find(query, 1, 1, "g", Gender.FEMALE);
- Assert.assertEquals(1, females.size());
- Personne hortense = (Personne)females.get(0);
-
- Assert.assertFalse(hortense.equals(charlotte));
-
- // endIndex = -1 not supported in ToPIA 2.6, wait for 3.0
-// females = context.find(query, 0, -1, "g", Gender.FEMALE);
-// Assert.assertEquals(2, females.size());
- }
-
- @Test
- public void testFindUnique() throws TopiaException {
- Assert.assertEquals(3, personneDAO.count());
-
- String query = "from " + Personne.class.getName() +
- " where " + Personne.PROPERTY_GENDER + "=:g";
-
- Object male = jpaSupport.findUnique(query, "g", Gender.MALE);
- Assert.assertNotNull(male);
-
- Object none = jpaSupport.findUnique("from " + Personne.class.getName() +
- " where " + Personne.PROPERTY_NAME + "=:pax", "pax", "nobody");
- Assert.assertNull(none);
- }
-
- @Test(expected = TopiaException.class)
- public void testFindUniqueOutOfBounds() throws TopiaException {
- Assert.assertEquals(3, personneDAO.count());
-
- String query = "from " + Personne.class.getName() +
- " where " + Personne.PROPERTY_GENDER + "=:g";
-
- Object female = jpaSupport.findUnique(query, "g", Gender.FEMALE);
- Assert.assertNotNull(female);
- }
-
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/EntityStateTest.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/EntityStateTest.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/EntityStateTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,96 +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%
- */
-
-package org.nuiton.topia.framework;
-
-import org.junit.Assert;
-import org.junit.Test;
-
-/**
- * EntityStateTest.java
- * <p/>
- * Created: 22 nov. 06 12:15:11
- *
- * @author poussin <poussin(a)codelutin.com>
- * @version $Revision$
- * <p/>
- * Last update: $Date$
- * by : $Author$
- */
-public class EntityStateTest {
-
- /**
- * Test les changements d'etat de {@link EntityState}.
- *
- * @throws Exception
- */
- @Test
- public void testState() throws Exception {
- EntityState state = new EntityState();
-
- state.addLoad();
- Assert.assertTrue(state.isLoad());
- Assert.assertFalse(state.isRead());
- Assert.assertFalse(state.isCreate());
- Assert.assertFalse(state.isUpdate());
- Assert.assertFalse(state.isDelete());
-
- state.addRead();
- Assert.assertTrue(state.isLoad());
- Assert.assertTrue(state.isRead());
- Assert.assertFalse(state.isCreate());
- Assert.assertFalse(state.isUpdate());
- Assert.assertFalse(state.isDelete());
-
- //state.addRead();
- state.addCreate();
- Assert.assertTrue(state.isLoad());
- Assert.assertTrue(state.isRead());
- Assert.assertTrue(state.isCreate());
- Assert.assertFalse(state.isUpdate());
- Assert.assertFalse(state.isDelete());
-
- state.addUpdate();
- Assert.assertTrue(state.isLoad());
- Assert.assertTrue(state.isRead());
- Assert.assertTrue(state.isCreate());
- Assert.assertTrue(state.isUpdate());
- Assert.assertFalse(state.isDelete());
-
- state.addDelete();
- Assert.assertTrue(state.isLoad());
- Assert.assertTrue(state.isRead());
- Assert.assertTrue(state.isCreate());
- Assert.assertTrue(state.isUpdate());
- Assert.assertTrue(state.isDelete());
-
- state = new EntityState();
- state.addDelete();
- Assert.assertFalse(state.isRead());
- Assert.assertFalse(state.isCreate());
- Assert.assertFalse(state.isUpdate());
- Assert.assertTrue(state.isDelete());
- }
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaConnectionProviderHardCoded.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaConnectionProviderHardCoded.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaConnectionProviderHardCoded.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,210 +0,0 @@
-/*
- * #%L
- * ToPIA :: Persistence
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2004 - 2011 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%
- */
-package org.nuiton.topia.framework;
-
-import java.sql.Connection;
-import java.sql.DriverManager;
-import java.sql.SQLException;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.Properties;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.hibernate.HibernateException;
-import org.hibernate.cfg.Environment;
-import org.hibernate.internal.util.ReflectHelper;
-import org.hibernate.internal.util.config.ConfigurationHelper;
-import org.hibernate.service.jdbc.connections.internal.ConnectionProviderInitiator;
-import org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl;
-
-/**
- * Customized connection provider.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 2.5.3
- */
-public class TopiaConnectionProviderHardCoded extends DriverManagerConnectionProviderImpl {
-
- private String url;
-
- private Properties connectionProps;
-
- private Integer isolation;
-
- private final ArrayList pool = new ArrayList();
-
- private int poolSize;
-
- private int checkedOut = 0;
-
- private boolean autocommit;
-
- /** Logger. */
- private static final Log log =
- LogFactory.getLog(TopiaConnectionProviderHardCoded.class);
-
- @Override
- public void configure(Map configurationValues) throws HibernateException {
- String driverClass = (String)configurationValues.get(Environment.DRIVER);
-
- poolSize = ConfigurationHelper.getInt(Environment.POOL_SIZE, configurationValues, 20); //default pool size 20
- log.info("Using Hibernate built-in connection pool (not for production use!)");
- log.info("Hibernate connection pool size: " + poolSize);
-
- autocommit = ConfigurationHelper.getBoolean(Environment.AUTOCOMMIT, configurationValues);
- log.info("autocommit mode: " + autocommit);
-
- isolation = ConfigurationHelper.getInteger(Environment.ISOLATION, configurationValues);
- if (isolation != null)
- log.info("JDBC isolation level: " + Environment.isolationLevelToString(isolation));
-
- if (driverClass == null) {
- log.warn("no JDBC Driver class was specified by property " + Environment.DRIVER);
- } else {
- try {
- // trying via forName() first to be as close to DriverManager's semantics
- Class.forName(driverClass);
- } catch (ClassNotFoundException cnfe) {
- try {
- ReflectHelper.classForName(driverClass);
- } catch (ClassNotFoundException e) {
- String msg = "JDBC Driver class not found: " + driverClass;
- log.error(msg, e);
- throw new HibernateException(msg, e);
- }
- }
- }
-
- // use a dummy directory to make sure only the connection provider knows
- // the real directory where db is and then make sure hibernate always
- // use the connection provider...
- String directory =
- (String)configurationValues.get(TopiaConnectionProviderTest.TEST_URL);
-
- url = directory;
-// url = props.getProperty(Environment.URL);
-
-// if (url == null) {
-// String msg = "JDBC URL was not specified by property " + Environment.URL;
-// log.error(msg);
-// throw new HibernateException(msg);
-// }
-
- connectionProps = ConnectionProviderInitiator.getConnectionProperties(configurationValues);
-
- log.info("using driver: " + driverClass + " at URL: " + url);
- // if debug level is enabled, then log the password, otherwise mask it
- if (log.isDebugEnabled()) {
- log.info("connection properties: " + connectionProps);
- } else if (log.isInfoEnabled()) {
- log.info("connection properties: " + ConfigurationHelper.maskOut(connectionProps, "password"));
- }
- }
-
- @Override
- public Connection getConnection() throws SQLException {
- if (log.isTraceEnabled())
- log.trace("total checked-out connections: " + checkedOut);
-
- synchronized (pool) {
- if (!pool.isEmpty()) {
- int last = pool.size() - 1;
- if (log.isTraceEnabled()) {
- log.trace("using pooled JDBC connection, pool size: " + last);
- }
- checkedOut++;
- Connection pooled = (Connection) pool.remove(last);
- if (isolation != null)
- pooled.setTransactionIsolation(isolation.intValue());
- if (pooled.getAutoCommit() != autocommit)
- pooled.setAutoCommit(autocommit);
- return pooled;
- }
- }
-
- log.debug("opening new JDBC connection");
- Connection conn = DriverManager.getConnection(url, connectionProps);
- if (isolation != null) conn.setTransactionIsolation(isolation);
- if (conn.getAutoCommit() != autocommit) conn.setAutoCommit(autocommit);
-
- if (log.isDebugEnabled()) {
- log.debug("created connection to: " + url + ", Isolation Level: " + conn.getTransactionIsolation());
- }
-// if ( log.isTraceEnabled() )
- checkedOut++;
-
- return conn;
- }
-
- @Override
- public void closeConnection(Connection conn) throws SQLException {
-// if ( log.isDebugEnabled() )
- checkedOut--;
-
- synchronized (pool) {
- int currentSize = pool.size();
- if (currentSize < poolSize) {
- if (log.isTraceEnabled()) {
- log.trace("returning connection to pool, pool size: " + (currentSize + 1));
- }
- pool.add(conn);
- return;
- }
- }
-
- log.debug("closing JDBC connection");
-
- conn.close();
- }
-
- @Override
- protected void finalize() throws Throwable {
- super.finalize();
- close();
- }
-
- public void close() {
-
- log.info("cleaning up connection pool: " + url);
-
- Iterator iter = pool.iterator();
- while (iter.hasNext()) {
- try {
- ((Connection) iter.next()).close();
- } catch (SQLException sqle) {
- log.warn("problem closing pooled connection", sqle);
- }
- }
- pool.clear();
-
- }
-
- @Override
- public boolean supportsAggressiveRelease() {
- return false;
- }
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaConnectionProviderTest.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaConnectionProviderTest.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaConnectionProviderTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,141 +0,0 @@
-/*
- * #%L
- * ToPIA :: Persistence
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2004 - 2011 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%
- */
-package org.nuiton.topia.framework;
-
-import org.junit.Assert;
-import org.junit.Rule;
-import org.junit.Test;
-import org.nuiton.topia.TopiaContextFactory;
-import org.nuiton.topia.TopiaDatabase;
-import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.TopiaTestDAOHelper;
-import org.nuiton.topia.TopiaTestTopiaPersistenceContext;
-import org.nuiton.topia.test.entities.Person;
-import org.nuiton.topia.test.entities.PersonDAO;
-import org.nuiton.topia.test.entities.PersonTopiaDao;
-import org.nuiton.topiatest.Personne;
-
-import java.io.File;
-import java.util.Locale;
-import java.util.Properties;
-
-import static org.junit.Assert.assertNotNull;
-
-/**
- * To test the {@link TopiaConnectionProvider} and make sure all connections
- * are done from here...
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 2.5.3
- */
-public class TopiaConnectionProviderTest {
-
-// private static final Log log =
-// LogFactory.getLog(TopiaConnectionProviderTest.class);
-
- public static final String TEST_URL = "testURL";
-
- @Rule
- public final TopiaDatabase db =
- new TopiaDatabase("/TopiaConnectionProviderHardcoded.properties") {
-
- @Override
- protected void onDbConfigurationCreate(Properties configuration,
- File testdir,
- String dbPath) {
-
- Assert.assertFalse(testdir.exists());
-
- String dbPathFake = new File(testdir, "fake" + File.separator + "db").getAbsolutePath();
-
- Assert.assertFalse(new File(dbPathFake).getParentFile().exists());
-
- configuration.setProperty("dbPath", dbPath);
- configuration.setProperty("dbPathFake", dbPathFake);
-
- // give the path where connection provider will create db
- configuration.setProperty(TEST_URL,
- "jdbc:h2:file:" + dbPath);
-
- // give a fake db path (we will make sure it is never create after hibernate usage).
- configuration.setProperty(TopiaContextFactory.CONFIG_URL,
- "jdbc:h2:file:" + dbPathFake);
- }
- };
-
- @Test
- public void testWithHardcoded() throws Exception {
-
-// Properties dbProperties = TestHelper.loadHibernateConfiguration(
-// "/TopiaConnectionProviderHardcoded.properties");
-//
-// File directory = new File(TestHelper.getDbName(testBasedir, "testWithHardcoded"));
-
- String dbPath = (String) db.getDbConfiguration().get("dbPath");
- String dbPathFake = (String) db.getDbConfiguration().get("dbPathFake");
-
-// new File(directory, "real" + File.separator + "db").getAbsolutePath();
-// Assert.assertFalse(new File(dbPath).getParentFile().exists());
-
-// String dbPathFake = new File(directory, "fake" + File.separator + "db").getAbsolutePath();
-
-// Assert.assertFalse(new File(dbPathFake).getParentFile().exists());
-
-// // give the path where connection provider will create db
-// dbProperties.setProperty(TEST_URL, "jdbc:h2:file:" + dbPath);
-//
-// // give a fake db path (we will make sure it is never create after hibernate usage).
-// dbProperties.setProperty(Environment.URL, "jdbc:h2:file:" + dbPathFake);
-//
-// root = TopiaContextFactory.getContext(dbProperties);
-
- Locale.setDefault(Locale.FRANCE);
-
- doStuffOnDb();
-
- // the db file must have been created
- Assert.assertTrue(new File(dbPath).getParentFile().exists());
-
- // make sure the fake db path was never used
- Assert.assertFalse(new File(dbPathFake).getParentFile().exists());
- }
-
- private void doStuffOnDb() throws TopiaException {
- TopiaTestTopiaPersistenceContext transaction = db.beginTransaction();
-
- try {
- PersonDAO dao = TopiaTestDAOHelper.getPersonDAO(transaction);
-
- Person personne = dao.create(Personne.PROPERTY_NAME, "Jack Bauer");
- transaction.commitTransaction();
- String idPersonne = personne.getTopiaId();
- assertNotNull(idPersonne);
-
- transaction.commitTransaction();
- } finally {
- transaction.closeContext();
- }
- }
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaContextImplTest.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaContextImplTest.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaContextImplTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,549 +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%
- */
-package org.nuiton.topia.framework;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.h2.Driver;
-import org.hibernate.cfg.Configuration;
-import org.hibernate.mapping.PersistentClass;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.nuiton.topia.TopiaContextFactory;
-import org.nuiton.topia.TopiaDatabase;
-import org.nuiton.topia.TopiaNotFoundException;
-import org.nuiton.topiatest.persistence.Entity1;
-import org.nuiton.topiatest.persistence.Entity1Impl;
-import org.nuiton.topiatest.service.FakeService;
-import org.nuiton.topiatest.service.TestService;
-
-import java.io.File;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Properties;
-
-/**
- * Created: 10 mai 2010
- *
- * @author fdesbois <fdesbois(a)codelutin.com>
- * @version $Id$
- */
-public class TopiaContextImplTest {
-
- private static final Log log =
- LogFactory.getLog(TopiaContextImplTest.class);
-
- protected Properties properties = new Properties();
-
- static File testBasedir;
-
- @BeforeClass
- public static void setUpClass() throws Exception {
-
- testBasedir = TopiaDatabase.getTestSpecificDirectory(TopiaContextImplTest.class, "dummy");
- }
-
- @Before
- public void setUp() throws Exception {
- properties.clear();
- }
-
- @After
- public void tearDown() throws Exception {
- }
-
- @Test
- public void testLoadServices() throws Exception {
- if (log.isDebugEnabled()) {
- log.debug("## testLoadServices");
- }
-
- /** PREPARE DATA **/
- properties.setProperty("topia.service.test",
- TestService.class.getName());
-
- AbstractTopiaContext context = new AbstractTopiaContext();
-
- /** EXEC METHOD **/
- if (log.isInfoEnabled()) {
- log.info("test 1 : load a simple TestService from properties");
- }
- Map<String, TopiaService> results = context.loadServices(properties);
- Assert.assertEquals(1, results.size());
- Assert.assertTrue(results.containsKey("test"));
- TopiaService service = results.get("test");
- Assert.assertEquals(TestService.class, service.getClass());
-
- if (log.isInfoEnabled()) {
- log.info("test 2 : load with wrong key : will display a WARN");
- }
- properties.clear();
-
- properties.setProperty("topia.service.fake",
- TestService.class.getName());
-
- results = context.loadServices(properties);
- Assert.assertEquals(0, results.size());
- Assert.assertFalse(results.containsKey("fake"));
-
- if (log.isInfoEnabled()) {
- log.info("test 3 : load with fake service name : will display an ERROR");
- }
- properties.clear();
-
- properties.setProperty("topia.service.test", "FAKE");
-
- results = context.loadServices(properties);
- Assert.assertEquals(0, results.size());
- Assert.assertFalse(results.containsKey("test"));
- }
-
- @Test
- public void testGetServices() throws Exception {
- if (log.isDebugEnabled()) {
- log.debug("## testGetServices");
- }
-
- /** PREPARE DATA **/
- properties.setProperty("topia.service.test",
- TestService.class.getName());
-
- // Calling the constructor with properties will load the services
- AbstractTopiaContext context = new AbstractTopiaContext(properties);
-
- // Instantiate a child context and set its parent
- AbstractTopiaContext child = new AbstractTopiaContext(context);
-
- /** EXEC METHOD **/
- if (log.isInfoEnabled()) {
- log.info("test 1 : with child context");
- }
- Map<String, TopiaService> test1 = child.getServices();
- Assert.assertEquals(1, test1.size());
- Assert.assertTrue(test1.containsKey("test"));
-
- if (log.isInfoEnabled()) {
- log.info("test 2 : test serviceEnabled method");
- }
- boolean test2 = child.serviceEnabled("test");
- Assert.assertTrue(test2);
-
- if (log.isInfoEnabled()) {
- log.info("test 3 : test getService method");
- }
- TopiaService test3 = child.getService("test");
- Assert.assertEquals(TestService.class, test3.getClass());
-
- if (log.isInfoEnabled()) {
- log.info("test 4 : test serviceEnabled from class TestService");
- }
- boolean test4 = child.serviceEnabled(TestService.class);
- Assert.assertTrue(test4);
-
- if (log.isInfoEnabled()) {
- log.info("test 5 : test getService from class TestService");
- }
- TestService test5 = child.getService(TestService.class);
- Assert.assertNotNull(test5);
-
- if (log.isInfoEnabled()) {
- log.info("test 6 : test serviceEnabled error with class FakeService");
- }
- // FakeService doesn't contains property SERVICE_NAME used by
- // serviceEnabled method
- // Even it's properly loaded the serviceEnabled method will return false
- properties.clear();
- properties.setProperty("topia.service.fake",
- FakeService.class.getName());
- AbstractTopiaContext otherContext = new AbstractTopiaContext(properties);
-
- boolean test6 = otherContext.serviceEnabled(FakeService.class);
- Assert.assertFalse(test6);
-
- if (log.isInfoEnabled()) {
- log.info("test 7 : test getService with error TopiaNotFoundException" +
- " : service not loaded");
- }
- // TestService is not loaded in otherContext
- try {
- TestService test7 = otherContext.getService(TestService.class);
- Assert.fail();
- } catch (TopiaNotFoundException eee) {
- //log.error(eee.getClass().getSimpleName() + " : " + eee.getMessage());
- //Assert.assertEquals(TopiaNotFoundException.class, eee.getClass());
- } catch (Exception e) {
- Assert.fail();
- }
- }
-
- @Test
- public void testContextHierarchy() throws Exception {
- if (log.isDebugEnabled()) {
- log.debug("## testContextHierarchy");
- }
-
- /** PREPARE DATA **/
- AbstractTopiaContext context = new AbstractTopiaContext(properties);
-
- /** EXEC METHODS **/
- if (log.isInfoEnabled()) {
- log.info("test 1 : constructor with parent context");
- }
- AbstractTopiaContext test1 = new AbstractTopiaContext(context);
- Assert.assertEquals(context, test1.parentContext);
-
- if (log.isInfoEnabled()) {
- log.info("test 2 : addChildContext");
- }
- AbstractTopiaContext test2 = new AbstractTopiaContext(properties);
- AbstractTopiaContext child2 = new AbstractTopiaContext();
- test2.addChildContext(child2);
- Assert.assertEquals(1, test2.childContext.size());
-
- if (log.isInfoEnabled()) {
- log.info("test 3 : removeChildContext");
- }
- AbstractTopiaContext test3 = new AbstractTopiaContext(properties);
- AbstractTopiaContext child3 = new AbstractTopiaContext(test3);
- test3.childContext.add(child3);
- test3.removeChildContext(child3);
- Assert.assertEquals(0, test3.childContext.size());
-
- // No remove if context is closed
- test3.childContext.add(child3);
- test3.closed = true;
- test3.removeChildContext(child3);
- Assert.assertEquals(1, test3.childContext.size());
-
- if (log.isInfoEnabled()) {
- log.info("test 4 : getRootContext");
- }
- TopiaContextImplementor test4 = child3.getRootContext();
- Assert.assertEquals(test3, test4);
-
- // Note : existing test is already done for concurrency problem on
- // getChildContext(). Go to : http://www.nuiton.org/repositories/browse/sandbox/testTopiaPostgresError/tr…
- }
-//
-// @Test
-// public void testCreateSchema() throws Exception {
-// }
-//
-// @Test
-// public void testShowCreateSchema() throws Exception {
-// }
-//
-// @Test
-// public void testUpdateSchema() throws Exception {
-// }
-//
-// @Test
-// public void testGetHibernate() throws Exception {
-// }
-//
-
- @Test
- public void testGetHibernateFactory() throws Exception {
- if (log.isDebugEnabled()) {
- log.debug("## testGetHibernateFactory");
- }
-
- /** PREPARE DATA **/
- AbstractTopiaContext context = new AbstractTopiaContext();
- context.services = new HashMap<String, TopiaService>();
-
- String basedir = System.getenv("basedir");
- if (basedir == null) {
-
- // says basedir is where we start tests.
- basedir = new File("").getAbsolutePath();
- }
-
- if (log.isDebugEnabled()) {
- log.debug("baseDir : " + basedir);
- }
- File persistenceDir = new File(basedir,
- "target" + File.separator +
- "test-classes" + File.separator +
- "org" + File.separator +
- "nuiton" + File.separator +
- "topiatest" + File.separator +
- "persistence");
- if (log.isDebugEnabled()) {
- log.debug("persistenceDir : " + persistenceDir);
- }
- File resourcesDir = new File(basedir,
- "target" + File.separator +
- "test-classes");
-
- /** EXEC METHOD **/
- if (log.isInfoEnabled()) {
- log.info("test 1 : load mappings from directory");
- }
-
- properties.setProperty(TopiaContextFactory.CONFIG_PERSISTENCE_DIRECTORIES,
- persistenceDir.getAbsolutePath());
- context.config = properties;
-
- Configuration test1 = context.getHibernateConfiguration();
- PersistentClass persistentClass =
- test1.getClassMapping(Entity1Impl.class.getName());
- Assert.assertNotNull(persistentClass);
- Assert.assertEquals(Entity1.class, persistentClass.getProxyInterface());
-
-// for (Iterator<RootClass> it = test1.getClassMappings(); it.hasNext();) {
-// RootClass o = it.next();
-// log.debug("entity : " + o.getEntityName());
-// }
-
- if (log.isInfoEnabled()) {
- log.info("test 2 : load mappings for all entities");
- }
- //reset from previous test
- context = new AbstractTopiaContext();
- context.services = new HashMap<String, TopiaService>();
- properties.clear();
-
- // use property TOPIA_PERSISTENCE_CLASSES
- properties.setProperty(TopiaContextFactory.CONFIG_PERSISTENCE_CLASSES,
- Entity1Impl.class.getName());
- context.config = properties;
-
- Configuration test2 = context.getHibernateConfiguration();
- persistentClass = test2.getClassMapping(Entity1Impl.class.getName());
- Assert.assertNotNull(persistentClass);
- Assert.assertEquals(Entity1.class, persistentClass.getProxyInterface());
-
- if (log.isInfoEnabled()) {
- log.info("test 3 : add properties from file");
- }
- //reset from previous test
- context = new AbstractTopiaContext();
- context.services = new HashMap<String, TopiaService>();
- properties.clear();
-
- // use property TOPIA_PERSISTENCE_PROPERTIES_FILE to add default
- // properties from file
- properties.setProperty(TopiaContextFactory.CONFIG_PERSISTENCE_PROPERTIES_FILE,
- resourcesDir + File.separator + "TopiaContextImpl.properties");
- context.config = properties;
-
- Configuration test3 = context.getHibernateConfiguration();
- Assert.assertEquals(
- test3.getProperty("hibernate.connection.driver_class"),
- Driver.class.getName());
-
- // Note : maybe add a test to load classes from services
- }
-
-// @Test
-// public void replicateEntity() throws Exception {
-//
-// Properties configSource = TestHelper.initTopiaContextConfiguration(
-// testBasedir,
-// "/TopiaContextImpl.properties",
-// "replicateSource");
-//
-// Properties configTarget = TestHelper.initTopiaContextConfiguration(
-// testBasedir,
-// "/TopiaContextImpl.properties",
-// "replicateTarget");
-//
-//
-// TopiaContext contextSource = null;
-// TopiaContext contextTarget = null;
-//
-// try {
-// contextSource = TopiaContextFactory.getContext(configSource);
-// contextTarget = TopiaContextFactory.getContext(configTarget);
-//
-// TopiaContext txSource;
-// TopiaContext txTarget;
-// PersonDAO daoSource, daoTarget;
-// PetDAO petDAOSource, petDAOTarget;
-// Person personSource, personTarget;
-// Pet petSource, petTarget;
-//
-// txSource = contextSource.beginTransaction();
-// daoSource = TopiaTestDAOHelper.getPersonDAO(txSource);
-// petDAOSource = TopiaTestDAOHelper.getPetDAO(txSource);
-//
-// personSource = daoSource.create(Person.PROPERTY_FIRSTNAME, " firstName",
-// Person.PROPERTY_NAME, " name"
-// );
-//
-// petSource = petDAOSource.create(Pet.PROPERTY_NAME, "name",
-// Pet.PROPERTY_TYPE, "type",
-// Pet.PROPERTY_PERSON, personSource
-// );
-//
-// personSource.addPet(petSource);
-//
-// txSource.commitTransaction();
-//
-// daoSource = TopiaTestDAOHelper.getPersonDAO(txSource);
-//
-// personSource = daoSource.findByTopiaId(personSource.getTopiaId());
-// Assert.assertNotNull(personSource);
-//
-// petSource = petDAOSource.findByTopiaId(petSource.getTopiaId());
-// Assert.assertNotNull(petSource);
-// Assert.assertEquals(1, personSource.sizePet());
-// Assert.assertEquals(petSource, personSource.getPet().iterator().next());
-//
-// txTarget = contextTarget.beginTransaction();
-//
-// txSource.replicateEntity(txTarget, petSource);
-// txSource.replicateEntity(txTarget, personSource);
-//
-// txTarget.commitTransaction();
-//
-// daoTarget = TopiaTestDAOHelper.getPersonDAO(txTarget);
-// petDAOTarget = TopiaTestDAOHelper.getPetDAO(txTarget);
-//
-// personTarget = daoTarget.findByTopiaId(personSource.getTopiaId());
-// Assert.assertNotNull(personTarget);
-// Assert.assertEquals(personSource, personTarget);
-// Assert.assertEquals(1, personTarget.sizePet());
-//
-// petTarget = petDAOTarget.findByTopiaId(petSource.getTopiaId());
-// Assert.assertNotNull(petTarget);
-// Assert.assertEquals(petSource, petTarget);
-//
-// Assert.assertEquals(petTarget, personTarget.getPet().iterator().next());
-//
-//
-// } finally {
-// closeDb(contextSource);
-// closeDb(contextTarget);
-// }
-//
-// }
-//
-// protected static void closeDb(TopiaContext contextSource) {
-// if (contextSource != null && !contextSource.isClosed())
-// try {
-// contextSource.clear(false);
-// } catch (TopiaException e) {
-// if (log.isErrorEnabled()) {
-// log.error("Could not close db " + contextSource, e);
-// }
-// }
-// }
-
-
-//
-// @Test
-// public void testGetHibernateConfiguration() throws Exception {
-// }
-//
-// @Test
-// public void testGetDAO() throws Exception {
-// }
-//
-// @Test
-// public void testBeginTransaction() throws Exception {
-// }
-//
-// @Test
-// public void testCommitTransaction() throws Exception {
-// }
-//
-// @Test
-// public void testRollbackTransaction() throws Exception {
-// }
-//
-// @Test
-// public void testCloseContext() throws Exception {
-// }
-//
-// @Test
-// public void testIsClosed() throws Exception {
-// }
-//
-// @Test
-// public void testFindByTopiaId() throws Exception {
-// }
-//
-// @Test
-// public void testFind() throws Exception {
-// }
-//
-// @Test
-// public void testFind2() throws Exception {
-// }
-//
-// @Test
-// public void testExecute() throws Exception {
-// }
-//
-// @Test
-// public void testAdd() throws Exception {
-// }
-//
-// @Test
-// public void testImportXML() throws Exception {
-// }
-//
-// @Test
-// public void testExportXML() throws Exception {
-// }
-//
-//
-// @Test
-// public void testReplicateEntity() throws Exception {
-// }
-//
-// @Test
-// public void testReplicateEntities() throws Exception {
-// }
-//
-// @Test
-// public void testGetFiresSupport() throws Exception {
-// }
-//
-// @Test
-// public void testBackup() throws Exception {
-// }
-//
-// @Test
-// public void testRestore() throws Exception {
-// }
-//
-// @Test
-// public void testClear() throws Exception {
-// }
-//
-// @Test
-// public void testGetPersistenceClasses() throws Exception {
-// }
-//
-// @Test
-// public void testIsSchemaExist() throws Exception {
-// }
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaContextReplicateTest.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaContextReplicateTest.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaContextReplicateTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,155 +0,0 @@
-/*
- * #%L
- * ToPIA :: Persistence
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2004 - 2012 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%
- */
-package org.nuiton.topia.framework;
-
-import org.junit.Assert;
-import org.junit.Rule;
-import org.junit.Test;
-import org.nuiton.topia.TopiaContextFactory;
-import org.nuiton.topia.TopiaDatabase;
-import org.nuiton.topia.TopiaTestDAOHelper;
-import org.nuiton.topia.TopiaTestTopiaPersistenceContext;
-import org.nuiton.topia.test.entities.Person;
-import org.nuiton.topia.test.entities.PersonDAO;
-import org.nuiton.topia.test.entities.Pet;
-import org.nuiton.topia.test.entities.PetDAO;
-
-import java.io.File;
-import java.util.Properties;
-
-/**
- * To test replication sugin TopiaContext.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 2.6.8
- */
-public class TopiaContextReplicateTest {
-
- @Rule
- public final TopiaDatabase dbSource =
- new TopiaDatabase() {
-
- @Override
- protected void onDbConfigurationCreate(Properties configuration, File testDir, String dbPath) {
- configuration.setProperty(
- TopiaContextFactory.CONFIG_URL, "jdbc:h2:file:" + dbPath + "-source");
-
- }
- };
-
- @Rule
- public final TopiaDatabase dbTarget =
- new TopiaDatabase() {
-
- @Override
- protected void onDbConfigurationCreate(Properties configuration, File testDir, String dbPath) {
- configuration.setProperty(
- TopiaContextFactory.CONFIG_URL, "jdbc:h2:file:" + dbPath + "-target");
-
- }
- };
-
- @Test
- public void replicateEntity() throws Exception {
-//
-// Properties configSource = TestHelper.initTopiaContextConfiguration(
-// testBasedir,
-// "/TopiaContextImpl.properties",
-// "replicateSource");
-//
-// Properties configTarget = TestHelper.initTopiaContextConfiguration(
-// testBasedir,
-// "/TopiaContextImpl.properties",
-// "replicateTarget");
-//
-
-
-// try {
-// contextSource = TopiaContextFactory.getContext(configSource);
-// contextTarget = TopiaContextFactory.getContext(configTarget);
-
- TopiaTestTopiaPersistenceContext txSource;
- TopiaTestTopiaPersistenceContext txTarget;
- PersonDAO daoSource, daoTarget;
- PetDAO petDAOSource, petDAOTarget;
- Person personSource, personTarget;
- Pet petSource, petTarget;
-
- txSource = dbSource.beginTransaction();
- daoSource = TopiaTestDAOHelper.getPersonDAO(txSource);
- petDAOSource = TopiaTestDAOHelper.getPetDAO(txSource);
-
- personSource = daoSource.create(Person.PROPERTY_FIRSTNAME, " firstName",
- Person.PROPERTY_NAME, " name"
- );
-
- petSource = petDAOSource.create(Pet.PROPERTY_NAME, "name",
- Pet.PROPERTY_TYPE, "type",
- Pet.PROPERTY_PERSON, personSource
- );
-
- personSource.addPet(petSource);
-
- txSource.commitTransaction();
-
- daoSource = TopiaTestDAOHelper.getPersonDAO(txSource);
-
- personSource = daoSource.findByTopiaId(personSource.getTopiaId());
- Assert.assertNotNull(personSource);
-
- petSource = petDAOSource.findByTopiaId(petSource.getTopiaId());
- Assert.assertNotNull(petSource);
- Assert.assertEquals(1, personSource.sizePet());
- Assert.assertEquals(petSource, personSource.getPet().iterator().next());
-
- txTarget = dbTarget.beginTransaction();
-
- txSource.replicateEntity(txTarget, petSource);
- txSource.replicateEntity(txTarget, personSource);
-
- txTarget.commitTransaction();
-
- daoTarget = TopiaTestDAOHelper.getPersonDAO(txTarget);
- petDAOTarget = TopiaTestDAOHelper.getPetDAO(txTarget);
-
- personTarget = daoTarget.findByTopiaId(personSource.getTopiaId());
- Assert.assertNotNull(personTarget);
- Assert.assertEquals(personSource, personTarget);
- Assert.assertEquals(1, personTarget.sizePet());
-
- petTarget = petDAOTarget.findByTopiaId(petSource.getTopiaId());
- Assert.assertNotNull(petTarget);
- Assert.assertEquals(petSource, petTarget);
-
- Assert.assertEquals(petTarget, personTarget.getPet().iterator().next());
-
-
-// } finally {
-// closeDb(contextSource);
-// closeDb(contextTarget);
-// }
-
- }
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaUtilTest.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaUtilTest.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaUtilTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,113 +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%
- */
-
-package org.nuiton.topia.framework;
-
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import org.hibernate.cfg.Configuration;
-import org.junit.Rule;
-import org.junit.Test;
-import org.nuiton.topia.TopiaDatabase;
-import org.nuiton.topia.test.entities.PersonImpl;
-import org.nuiton.topiatest.Personne;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-/**
- * Test pour les methodes de {@link TopiaUtil}.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @version $Revision$
- * <p/>
- * Last update: $Date$
- * by : $Author$
- */
-public class TopiaUtilTest {
-
- protected static final String PERSON_ID = "org.nuiton.topiatest.Personne#1226701039001#0.6502325993664224";
-
- protected static final String PERSON_ID2 = "org.nuiton.topiatest.Personne#1226701039001#0.6502325993664999";
-
- @Rule
- public final TopiaDatabase db = new TopiaDatabase();
-
- @Test
- public void testGetTopiaIdPattern() throws Exception {
- String expected;
- String actual;
-
- expected = "org\\.nuiton\\.topiatest\\.Personne#(?:\\d+?)#(?:\\d+)\\.(?:\\d+)";
- actual = TopiaUtil.getTopiaIdPattern(Personne.class);
- assertEquals(expected, actual);
- }
-
- @Test
- public void testGetTopiaPattern() throws Exception {
- String expected;
- Pattern pattern;
-
- expected = "(\\d+)-(org\\.nuiton\\.topiatest\\.Personne#(?:\\d+?)#(?:\\d+)\\.(?:\\d+))-(org\\.nuiton\\.topiatest\\.Personne#(?:\\d+?)#(?:\\d+)\\.(?:\\d+))(.*)";
- pattern = TopiaUtil.getTopiaPattern("(\\d+)-%1$s-%1$s(.*)", Personne.class);
- assertEquals(expected, pattern.toString());
-
- String expression = 123 + "-" + PERSON_ID + "-" + PERSON_ID2 + "-afterall";
-
- Matcher matcher = pattern.matcher(expression);
-
- assertTrue(matcher.matches());
-
- assertTrue(matcher.matches());
- assertEquals(4, matcher.groupCount());
- assertEquals("123", matcher.group(1));
- assertEquals(PERSON_ID, matcher.group(2));
- assertEquals(PERSON_ID2, matcher.group(3));
- assertEquals("-afterall", matcher.group(4));
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testIsSchemaExistFailed() throws Exception {
- TopiaUtil.isSchemaExist(db.getHibernateCfg(), "fake");
- }
-
- @Test
- public void testIsSchemaExist() throws Exception {
-
- String personClassName = PersonImpl.class.getName();
- Configuration hibernateCfg = db.getHibernateCfg();
-
- // First, test before DB is created, the table should not exist
- assertFalse(TopiaUtil.isSchemaExist(hibernateCfg, personClassName));
-
- // Create schema
- db.getApplicationContext().createSchema();
-
- // Now table should exist
- assertTrue(TopiaUtil.isSchemaExist(hibernateCfg, personClassName));
- }
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/TopiaGeneratorUtilTest.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/TopiaGeneratorUtilTest.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/TopiaGeneratorUtilTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,64 +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%
- */
-
-package org.nuiton.topia.generator;
-
-import org.junit.Test;
-
-import static org.junit.Assert.assertEquals;
-
-/** @author tchemit <chemit(a)codelutin.com> */
-public class TopiaGeneratorUtilTest {
-
- @Deprecated
- @Test
- public void testConvertVariableNameToConstantName() {
-
- String variableName = "abc";
- String expResult = "ABC";
- String result = TopiaGeneratorUtil.convertVariableNameToConstantName(variableName);
- assertEquals(expResult, result);
-
- variableName = "ABC";
- expResult = "ABC";
- result = TopiaGeneratorUtil.convertVariableNameToConstantName(variableName);
- assertEquals(expResult, result);
-
- variableName = "abC";
- expResult = "AB_C";
- result = TopiaGeneratorUtil.convertVariableNameToConstantName(variableName);
- assertEquals(expResult, result);
-
- variableName = "AbC";
- expResult = "AB_C";
- result = TopiaGeneratorUtil.convertVariableNameToConstantName(variableName);
- assertEquals(expResult, result);
-
- variableName = "AbC";
- expResult = "AB_C";
- result = TopiaGeneratorUtil.convertVariableNameToConstantName(variableName);
- assertEquals(expResult, result);
- }
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/TopiaModelPropertiesProviderTest.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/TopiaModelPropertiesProviderTest.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/TopiaModelPropertiesProviderTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,80 +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%
- */
-package org.nuiton.topia.generator;
-
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.nuiton.eugene.ModelPropertiesUtil;
-import org.nuiton.eugene.models.object.ObjectModelClassifier;
-import org.nuiton.eugene.models.object.ObjectModelOperation;
-
-/**
- * To test {@link TopiaGeneratorUtil.TopiaModelPropertiesProvider}.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 2.3
- */
-public class TopiaModelPropertiesProviderTest {
-
- protected ModelPropertiesUtil.ModelPropertiesProvider provider;
-
- @Before
- public void setUp() throws Exception {
- provider = new TopiaGeneratorUtil.TopiaModelPropertiesProvider();
- provider.init();
- }
-
- @Test
- public void testGetTagValueTarget() throws Exception {
- testTagValue(TopiaTagValues.TAG_PERSISTENCE_TYPE, ObjectModelClassifier.class);
- //TODO Finish with other tag values...
- }
-
- @Test
- public void testGetStereotypeTarget() throws Exception {
-
- testStereotype(TopiaStereoTypes.STEREOTYPE_DAO, ObjectModelClassifier.class, ObjectModelOperation.class);
- //TODO Finish with other stereotypes...
- }
-
- @Test
- public void testGetStore() throws Exception {
- }
-
- protected void testStereotype(String name, Class<?>... expected) {
- Class<?>[] classes = provider.getStereotypeTarget(name);
- Assert.assertNotNull("Could not find target for " + name, classes);
- Assert.assertEquals("Should have " + expected.length + " targets for " + name + " but had " + classes.length, classes.length, expected.length);
- Assert.assertArrayEquals(expected, classes);
- }
-
- protected void testTagValue(String name, Class<?>... expected) {
- Class<?>[] classes = provider.getTagValueTarget(name);
- Assert.assertNotNull("Could not find target for " + name, classes);
- Assert.assertEquals("Should have " + expected.length + " targets for " + name + " but had " + classes.length, classes.length, expected.length);
- Assert.assertArrayEquals(expected, classes);
- }
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/TopiaTestCase.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/TopiaTestCase.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/TopiaTestCase.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,170 +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%
- */
-
-package org.nuiton.topia.generator;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.junit.Assert;
-import org.junit.Rule;
-import org.junit.Test;
-import org.nuiton.topia.TopiaDatabase;
-import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.TopiaTestDAOHelper;
-import org.nuiton.topia.TopiaTestTopiaPersistenceContext;
-import org.nuiton.topiatest.Company;
-import org.nuiton.topiatest.CompanyDAO;
-import org.nuiton.topiatest.Department;
-import org.nuiton.topiatest.DepartmentDAO;
-
-/**
- * TopiaTestCase.
- *
- * @author chatellier
- * @version $Revision$
- * <p/>
- * Last update : $Date$
- * By : $Author$
- */
-public class TopiaTestCase {
-
- /** Logger */
- private final static Log log = LogFactory.getLog(TopiaTestCase.class);
-
- @Rule
- public final TopiaDatabase db = new TopiaDatabase();
-
-// /** Proprietes */
-// protected static Properties config;
-//
-// /** TopiaContext */
-// protected static TopiaContext context;
-
-// /**
-// * Init les proprietes de connection a la base
-// *
-// * @throws IOException for any IO error while getting configuration.
-// */
-// @BeforeClass
-// public static void init() throws IOException {
-//
-// File testBasedir = TestHelper.getTestBasedir(TopiaTestCase.class);
-//
-// config = TestHelper.initTopiaContextConfiguration(
-// testBasedir,
-// "/TopiaContextImpl.properties",
-// "TopiaTestCaseDb");
-//// config = new Properties();
-//// config.setProperty("topia.persistence.classes", TopiaTestDAOHelper.getImplementationClassesAsString());
-////
-//// config.setProperty(Environment.USER, "sa");
-//// config.setProperty(Environment.PASS, "");
-//// config.setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread");
-//// config.setProperty(Environment.DIALECT, "org.hibernate.dialect.H2Dialect");
-//// config.setProperty(Environment.DRIVER, "org.h2.Driver");
-//// config.setProperty(Environment.URL, "jdbc:h2:file:" + testBasedir + "/db/data_" + System.currentTimeMillis());
-// }
-//
-// @AfterClass
-// public static void after() throws TopiaException {
-// // destroy database
-// context.clear(false);
-// }
-
-// /** Create base with schema created. */
-// @Before
-// public void setUp() {
-//
-// if (log.isDebugEnabled()) {
-// log.debug("Junit beforeTest");
-// }
-//
-// try {
-// context = TopiaContextFactory.getContext(config);
-//
-// try {
-// context.createSchema();
-// } catch (TopiaException e) {
-// log.error("Erreur à la creation du schema", e);
-// }
-// } catch (TopiaNotFoundException e) {
-// log.error("Erreur à la creation du topia context", e);
-// }
-// }
-
- @Test
- public void testCompositeAssociations() throws TopiaException {
- if (log.isDebugEnabled()) {
- log.debug("Junit Test testCompositeAssociations");
- }
-
-// try {
- TopiaTestTopiaPersistenceContext newContext = db.beginTransaction();
-
- CompanyDAO companyDAO = newContext.getCompanyDao();
- DepartmentDAO departmentDAO = newContext.getDepartmentDao();
-
- Company company = companyDAO.create();
- company.setName("Ma société");
-
-
- Department dep1 = departmentDAO.create();
- dep1.setName("Departement 1");
- Department dep2 = departmentDAO.create();
- dep2.setName("Departement 2");
- Department dep3 = departmentDAO.create();
- dep3.setName("Departement 3");
- Department dep4 = departmentDAO.create();
- dep4.setName("Departement 7");
-
- departmentDAO.update(dep1);
- departmentDAO.update(dep2);
- departmentDAO.update(dep3);
- departmentDAO.update(dep4);
-
- company.addDepartment(dep1);
- company.addDepartment(dep2);
- company.addDepartment(dep3);
- company.addDepartment(dep4);
-
- companyDAO.update(company);
- newContext.commitTransaction();
-
- newContext = db.beginTransaction();
-
- companyDAO = TopiaTestDAOHelper.getCompanyDAO(newContext);
-
- company = companyDAO.findByTopiaId(company.getTopiaId());
-
- Assert.assertEquals(company.getName(), "Ma société");
- Assert.assertEquals(company.getDepartment().size(), 4);
-
- newContext.commitTransaction();
-// newContext.closeContext();
-// } catch (TopiaException e) {
-// log.error("Erreur pendant le test testCompositeAssociations", e);
-// }
- }
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/EntityVisitorExportXmlTest.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/EntityVisitorExportXmlTest.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/EntityVisitorExportXmlTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,131 +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%
- */
-
-package org.nuiton.topia.persistence;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.nuiton.topia.TopiaDatabase;
-import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.TopiaTestTopiaPersistenceContext;
-import org.nuiton.topiatest.Address;
-import org.nuiton.topiatest.AddressTopiaDao;
-import org.nuiton.topiatest.Company;
-import org.nuiton.topiatest.CompanyTopiaDao;
-import org.nuiton.topiatest.Department;
-import org.nuiton.topiatest.DepartmentTopiaDao;
-import org.nuiton.topiatest.Employe;
-import org.nuiton.topiatest.EmployeTopiaDao;
-
-/**
- * Test de visitor.
- *
- * @author chatellier
- * @version $Revision$
- * <p/>
- * Last update : $Date$
- * By : $Author$
- */
-public class EntityVisitorExportXmlTest {
-
- private static final Log log =
- LogFactory.getLog(EntityVisitorExportXmlTest.class);
-
- @Rule
- public final TopiaDatabase db = new TopiaDatabase();
-
- /**
- * Prepare test.
- * <p/>
- * Add all tests commons data
- *
- * @throws TopiaException if could not create datas
- */
- @Before
- public void setUp() throws TopiaException {
-
- TopiaTestTopiaPersistenceContext newContext = db.beginTransaction();
- try {
- // company
- CompanyTopiaDao companyDAO = newContext.getCompanyDao();
- Company clCompany = companyDAO.create(Company.PROPERTY_NAME, "CodeLutin");
-
- // employe
- EmployeTopiaDao employeDAO = newContext.getEmployeDao();
- Employe empl1 = employeDAO.create(Employe.PROPERTY_NAME, "boss", Employe.PROPERTY_SALARY, 30000);
-
- AddressTopiaDao adressDAO = newContext.getAddressDao();
- Address addr1 = adressDAO.create(Address.PROPERTY_CITY, "Nantes", Address.PROPERTY_ADRESS, "12 Avenue Jules Vernes");
- empl1.setAddress(addr1);
-
- Employe empl2 = employeDAO.create(Employe.PROPERTY_NAME, "boss2", Employe.PROPERTY_SALARY, 29000);
- Address addr2 = adressDAO.create(Address.PROPERTY_CITY, "Nantes", Address.PROPERTY_ADRESS, "12 Avenue Jules Vernes");
- empl2.setAddress(addr2);
-
- // departement
- DepartmentTopiaDao departmentDAO = newContext.getDepartmentDao();
- Department depComm = departmentDAO.create(Department.PROPERTY_NAME, "Commercial");
- depComm.setLeader(empl1);
-
- Department depDev = departmentDAO.create(Department.PROPERTY_NAME, "Dev");
- depDev.setLeader(empl2);
- clCompany.addDepartment(depComm);
- clCompany.addDepartment(depDev);
-
- newContext.commitTransaction();
- } finally {
-
- newContext.closeContext();
- }
- }
-
-
- /**
- * Test l'export XML via un visiteur.
- * <p/>
- * Parcourt en profondeur.
- *
- * @throws TopiaException
- */
- @Test
- public void testExportXMLDepth() throws TopiaException {
-
- TopiaTestTopiaPersistenceContext context = db.beginTransaction();
-
- CompanyTopiaDao companyDAO = context.getCompanyDao();
- Company clCompany = companyDAO.findByName("CodeLutin");
-
- EntityVisitor delegateVisitor = new ExportXMLVisitor();
- EntityVisitor visitor = new DepthEntityVisitor(delegateVisitor);
- clCompany.accept(visitor);
-
- if (log.isInfoEnabled()) {
- log.info("Export XML = \n" + delegateVisitor.toString());
- }
- }
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/ExportXMLVisitor.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/ExportXMLVisitor.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/ExportXMLVisitor.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,107 +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%
- */
-
-package org.nuiton.topia.persistence;
-
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.junit.Ignore;
-
-/**
- * Visitor pour export xml.
- *
- * @author chatellier
- * @version $Revision$
- * <p/>
- * Last update : $Date$
- * By : $Author$
- */
-@Ignore
-public class ExportXMLVisitor implements EntityVisitor {
-
- /** log. */
- private static Log log = LogFactory.getLog(ExportXMLVisitor.class);
-
- protected StringBuffer buffer;
-
- public ExportXMLVisitor() {
- buffer = new StringBuffer();
- }
-
- @Override
- public void start(TopiaEntity e) {
- if (log.isDebugEnabled()) {
- log.debug("start : " + e);
- }
-
- buffer.append("<").append(e.getClass().getName());
- buffer.append(" topiaId=\"").append(e.getTopiaId()).append("\"");
- buffer.append(" topiaCreateDate=\"").append(e.getTopiaCreateDate()).append("\"");
- buffer.append(" topiaVersion=\"").append(e.getTopiaVersion()).append("\"");
- buffer.append(">\n");
- }
-
- @Override
- public void visit(TopiaEntity e, String name, Class<?> type, Object value) {
- if (log.isDebugEnabled()) {
- log.debug("visit : " + e);
- }
-
- buffer.append("<").append(type.getName()).append(">").append(value).append("</").append(type.getName()).append(">\n");
- }
-
- @Override
- public void visit(TopiaEntity e, String name, Class<?> collectionType, Class<?> type,
- Object value) {
- }
-
- @Override
- public void visit(TopiaEntity e, String name, Class<?> collectionType, Class<?> type, int index, Object value) {
- visit(e, name, type, value);
- }
-
- @Override
- public void end(TopiaEntity e) {
- if (log.isDebugEnabled()) {
- log.debug("end : " + e);
- }
-
- buffer.append("</").append(e.getClass().getName()).append(">\n");
- }
-
- @Override
- public String toString() {
- String content = buffer.toString();
- return content;
- }
-
- @Override
- public void clear() {
- // do nothing
- }
-
-
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/HqlAndParametersBuilderTest.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/HqlAndParametersBuilderTest.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/HqlAndParametersBuilderTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,116 +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 com.google.common.collect.Lists;
-import org.junit.Assert;
-import org.junit.Test;
-
-import java.util.Collection;
-
-public class HqlAndParametersBuilderTest {
-
- protected HqlAndParametersBuilder hqlAndParametersBuilder =
- new HqlAndParametersBuilder(TopiaEntity.class);
-
- protected static final Collection<String> SOME_VALUES =
- Lists.newArrayList("value1", "value2", "value3");
-
- protected static final Collection<String> SOME_VALUES_WITH_NULL =
- Lists.newArrayList("value1", "value2", null, "value3");
-
- @Test
- public void testFindAvailableHqlParameterName() {
-
- String availableHqlParameterName1 = hqlAndParametersBuilder.putHqlParameterWithAvailableName("survey.topiaId", "topiaId1");
- String availableHqlParameterName2 = hqlAndParametersBuilder.putHqlParameterWithAvailableName("survey.topiaId", "topiaId1");
-
- Assert.assertNotEquals(availableHqlParameterName1, availableHqlParameterName2);
- Assert.assertFalse(availableHqlParameterName1.contains("."));
- Assert.assertFalse(availableHqlParameterName2.contains("."));
-
- }
-
- @Test
- public void testEqualsNull() {
-
- hqlAndParametersBuilder.addEquals("myProp", null);
-
- String actualHql = hqlAndParametersBuilder.getHql();
-
- Assert.assertFalse(actualHql.contains("myProp = null"));
- Assert.assertTrue(actualHql.contains("myProp is null"));
-
- }
-
- @Test
- public void testAddInWithNull() {
-
- hqlAndParametersBuilder.addIn("myProp", SOME_VALUES_WITH_NULL);
-
- String actualHql = hqlAndParametersBuilder.getHql();
-
- Assert.assertTrue(actualHql.contains("myProp is null or topiaEntity_.myProp in ("));
- Assert.assertEquals(
- SOME_VALUES_WITH_NULL.size() - 1, // there should be as many argument as in collection minus 1 because null is removed
- hqlAndParametersBuilder.getHqlParameters().size());
-
- }
-
- @Test
- public void testAddNotEqualsToValue() {
-
- hqlAndParametersBuilder.addNotEquals("myProp", "value");
-
- String actualHql = hqlAndParametersBuilder.getHql();
-
- Assert.assertTrue(actualHql.contains("myProp != "));
- Assert.assertFalse(actualHql.contains("myProp = "));
-
- }
-
- @Test
- public void testAddNotEqualsToNull() {
-
- hqlAndParametersBuilder.addNotEquals("myProp", null);
-
- String actualHql = hqlAndParametersBuilder.getHql();
-
- Assert.assertTrue(actualHql.contains("myProp is not null"));
-
- }
-
- @Test
- public void testAddNotInWithNull() {
-
- hqlAndParametersBuilder.addNotIn("myProp", SOME_VALUES_WITH_NULL);
-
- String actualHql = hqlAndParametersBuilder.getHql();
-
- Assert.assertTrue(actualHql.contains("myProp is not null and "));
-
- }
-
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/NaturalIdTest.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/NaturalIdTest.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/NaturalIdTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,185 +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%
- */
-
-package org.nuiton.topia.persistence;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.hibernate.PropertyValueException;
-import org.junit.Assert;
-import org.junit.Rule;
-import org.junit.Test;
-import org.nuiton.topia.TopiaDatabase;
-import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.TopiaTestDAOHelper;
-import org.nuiton.topia.TopiaTestTopiaPersistenceContext;
-import org.nuiton.topiatest.NaturalizedEntity;
-import org.nuiton.topiatest.NaturalizedEntityDAO;
-
-/**
- * NaturalIdTest
- * <p/>
- * Created: 18 févr. 2010
- *
- * @author fdesbois
- * @version $Revision$
- * <p/>
- * Mise a jour: $Date$
- * par : $Author$
- */
-public class NaturalIdTest {
-
- private static final Log log = LogFactory.getLog(NaturalIdTest.class);
-
- @Rule
- public final TopiaDatabase db = new TopiaDatabase();
-
- @Test
- public void testCreateSucessfull() throws Exception {
- log.debug("Test naturalId : create succesfull");
- TopiaTestTopiaPersistenceContext persistenceContext = db.beginTransaction();
-
- NaturalizedEntityDAO dao =
- persistenceContext.getNaturalizedEntityDao();
-
- // No exception will be thrown with the two properties
- dao.createByNaturalId(5, "str");
- persistenceContext.commitTransaction();
-
- // No exception will only the need property
- dao.createByNotNull(3);
- persistenceContext.commitTransaction();
-
- // No exception will only the need property
- dao.create(NaturalizedEntity.PROPERTY_NATURAL_ID_NOT_NULL, 3);
- persistenceContext.commitTransaction();
- }
-
- @Test
- public void testCreateFailed() throws Exception {
- log.debug("Test naturalId : create failed");
- TopiaTestTopiaPersistenceContext persistenceContext = db.beginTransaction();
-
- NaturalizedEntityDAO dao =
- persistenceContext.getNaturalizedEntityDao();
-
- // Exception will be throw
- try {
- dao.create();
- persistenceContext.commitTransaction();
-
- // Note : this is possible to create an empty entity if the type
- // is primitive like 'int' which have a default value of '0'
- } catch (TopiaException eee) {
- Assert.assertNotNull(eee.getCause());
- Assert.assertTrue(eee.getCause() instanceof PropertyValueException);
- Assert.assertEquals("naturalIdNotNull", ((PropertyValueException)eee.getCause()).getPropertyName());
- }
-// catch (PropertyValueException eee) {
-// Assert.assertEquals("naturalIdNotNull", eee.getPropertyName());
-// }
- }
-
- @Test
- public void testUpdateFailed() throws Exception {
- log.debug("Test naturalId : update failed");
-
- TopiaTestTopiaPersistenceContext persistenceContext = db.beginTransaction();
-
- NaturalizedEntityDAO dao =
- persistenceContext.getNaturalizedEntityDao();
-
- NaturalizedEntity entity =
- dao.createByNaturalId(5, "str");
- persistenceContext.commitTransaction();
-
- // Exception will be throw : not allowed to modify a naturalId property
- try {
- entity.setNaturalIdNotNull(8);
- persistenceContext.commitTransaction();
- } catch (TopiaException eee) {
- Assert.assertEquals("org.hibernate.HibernateException",
- eee.getCause().getClass().getName());
- }
- }
-
- @Test
- public void testFindByNaturalId() throws Exception {
- log.debug("Test naturalId : findByNaturalId");
- TopiaTestTopiaPersistenceContext persistenceContext = db.beginTransaction();
-
-
- NaturalizedEntityDAO dao =
- persistenceContext.getNaturalizedEntityDao();
-
- NaturalizedEntity entity =
- dao.createByNaturalId(5, "str");
- persistenceContext.commitTransaction();
-
- NaturalizedEntity result = dao.findByNaturalId(5, "str");
-
- Assert.assertEquals(entity, result);
- }
-
- @Test
- public void testExistNaturalId() throws Exception {
- log.debug("Test naturalId : existNaturalId");
- TopiaTestTopiaPersistenceContext persistenceContext = db.beginTransaction();
-
-
- NaturalizedEntityDAO dao =
- persistenceContext.getNaturalizedEntityDao();
-
- dao.createByNaturalId(5, "str");
- persistenceContext.commitTransaction();
-
- boolean result = dao.existByNaturalId(5, "str");
-
- Assert.assertTrue(result);
-
- // not find with only one correct property
- result = dao.existByNaturalId(8, "str");
-
- Assert.assertFalse(result);
- }
-
- @Test
- public void testNaturalIdAreGeneralized() throws Exception {
-
- // test that natural ids are generalized
- String[] generalizedNaturalizedNaturalIds = TopiaTestDAOHelper.TopiaTestEntityEnum.GeneralizedNaturalizedEntity.getNaturalIds();
- String[] naturalizedNaturalIds = TopiaTestDAOHelper.TopiaTestEntityEnum.NaturalizedEntity.getNaturalIds();
- Assert.assertArrayEquals(generalizedNaturalizedNaturalIds, naturalizedNaturalIds);
- }
-
- @Test
- public void testNotNullsAreGeneralized() throws Exception {
-
- // test that not nulls are generalized
- String[] generalizedNaturalizedNotNulls = TopiaTestDAOHelper.TopiaTestEntityEnum.GeneralizedNaturalizedEntity.getNotNulls();
- String[] naturalizedNotNulls = TopiaTestDAOHelper.TopiaTestEntityEnum.NaturalizedEntity.getNotNulls();
- Assert.assertArrayEquals(generalizedNaturalizedNotNulls, naturalizedNotNulls);
- }
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/TopiaDAOTest.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/TopiaDAOTest.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/TopiaDAOTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,201 +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 org.hamcrest.CoreMatchers;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Rule;
-import org.junit.Test;
-import org.nuiton.topia.TopiaDatabase;
-import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.TopiaTestTopiaPersistenceContext;
-import org.nuiton.topia.test.entities.Person;
-import org.nuiton.topia.test.entities.PersonDAO;
-
-import com.google.common.collect.Lists;
-
-/**
- * Test on {@link TopiaDAO}.
- * <p/>
- * Last update : $Date$
- * By : $Author$
- *
- * @author chatellier
- * @version $Revision$
- */
-public class TopiaDAOTest {
-
- @Rule
- public final TopiaDatabase db = new TopiaDatabase();
-
- protected TopiaTestTopiaPersistenceContext context;
-
- protected PersonDAO 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.commitTransaction();
-
- // 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.rollbackTransaction();
-
- // meme test apres roolback
- Person person3 = createPerson("tata");
- allPerson = dao.findAll();
- Assert.assertEquals(2, allPerson.size());
- Assert.assertThat(allPerson, CoreMatchers.hasItem(person3));
-
- context.commitTransaction();
- }
-
- @Test
- public void findAllLazyByQuery() throws TopiaException {
-
- Assert.assertEquals(dao.count(), 0);
-
- createPersons(101);
-
- Iterable<Person> allByLazy = dao.findAllLazyByQuery(
- 100,
- "FROM " + dao.getTopiaEntityEnum().getImplementationFQN() + " ORDER BY id");
-
- List<Person> actual = Lists.newArrayList();
-
- for (Person person : allByLazy) {
- actual.add(person);
- }
- Assert.assertEquals(dao.count(), actual.size());
-
- allByLazy = dao.findAllLazyByQuery(
- 54,
- "FROM " + dao.getTopiaEntityEnum().getImplementationFQN() + " ORDER BY id");
-
- actual = Lists.newArrayList();
-
- for (Person person : allByLazy) {
- actual.add(person);
- }
- Assert.assertEquals(dao.count(), actual.size());
-
- allByLazy = dao.findAllLazyByQuery(
- 49,
- "FROM " + dao.getTopiaEntityEnum().getImplementationFQN() + " ORDER BY id");
-
- actual = Lists.newArrayList();
-
- for (Person person : allByLazy) {
- actual.add(person);
- }
- Assert.assertEquals(dao.count(), actual.size());
-
- allByLazy = dao.findAllLazyByQuery(
- 101,
- "FROM " + dao.getTopiaEntityEnum().getImplementationFQN() + " ORDER BY id");
-
- actual = Lists.newArrayList();
-
- for (Person person : allByLazy) {
- actual.add(person);
- }
- Assert.assertEquals(dao.count(), actual.size());
-
- allByLazy = dao.findAllLazyByQuery(
- 102,
- "FROM " + dao.getTopiaEntityEnum().getImplementationFQN() + " ORDER BY id");
-
- 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.commitTransaction();
- }
-
- protected Person createPerson(String name) throws TopiaException {
- return dao.create(Person.PROPERTY_NAME, name);
- }
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/CollectorTest.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/CollectorTest.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/CollectorTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,124 +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%
- */
-
-package org.nuiton.topia.persistence.util;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.TopiaTestDAOHelper;
-import org.nuiton.topia.persistence.TopiaEntity;
-import org.nuiton.topia.persistence.TopiaEntityEnum;
-import org.nuiton.topiatest.Company;
-import org.nuiton.topiatest.CompanyImpl;
-import org.nuiton.topiatest.Department;
-import org.nuiton.topiatest.DepartmentImpl;
-import org.nuiton.topiatest.EmployeImpl;
-
-/** @author tchemit <chemit(a)codelutin.com> */
-public class CollectorTest {
-
-
- private static Log log = LogFactory.getLog(CollectorTest.class);
-
-
- static TopiaEntityEnum[] contracts;
-
- @BeforeClass
- public static void setUpClass() throws Exception {
- contracts = TopiaTestDAOHelper.getContracts();
- }
-
- @AfterClass
- public static void tearDownClass() throws Exception {
- contracts = null;
- }
-
- @Test
- public void testCollector() throws Exception {
-
- Collector<Integer> detector = new Collector<Integer>(contracts) {
-
- int hits;
-
- @Override
- protected void beforeAll(CollectorVisitor visitor, TopiaEntity... entities) {
- super.beforeAll(visitor, entities);
- hits = 0;
- }
-
- @Override
- protected Integer afterAll(CollectorVisitor visitor, TopiaEntity... entities) {
- return hits;
- }
-
- @Override
- protected void onStarted(TopiaEntity e, boolean enter) {
- super.onStarted(e, enter);
- int level = stackSize();
- log.info(String.format("(%1$2d) %2$" + level * 2 + "s %3$s", level, ">>", getStack()));
-
- hits++;
- }
-
- @Override
- protected void onEnded(TopiaEntity e, boolean enter) {
- super.onEnded(e, enter);
- int level = stackSize() + 1;
- log.info(String.format("(%1$2d) %2$" + level * 2 + "s %3$s", level, "<<", getStack()));
- }
- };
-
- Company company = new CompanyImpl();
- EmployeImpl employe = new EmployeImpl();
- Department department = new DepartmentImpl();
-
- detect(detector, 1, company);
-
- company.addEmploye(employe);
- detect(detector, 2, company);
-
- company.addDepartment(department);
- detect(detector, 3, company);
-
- company.removeEmploye(employe);
- detect(detector, 2, company);
-
- company.removeDepartment(department);
- detect(detector, 1, company);
- }
-
- protected void detect(Collector<Integer> detector,
- int expectedResult,
- TopiaEntity... entities) throws TopiaException {
- Integer result = detector.detect(entities);
- Assert.assertNotNull(result);
- Assert.assertEquals(expectedResult, result.intValue());
- }
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/EntityOperatorTest.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/EntityOperatorTest.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/EntityOperatorTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,238 +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%
- */
-
-package org.nuiton.topia.persistence.util;
-
-import org.junit.After;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.nuiton.topia.TopiaTestDAOHelper;
-import org.nuiton.topiatest.Company;
-import org.nuiton.topiatest.CompanyImpl;
-import org.nuiton.topiatest.Department;
-import org.nuiton.topiatest.DepartmentImpl;
-import org.nuiton.topiatest.Employe;
-import org.nuiton.topiatest.EmployeImpl;
-import org.nuiton.topiatest.Personne;
-import org.nuiton.topiatest.PersonneImpl;
-
-import java.util.Collection;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-
-/** @author tchemit <chemit(a)codelutin.com> */
-public class EntityOperatorTest {
-
- public EntityOperatorTest() {
- }
-
- static EntityOperator<Company> operationC;
-
- static EntityOperator<Employe> operationE;
-
- static EntityOperator<Personne> operationP;
-
- static EntityOperator<Department> operationD;
-
- Company c;
-
- Department d;
-
- Employe e;
-
- Personne p;
-
- @BeforeClass
- public static void setUpClass() throws Exception {
- operationC = TopiaTestDAOHelper.getOperator(Company.class);
- operationE = TopiaTestDAOHelper.getOperator(Employe.class);
- operationP = TopiaTestDAOHelper.getOperator(Personne.class);
- operationD = TopiaTestDAOHelper.getOperator(Department.class);
- }
-
- @AfterClass
- public static void tearDownClass() throws Throwable {
- operationC.finalize();
- operationE.finalize();
- operationP.finalize();
- operationD.finalize();
- }
-
- @Before
- public void setUp() {
- c = new CompanyImpl();
- d = new DepartmentImpl();
- e = new EmployeImpl();
- p = new PersonneImpl();
- }
-
- @After
- public void tearDown() {
- c = null;
- d = null;
- e = null;
- p = null;
- }
-
- /** Test of newOperator method, of class EntityOperator. */
- @Test
- public void testGet() {
-
- Object actual;
- String name;
-
- e.setName(name = "name");
- actual = operationE.get(Employe.PROPERTY_NAME, e);
- assertEquals(name, actual);
-
- actual = operationP.get(Employe.PROPERTY_NAME, e);
- assertEquals(name, actual);
-
- actual = operationD.get(Department.PROPERTY_COMPANY, d);
- assertNull(actual);
-
- d.setCompany(c);
- actual = operationD.get(Department.PROPERTY_COMPANY, d);
- assertNotNull(actual);
- assertEquals(c, actual);
-
- actual = operationC.get(Company.PROPERTY_DEPARTMENT, c);
- assertNull(actual);
-
- c.addDepartment(d);
- actual = operationC.get(Company.PROPERTY_DEPARTMENT, c);
- assertNotNull(actual);
- assertFalse(((Collection<?>) actual).isEmpty());
- }
-
- /** Test of set method, of class EntityOperator. */
- @Test
- public void testSet() {
-
- String name;
-
- operationE.set(Employe.PROPERTY_NAME, e, name = "name");
- assertEquals(name, e.getName());
-
- operationP.set(Employe.PROPERTY_NAME, e, name = "name2");
- assertEquals(name, e.getName());
- }
-
- /** Test of getChild method, of class EntityOperator. */
- @Test
- public void testGetChild() {
- Object actual;
- String topiaId;
-
- topiaId = "0";
-
- actual = operationC.get(Company.PROPERTY_DEPARTMENT, c);
- assertNull(actual);
-
- actual = operationC.getChild(Company.PROPERTY_DEPARTMENT, c, topiaId);
- assertNull(actual);
-
- c.addDepartment(d);
-
- actual = operationC.get(Company.PROPERTY_DEPARTMENT, c);
- assertNotNull(actual);
- assertFalse(((Collection<?>) actual).isEmpty());
-
- actual = operationC.getChild(Company.PROPERTY_DEPARTMENT, c, topiaId);
- assertNull(actual);
-
- d.setTopiaId(topiaId);
- actual = operationC.getChild(Company.PROPERTY_DEPARTMENT, c, topiaId);
- assertNotNull(actual);
- assertEquals(d, actual);
-
- }
-
- /** Test of addChild method, of class EntityOperator. */
- @Test
- public void testAddChild() {
-
- assertTrue(c.isDepartmentEmpty());
-
- operationC.addChild(Company.PROPERTY_DEPARTMENT, c, d);
- assertFalse(c.isDepartmentEmpty());
- assertEquals(d, c.getDepartment().iterator().next());
- }
-
- /** Test of isChildEmpty method, of class EntityOperator. */
- @Test
- public void testIsChildEmpty() {
-
- assertTrue(c.isDepartmentEmpty());
-
- boolean actual = operationC.isChildEmpty(Company.PROPERTY_DEPARTMENT, c);
- assertTrue(actual);
-
- c.addDepartment(d);
-
- actual = operationC.isChildEmpty(Company.PROPERTY_DEPARTMENT, c);
- assertFalse(actual);
- }
-
- /** Test of sizeChild method, of class EntityOperator. */
- @Test
- public void testChildSize() {
-
- assertTrue(c.isDepartmentEmpty());
-
- int actual = operationC.sizeChild(Company.PROPERTY_DEPARTMENT, c);
- assertEquals(0, actual);
-
- c.addDepartment(d);
-
- actual = operationC.sizeChild(Company.PROPERTY_DEPARTMENT, c);
- assertEquals(1, actual);
- c.clearDepartment();
-
- actual = operationC.sizeChild(Company.PROPERTY_DEPARTMENT, c);
- assertEquals(0, actual);
- }
-
- /** Test of removeChild method, of class EntityOperator. */
- @Test
- public void testRemoveChild() {
-
- assertTrue(c.isDepartmentEmpty());
-
- c.addDepartment(d);
-
- assertFalse(c.isDepartmentEmpty());
-
- operationC.removeChild(Company.PROPERTY_DEPARTMENT, c, d);
-
- assertTrue(c.isDepartmentEmpty());
- }
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityBinderTest.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityBinderTest.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityBinderTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,105 +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%
- */
-
-package org.nuiton.topia.persistence.util;
-
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.nuiton.topia.TopiaTestDAOHelper;
-import org.nuiton.topia.persistence.TopiaEntity;
-import org.nuiton.topia.persistence.TopiaEntityEnum;
-import org.nuiton.topiatest.Company;
-import org.nuiton.util.beans.Binder;
-import org.nuiton.util.beans.BinderFactory;
-import org.nuiton.util.beans.BinderModelBuilder;
-
-public class TopiaEntityBinderTest {
-
- static TopiaEntityEnum[] contracts;
-
- @BeforeClass
- public static void setUpClass() throws Exception {
- contracts = TopiaTestDAOHelper.getContracts();
- }
-
- public static class CompanyDTO {
-
- protected String name;
-
- protected int siret;
-
- protected String id;
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public int getSiret() {
- return siret;
- }
-
- public void setSiret(int siret) {
- this.siret = siret;
- }
-
- public String getTopiaId() {
- return id;
- }
-
- public void setId(String id) {
- this.id = id;
- }
- }
-
- @Before
- public void setUp() {
- BinderFactory.clear();
- }
-
- @AfterClass
- public static void afterClass() {
- BinderFactory.clear();
- }
-
- @Test
- public void testBinder() {
-
- BinderModelBuilder<Company, CompanyDTO> builder = BinderModelBuilder.newEmptyBuilder(Company.class, CompanyDTO.class);
- builder.addSimpleProperties(Company.PROPERTY_NAME, Company.PROPERTY_SIRET);
- builder.addProperties(TopiaEntity.PROPERTY_TOPIA_ID, "id");
- BinderFactory.registerBinderModel(builder);
-
- Binder<Company, CompanyDTO> binder =
- BinderFactory.newBinder(Company.class, CompanyDTO.class);
- Assert.assertNotNull(binder);
- }
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityHelperTest.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityHelperTest.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityHelperTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,282 +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%
- */
-
-package org.nuiton.topia.persistence.util;
-
-import org.junit.AfterClass;
-import org.junit.Assert;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.TopiaTestDAOHelper;
-import org.nuiton.topia.persistence.DefaultTopiaIdFactory;
-import org.nuiton.topia.persistence.TopiaEntity;
-import org.nuiton.topia.persistence.TopiaEntityEnum;
-import org.nuiton.topia.persistence.TopiaIdFactory;
-import org.nuiton.topiatest.Company;
-import org.nuiton.topiatest.CompanyImpl;
-import org.nuiton.topiatest.Department;
-import org.nuiton.topiatest.DepartmentImpl;
-import org.nuiton.topiatest.Employe;
-import org.nuiton.topiatest.EmployeAbstract;
-import org.nuiton.topiatest.EmployeImpl;
-import org.nuiton.topiatest.Personne;
-import org.nuiton.topiatest.PersonneAbstract;
-import org.nuiton.topiatest.PersonneImpl;
-
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
-
-/** @author tchemit <chemit(a)codelutin.com> */
-public class TopiaEntityHelperTest {
-
- protected static TopiaIdFactory topiaIdFactory = new DefaultTopiaIdFactory();
-
- protected static TopiaEntityEnum[] contracts;
-
- protected final Set<Class<? extends TopiaEntity>> contractsClass;
-
- public TopiaEntityHelperTest() {
- contractsClass = new HashSet<Class<? extends TopiaEntity>>();
- contractsClass.add(Company.class);
- contractsClass.add(Employe.class);
- contractsClass.add(Department.class);
- }
-
- @BeforeClass
- public static void setUpClass() throws Exception {
- contracts = TopiaTestDAOHelper.getContracts();
- }
-
- @AfterClass
- public static void tearDownClass() throws Exception {
- contracts = null;
- }
-
- /** Test of getContractClass method, of class TopiaEntityHelper. */
- @Test
- public void testgetContract() {
-
- Class<?> result = TopiaEntityHelper.getContractClass(null, Company.class);
- assertNull(result);
-
- Class<? extends TopiaEntity> expResult;
-
- expResult = Employe.class;
-
- getContractClass(expResult, EmployeImpl.class);
- getContractClass(expResult, EmployeAbstract.class);
- getContractClass(expResult, Employe.class);
-
- expResult = Personne.class;
-
- getContractClass(expResult, PersonneImpl.class);
- getContractClass(expResult, PersonneAbstract.class);
- getContractClass(expResult, Personne.class);
- }
-
- /** Test of retainContracts method, of class TopiaEntityHelper. */
- @Test
- public void testRetainContracts() {
- Set<Class<? extends TopiaEntity>> classes = new HashSet<Class<? extends TopiaEntity>>();
- Set<Class<? extends TopiaEntity>> result = TopiaEntityHelper.retainContracts(contracts, classes);
-
- assertTrue(result.isEmpty());
-
- classes.add(PersonneImpl.class);
- result = TopiaEntityHelper.retainContracts(contracts, classes);
- assertEquals(1, result.size());
- assertTrue(result.contains(Personne.class));
-
- classes.add(PersonneAbstract.class);
- result = TopiaEntityHelper.retainContracts(contracts, classes);
- assertEquals(1, result.size());
- assertTrue(result.contains(Personne.class));
-
- classes.add(Personne.class);
- result = TopiaEntityHelper.retainContracts(contracts, classes);
- assertEquals(1, result.size());
- assertTrue(result.contains(Personne.class));
-
- classes.clear();
- classes.add(EmployeImpl.class);
- result = TopiaEntityHelper.retainContracts(contracts, classes);
- assertEquals(1, result.size());
- assertTrue(result.contains(Employe.class));
-
- classes.add(PersonneImpl.class);
- result = TopiaEntityHelper.retainContracts(contracts, classes);
- assertEquals(2, result.size());
- assertTrue(result.contains(Personne.class));
- assertTrue(result.contains(Employe.class));
-
- }
-
- /**
- * Test of detectTypes method, of class TopiaEntityHelper.
- *
- * @throws TopiaException
- */
- @Test
- public void testDetectTypes() throws TopiaException {
- Company company = new CompanyImpl();
- EmployeImpl employe = new EmployeImpl();
- Department departmnet = new DepartmentImpl();
-
- detectTypes(new Class<?>[]{Company.class, Employe.class, Department.class}, company, employe, departmnet);
-
- company.addEmploye(employe);
- detectTypes(new Class<?>[]{Company.class, Employe.class}, company);
-
- company.addDepartment(departmnet);
- departmnet.setCompany(company);
- detectTypes(new Class<?>[]{Company.class, Employe.class, Department.class}, company);
-
- company.removeEmploye(employe);
- company.removeDepartment(departmnet);
- detectTypes(new Class<?>[]{Company.class}, company);
- }
-
- @Test
- public void testDetector() throws Exception {
-
- Company company = new CompanyImpl();
- company.setTopiaId(topiaIdFactory.newTopiaId(Company.class, company));
- Employe employe = new EmployeImpl();
- employe.setTopiaId(topiaIdFactory.newTopiaId(Employe.class, employe));
- Department department = new DepartmentImpl();
- department.setTopiaId(topiaIdFactory.newTopiaId(Department.class, department));
-
- detectEntities(new Class<?>[]{Company.class, Employe.class, Department.class}, new int[]{1, 1, 1}, company, employe, department);
- detectEntityIds(new Class<?>[]{Company.class, Employe.class, Department.class}, new int[]{1, 1, 1}, company, employe, department);
-
- company.addEmploye(employe);
- detectEntities(new Class<?>[]{Company.class, Employe.class}, new int[]{1, 1, 1}, company);
- detectEntityIds(new Class<?>[]{Company.class, Employe.class}, new int[]{1, 1, 1}, company);
-
- company.addDepartment(department);
- department.setCompany(company);
-
- detectEntities(new Class<?>[]{Company.class, Employe.class, Department.class}, new int[]{1, 1, 1}, company);
- detectEntityIds(new Class<?>[]{Company.class, Employe.class, Department.class}, new int[]{1, 1, 1}, company);
-
- company.removeEmploye(employe);
- company.removeDepartment(department);
-
-
- detectEntities(new Class<?>[]{Company.class}, new int[]{1}, company);
- detectEntityIds(new Class<?>[]{Company.class}, new int[]{1}, company);
-
- detectEntities(new Class<?>[]{Company.class}, new int[]{2}, company, new CompanyImpl());
- detectEntityIds(new Class<?>[]{Company.class}, new int[]{2}, company, new CompanyImpl());
-
- department.setCompany(company);
-
- detectEntities(new Class<?>[]{Company.class, Department.class}, new int[]{1, 1}, department);
- detectEntityIds(new Class<?>[]{Company.class, Department.class}, new int[]{1, 1}, department);
-
- //TODO faire des tests avec des entites avec cycles
- }
-
- protected void detectEntities(Class<?>[] expected,
- int[] sizes,
- TopiaEntity... data) throws TopiaException {
-
- Map<Class<? extends TopiaEntity>, List<TopiaEntity>> actual = null;
-
- try {
- actual = TopiaEntityHelper.detectEntities(contracts, contractsClass, data);
-
- Assert.assertEquals(expected.length, actual.size());
- int index = 0;
- for (Class<?> c : expected) {
- List<TopiaEntity> value = actual.get(c);
- int expectedSize = sizes[index++];
- Assert.assertEquals(expectedSize, value.size());
- }
- } finally {
- if (actual != null) {
- actual.clear();
- }
- }
- }
-
- protected void detectEntityIds(Class<?>[] expected,
- int[] sizes,
- TopiaEntity... data) throws TopiaException {
-
- TopiaEntityIdsMap actual = null;
-
- try {
- actual = TopiaEntityHelper.detectEntityIds(contracts,
- contractsClass,
- data
- );
-
- Assert.assertEquals(expected.length, actual.size());
- int index = 0;
- for (Class<?> c : expected) {
- List<String> value = actual.get(c);
- int expectedSize = sizes[index++];
- Assert.assertEquals(expectedSize, value.size());
- }
- } finally {
- if (actual != null) {
- actual.clear();
- }
- }
- }
-
- protected void detectTypes(Class<?>[] expected, TopiaEntity... data) throws TopiaException {
- Set<String> fqns = new HashSet<String>(expected.length);
- Set<Class<? extends TopiaEntity>> actual = null;
- for (Class<?> c : expected) {
- fqns.add(c.getName());
- }
- try {
- actual = TopiaEntityHelper.detectTypes(contracts, data);
- Assert.assertEquals(expected.length, actual.size());
- for (Class<? extends TopiaEntity> c : actual) {
- Assert.assertTrue(fqns.contains(c.getName()));
- }
- } finally {
- fqns.clear();
- if (actual != null) {
- actual.clear();
- }
- }
- }
-
- protected void getContractClass(Class<?> expected, Class<? extends TopiaEntity> klass) {
- Class<?> result = TopiaEntityHelper.getContractClass(contracts, klass);
- assertEquals(expected, result);
- }
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTester.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTester.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTester.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,331 +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%
- */
-
-package org.nuiton.topia.persistence.util;
-
-import org.junit.After;
-import org.junit.Assert;
-import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.persistence.TopiaEntity;
-import org.nuiton.topia.persistence.TopiaEntityEnum;
-
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-import java.util.SortedMap;
-
-import static java.util.Map.Entry;
-
-/**
- * A abstract class to help testing {@link TopiaEntityRef} as detectes types, or
- * detects or references.
- * <p/>
- * An example of use if given in the test {@link TopiaEntityRefTesterTest}.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 2.3.1
- */
-public abstract class TopiaEntityRefTester<T extends TopiaEntityEnum> {
-
- protected SortedMap<TopiaEntity, List<TopiaEntityRef>> detected;
-
- protected Iterator<Entry<TopiaEntity, List<TopiaEntityRef>>> itr;
-
- protected Entry<TopiaEntity, List<TopiaEntityRef>> entry;
-
- protected List<TopiaEntityRef> refs;
-
- protected T[] contracts;
-
- protected int index;
-
- protected T[] getContracts() {
- if (contracts == null) {
- contracts = getContracts0();
- }
- return contracts;
- }
-
- /** @return all the {@link TopiaEntityEnum} to be used */
- protected abstract T[] getContracts0();
-
- @After
- public void after() {
- itr = null;
- entry = null;
- refs = null;
- detected = null;
- index = 0;
- }
-
- /**
- * Creates a new entity with the given {@code topiaId} (will use the {@link
- * TopiaEntityEnum#getImplementation()} class).
- *
- * @param constant the constant defining the entity
- * @param topiaId the topia to assign
- * @param <T> the type of entity
- * @return the new entity
- * @throws IllegalAccessException if can no access entity constructor
- * @throws InstantiationException if can no instanciate the entity
- */
- protected <T extends TopiaEntity> T newEntity(
- TopiaEntityEnum constant, String topiaId) throws
- IllegalAccessException,
- InstantiationException {
- Class<? extends TopiaEntity> impl = constant.getImplementation();
- TopiaEntity topiaEntity = impl.newInstance();
- topiaEntity.setTopiaId(topiaId);
- return (T) topiaEntity;
- }
-
- /**
- * Obtain the reference of an association for a given entity.
- * <p/>
- * Example, to obtain the Pet 'pudding' on a Person :
- * <pre>pet[@topiaId='pudding']</pre>
- * invoke
- * <pre>getAssociationRef('pet',pet);</pre>
- *
- * @param associationName the name of the association
- * @param e the required entity
- * @return the reference of the association
- */
- protected String getAssociationRef(String associationName, TopiaEntity e) {
- return getAssociationRef(associationName, e.getTopiaId());
- }
-
- /**
- * Obtain the reference of an association for a given id.
- * <p/>
- * Example to obtain the Pet 'pudding' on a Person :
- * <pre>pet[@topiaId='pudding']</pre>
- * invoke
- * <pre>getAssociationRef('pet','pudding');</pre>
- *
- * @param associationName the name of the association
- * @param e the id
- * @return the reference of the association
- */
- protected String getAssociationRef(String associationName, String e) {
- String s = String.format(
- TopiaEntityHelper.ASSOCIATION_PATTERN,
- associationName,
- e
- );
- return s;
- }
-
- /**
- * Obtain the next entry from the iterator.
- * <p/>
- * As a side-effect, it will increment the state {@link #index}.
- */
- protected void nextEntry() {
- if (!itr.hasNext()) {
- throw new IllegalStateException("no more entry to get...");
- }
- entry = itr.next();
- index = 0;
- }
-
- /**
- * Detects the references from the given {@code entity} which have their
- * topiaId in the given list of {@code ids}.
- * <p/>
- * As a side-effect, it will update the states {@code detected} and set the
- * iterator {@code itr} to the first position on detected entries.
- *
- * @param entity the entity to seek
- * @param nb the required number of entries
- * @param ids the ids to seek
- * @throws TopiaException if any pb while visiting entities
- */
- protected void detectReferences(
- TopiaEntity entity, int nb, String... ids) throws TopiaException {
- detected = TopiaEntityHelper.detectReferences(
- getContracts(), ids, entity);
- assertDetected(nb);
-
- }
-
- /**
- * Detects the references from the given {@code entity} which have their
- * topiaId in the given list of {@code ids}.
- * <p/>
- * As a side-effect, it will update the states {@code detected} and set the
- * iterator {@code itr} to the first position on detected entries.
- *
- * @param entity the entity to seek
- * @param nb the required number of entries
- * @param ids the ids to seek
- * @throws TopiaException if any pb while visiting entities
- */
- protected void detectReferences(
- Collection<? extends TopiaEntity> entity,
- int nb, String... ids) throws TopiaException {
- detected = TopiaEntityHelper.detectReferences(
- getContracts(), ids, entity);
- assertDetected(nb);
- }
-
- /**
- * Detects the type of entities fro the given {@code data}.
- *
- * @param expected the array of expected types
- * @param data the data to seek
- * @throws TopiaException if any pb while visiting data
- */
- protected void detectTypes(Class<?>[] expected,
- TopiaEntity... data) throws TopiaException {
- Set<String> fqns = new HashSet<String>(expected.length);
- Set<Class<? extends TopiaEntity>> actual = null;
- for (Class<?> c : expected) {
- fqns.add(c.getName());
- }
- try {
- actual = TopiaEntityHelper.detectTypes(getContracts(), data);
- Assert.assertEquals(expected.length, actual.size());
- for (Class<? extends TopiaEntity> c : actual) {
- Assert.assertTrue(fqns.contains(c.getName()));
- }
- } finally {
- fqns.clear();
- if (actual != null) {
- actual.clear();
- }
- }
- }
-
- /**
- * Asserts if the given entry definition is equals to the next entry
- * references on internal state state {@code entry}.
- *
- * @param invoker the invoker of the reference
- * @param invokerProperty the access path of the reference
- * @param expected the expected topia entities path to access
- * reference target
- */
- protected void assertNextEntityRef(TopiaEntity invoker,
- String invokerProperty,
- TopiaEntity... expected) {
- assertEntityRef(index, invoker, invokerProperty, expected);
- index++;
- }
-
- /**
- * Asserts if the given entry definition (of an association) is equals to
- * the next entry reference on internal state {@code entry}.
- *
- * @param invoker the invoker of the reference
- * @param association the association name
- * @param id the id of the association ( see {@link
- * #getAssociationRef(String, TopiaEntity)}
- * @param expected the expected topia entities path to access reference
- * target
- */
- protected void assertNextAssociationEntityRef(TopiaEntity invoker,
- String association,
- String id,
- TopiaEntity... expected) {
- String invokerProperty = getAssociationRef(association, id);
- assertNextEntityRef(invoker, invokerProperty, expected);
- }
-
- /**
- * Asserts if the given entry definition is equals to the reference entry at
- * position {@code index} on internal state {@code entry}.
- *
- * @param index the index of the reference to test in {@code
- * entry}
- * @param invoker the invoker of the reference
- * @param invokerProperty the path of the reference
- * @param expected th expected topia entities path to access
- * reference target
- */
- protected void assertEntityRef(int index,
- TopiaEntity invoker,
- String invokerProperty,
- TopiaEntity... expected) {
- Assert.assertNotNull(refs);
- Assert.assertTrue("no index [" + index + "] in refs of size " +
- refs.size(), index < refs.size());
- TopiaEntityRef actual = refs.get(index);
- Assert.assertEquals(actual.getInvoker(), invoker);
- Assert.assertEquals(actual.getInvokerProperty(), invokerProperty);
-
- TopiaEntity[] path = actual.getPath();
- Assert.assertEquals(expected.length, path.length);
- for (int i = 0; i < expected.length; i++) {
- Assert.assertEquals(expected[i].getTopiaId(), path[i].getTopiaId());
- }
- }
-
- /**
- * Asserts if the given {@code expected} entity is equals to the source of
- * the internal state {@code entry}.
- *
- * @param expected the required source of the entry
- * @param nbPath the expected number of references of the given entry
- */
- protected void assertCurrentEntry(TopiaEntity expected,
- int nbPath) {
- assertEntry(expected, nbPath, entry);
- }
-
- /**
- * Asserts if the given {@code entry} has a good source and a good number of
- * references.
- *
- * @param expected the expected entry source
- * @param nbPath the expected number of reference of the entry
- * @param entry the entry to test
- */
- private void assertEntry(TopiaEntity expected,
- int nbPath,
- Entry<TopiaEntity, List<TopiaEntityRef>> entry) {
- Assert.assertNotNull(entry);
- Assert.assertEquals(expected, entry.getKey());
- refs = entry.getValue();
- Assert.assertEquals(nbPath, refs.size());
- }
-
- /**
- * Asserts that the number of detected entries (store in internal state
- * {@code detected}) is ok.
- * <p/>
- * As a side-effect, it will reset the internal state {@code itr} on the
- * first entry of the {@code detected} list.
- *
- * @param size the expected number of detected entries
- */
- protected void assertDetected(int size) {
- Assert.assertNotNull(detected);
- Assert.assertEquals(size, detected.size());
- itr = detected.entrySet().iterator();
- }
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTesterTest.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTesterTest.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTesterTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,155 +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%
- */
-
-package org.nuiton.topia.persistence.util;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.junit.Test;
-import org.nuiton.topia.TopiaTestDAOHelper.TopiaTestEntityEnum;
-import org.nuiton.topia.test.entities.Person;
-import org.nuiton.topia.test.entities.Pet;
-import org.nuiton.topia.test.entities.Race;
-
-/**
- * Test the {@link TopiaEntityRefTester} on
- * <p/>
- * <ul> <li>{@link Pet}</li> <li>{@link Race}</li> <li>{@link Person}</li>
- * </ul>
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 2.3.1
- */
-public class TopiaEntityRefTesterTest extends TopiaEntityRefTester<TopiaTestEntityEnum> {
-
- /** Logger */
- private static final Log log =
- LogFactory.getLog(TopiaEntityRefTesterTest.class);
-
- private static final String PET1 = "pet1";
-
- private static final String PET2 = "pet2";
-
- private static final String RACE1 = "race1";
-
- private static final String PERSON1 = "person1";
-
- @Override
- protected TopiaTestEntityEnum[] getContracts0() {
- return new TopiaTestEntityEnum[]{
- TopiaTestEntityEnum.Pet,
- TopiaTestEntityEnum.Person,
- TopiaTestEntityEnum.Race,
- };
- }
-
- @Test
- public void testNoReferences() throws Exception {
-
- Pet pet = newEntity(TopiaTestEntityEnum.Pet, PET1);
-
- detectReferences(pet, 0);
-
- Race race = newEntity(TopiaTestEntityEnum.Race, RACE1);
-
- detectReferences(race, 0);
-
- Person person = newEntity(TopiaTestEntityEnum.Person, PERSON1);
-
- detectReferences(person, 0);
-
- }
-
- @Test
- public void testReferences() throws Exception {
-
- Pet pet = newEntity(TopiaTestEntityEnum.Pet, PET1);
- Race race = newEntity(TopiaTestEntityEnum.Race, RACE1);
- pet.setRace(race);
- Person person = newEntity(TopiaTestEntityEnum.Person, PERSON1);
-
- detectReferences(pet, 1, RACE1);
-
- nextEntry();
- assertCurrentEntry(race, 1);
- assertNextEntityRef(pet, Pet.PROPERTY_RACE, pet, race);
-
- pet.setPerson(person);
-
- detectReferences(pet, 2, RACE1, PERSON1);
-
- nextEntry();
- assertCurrentEntry(person, 1);
- assertNextEntityRef(pet, Pet.PROPERTY_PERSON, pet, person);
-
- nextEntry();
- assertCurrentEntry(race, 1);
- assertNextEntityRef(pet, Pet.PROPERTY_RACE, pet, race);
-
- person.addPet(pet);
-
- detectReferences(person, 1, PET1);
-
- nextEntry();
- assertCurrentEntry(pet, 1);
- assertNextAssociationEntityRef(person, Person.PROPERTY_PET, PET1, person, pet);
-
- Pet pet2 = newEntity(TopiaTestEntityEnum.Pet, PET2);
-
- person.addPet(pet2);
-
- detectReferences(person, 3, PET1, PET2, RACE1);
-
- nextEntry();
- assertCurrentEntry(pet, 1);
- assertNextAssociationEntityRef(person, Person.PROPERTY_PET, PET1, person, pet);
-
- nextEntry();
- assertCurrentEntry(pet2, 1);
- assertNextAssociationEntityRef(person, Person.PROPERTY_PET, PET2, person, pet2);
-
- nextEntry();
- assertCurrentEntry(race, 1);
- assertNextEntityRef(pet, Pet.PROPERTY_RACE, person, pet, race);
-
- pet2.setRace(race);
-
- detectReferences(person, 3, PET1, PET2, RACE1);
-
- nextEntry();
- assertCurrentEntry(pet, 1);
- assertNextAssociationEntityRef(person, Person.PROPERTY_PET, PET1, person, pet);
-
- nextEntry();
- assertCurrentEntry(pet2, 1);
- assertNextAssociationEntityRef(person, Person.PROPERTY_PET, PET2, person, pet2);
-
- nextEntry();
- assertCurrentEntry(race, 2);
- assertNextEntityRef(pet, Pet.PROPERTY_RACE, person, pet, race);
- assertNextEntityRef(pet2, Pet.PROPERTY_RACE, person, pet2, race);
-
- }
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/test/ano1882/DAOAbstractTransformerTest.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/test/ano1882/DAOAbstractTransformerTest.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/test/ano1882/DAOAbstractTransformerTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,57 +0,0 @@
-/*
- * #%L
- * ToPIA :: Persistence
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2004 - 2012 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%
- */
-package org.nuiton.topia.test.ano1882;
-
-import org.junit.Rule;
-import org.junit.Test;
-import org.nuiton.topia.TopiaDatabase;
-import org.nuiton.topia.TopiaTestDAOHelper;
-import org.nuiton.topia.TopiaTestTopiaPersistenceContext;
-
-import java.util.Arrays;
-
-public class DAOAbstractTransformerTest {
-
- @Rule
- public final TopiaDatabase db = new TopiaDatabase();
-
- @Test
- public void testAno1882() throws Exception {
- TopiaTestTopiaPersistenceContext transaction = db.beginTransaction();
-
- FrenchCompanyDAO dao = TopiaTestDAOHelper.getFrenchCompanyDAO(transaction);
- SIRETDAO siretDAO = TopiaTestDAOHelper.getSIRETDAO(transaction);
- SIRET siret = siretDAO.create();
- FrenchCompany entity =
- dao.create(
- FrenchCompany.PROPERTY_S_IREN, null,
- FrenchCompany.PROPERTY_SIREN2, null,
- FrenchCompany.PROPERTY_S_IRET, Arrays.asList(siret),
- FrenchCompany.PROPERTY_SIRET2, null);
- transaction.commitTransaction();
- dao.delete(entity);
- transaction.commitTransaction();
- }
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/test/evo1912/EntityDTOTransformerTest.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topia/test/evo1912/EntityDTOTransformerTest.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topia/test/evo1912/EntityDTOTransformerTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,46 +0,0 @@
-/*
- * #%L
- * ToPIA :: Persistence
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2004 - 2012 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%
- */
-package org.nuiton.topia.test.evo1912;
-
-import org.junit.Assert;
-import org.junit.Test;
-import org.nuiton.topiatest.CompanyDTO;
-
-/** @author ymartel <martel(a)codelutin.com> */
-public class EntityDTOTransformerTest {
-
- @Test
- public void testEvo1912() throws Exception {
- // simply test the getter/setter on id property : with the tagValue, they should be generated
- CompanyDTO companyDTO = new CompanyDTO();
- String originalId = companyDTO.getTopiaId();
- Assert.assertNull(originalId);
- String wantedId = "mycompany";
- companyDTO.setTopiaId(wantedId);
- String updatedId = companyDTO.getTopiaId();
- Assert.assertEquals(wantedId, updatedId);
- }
-
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topiatest/AbstractExtraDAOEntityTopiaDao.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topiatest/AbstractExtraDAOEntityTopiaDao.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topiatest/AbstractExtraDAOEntityTopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,40 +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%
- */
-package org.nuiton.topiatest;
-
-import org.nuiton.topia.TopiaException;
-
-/**
- * Created: 26 mai 2010
- *
- * @author fdesbois <fdesbois(a)codelutin.com>
- * @version $Id$
- */
-public class AbstractExtraDAOEntityTopiaDao<E extends ExtraDAOEntity> extends GeneratedExtraDAOEntityTopiaDao<E> {
-
- @Override
- public void extra() throws TopiaException {
- }
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topiatest/EnumTest.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topiatest/EnumTest.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topiatest/EnumTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,75 +0,0 @@
-/*
- * #%L
- * ToPIA :: Persistence
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2004 - 2011 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%
- */
-package org.nuiton.topiatest;
-
-import org.junit.Assert;
-import org.junit.Rule;
-import org.junit.Test;
-import org.nuiton.topia.TopiaDatabase;
-import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.TopiaTestDAOHelper;
-import org.nuiton.topia.TopiaTestTopiaPersistenceContext;
-
-/**
- * Test the support of possibility to have an attribute of type enumeration
- * in a entity
- */
-public class EnumTest {
-
- @Rule
- public final TopiaDatabase db = new TopiaDatabase();
-
- /**
- * Create an entity having two field of type enumeration. One is stored
- * using ordinal, the other using the name.
- * <p/>
- * The test check that values are stored, and that find methods works
- *
- * @throws TopiaException if any exception with db
- */
- @Test
- public void storeEntityWithEnumValue() throws TopiaException {
- TopiaTestTopiaPersistenceContext transaction = db.beginTransaction();
-
- PersonneDAO dao = TopiaTestDAOHelper.getPersonneDAO(transaction);
- Personne personne = new PersonneImpl();
- personne.setGender(Gender.FEMALE);
- personne.setOtherGender(Gender.MALE);
- dao.create(personne);
- String topiaId = personne.getTopiaId();
- transaction.commitTransaction();
- transaction.closeContext();
-
- transaction = db.beginTransaction();
- dao = TopiaTestDAOHelper.getPersonneDAO(transaction);
- dao.findByTopiaId(topiaId);
- Assert.assertEquals(Gender.FEMALE, personne.getGender());
- Assert.assertEquals(Gender.MALE, personne.getOtherGender());
-
- Assert.assertNotNull(dao.findByGender(Gender.FEMALE));
- Assert.assertNotNull(dao.findByOtherGender(Gender.MALE));
- transaction.closeContext();
- }
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topiatest/Gender.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topiatest/Gender.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topiatest/Gender.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,29 +0,0 @@
-/*
- * #%L
- * ToPIA :: Persistence
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2004 - 2011 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%
- */
-package org.nuiton.topiatest;
-
-public enum Gender {
- MALE, FEMALE
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topiatest/Title.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topiatest/Title.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topiatest/Title.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,37 +0,0 @@
-/*
- * #%L
- * ToPIA :: Persistence
- *
- * $Id$
- * $HeadURL$
- * %%
- * Copyright (C) 2004 - 2011 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%
- */
-package org.nuiton.topiatest;
-
-/**
- * To test http://nuiton.org/issues/1732.
- *
- * @author tchemit <chemit(a)codelutin.com>
- * @since 2.6.2
- */
-public enum Title {
- Mr,
- Madam,
- Other
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topiatest/beangen/RoueImpl.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topiatest/beangen/RoueImpl.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topiatest/beangen/RoueImpl.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,53 +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%
- */
-
-package org.nuiton.topiatest.beangen;
-
-import org.nuiton.topiatest.Product;
-
-/**
- * RoueImpl
- *
- * Created: 14 janv. 2010
- *
- * @author fdesbois
- * @version $Revision$
- *
- * Mise a jour: $Date$
- * par : $Author$
- */
-public class RoueImpl extends Roue {
-
- @Override
- public void mount() {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
- @Override
- public Product getModel(String id) {
- throw new UnsupportedOperationException("Not supported yet.");
- }
-
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topiatest/deletetest/AbstractContact2TopiaDao.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topiatest/deletetest/AbstractContact2TopiaDao.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topiatest/deletetest/AbstractContact2TopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,51 +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%
- */
-
-package org.nuiton.topiatest.deletetest;
-
-
-import org.nuiton.topia.TopiaException;
-import org.nuiton.topiatest.Company;
-import org.nuiton.topiatest.Employe;
-
-import java.util.Set;
-import java.util.TreeSet;
-
-/**
- *
- * @author desbois
- */
-public class AbstractContact2TopiaDao<E extends Contact2> extends GeneratedContact2TopiaDao<E> {
-
- @Override
- public Set<Contact2> findAllByCompany(Company company) throws TopiaException {
- Set<Contact2> contacts = new TreeSet<Contact2>();
- for (Employe e : company.getEmploye()) {
- contacts.addAll(e.getContacts());
- }
- return contacts;
- }
-
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topiatest/deletetest/DeleteEntityTest.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topiatest/deletetest/DeleteEntityTest.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topiatest/deletetest/DeleteEntityTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,206 +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%
- */
-
-
-/**
- * DeleteEntityTest.java
- *
- * Created: 4 juin 2009
- *
- * @author Florian Desbois <fdesbois(a)codelutin.com>
- * @version $Revision$
- *
- * Mise a jour: $Date$
- * par : $Author$
- */
-
-package org.nuiton.topiatest.deletetest;
-
-import org.apache.commons.logging.Log;
-import org.apache.commons.logging.LogFactory;
-import org.junit.Assert;
-import org.junit.Rule;
-import org.junit.Test;
-import org.nuiton.topia.TopiaDatabase;
-import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.TopiaTestDAOHelper;
-import org.nuiton.topia.TopiaTestTopiaPersistenceContext;
-import org.nuiton.topiatest.Gender;
-import org.nuiton.topiatest.Personne;
-import org.nuiton.topiatest.PersonneDAO;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-
-/**
- * Deleting tests with DAO and Entities generated with ToPIA (diagram
- * delete-test in topiatest.zargo). Different case of deleting, with inheritance
- * or NMultiplicity relationship between two entities, or both. Initiate from an
- * issue with DAOAbstractGenerator delete method generation. Tests with H2
- * Database. Configuration in src/test/resources/TopiaContextImpl.properties
- */
-public class DeleteEntityTest {
-
- private static final Log log = LogFactory.getLog(DeleteEntityTest.class);
-
- @Rule
- public final TopiaDatabase db = new TopiaDatabase();
-
- /**
- * Test for deleting entities with inheritance. Delete from the DAO linked
- * with the subclass entity and from the DAO linked with the superclass
- * entity. In the test model, the two entities have NMultiplicity
- * relationship without association class entity.
- *
- * @throws TopiaException if any exception while manipulating db
- */
- @Test
- public void testDeleteEntityWithInheritance() throws TopiaException {
- log.debug("START TEST : testDeleteEntityWithInheritance");
-
- TopiaTestTopiaPersistenceContext transaction = db.beginTransaction();
-
- log.debug("DAO : PersonneDAO");
- PersonneDAO dao = TopiaTestDAOHelper.getPersonneDAO(transaction);
-
- log.debug("CREATE PERSONNE : Bob Marley");
- Personne personne = dao.create(Personne.PROPERTY_NAME, "Bob Marley");
- transaction.commitTransaction();
- String idPersonne = personne.getTopiaId();
- assertNotNull(idPersonne);
- log.debug("ENTITY PERSONNE SAVED !");
-
- log.debug("DELETE PERSONNE");
- dao.delete(personne);
- transaction.commitTransaction();
- Personne res = dao.forTopiaIdEquals(idPersonne).findAnyOrNull();
- assertNull(res);
- log.debug("ENTITY PERSONNE DELETED !");
-
- log.debug("CREATE PERSONNE : Ziggy Marley");
- Personne personne2 = dao.create(Personne.PROPERTY_NAME, "Ziggy Marley");
- transaction.commitTransaction();
- String idPersonne2 = personne2.getTopiaId();
- assertNotNull(idPersonne2);
- log.debug("ENTITY PERSONNE SAVED !");
-
- log.debug("DAO parent (abstract) : PartyDAO");
- Party2DAO dao2 = TopiaTestDAOHelper.getParty2DAO(transaction);
-
- log.debug("DELETE PERSONNE with PartyDAO");
- dao2.delete(personne2);
- transaction.commitTransaction();
- Party2 res2 = dao2.forTopiaIdEquals(idPersonne2).findAnyOrNull();
- assertNull(res2);
- log.debug("ENTITY PERSONNE DELETED !");
-
-
- }
-
- /**
- * Test for deleting entities with NMultiplicity relation without
- * association class entity. Test DAO generation for deleting references
- * between two entities with NMultiplicity relation. In the test model, the
- * two entities have both inheritance.
- *
- * @throws TopiaException if any exception while manipulating db
- */
- @Test
- public void testDeleteEntityWithManyToManyRelation() throws TopiaException {
- log.debug("START TEST : testDeleteEntityWithManyToManyRelation");
-
- TopiaTestTopiaPersistenceContext transaction = db.beginTransaction();
-
- PersonneDAO dao = TopiaTestDAOHelper.getPersonneDAO(transaction);
-
- log.debug("CREATE PERSONNE : Bob Marley");
- Personne personne = dao.create(Personne.PROPERTY_NAME, "Bob Marley");
- transaction.commitTransaction();
- String idPersonne = personne.getTopiaId();
- assertNotNull(idPersonne);
- log.debug("ENTITY PERSONNE SAVED !");
-
- Contact2DAO contactDAO = TopiaTestDAOHelper.getContact2DAO(transaction);
-
- log.debug("CREATE CONTACT : jaja(a)codelutin.com");
- Contact2 contact = contactDAO.create(Contact2.PROPERTY_CONTACT_VALUE, "jaja(a)codelutin.com");
- transaction.commitTransaction();
- String idContact = contact.getTopiaId();
- assertNotNull(idContact);
- log.debug("ENTITY CONTACT SAVED !");
-
- log.debug("ADD CONTACT TO PERSONNE");
- personne.addContacts(contact);
- transaction.commitTransaction();
- assertEquals(1, personne.getContacts().size());
- log.debug("CONTACT ADDED !");
-
- log.debug("DELETE PERSONNE");
- dao.delete(personne);
- transaction.commitTransaction();
- Personne res = dao.forTopiaIdEquals(idPersonne).findAnyOrNull();
- assertNull(res);
- log.debug("ENTITY PERSONNE DELETED !");
-
- assertEquals(0, contact.getParty2().size());
-
- log.debug("DELETE CONTACT");
- contactDAO.delete(contact);
- transaction.commitTransaction();
- Contact2 res2 = contactDAO.forTopiaIdEquals(idContact).findAnyOrNull();
- assertNull(res2);
- log.debug("ENTITY PERSONNE DELETED !");
-
- }
-
- /**
- * Test than deleting entities will modify isPersisted() result
- */
- @Test
- public void testIsPersisted() {
- log.debug("START TEST : testIsPersisted");
-
- TopiaTestTopiaPersistenceContext transaction = db.beginTransaction();
-
- PersonneDAO dao = TopiaTestDAOHelper.getPersonneDAO(transaction);
-
- Personne person = dao.newInstance();
- Assert.assertNull(person.getTopiaId());
-
- person.setName("Arno");
- person.setGender(Gender.MALE);
- Assert.assertFalse(person.isPersisted());
-
- Personne person2 = dao.create(person);
- Assert.assertTrue(person.isPersisted());
- Assert.assertTrue(person2.isPersisted());
-
- dao.delete(person2);
- Assert.assertFalse(person.isPersisted());
- Assert.assertFalse(person2.isPersisted());
- }
-
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,49 +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%
- */
-package org.nuiton.topiatest.persistence;
-
-import org.nuiton.topia.persistence.TopiaEntity;
-
-/**
- * Created: 11 mai 2010
- *
- * @author fdesbois <fdesbois(a)codelutin.com>
- * @version $Id$
- */
-public interface Entity1 extends TopiaEntity {
-
- String ATTR_1 = "attr1";
-
- String ATTR_2 = "attr2";
-
- String getAttr1();
-
- void setAttr1(String attr1);
-
- String getAttr2();
-
- void setAttr2(String attr2);
-
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1Abstract.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1Abstract.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1Abstract.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,83 +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%
- */
-package org.nuiton.topiatest.persistence;
-
-import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.persistence.EntityVisitor;
-import org.nuiton.topia.persistence.TopiaEntityAbstract;
-
-/**
- * Created: 11 mai 2010
- *
- * @author fdesbois <fdesbois(a)codelutin.com>
- * @version $Id$
- */
-public abstract class Entity1Abstract extends TopiaEntityAbstract
- implements Entity1 {
-
- protected String attr1;
-
- protected String attr2;
-
- @Override
- public String getAttr1() {
- fireOnPreRead(ATTR_1, attr1);
- String result = attr1;
- fireOnPostRead(ATTR_1, attr1);
- return result;
- }
-
- @Override
- public void setAttr1(String attr1) {
- String _oldValue = this.attr1;
- fireOnPreWrite(ATTR_1, _oldValue, attr1);
- this.attr1 = attr1;
- fireOnPostWrite(ATTR_1, _oldValue, attr1);
- }
-
- @Override
- public String getAttr2() {
- fireOnPreRead(ATTR_2, attr2);
- String result = attr2;
- fireOnPostRead(ATTR_2, attr2);
- return result;
- }
-
- @Override
- public void setAttr2(String attr2) {
- String _oldValue = this.attr2;
- fireOnPreWrite(ATTR_2, _oldValue, attr2);
- this.attr2 = attr2;
- fireOnPostWrite(ATTR_2, _oldValue, attr2);
- }
-
- @Override
- public void accept(EntityVisitor visitor) throws TopiaException {
- visitor.start(this);
- visitor.visit(this, ATTR_1, String.class, attr1);
- visitor.visit(this, ATTR_2, String.class, attr2);
- visitor.end(this);
- }
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1Impl.hbm.xml
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1Impl.hbm.xml 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1Impl.hbm.xml 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,37 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- #%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%
- -->
-
-<!--<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">-->
-<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
-<hibernate-mapping default-access="field" auto-import="true" package="org.nuiton.topiatest">
- <class name="org.nuiton.topiatest.persistence.Entity1Impl" table="entity1" node="org.nuiton.topiatest.persistence.Entity1Impl" abstract="false" proxy="org.nuiton.topiatest.persistence.Entity1" >
- <id name="topiaId" type="string" length="255" node="@topiaId"/>
- <version name="topiaVersion" type="long" node="@topiaVersion"/>
- <property name="topiaCreateDate" type="timestamp" node="@topiaCreateDate"/>
- <property name="attr1" type="java.lang.String" access="field" column="attr1" node="attr1"/>
- <property name="attr2" type="java.lang.String" access="field" column="attr2" node="attr2"/>
- </class>
-</hibernate-mapping>
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1Impl.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1Impl.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1Impl.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,37 +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%
- */
-package org.nuiton.topiatest.persistence;
-
-import org.nuiton.topia.TopiaException;
-import org.nuiton.topia.persistence.EntityVisitor;
-
-/**
- * Created: 11 mai 2010
- *
- * @author fdesbois <fdesbois(a)codelutin.com>
- * @version $Id$
- */
-public class Entity1Impl extends Entity1Abstract {
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/package-info.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/package-info.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/package-info.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,28 +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%
- */
-/**
- * Contains persistent entities for Tests.
- */
-package org.nuiton.topiatest.persistence;
\ No newline at end of file
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topiatest/service/FakeService.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topiatest/service/FakeService.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topiatest/service/FakeService.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,63 +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%
- */
-package org.nuiton.topiatest.service;
-
-import org.nuiton.topia.TopiaContext;
-import org.nuiton.topia.framework.TopiaContextImplTest;
-import org.nuiton.topia.framework.TopiaService;
-
-/**
- * FakeService which implements {@link TopiaService} to test existing service
- * from {@link TopiaContextImplTest#testGetServices()}. This fake service
- * doesn't contains property SERVICE_NAME used by {@link
- * org.nuiton.topia.framework.AbstractTopiaContext#serviceEnabled(Class)}.
- * <p/>
- * Created: 10 mai 2010
- *
- * @author fdesbois <fdesbois(a)codelutin.com>
- * @version $Id$
- */
-public class FakeService implements TopiaService {
-
- @Override
- public String getServiceName() {
- return "fake";
- }
-
- @Override
- public Class<?>[] getPersistenceClasses() {
- return new Class<?>[0];
- }
-
- @Override
- public boolean preInit(TopiaContext context) {
- return true;
- }
-
- @Override
- public boolean postInit(TopiaContext context) {
- return true;
- }
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topiatest/service/TestService.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topiatest/service/TestService.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topiatest/service/TestService.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,67 +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%
- */
-package org.nuiton.topiatest.service;
-
-import org.junit.Ignore;
-import org.nuiton.topia.TopiaContext;
-import org.nuiton.topia.framework.TopiaContextImplTest;
-import org.nuiton.topia.framework.TopiaContextImplementor;
-import org.nuiton.topia.framework.TopiaService;
-
-/**
- * TestService which implements {@link TopiaService} to test loading from {@link
- * TopiaContextImplTest#testLoadServices()}.
- * <p/>
- * Created: 10 mai 2010
- *
- * @author fdesbois <fdesbois(a)codelutin.com>
- * @version $Id$
- */
-@Ignore
-public class TestService implements TopiaService {
-
- /** Needed field to use {@link TopiaContext#serviceEnabled(Class)} * */
- public static final String SERVICE_NAME = "test";
-
- @Override
- public String getServiceName() {
- return SERVICE_NAME;
- }
-
- @Override
- public Class<?>[] getPersistenceClasses() {
- return new Class<?>[0];
- }
-
- @Override
- public boolean preInit(TopiaContext context) {
- return true;
- }
-
- @Override
- public boolean postInit(TopiaContext context) {
- return true;
- }
-}
Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topiatest/service/package-info.java
===================================================================
--- trunk/topia-persistence/src/test/java/org/nuiton/topiatest/service/package-info.java 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/java/org/nuiton/topiatest/service/package-info.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,29 +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%
- */
-/**
- * This package contains classes which implements {@link
- * org.nuiton.topia.framework.TopiaService} to test services API.
- */
-package org.nuiton.topiatest.service;
\ No newline at end of file
Deleted: trunk/topia-persistence/src/test/resources/TopiaConnectionProviderHardcoded.properties
===================================================================
--- trunk/topia-persistence/src/test/resources/TopiaConnectionProviderHardcoded.properties 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/resources/TopiaConnectionProviderHardcoded.properties 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,35 +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%
-###
-# Proprietes par defaut pour une base de donnees de type H2
-hibernate.hbm2ddl.auto=update
-hibernate.show_sql=false
-
-hibernate.dialect=org.hibernate.dialect.H2Dialect
-hibernate.connection.username=sa
-hibernate.connection.password=
-hibernate.connection.driver_class=org.h2.Driver
-hibernate.connection.provider_class=org.nuiton.topia.framework.TopiaConnectionProviderHardCoded
-# tchemit 2010-11-28 : comment this line, each test must define his own db path
-#hibernate.connection.url=jdbc:h2:file:target/surefire-workdir/h2data
\ No newline at end of file
Deleted: trunk/topia-persistence/src/test/resources/TopiaContextImpl.properties
===================================================================
--- trunk/topia-persistence/src/test/resources/TopiaContextImpl.properties 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/resources/TopiaContextImpl.properties 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,34 +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%
-###
-# Proprietes par defaut pour une base de donnees de type H2
-hibernate.hbm2ddl.auto=update
-hibernate.show_sql=false
-
-hibernate.dialect=org.hibernate.dialect.H2Dialect
-hibernate.connection.username=sa
-hibernate.connection.password=
-hibernate.connection.driver_class=org.h2.Driver
-# tchemit 2010-11-28 : comment this line, each test must define his own db path
-#hibernate.connection.url=jdbc:h2:file:target/surefire-workdir/h2data
\ No newline at end of file
Deleted: trunk/topia-persistence/src/test/resources/log4j.properties
===================================================================
--- trunk/topia-persistence/src/test/resources/log4j.properties 2013-11-22 17:48:55 UTC (rev 2883)
+++ trunk/topia-persistence/src/test/resources/log4j.properties 2013-11-22 18:03:47 UTC (rev 2884)
@@ -1,36 +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%
-###
-#\u00a0This log is used to display trace in generation
-
-# Global logging configuration
-log4j.rootLogger=WARN, stdout
-# Console output...
-log4j.appender.stdout=org.apache.log4j.ConsoleAppender
-log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
-log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) %M - %m%n
-# package level
-log4j.logger.org.nuiton.topia=INFO
-#log4j.logger.org.nuiton.topiatest=DEBUG
-log4j.logger.org.nuiton.topia.persistence.util=INFO
Property changes on: trunk/topia-templates
___________________________________________________________________
Added: svn:ignore
+ target
*.ipr
*.iws
*.iml
.idea
Property changes on: trunk/topia-templates/LICENSE.txt
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision
Added: svn:eol-style
+ native
Property changes on: trunk/topia-templates/README.txt
___________________________________________________________________
Added: svn:keywords
+ Author Date Id Revision
Added: svn:eol-style
+ native
Added: trunk/topia-templates/pom.xml
===================================================================
--- trunk/topia-templates/pom.xml (rev 0)
+++ trunk/topia-templates/pom.xml 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,187 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ #%L
+ ToPIA :: Persistence
+
+ $Id$
+ $HeadURL: http://svn.nuiton.org/svn/topia/trunk/topia-persistence/pom.xml $
+ %%
+ 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-templates</artifactId>
+ <packaging>jar</packaging>
+
+ <name>ToPIA :: Templates</name>
+ <description>Persistence templates</description>
+
+ <dependencies>
+
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>topia-persistence</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.nuiton.eugene</groupId>
+ <artifactId>eugene</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.nuiton.eugene</groupId>
+ <artifactId>eugene-java-templates</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>commons-collections</groupId>
+ <artifactId>commons-collections</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>commons-beanutils</groupId>
+ <artifactId>commons-beanutils</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>commons-logging</groupId>
+ <artifactId>commons-logging</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>commons-io</groupId>
+ <artifactId>commons-io</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-lang3</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.hibernate</groupId>
+ <artifactId>hibernate-core</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.hibernate</groupId>
+ <artifactId>hibernate-ehcache</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>javassist</groupId>
+ <artifactId>javassist</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-log4j12</artifactId>
+ </dependency>
+
+ <!-- BD H2 for testing -->
+ <dependency>
+ <groupId>com.h2database</groupId>
+ <artifactId>h2</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.hamcrest</groupId>
+ <artifactId>hamcrest-core</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>log4j</groupId>
+ <artifactId>log4j</artifactId>
+ <scope>test</scope>
+ </dependency>
+
+ </dependencies>
+
+ <build>
+
+ <plugins>
+
+ <!-- process templates -->
+ <plugin>
+ <groupId>org.nuiton.processor</groupId>
+ <artifactId>processor-maven-plugin</artifactId>
+ </plugin>
+
+ <!-- expose new plexus components -->
+ <plugin>
+ <groupId>org.codehaus.plexus</groupId>
+ <artifactId>plexus-component-metadata</artifactId>
+ <executions>
+ <execution>
+ <goals>
+ <goal>generate-metadata</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+
+ </plugins>
+ </build>
+
+ <profiles>
+
+ <!-- reporting at release time -->
+ <profile>
+ <id>reporting</id>
+ <activation>
+ <property>
+ <name>performRelease</name>
+ <value>true</value>
+ </property>
+ </activation>
+
+ <reporting>
+ <plugins>
+
+ <plugin>
+ <groupId>org.codehaus.plexus</groupId>
+ <artifactId>plexus-maven-plugin</artifactId>
+ <version>${plexusPluginVersion}</version>
+ </plugin>
+
+ </plugins>
+ </reporting>
+
+ </profile>
+
+ </profiles>
+</project>
Property changes on: trunk/topia-templates/pom.xml
___________________________________________________________________
Added: svn:mime-type
+ text/xml
Added: svn:keywords
+ Author Date Id Revision
Added: svn:eol-style
+ native
Property changes on: trunk/topia-templates/src
___________________________________________________________________
Added: svn:ignore
+ target
*.ipr
*.iws
*.iml
.idea
Property changes on: trunk/topia-templates/src/main
___________________________________________________________________
Added: svn:ignore
+ target
*.ipr
*.iws
*.iml
.idea
Property changes on: trunk/topia-templates/src/main/java
___________________________________________________________________
Added: svn:ignore
+ target
*.ipr
*.iws
*.iml
.idea
Property changes on: trunk/topia-templates/src/main/java/org
___________________________________________________________________
Added: svn:ignore
+ target
*.ipr
*.iws
*.iml
.idea
Property changes on: trunk/topia-templates/src/main/java/org/nuiton
___________________________________________________________________
Added: svn:ignore
+ target
*.ipr
*.iws
*.iml
.idea
Property changes on: trunk/topia-templates/src/main/java/org/nuiton/topia
___________________________________________________________________
Added: svn:ignore
+ target
*.ipr
*.iws
*.iml
.idea
Property changes on: trunk/topia-templates/src/main/java/org/nuiton/topia/templates
___________________________________________________________________
Added: svn:ignore
+ target
*.ipr
*.iws
*.iml
.idea
Copied: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/ApplicationContextTransformer.java (from rev 2882, trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/ApplicationContextTransformer.java)
===================================================================
--- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/ApplicationContextTransformer.java (rev 0)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/ApplicationContextTransformer.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,269 @@
+package org.nuiton.topia.templates;
+
+/*{generator option: parentheses = false}*/
+
+/*{generator option: writeString = +}*/
+
+import org.nuiton.eugene.java.ObjectModelTransformerToJava;
+import org.nuiton.eugene.models.object.ObjectModel;
+import org.nuiton.eugene.models.object.ObjectModelClass;
+import org.nuiton.eugene.models.object.ObjectModelJavaModifier;
+import org.nuiton.eugene.models.object.ObjectModelOperation;
+import org.nuiton.topia.AbstractTopiaApplicationContext;
+import org.nuiton.topia.persistence.TopiaEntity;
+import org.nuiton.topia.persistence.util.EntityOperator;
+import org.nuiton.topia.persistence.util.EntityOperatorStore;
+
+import java.lang.reflect.Array;
+import java.util.List;
+import java.util.Properties;
+
+/**
+ * To generate PersistenceHelper
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.templates.ApplicationContextTransformer"
+ * @since 3.0
+ */
+public class ApplicationContextTransformer extends ObjectModelTransformerToJava {
+
+ @Override
+ public void transformFromModel(ObjectModel input) {
+
+ String packageName = TopiaGeneratorUtil.getApplicationContextPackage(this, model);
+
+ String applicationContextAbstractName = TopiaGeneratorUtil.getApplicationContextAbstractName(model);
+
+ String applicationContextConcreteName = TopiaGeneratorUtil.getApplicationContextConcreteName(model);
+
+ boolean generateAbstract = !isInClassPath(packageName, applicationContextAbstractName);
+
+ boolean generateConcrete = !isInClassPath(packageName, applicationContextConcreteName);
+
+
+ if (generateAbstract) {
+
+ generateAbstract(packageName,
+ applicationContextAbstractName);
+ }
+
+ if (generateConcrete) {
+
+ generateImpl(packageName,
+ applicationContextAbstractName,
+ applicationContextConcreteName);
+ }
+
+ }
+
+ protected void generateAbstract(String packageName,
+ String className) {
+
+ // try to find a super class by tag-value
+// String superClass = TopiaGeneratorUtil.getPersistenceContextSuperClassTagValue(model);
+ String superClass = null;
+
+ if (superClass == null) {
+
+ // no super-class, use default one
+ superClass = AbstractTopiaApplicationContext.class.getName();
+ }
+
+ ObjectModelClass output = createAbstractClass(className, packageName);
+
+ String persistenceContextConcreteName = TopiaGeneratorUtil.getPersistenceContextConcreteName(model);
+ setSuperClass(output, superClass + "<" + persistenceContextConcreteName + ">");
+
+ // detect if there is a contract to set on abstract
+ String contractName = TopiaGeneratorUtil.getPersistenceContextInterfaceName(model);
+
+// addInterface(output, TopiaPersistenceContext.class);
+
+ boolean addPersistenceContextContract = isInClassPath(packageName, contractName);
+
+ if (addPersistenceContextContract) {
+ addInterface(output, packageName + "." + contractName);
+ }
+
+ String modelName = model.getName();
+ String daoHelperClazzName = modelName + "DAOHelper";
+
+ String entityEnumName = modelName + "EntityEnum";
+
+ List<ObjectModelClass> entityClasses =
+ TopiaGeneratorUtil.getEntityClasses(model, true);
+
+ boolean generateOperator =
+ TopiaGeneratorUtil.shouldGenerateOperatorForDAOHelper(model);
+
+ boolean generateStandaloneEnum =
+ TopiaGeneratorUtil.shouldGenerateStandaloneEnumForDAOHelper(model);
+
+ if (!generateStandaloneEnum) {
+
+ addImport(output, packageName + "." + daoHelperClazzName + "." + entityEnumName);
+
+ }
+
+ addImport(output, TopiaEntity.class);
+ addImport(output, Array.class);
+ addImport(output, Array.class);
+
+ if (generateOperator) {
+ addImport(output, EntityOperator.class);
+ addImport(output, EntityOperatorStore.class);
+ }
+
+ // add public constructor
+ ObjectModelOperation constructor = addConstructor(
+ output,
+ ObjectModelJavaModifier.PUBLIC);
+ addParameter(constructor, Properties.class, "properties");
+ setOperationBody(constructor, ""
+/*{
+ super(properties);
+ }*/
+ );
+
+ constructor = addConstructor(
+ output,
+ ObjectModelJavaModifier.PUBLIC);
+ addParameter(constructor, "java.util.Map<String, String>", "configuration");
+ setOperationBody(constructor, ""
+/*{
+ super(configuration);
+ }*/
+ );
+
+ ObjectModelOperation op;
+
+ // getModelVersion method
+ op = addOperation(output, "newPersistenceContext", persistenceContextConcreteName, ObjectModelJavaModifier.PUBLIC);
+ addAnnotation(output, op, Override.class);
+ setOperationBody(op, ""
+/*{
+ <%=persistenceContextConcreteName%> newContext = new <%=persistenceContextConcreteName%>(
+ getHibernateProvider(), getTopiaListenableSupport(), getTopiaIdFactory());
+ registerPersistenceContext(newContext);
+ return newContext;
+ }*/
+ );
+
+ // getModelVersion method
+ String modelVersion = model.getVersion();
+ op = addOperation(output, "getModelVersion", "String", ObjectModelJavaModifier.PUBLIC);
+ setOperationBody(op, ""
+/*{
+ return "<%=modelVersion%>";
+ }*/
+ );
+
+ // getModelName method
+ op = addOperation(output, "getModelName", "String", ObjectModelJavaModifier.PUBLIC);
+ setOperationBody(op, ""
+/*{
+ return "<%=modelName%>";
+ }*/
+ );
+
+ // getContractClass method
+ op = addOperation(output, "getContractClass", "<T extends TopiaEntity> Class<T>", ObjectModelJavaModifier.PUBLIC);
+ addParameter(op, "Class<T>", "klass");
+ setOperationBody(op, ""
+/*{
+ <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass);
+ return (Class<T>) constant.getContract();
+ }*/
+ );
+
+ // getImplementationClass method
+ op = addOperation(output, "getImplementationClass", "<T extends TopiaEntity> Class<T>", ObjectModelJavaModifier.PUBLIC);
+ addParameter(op, "Class<T>", "klass");
+ setOperationBody(op, ""
+/*{
+ <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass);
+ return (Class<T>) constant.getImplementation();
+ }*/
+ );
+
+ // getContractClasses method
+ op = addOperation(output, "getContractClasses", "Class<? extends TopiaEntity>[]", ObjectModelJavaModifier.PUBLIC);
+ setOperationBody(op, ""
+/*{
+ <%=entityEnumName%>[] values = <%=entityEnumName%>.values();
+ Class<? extends TopiaEntity>[] result = (Class<? extends TopiaEntity>[]) Array.newInstance(Class.class, values.length);
+ for (int i = 0; i < values.length; i++) {
+ result[i] = values[i].getContract();
+ }
+ return result;
+ }*/
+ );
+
+ // getImplementationClasses method
+ op = addOperation(output, "getImplementationClasses", "Class<? extends TopiaEntity>[]", ObjectModelJavaModifier.PUBLIC);
+ setOperationBody(op, ""
+/*{
+ <%=entityEnumName%>[] values = <%=entityEnumName%>.values();
+ Class<? extends TopiaEntity>[] result = (Class<? extends TopiaEntity>[]) Array.newInstance(Class.class, values.length);
+ for (int i = 0; i < values.length; i++) {
+ result[i] = values[i].getImplementation();
+ }
+ return result;
+ }*/
+ );
+
+ // getContracts method
+ op = addOperation(output, "getContracts", entityEnumName + "[]", ObjectModelJavaModifier.PUBLIC);
+ setOperationBody(op, ""
+/*{
+ return <%=entityEnumName%>.values();
+ }*/
+ );
+
+ if (generateOperator) {
+ // getOperator method
+ op = addOperation(output, "getOperator", "<T extends TopiaEntity> EntityOperator<T>", ObjectModelJavaModifier.PUBLIC);
+ addParameter(op, "Class<T>", "klass");
+ setOperationBody(op, ""
+/*{
+ <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass);
+ return EntityOperatorStore.getOperator(constant);
+ }*/
+ );
+ }
+
+ }
+
+ protected ObjectModelClass generateImpl(String packageName,
+ String applicationContextAbstractName,
+ String applicationContextConcreteName) {
+
+ ObjectModelClass output = createClass(applicationContextConcreteName, packageName);
+
+ setSuperClass(output, applicationContextAbstractName);
+
+ // add public constructor
+ ObjectModelOperation constructor = addConstructor(
+ output,
+ ObjectModelJavaModifier.PUBLIC);
+ addParameter(constructor, Properties.class, "properties");
+ setOperationBody(constructor, ""
+/*{
+ super(properties);
+ }*/
+ );
+
+ constructor = addConstructor(
+ output,
+ ObjectModelJavaModifier.PUBLIC);
+ addParameter(constructor, "java.util.Map<String, String>", "configuration");
+ setOperationBody(constructor, ""
+/*{
+ super(configuration);
+ }*/
+ );
+
+ return output;
+ }
+
+}
Copied: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/BinderHelperTransformer.java (from rev 2882, trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/BinderHelperTransformer.java)
===================================================================
--- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/BinderHelperTransformer.java (rev 0)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/BinderHelperTransformer.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,249 @@
+package org.nuiton.topia.templates;
+
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.eugene.GeneratorUtil;
+import org.nuiton.eugene.java.ObjectModelTransformerToJava;
+import org.nuiton.eugene.models.object.*;
+import org.nuiton.topia.persistence.TopiaEntity;
+import org.nuiton.topia.persistence.util.TopiaEntityBinder;
+import org.nuiton.topia.persistence.util.TopiaEntityHelper;
+import org.nuiton.util.beans.BinderModelBuilder;
+import org.nuiton.util.beans.BinderFactory;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+
+/*{generator option: parentheses = false}*/
+/*{generator option: writeString = +}*/
+
+/**
+ * A template to generate a helper for {@link TopiaEntityBinder}.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @version $Id$
+ * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.templates.BinderHelperTransformer"
+ * @since 2.3.1
+ */
+public class BinderHelperTransformer extends ObjectModelTransformerToJava {
+
+ private static final Log log =
+ LogFactory.getLog(BinderHelperTransformer.class);
+
+
+ @Override
+ public void transformFromModel(ObjectModel model) {
+ ObjectModelClass resultClass;
+
+ List<ObjectModelClass> classes = TopiaGeneratorUtil.getEntityClasses(model, true);
+
+ if (CollectionUtils.isEmpty(classes)) {
+
+ // no entity classes, so no generation
+ log.warn("No entity to generate, " + getClass().getName() + " is skipped");
+ return;
+ }
+
+ String packageName = getOutputProperties().getProperty(PROP_DEFAULT_PACKAGE);
+ String modelName = model.getName();
+ String binderHelperClazzName = modelName + "BinderHelper";
+ String daoHelperClazzName = modelName + "DAOHelper";
+
+ resultClass = createClass(binderHelperClazzName, packageName);
+
+ setSuperClass(resultClass, BinderFactory.class);
+
+
+ addImport(resultClass, TopiaEntityBinder.class);
+ addImport(resultClass, TopiaEntityHelper.class);
+ addImport(resultClass, TopiaEntity.class);
+ addImport(resultClass, BinderModelBuilder.class);
+
+ ObjectModelOperation op;
+
+ op = addOperation(resultClass,
+ "getTopiaBinder",
+ "<E extends TopiaEntity> TopiaEntityBinder<E>",
+ ObjectModelJavaModifier.PUBLIC,
+ ObjectModelJavaModifier.STATIC);
+ addParameter(op, "Class<E>", "entityClass");
+ addParameter(op, "String", "contextName");
+ setOperationBody(op, ""
+/*{
+ return (TopiaEntityBinder<E>) newBinder(entityClass, entityClass, contextName, TopiaEntityBinder.class);
+ }*/
+ );
+
+ op = addOperation(resultClass,
+ "getSimpleTopiaBinder",
+ "<E extends TopiaEntity> TopiaEntityBinder<E>",
+ ObjectModelJavaModifier.PUBLIC,
+ ObjectModelJavaModifier.STATIC);
+ addParameter(op, "Class<E>", "entityClass");
+ setOperationBody(op, ""
+/*{
+ return getTopiaBinder(entityClass, "<%=modelName%>");
+ }*/
+ );
+
+ op = addOperation(resultClass,
+ "registerTopiaBinder",
+ "void",
+ ObjectModelJavaModifier.PUBLIC,
+ ObjectModelJavaModifier.STATIC);
+ addParameter(op, "BinderModelBuilder", "builder");
+ addParameter(op, "String", "contextName");
+ setOperationBody(op, ""
+/*{
+ registerBinderModel(builder, contextName);
+ }*/
+ );
+
+ op = addOperation(resultClass,
+ "registerTopiaBinder",
+ "<E extends TopiaEntity> TopiaEntityBinder<E>",
+ ObjectModelJavaModifier.PUBLIC,
+ ObjectModelJavaModifier.STATIC);
+ addParameter(op, "Class<E>", "entityClass");
+ addParameter(op, "BinderModelBuilder", "builder");
+ addParameter(op, "String", "contextName");
+ setOperationBody(op, ""
+/*{
+ registerBinderModel(builder, contextName);
+ return getTopiaBinder(entityClass, contextName);
+ }*/
+ );
+
+ op = addOperation(resultClass,
+ "copy",
+ "<E extends TopiaEntity> void",
+ ObjectModelJavaModifier.PUBLIC,
+ ObjectModelJavaModifier.STATIC);
+ addParameter(op, "String", "contextName");
+ addParameter(op, "E", "source");
+ addParameter(op, "E", "target");
+ addParameter(op, "boolean", "tech");
+ setOperationBody(op, ""
+/*{
+ Class<E> entityClass = (Class<E>) TopiaEntityHelper.getContractClass(<%=daoHelperClazzName%>.getContracts(), target.getClass());
+ TopiaEntityBinder<E> binder = getTopiaBinder(entityClass, contextName);
+ if (binder == null) {
+ throw new NullPointerException("could not find a simple topia binder of type : " + target.getClass());
+ }
+ binder.load(source, target, tech);
+ }*/
+ );
+
+ op = addOperation(resultClass,
+ "simpleCopy",
+ "<E extends TopiaEntity> void",
+ ObjectModelJavaModifier.PUBLIC,
+ ObjectModelJavaModifier.STATIC);
+ addParameter(op, "E", "source");
+ addParameter(op, "E", "target");
+ addParameter(op, "boolean", "tech");
+ setOperationBody(op, ""
+/*{
+ Class<E> entityClass = (Class<E>) TopiaEntityHelper.getContractClass(<%=daoHelperClazzName%>.getContracts(), target.getClass());
+ TopiaEntityBinder<E> binder = getSimpleTopiaBinder(entityClass);
+ if (binder == null) {
+ throw new NullPointerException("could not find a simple topia binder of type : " + target.getClass());
+ }
+ binder.load(source, target, tech);
+ }*/
+ );
+
+ StringBuilder initCode = new StringBuilder();
+
+ for (ObjectModelClass clazz : classes) {
+
+ String prefix = getConstantPrefix(clazz, "");
+
+ if (StringUtils.isEmpty(prefix)) {
+
+ // no specific prefix, so no prefix
+ if (log.isWarnEnabled()) {
+ log.warn("[" + clazz.getName() + "] Will generate constants with NO prefix, not a good idea...");
+ }
+ }
+
+ setConstantPrefix(prefix);
+
+ generateBinder(modelName, clazz, resultClass, initCode);
+
+ }
+
+ op = addOperation(resultClass, "initBinders", "void", ObjectModelJavaModifier.PROTECTED, ObjectModelJavaModifier.STATIC);
+ setOperationBody(op, initCode.toString());
+
+ op = addOperation(resultClass, null, (String) null, ObjectModelJavaModifier.STATIC);
+ setOperationBody(op, ""
+ /*{
+ initBinders();
+}*/
+ );
+ }
+
+ protected void generateBinder(String modelName,
+ ObjectModelClass clazz,
+ ObjectModelClass resultClass,
+ StringBuilder initCode) {
+
+ List<ObjectModelAttribute> list = new ArrayList<ObjectModelAttribute>();
+ for (ObjectModelAttribute attr : clazz.getAttributes()) {
+ if (!attr.isNavigable()) {
+ continue;
+ }
+
+ if (GeneratorUtil.isNMultiplicity(attr)) {
+ // not dealing with association
+ continue;
+ }
+
+ list.add(attr);
+ }
+
+ String clazzName = clazz.getName();
+
+ if (list.isEmpty()) {
+ // no attribute, do nothing
+ if (log.isDebugEnabled()) {
+ log.debug("no attribute to add in a binder for " + clazzName +
+ ", will not generate it.");
+ }
+ return;
+ }
+
+ if (log.isDebugEnabled()) {
+ log.debug("generate simple binder for " + clazzName);
+ }
+ addImport(resultClass, clazz);
+ initCode.append(""
+/*{
+ BinderModelBuilder<<%=clazzName%>, <%=clazzName%>> builder<%=clazzName%> =
+ BinderModelBuilder.newEmptyBuilder(<%=clazzName%>.class);
+ builder<%=clazzName%>.addSimpleProperties(
+}*/
+ );
+ Iterator<ObjectModelAttribute> itr = list.iterator();
+ while (itr.hasNext()) {
+ ObjectModelAttribute attr = itr.next();
+ String attrName = attr.getName();
+ boolean hasNext = itr.hasNext();
+ initCode.append(""
+/*{ <%=clazzName%>.<%=getConstantName(attrName)%><%=(hasNext?",\n":"")%>}*/
+ );
+ }
+ initCode.append(""
+/*{
+ );
+ registerTopiaBinder(builder<%=clazzName%>, "<%=modelName%>");
+ }*/
+ );
+ }
+}
+
Copied: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/DAOHelperTransformer.java (from rev 2882, trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DAOHelperTransformer.java)
===================================================================
--- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/DAOHelperTransformer.java (rev 0)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/DAOHelperTransformer.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,501 @@
+package org.nuiton.topia.templates;
+
+import org.apache.commons.lang3.ArrayUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.eugene.java.ObjectModelTransformerToJava;
+import org.nuiton.eugene.models.object.ObjectModel;
+import org.nuiton.eugene.models.object.ObjectModelAttribute;
+import org.nuiton.eugene.models.object.ObjectModelClass;
+import org.nuiton.eugene.models.object.ObjectModelEnumeration;
+import org.nuiton.eugene.models.object.ObjectModelJavaModifier;
+import org.nuiton.eugene.models.object.ObjectModelOperation;
+import org.nuiton.eugene.models.object.ObjectModelType;
+import org.nuiton.eugene.models.object.xml.ObjectModelAttributeImpl;
+import org.nuiton.eugene.models.object.xml.ObjectModelEnumerationImpl;
+import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.TopiaDaoSupplier;
+import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.persistence.TopiaDAO;
+import org.nuiton.topia.persistence.TopiaEntity;
+import org.nuiton.topia.persistence.TopiaEntityEnum;
+import org.nuiton.topia.persistence.util.EntityOperator;
+import org.nuiton.topia.persistence.util.EntityOperatorStore;
+
+import java.lang.reflect.Array;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Set;
+
+
+/*{generator option: parentheses = false}*/
+
+/*{generator option: writeString = +}*/
+
+/**
+ * Created: 13 nov. 2009 09:05:17
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @version $Id$
+ * @since 2.3.0
+ * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.templates.DAOHelperTransformer"
+ */
+public class DAOHelperTransformer extends ObjectModelTransformerToJava {
+
+ private static final Log log =
+ LogFactory.getLog(DAOHelperTransformer.class);
+
+ @Override
+ public void transformFromModel(ObjectModel model) {
+ String packageName =
+ getOutputProperties().getProperty(PROP_DEFAULT_PACKAGE);
+ String modelName = model.getName();
+ String daoHelperClazzName = modelName + "DAOHelper";
+ String entityEnumName = modelName + "EntityEnum";
+
+ List<ObjectModelClass> classes =
+ TopiaGeneratorUtil.getEntityClasses(model, true);
+
+ boolean generateOperator =
+ TopiaGeneratorUtil.shouldGenerateOperatorForDAOHelper(model);
+
+ boolean generateStandaloneEnum =
+ TopiaGeneratorUtil.shouldGenerateStandaloneEnumForDAOHelper(model);
+
+ ObjectModelClass daoHelper = createClass(daoHelperClazzName,
+ packageName);
+
+ ObjectModelEnumeration entityEnum;
+
+ if (generateStandaloneEnum) {
+ if (log.isDebugEnabled()) {
+ log.debug("Will generate standalone " + entityEnumName +
+ " in package " + packageName);
+ }
+ entityEnum = createEnumeration(entityEnumName, packageName);
+ addImport(entityEnum, TopiaEntity.class);
+ addImport(entityEnum, EntityOperatorStore.class);
+ addImport(entityEnum, Arrays.class);
+ addImport(entityEnum, ArrayUtils.class);
+
+ } else {
+ entityEnum = (ObjectModelEnumerationImpl)
+ addInnerClassifier(daoHelper,
+ ObjectModelType.OBJECT_MODEL_ENUMERATION,
+ entityEnumName
+ );
+ addImport(daoHelper, TopiaEntityEnum.class);
+ addImport(daoHelper, EntityOperatorStore.class);
+ addImport(daoHelper, Arrays.class);
+ addImport(daoHelper, ArrayUtils.class);
+ }
+
+ // generate DAOHelper
+ createDAOHelper(model,
+ daoHelper,
+ daoHelperClazzName,
+ entityEnumName,
+ generateOperator,
+ classes
+ );
+
+ // generate TopiaEntityEnum
+ createEntityEnum(entityEnum,
+ daoHelperClazzName,
+ entityEnumName,
+ generateOperator,
+ generateStandaloneEnum,
+ classes
+ );
+ }
+
+ protected void createDAOHelper(ObjectModel model,
+ ObjectModelClass daoHelper,
+ String daoHelperClazzName,
+ String entityEnumName,
+ boolean generateOperator,
+ List<ObjectModelClass> classes) {
+
+ String modelName = model.getName();
+ String modelVersion = model.getVersion();
+
+ addImport(daoHelper, TopiaDAO.class);
+ addImport(daoHelper, TopiaEntity.class);
+ addImport(daoHelper, TopiaContext.class);
+ addImport(daoHelper, Array.class);
+
+ if (generateOperator) {
+ addImport(daoHelper,EntityOperator.class);
+ addImport(daoHelper, EntityOperatorStore.class);
+ }
+
+ addAnnotation(daoHelper, daoHelper, Deprecated.class);
+
+ // add non public constructor
+ ObjectModelOperation constructor =
+ addConstructor(daoHelper, ObjectModelJavaModifier.PROTECTED);
+ setOperationBody(constructor," ");
+
+ ObjectModelOperation op;
+
+ // getModelVersion method
+ op = addOperation(daoHelper, "getModelVersion", "String", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
+ setOperationBody(op, ""
+/*{
+ return "<%=modelVersion%>";
+ }*/
+ );
+
+ // getModelName method
+ op = addOperation(daoHelper, "getModelName", "String", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
+ setOperationBody(op, ""
+/*{
+ return "<%=modelName%>";
+ }*/
+ );
+
+
+ for (ObjectModelClass clazz : classes) {
+ String clazzName = clazz.getName();
+ String daoClazzName = clazzName + "DAO";
+
+ // specialized getXXXDao method
+ op = addOperation(daoHelper, "get" + daoClazzName, clazz.getPackageName() + '.' + daoClazzName, ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
+ addParameter(op, TopiaDaoSupplier.class, "supplier");
+ addImport(daoHelper, clazz);
+ addException(op, TopiaException.class);
+ setOperationBody(op, ""
+/*{
+ <%=daoClazzName%> result = supplier.getDao(<%=clazzName%>.class, <%=daoClazzName%>.class);
+ return result;
+ }*/
+ );
+
+ }
+
+ // obsolete generic getDAO method
+ op = addOperation(daoHelper, "getDAO", "<T extends TopiaEntity, D extends TopiaDAO<? super T>> D", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
+ addParameter(op, TopiaContext.class, "context");
+ addParameter(op, "Class<T>", "klass");
+ addException(op, TopiaException.class);
+ addAnnotation(daoHelper, op, Deprecated.class);
+ setOperationBody(op, ""
+/*{
+ D dao = getDao(context, klass);
+ return dao;
+ }*/
+ );
+
+ // generic getDao method
+ op = addOperation(daoHelper, "getDao", "<T extends TopiaEntity, D extends TopiaDAO<? super T>> D", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
+ addParameter(op, TopiaContext.class, "context");
+ addParameter(op, "Class<T>", "klass");
+ addException(op, TopiaException.class);
+ setOperationBody(op, ""
+/*{
+ <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass);
+ D dao = (D) context.getDao(constant.getContract());
+ return dao;
+ }*/
+ );
+
+ op = addOperation(daoHelper, "getDao", "<T extends TopiaEntity, D extends TopiaDAO<? super T>> D", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
+ addParameter(op, TopiaContext.class, "context");
+ addParameter(op, "T", "entity");
+ addException(op, TopiaException.class);
+ setOperationBody(op, ""
+/*{
+ <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(entity);
+ D dao = (D) context.getDao(constant.getContract());
+ return dao;
+ }*/
+ );
+
+ // getContractClass method
+ op = addOperation(daoHelper, "getContractClass", "<T extends TopiaEntity> Class<T>", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
+ addParameter(op, "Class<T>", "klass");
+ setOperationBody(op, ""
+/*{
+ <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass);
+ return (Class<T>) constant.getContract();
+ }*/
+ );
+
+ // getImplementationClass method
+ op = addOperation(daoHelper, "getImplementationClass", "<T extends TopiaEntity> Class<T>", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
+ addParameter(op, "Class<T>", "klass");
+ setOperationBody(op, ""
+/*{
+ <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass);
+ return (Class<T>) constant.getImplementation();
+ }*/
+ );
+
+ // getContractClasses method
+ op = addOperation(daoHelper, "getContractClasses", "Class<? extends TopiaEntity>[]", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
+ setOperationBody(op, ""
+/*{
+ <%=entityEnumName%>[] values = <%=entityEnumName%>.values();
+ Class<? extends TopiaEntity>[] result = (Class<? extends TopiaEntity>[]) Array.newInstance(Class.class, values.length);
+ for (int i = 0; i < values.length; i++) {
+ result[i] = values[i].getContract();
+ }
+ return result;
+ }*/
+ );
+
+ // getImplementationClasses method
+ op = addOperation(daoHelper, "getImplementationClasses", "Class<? extends TopiaEntity>[]", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
+ setOperationBody(op, ""
+/*{
+ <%=entityEnumName%>[] values = <%=entityEnumName%>.values();
+ Class<? extends TopiaEntity>[] result = (Class<? extends TopiaEntity>[]) Array.newInstance(Class.class, values.length);
+ for (int i = 0; i < values.length; i++) {
+ result[i] = values[i].getImplementation();
+ }
+ return result;
+ }*/
+ );
+
+ // getImplementationClassesAsString method
+ op = addOperation(daoHelper, "getImplementationClassesAsString", "String", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
+ setOperationBody(op, ""
+/*{
+ StringBuilder buffer = new StringBuilder();
+ for (Class<? extends TopiaEntity> aClass : getImplementationClasses()) {
+ buffer.append(',').append(aClass.getName());
+ }
+ return buffer.substring(1);
+ }*/
+ );
+
+ // getContracts method
+ op = addOperation(daoHelper, "getContracts", entityEnumName+"[]", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
+ setOperationBody(op, ""
+/*{
+ return <%=entityEnumName%>.values();
+ }*/
+ );
+
+ if (generateOperator) {
+ // getOperator method
+ op = addOperation(daoHelper, "getOperator", "<T extends TopiaEntity> EntityOperator<T>", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
+ addParameter(op,"Class<T>","klass");
+ setOperationBody(op, ""
+/*{
+ <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass);
+ return EntityOperatorStore.getOperator(constant);
+ }*/
+ );
+ }
+ }
+
+ protected void createEntityEnum(ObjectModelEnumeration entityEnum,
+ String daoHelperClazzName,
+ String entityEnumName,
+ boolean generateOperator,
+ boolean generateStandaloneEnum,
+ List<ObjectModelClass> classes) {
+
+ ObjectModelAttributeImpl attr;
+ ObjectModelOperation op;
+
+ addInterface(entityEnum, TopiaEntityEnum.class);
+
+ for (ObjectModelClass clazz : classes) {
+ String clazzName = clazz.getName();
+
+ boolean withNatural = false;
+ boolean withNotNull = false;
+ StringBuilder naturalIdsParams = new StringBuilder();
+ StringBuilder notNullParams = new StringBuilder();
+
+ Set<ObjectModelAttribute> naturalIdsAttributes = TopiaGeneratorUtil.getNaturalIdAttributes(clazz);
+ for (ObjectModelAttribute attribute: naturalIdsAttributes) {
+ withNatural = true;
+ // attribut metier
+ naturalIdsParams.append(", \"").append(attribute.getName()).append("\"");
+ }
+ Set<ObjectModelAttribute> notNullIdsAttributes = TopiaGeneratorUtil.getNotNullAttributes(clazz);
+ for (ObjectModelAttribute attribute : notNullIdsAttributes) {
+ withNotNull = true;
+ // attribut not-null
+ notNullParams.append(", \"").append(attribute.getName()).append("\"");
+ }
+
+ StringBuilder params = new StringBuilder(clazzName + ".class");
+ if (withNotNull) {
+ params.append(", new String[]{ " + notNullParams.substring(2) + " }");
+ } else {
+ params.append(", ArrayUtils.EMPTY_STRING_ARRAY");
+ }
+ if (withNatural) {
+ params.append(", ").append(naturalIdsParams.substring(2));
+ }
+ addLiteral(entityEnum, clazzName + '(' + params.toString() + ')');
+
+ if (generateStandaloneEnum) {
+ addImport(entityEnum, clazz);
+ }
+ }
+
+ attr = (ObjectModelAttributeImpl) addAttribute(entityEnum, "contract", "Class<? extends TopiaEntity>");
+ attr.setDocumentation("The contract of the entity.");
+
+ attr = (ObjectModelAttributeImpl) addAttribute(entityEnum, "implementationFQN", "String");
+ attr.setDocumentation("The fully qualified name of the implementation of the entity.");
+
+ attr = (ObjectModelAttributeImpl) addAttribute(entityEnum, "implementation", "Class<? extends TopiaEntity>");
+ attr.setDocumentation("The implementation class of the entity (will be lazy computed at runtime).");
+
+ attr = (ObjectModelAttributeImpl) addAttribute(entityEnum, "naturalIds", "String[]");
+ attr.setDocumentation("The array of property involved in the natural key of the entity.");
+
+ attr = (ObjectModelAttributeImpl) addAttribute(entityEnum, "notNulls", "String[]");
+ attr.setDocumentation("The array of not null properties of the entity.");
+
+ // constructor
+ op = addConstructor(entityEnum, ObjectModelJavaModifier.PACKAGE);
+ addParameter(op,"Class<? extends TopiaEntity >","contract");
+ addParameter(op,"String[]","notNulls");
+ addParameter(op,"String...","naturalIds");
+ setOperationBody(op, ""
+/*{
+ this.contract = contract;
+ this.notNulls = Arrays.copyOf(notNulls, notNulls.length);
+ this.naturalIds = naturalIds;
+ implementationFQN = contract.getName() + "Impl";
+ }*/
+ );
+
+ // getContract method
+ op = addOperation(entityEnum, "getContract", "Class<? extends TopiaEntity>", ObjectModelJavaModifier.PUBLIC);
+ addAnnotation(entityEnum,op,Override.class);
+ setOperationBody(op, ""
+/*{
+ return contract;
+ }*/
+ );
+
+ // getNaturalIds method
+ op = addOperation(entityEnum, "getNaturalIds", "String[]", ObjectModelJavaModifier.PUBLIC);
+ addAnnotation(entityEnum,op,Override.class);
+ setOperationBody(op, ""
+/*{
+ return naturalIds;
+ }*/
+ );
+
+ // isUseNaturalIds method
+ op = addOperation(entityEnum, "isUseNaturalIds", "boolean", ObjectModelJavaModifier.PUBLIC);
+ addAnnotation(entityEnum,op,Override.class);
+ setOperationBody(op, ""
+/*{
+ return naturalIds.length > 0;
+ }*/
+ );
+
+ // getNotNulls method
+ op = addOperation(entityEnum, "getNotNulls", "String[]", ObjectModelJavaModifier.PUBLIC);
+ addAnnotation(entityEnum,op,Override.class);
+ setOperationBody(op, ""
+/*{
+ return notNulls;
+ }*/
+ );
+
+ // isUseNotNulls method
+ op = addOperation(entityEnum, "isUseNotNulls", "boolean", ObjectModelJavaModifier.PUBLIC);
+ addAnnotation(entityEnum,op,Override.class);
+ setOperationBody(op, ""
+/*{
+ return notNulls.length > 0;
+ }*/
+ );
+
+ // getImplementationFQN method
+ op = addOperation(entityEnum, "getImplementationFQN","String",ObjectModelJavaModifier.PUBLIC);
+ addAnnotation(entityEnum, op, Override.class);
+ setOperationBody(op, ""
+/*{
+ return implementationFQN;
+ }*/
+ );
+
+ // setImplementationFQN method
+ op = addOperation(entityEnum, "setImplementationFQN","void",ObjectModelJavaModifier.PUBLIC);
+ addAnnotation(entityEnum,op,Override.class);
+ addParameter(op,"String","implementationFQN");
+ if (generateOperator) {
+ setOperationBody(op, ""
+/*{
+ this.implementationFQN = implementationFQN;
+ implementation = null;
+ // reinit the operators store
+ EntityOperatorStore.clear();
+ }*/
+ );
+ } else {
+ setOperationBody(op, ""
+/*{
+ this.implementationFQN = implementationFQN;
+ this.implementation = null;
+ }*/
+ );
+ }
+
+ // accept method
+ op = addOperation(entityEnum, "accept","boolean",ObjectModelJavaModifier.PUBLIC);
+ addAnnotation(entityEnum,op,Override.class);
+ addParameter(op,"Class<? extends TopiaEntity>","klass");
+ setOperationBody(op, ""
+/*{
+ return <%=daoHelperClazzName%>.getContractClass(klass) == contract;
+ }*/
+ );
+
+ // getImplementation method
+ op = addOperation(entityEnum, "getImplementation","Class<? extends TopiaEntity>",ObjectModelJavaModifier.PUBLIC);
+ addAnnotation(entityEnum,op,Override.class);
+ addImport(entityEnum, TopiaException.class);
+ setOperationBody(op, ""
+/*{
+ if (implementation == null) {
+ try {
+ implementation = (Class<? extends TopiaEntity>) Class.forName(implementationFQN);
+ } catch (ClassNotFoundException e) {
+ throw new TopiaException("could not find class " + implementationFQN, e);
+ }
+ }
+ return implementation;
+ }*/
+ );
+
+ // valueOf method
+ op = addOperation(entityEnum, "valueOf", entityEnumName, ObjectModelJavaModifier.PUBLIC,ObjectModelJavaModifier.STATIC);
+ addParameter(op,"TopiaEntity", "entity");
+ setOperationBody(op, ""
+/*{
+ return valueOf(entity.getClass());
+ }*/
+ );
+
+ // valueOf method
+ op = addOperation(entityEnum, "valueOf", entityEnumName, ObjectModelJavaModifier.PUBLIC,ObjectModelJavaModifier.STATIC);
+ addParameter(op,"Class<?>", "klass");
+ setOperationBody(op, ""
+/*{
+ if (klass.isInterface()) {
+ return valueOf(klass.getSimpleName());
+ }
+ for (<%=entityEnumName%> entityEnum : <%=entityEnumName%>.values()) {
+ if (entityEnum.getContract().isAssignableFrom(klass)) {
+ //todo check it works for inheritance
+ return entityEnum;
+ }
+ }
+ throw new IllegalArgumentException("no entity defined for the class " + klass + " in : " + Arrays.toString(<%=entityEnumName%>.values()));
+ }*/
+ );
+ }
+}
Copied: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/DTOTransformer.java (from rev 2882, trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DTOTransformer.java)
===================================================================
--- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/DTOTransformer.java (rev 0)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/DTOTransformer.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,437 @@
+package org.nuiton.topia.templates;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.builder.ToStringBuilder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.eugene.GeneratorUtil;
+import org.nuiton.eugene.java.ObjectModelTransformerToJava;
+import org.nuiton.eugene.models.object.*;
+
+import java.beans.PropertyChangeListener;
+import java.beans.PropertyChangeSupport;
+import java.io.Serializable;
+import java.util.Collection;
+import java.util.List;
+
+
+/*{generator option: parentheses = false}*/
+
+/*{generator option: writeString = +}*/
+
+/**
+ * Created: 20 déc. 2009
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @version $Id$
+ * @since 2.3.0
+ * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.templates.DTOTransformer"
+ */
+public class DTOTransformer extends ObjectModelTransformerToJava {
+
+ /**
+ * Logger
+ */
+ private static final Log log = LogFactory.getLog(DTOTransformer.class);
+
+ @Override
+ public void transformFromClass(ObjectModelClass clazz) {
+ if (!TopiaGeneratorUtil.hasDtoStereotype(clazz)) {
+ return;
+ }
+ String clazzName = clazz.getName();
+ ObjectModelClass result;
+ result = createClass(clazzName + "DTO", clazz.getPackageName());
+ addImport(result, ToStringBuilder.class);
+ addImport(result, PropertyChangeListener.class);
+
+ setDocumentation(result, "Implantation DTO pour l'entité " + StringUtils.capitalize(clazzName) + ".");
+ String extendClass = "";
+ for (ObjectModelClass parent : clazz.getSuperclasses()) {
+ extendClass = parent.getQualifiedName() + "DTO";
+ // no multi-inheritance in java
+ break;
+ }
+ if (extendClass.length() > 0) {
+ setSuperClass(result, extendClass);
+ }
+
+ addInterface(result, Serializable.class);
+ for (ObjectModelInterface parentInterface : clazz.getInterfaces()) {
+ if (TopiaGeneratorUtil.hasDtoStereotype(parentInterface)) {
+ addInterface(result, parentInterface.getName() + "DTO");
+ } else {
+ addInterface(result, parentInterface.getName());
+ }
+ }
+
+ addAttributes(result, clazz);
+
+ addOperations(result, clazz);
+ }
+
+ protected void addAttributes(ObjectModelClass result, ObjectModelClass clazz) {
+
+ String svUID = TopiaGeneratorUtil.findTagValue("dto-serialVersionUID", clazz, model);
+ if (StringUtils.isNotEmpty(svUID)) {
+ addAttribute(result, "serialVersionUID", long.class, svUID, ObjectModelJavaModifier.FINAL, ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
+ }
+
+ addAttribute(result, "p", PropertyChangeSupport.class, null, ObjectModelJavaModifier.PROTECTED);
+
+/*
+* Définition des attributs
+*/
+ ObjectModelAttribute attr2;
+ for (ObjectModelAttribute attr : clazz.getAttributes()) {
+ ObjectModelAttribute reverse = attr.getReverseAttribute();
+
+ String attributeName;
+ String attributeType;
+ if (!(attr.isNavigable()
+ || attr.hasAssociationClass())) {
+ continue;
+ }
+
+ String attrName = attr.getName();
+ String attrVisibility = attr.getVisibility();
+ String attrType = attr.getType();
+ if (!GeneratorUtil.isNMultiplicity(attr)) {
+ if (!attr.hasAssociationClass()) {
+ if (isDTO(attrType)) {
+ attrType += "DTO";
+ }
+ attributeType = attrType;
+ attributeName = attrName;
+ } else {
+ String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(attr);
+ attributeType = attr.getAssociationClass().getQualifiedName();
+ attributeName = GeneratorUtil.toLowerCaseFirstLetter(assocAttrName);
+ }
+ } else {
+ if (!attr.hasAssociationClass()) {
+ String nMultType;
+ if (attr.isOrdered()) {
+ nMultType = List.class.getName() + "<";
+ } else {
+ nMultType = Collection.class.getName() + "<";
+ }
+ nMultType += attrType;
+ if (isDTO(attrType)) {
+ nMultType += "DTO";
+ }
+ nMultType += ">";
+
+ attributeType = nMultType;
+ attributeName = attrName;
+ } else {
+ String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(attr);
+ String assocClassFQN = attr.getAssociationClass().getQualifiedName();
+ String nMultType;
+ if (attr.isOrdered()) {
+ nMultType = List.class.getName() + "<";
+ } else {
+ nMultType = Collection.class.getName() + "<";
+ }
+ nMultType += assocClassFQN;
+ if (isDTO(attrType)) {
+ nMultType += "DTO";
+ }
+ nMultType += ">";
+ attributeType = nMultType;
+ attributeName = GeneratorUtil.toLowerCaseFirstLetter(assocAttrName);
+ }
+ }
+
+ attr2 = addAttribute(result, attributeName, attributeType, null, ObjectModelJavaModifier.PROTECTED);
+
+ if (attr2 != null) {
+ if (TopiaGeneratorUtil.hasDocumentation(attr)) {
+ setDocumentation(attr2, attr.getDocumentation());
+ }
+ String annotation = TopiaGeneratorUtil.getAnnotationTagValue(attr);
+ if (StringUtils.isNotEmpty(annotation)) {
+ addAnnotation(result, attr2, annotation);
+ }
+ }
+ } /* end for*/
+
+ //Déclaration des attributs d'une classe d'associations
+ if (clazz instanceof ObjectModelAssociationClass) {
+ ObjectModelAssociationClass assoc = (ObjectModelAssociationClass) clazz;
+ for (ObjectModelAttribute attr : assoc.getParticipantsAttributes()) {
+ if (attr != null) {
+ String attrName = attr.getName();
+ String attrVisibility = attr.getVisibility();
+ String attrType = attr.getType();
+ if (isDTO(attrType)) {
+ attrType += "DTO";
+ }
+ addAttribute(result, GeneratorUtil.toLowerCaseFirstLetter(attrName), attrType);
+ }
+ }
+ }
+
+ }
+
+ protected void addOperations(ObjectModelClass result, ObjectModelClass clazz) {
+ ObjectModelOperation op;
+ op = addOperation(result, "addPropertyChangeListener", "void", ObjectModelJavaModifier.PUBLIC);
+ addParameter(op, PropertyChangeListener.class, "listener");
+ setOperationBody(op, ""
+/*{
+ p.addPropertyChangeListener(listener);
+ }*/
+ );
+
+ op = addOperation(result, "addPropertyChangeListener", "void", ObjectModelJavaModifier.PUBLIC);
+ addParameter(op, String.class, "propertyName");
+ addParameter(op, PropertyChangeListener.class, "listener");
+ setOperationBody(op, ""
+/*{
+ p.addPropertyChangeListener(propertyName, listener);
+ }*/
+ );
+
+ op = addOperation(result, "removePropertyChangeListener", "void", ObjectModelJavaModifier.PUBLIC);
+ addParameter(op, PropertyChangeListener.class, "listener");
+ setOperationBody(op, ""
+/*{
+ p.removePropertyChangeListener(listener);
+ }*/
+ );
+
+ op = addOperation(result, "removePropertyChangeListener", "void", ObjectModelJavaModifier.PUBLIC);
+ addParameter(op, String.class, "propertyName");
+ addParameter(op, PropertyChangeListener.class, "listener");
+ setOperationBody(op, ""
+/*{
+ p.removePropertyChangeListener(propertyName, listener);
+ }*/
+ );
+ /*
+ * Définition des getteurs et setteurs
+ */
+ for (ObjectModelAttribute attr : clazz.getAttributes()) {
+
+ ObjectModelAttribute reverse = attr.getReverseAttribute();
+
+// if (!(attr.isNavigable() || hasUnidirectionalRelationOnAbstractType(reverse, model))) {
+ if (!attr.isNavigable()) {
+ continue;
+ }
+
+ String attrName = attr.getName();
+ String attrType = attr.getType();
+ String attrTypeDTO = attr.getType();
+ if (isDTO(attrType)) {
+ attrTypeDTO += "DTO";
+ }
+
+ if (!GeneratorUtil.isNMultiplicity(attr)) {
+ if (!attr.hasAssociationClass()) {
+ op = addOperation(result, "set" + StringUtils.capitalize(attrName), "void", ObjectModelJavaModifier.PUBLIC);
+ addParameter(op, attrTypeDTO, "value");
+ setOperationBody(op, ""
+/*{
+ <%=attrTypeDTO%> oldValue = this.<%=attrName%>;
+ this.<%=attrName%> = value;
+ p.firePropertyChange("<%=attrName%>", oldValue, value);
+ }*/
+ );
+
+ op = addOperation(result, "get" + StringUtils.capitalize(attrName), attrTypeDTO, ObjectModelJavaModifier.PUBLIC);
+ setOperationBody(op, ""
+/*{
+ return <%=attrName%>;
+ }*/
+ );
+
+ } else {
+ String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(attr);
+ String assocClassFQN = attr.getAssociationClass().getQualifiedName();
+ if (log.isTraceEnabled()) {
+ log.trace("assocAttrName: " + assocAttrName);
+ }
+ op = addOperation(result, "set" + StringUtils.capitalize(assocAttrName), "void", ObjectModelJavaModifier.PUBLIC);
+ addParameter(op, assocClassFQN + "DTO", "association");
+ setOperationBody(op, ""
+/*{
+ <%=assocClassFQN%>DTO oldAssocation = this.<%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%>;
+ this.<%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%> = association;
+ p.firePropertyChange("<%=attrName%>", oldAssocation, assocation);
+ }*/
+ );
+
+ op = addOperation(result, "get" + StringUtils.capitalize(assocAttrName), assocClassFQN + "DTO", ObjectModelJavaModifier.PUBLIC);
+ setOperationBody(op, ""
+/*{
+ return <%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%>;
+ }*/
+ );
+ }
+ } else { //NMultiplicity
+ if (!attr.hasAssociationClass()) { //Méthodes remplacées par des accesseurs sur les classes d'assoc
+
+ String nMultType;
+ if (attr.isOrdered()) {
+ nMultType = List.class.getName() + "<" + attrTypeDTO + ">";
+ } else {
+ nMultType = Collection.class.getName() + "<" + attrTypeDTO + ">";
+ }
+ op = addOperation(result, "set" + StringUtils.capitalize(attrName), "void", ObjectModelJavaModifier.PUBLIC);
+ addParameter(op, nMultType, "values");
+ setOperationBody(op, ""
+/*{
+ <%=nMultType%> oldValues = this.<%=attrName%>;
+ this.<%=attrName%> = values;
+ p.firePropertyChange("<%=attrName%>", oldValues, values);
+ }*/
+ );
+
+ op = addOperation(result, "addChild" + StringUtils.capitalize(attrName), attrTypeDTO, ObjectModelJavaModifier.PUBLIC);
+ addParameter(op, attrTypeDTO, attrName);
+ StringBuilder buffercode = new StringBuilder();
+
+ buffercode.append(""
+/*{
+ this.<%=attrName%>.add(<%=attrName%>);
+ }*/
+ );
+
+ if (reverse != null && reverse.isNavigable()) {
+ String reverseAttrName = reverse.getName();
+ buffercode.append(""
+/*{ <%=attrName%>.set<%=StringUtils.capitalize(reverseAttrName)%>(this);
+ }*/
+ );
+ }
+ buffercode.append(""
+/*{ return <%=attrName%>;
+ }*/
+ );
+ setOperationBody(op, buffercode.toString());
+
+ op = addOperation(result, "removeChild", "void");
+ addParameter(op, attrTypeDTO, attrName);
+
+ buffercode = new StringBuilder();
+ buffercode.append(""
+/*{
+ this.<%=attrName%>.remove(<%=attrName%>);
+ }*/
+ );
+
+ if (reverse != null && reverse.isNavigable()) {
+ String reverseAttrName = reverse.getName();
+ buffercode.append(""
+/*{ <%=attrName%>.set<%=StringUtils.capitalize(reverseAttrName)%>(null);
+ }*/
+ );
+ }
+ setOperationBody(op, buffercode.toString());
+
+ } else {
+ String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(attr);
+ String assocClassFQN = attr.getAssociationClass().getQualifiedName();
+ String nMultType;
+ if (attr.isOrdered()) {
+ nMultType = List.class.getName() + "<" + assocClassFQN + "DTO>";
+ } else {
+ nMultType = Collection.class.getName() + "<" + assocClassFQN + "DTO>";
+ }
+ if (log.isTraceEnabled()) {
+ log.trace("assocAttrName: " + assocAttrName);
+ }
+ op = addOperation(result, "set" + StringUtils.capitalize(assocAttrName), "void");
+ addParameter(op, nMultType, "values");
+ setOperationBody(op, ""
+/*{
+ <%=nMultType%> oldValues = this.<%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%>;
+ this.<%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%> = values;
+ p.firePropertyChange("<%=attrName%>", oldValues, values);
+ }*/
+ );
+ }
+ if (!attr.hasAssociationClass()) {
+ String nMultType;
+ if (attr.isOrdered()) {
+ nMultType = List.class.getName() + "<" + attrTypeDTO + ">";
+ } else {
+ nMultType = Collection.class.getName() + "<" + attrTypeDTO + ">";
+ }
+ op = addOperation(result, "get" + StringUtils.capitalize(attrName), nMultType);
+ setOperationBody(op, ""
+/*{
+ return this.<%=attrName%>;
+ }*/
+ );
+ } else {
+ String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(attr);
+ String assocClassFQN = attr.getAssociationClass().getQualifiedName();
+ String nMultType;
+ if (attr.isOrdered()) {
+ nMultType = List.class.getName() + "<" + assocClassFQN + "DTO>";
+ } else {
+ nMultType = Collection.class.getName() + "<" + assocClassFQN + "DTO>";
+ }
+ if (log.isTraceEnabled()) {
+ log.trace("assocAttrName: " + assocAttrName);
+ }
+ op = addOperation(result, "get" + StringUtils.capitalize(assocAttrName), nMultType);
+ setOperationBody(op, ""
+/*{
+ return this.<%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%>;
+ }*/
+ );
+ }
+ }
+ }
+
+ op = addOperation(result, "toString", String.class, ObjectModelJavaModifier.PUBLIC);
+ StringBuilder buffer = new StringBuilder();
+
+ buffer.append(""
+/*{
+ String result = new ToStringBuilder(this).
+}*/
+ );
+
+ for (Object o : clazz.getAttributes()) {
+ ObjectModelAttribute attr = (ObjectModelAttribute) o;
+ if (!(attr.isNavigable()
+ || attr.hasAssociationClass())) {
+ continue;
+ }
+ //FIXME possibilité de boucles (non directes)
+ ObjectModelClass attrEntity = null;
+ if (model.hasClass(attr.getType())) {
+ attrEntity = model.getClass(attr.getType());
+ }
+ boolean isDTO = attrEntity != null &&
+ TopiaGeneratorUtil.isEntity(attrEntity); //THIMEL : STEREOTYPE ENTITY ???
+ ObjectModelAttribute reverse = attr.getReverseAttribute();
+ if (isDTO && (reverse == null || !reverse.isNavigable()) && !attr.hasAssociationClass() || !isDTO) {
+ String attrName = attr.getName();
+ buffer.append(""
+/*{ append("<%=attrName%>", this.<%=attrName%>).
+}*/
+ );
+ }
+ }
+ buffer.append(""
+/*{ toString();
+ return result;
+ }*/
+ );
+ setOperationBody(op, buffer.toString());
+ }
+
+ public boolean isDTO(String type) {
+ ObjectModelClassifier clazz = model.getClassifier(type);
+ return clazz != null && TopiaGeneratorUtil.hasDtoStereotype(clazz);
+ }
+
+
+}
+
Copied: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityDTOTransformer.java (from rev 2882, trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityDTOTransformer.java)
===================================================================
--- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityDTOTransformer.java (rev 0)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityDTOTransformer.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,343 @@
+
+package org.nuiton.topia.templates;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.builder.ToStringBuilder;
+import org.nuiton.eugene.GeneratorUtil;
+import org.nuiton.eugene.java.ObjectModelTransformerToJava;
+import org.nuiton.eugene.models.object.ObjectModelAssociationClass;
+import org.nuiton.eugene.models.object.ObjectModelAttribute;
+import org.nuiton.eugene.models.object.ObjectModelClass;
+import org.nuiton.eugene.models.object.ObjectModelClassifier;
+import org.nuiton.eugene.models.object.ObjectModelJavaModifier;
+import org.nuiton.eugene.models.object.ObjectModelModifier;
+import org.nuiton.eugene.models.object.ObjectModelOperation;
+import org.nuiton.topia.templates.TopiaGeneratorUtil;
+
+import java.beans.PropertyChangeListener;
+import java.beans.PropertyChangeSupport;
+import java.io.Serializable;
+
+import static org.nuiton.topia.templates.TopiaGeneratorUtil.hasUnidirectionalRelationOnAbstractType;
+import static org.nuiton.topia.templates.TopiaGeneratorUtil.shouldGenerateDTOTopiaIdTagValue;
+
+
+/*{generator option: parentheses = false}*/
+
+/*{generator option: writeString = +}*/
+
+/**
+ * Created: 14 déc. 2009
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @version $Id$
+ * @since 2.3.0
+ * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.templates.EntityDTOTransformer"
+ * @deprecated since 3.0, will not be replaced
+ */
+@Deprecated
+public class EntityDTOTransformer extends ObjectModelTransformerToJava {
+
+ public boolean isEntity(String type) {
+ ObjectModelClassifier clazz = model.getClassifier(type);
+ return clazz != null && ! clazz.isEnum()
+ && TopiaGeneratorUtil.isEntity(clazz);
+ }
+
+ @Override
+ public void transformFromClass(ObjectModelClass clazz) {
+ if (!TopiaGeneratorUtil.isEntity(clazz)) {
+ return;
+ }
+ String clazzName = clazz.getName();
+ ObjectModelClass result;
+ result = createClass(clazzName + "DTO", clazz.getPackageName());
+ addImport(result, ToStringBuilder.class);
+ addImport(result, PropertyChangeListener.class);
+
+ setDocumentation(result, "Implantation DTO pour l'entité " + StringUtils.capitalize(clazzName) + ".");
+ String extendClass = "";
+ for (ObjectModelClass parent : clazz.getSuperclasses()) {
+ extendClass = parent.getQualifiedName() + "DTO";
+ // no multi-inheritance in java
+ break;
+ }
+ if (extendClass.length() > 0) {
+ setSuperClass(result, extendClass);
+ }
+ addInterface(result, Serializable.class);
+
+
+ addAttributes(result,clazz);
+
+ addOperations(result,clazz);
+
+ }
+
+ protected void addAttributes(ObjectModelClass result, ObjectModelClass clazz) {
+
+ String svUID = TopiaGeneratorUtil.findTagValue("dto-serialVersionUID", clazz, model);
+ if (svUID != null) {
+ addAttribute(result, "serialVersionUID", "long", svUID, ObjectModelJavaModifier.FINAL, ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
+ }
+
+ boolean generateDTOId = shouldGenerateDTOTopiaIdTagValue(clazz, model);
+ if (generateDTOId) {
+ addAttribute(result, "topiaId", "String");
+ }
+
+ ObjectModelAttribute attr2;
+ for (ObjectModelAttribute attr : clazz.getAttributes()) {
+ ObjectModelAttribute reverse = attr.getReverseAttribute();
+
+ // pour les asso quoi qu'il arrive il faut les lier des 2 cotes
+ // pour pouvoir supprimer en cascade l'asso lors de la suppression
+ // d'un des cotes
+ if (!(attr.isNavigable()
+ || hasUnidirectionalRelationOnAbstractType(reverse, model)
+ || attr.hasAssociationClass())) {
+ continue;
+ }
+
+ String attrVisibility = attr.getVisibility();
+ ObjectModelModifier modifier = ObjectModelJavaModifier.fromVisibility(attrVisibility);
+ if (!attr.hasAssociationClass()) {
+ String attrType = attr.getType();
+ String attrName = attr.getName();
+ if (isEntity(attrType)) {
+ attrType += "DTO";
+ }
+ if (!GeneratorUtil.isNMultiplicity(attr)) {
+ attr2 = addAttribute(result, attrName, attrType, null, modifier);
+ } else {
+ attr2 = addAttribute(result, attrName, attrType + "[]", null, modifier);
+ }
+ } else {
+ String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(attr);
+ String assocClassFQN = attr.getAssociationClass().getQualifiedName();
+ if (!GeneratorUtil.isNMultiplicity(attr)) {
+ attr2 = addAttribute(result, GeneratorUtil.toLowerCaseFirstLetter(assocAttrName), assocClassFQN + "DTO", null, modifier);
+ } else {
+ attr2 = addAttribute(result, GeneratorUtil.toLowerCaseFirstLetter(assocAttrName), assocClassFQN + "DTO[]", null, modifier);
+ }
+ }
+ if (attr2 != null) {
+ if (TopiaGeneratorUtil.hasDocumentation(attr)) {
+ setDocumentation(attr2, attr.getDocumentation());
+ }
+
+ String annotation = TopiaGeneratorUtil.getAnnotationTagValue(attr);
+ if (!StringUtils.isEmpty(annotation)) {
+ addAnnotation(result, attr2, annotation);
+ }
+ }
+ }
+
+ //Déclaration des attributs d'une classe d'associations
+ if (clazz instanceof ObjectModelAssociationClass) {
+ ObjectModelAssociationClass assoc = (ObjectModelAssociationClass) clazz;
+ for (ObjectModelAttribute attr : assoc.getParticipantsAttributes()) {
+ if (attr != null) {
+ String attrVisibility = attr.getVisibility();
+ ObjectModelModifier modifier = ObjectModelJavaModifier.fromVisibility(attrVisibility);
+ String attrType = attr.getType();
+ String attrName = attr.getName();
+ if (isEntity(attrType)) {
+ attrType += "DTO";
+ }
+ addAttribute(result, GeneratorUtil.toLowerCaseFirstLetter(attrName), attrType, null, modifier);
+ }
+ }
+ }
+
+ addAttribute(result,"p", PropertyChangeSupport.class,"new PropertyChangeSupport(this)",ObjectModelJavaModifier.PROTECTED,ObjectModelJavaModifier.FINAL);
+ }
+
+ protected void addOperations(ObjectModelClass result,ObjectModelClass clazz) {
+
+ boolean generateDTOId = shouldGenerateDTOTopiaIdTagValue(clazz, model);
+ ObjectModelOperation op;
+ if (generateDTOId) {
+ op = addOperation(result, "setTopiaId", "void", ObjectModelJavaModifier.PUBLIC);
+ addParameter(op, "String", "topiaId");
+ setOperationBody(op, ""
+/*{
+ this.topiaId = topiaId;
+ }*/
+ );
+
+ op = addOperation(result, "getTopiaId", "String", ObjectModelJavaModifier.PUBLIC);
+ setOperationBody(op, ""
+/*{
+ return topiaId;
+ }*/
+ );
+ }
+
+ op = addOperation(result, "addPropertyChangeListener", "void");
+ addParameter(op,PropertyChangeListener.class,"listener");
+ setOperationBody(op,""
+/*{
+ p.addPropertyChangeListener(listener);
+ }*/
+ );
+
+ op = addOperation(result, "addPropertyChangeListener", "void");
+ addParameter(op, String.class, "propertyName");
+ addParameter(op, PropertyChangeListener.class, "listener");
+ setOperationBody(op, ""
+/*{
+ p.addPropertyChangeListener(propertyName, listener);
+ }*/
+ );
+
+ op = addOperation(result, "removePropertyChangeListener", "void");
+ addParameter(op, PropertyChangeListener.class, "listener");
+ setOperationBody(op, ""
+/*{
+ p.removePropertyChangeListener(listener);
+ }*/
+ );
+
+ op = addOperation(result, "removePropertyChangeListener", "void");
+ addParameter(op, String.class, "propertyName");
+ addParameter(op, PropertyChangeListener.class, "listener");
+ setOperationBody(op, ""
+/*{
+ p.removePropertyChangeListener(propertyName, listener);
+ }*/
+ );
+
+ for (ObjectModelAttribute attr : clazz.getAttributes()) {
+
+ ObjectModelAttribute reverse = attr.getReverseAttribute();
+
+ if (!(attr.isNavigable() || hasUnidirectionalRelationOnAbstractType(reverse, model))) {
+ continue;
+ }
+
+ String attrName = attr.getName();
+
+ if (!attr.hasAssociationClass()) {
+ String attrType = attr.getType();
+ if (isEntity(attrType)) {
+ attrType += "DTO";
+ }
+ String setterName = getJavaBeanMethodName("set", attrName);
+ String getterName = getJavaBeanMethodName("get", attrName);
+ if (!GeneratorUtil.isNMultiplicity(attr)) {
+ op = addOperation(result, setterName, "void", ObjectModelJavaModifier.PUBLIC);
+ addParameter(op, attrType, "value");
+ setOperationBody(op, ""
+/*{
+ <%=attrType%> oldValue = this.<%=attrName%>;
+ this.<%=attrName%> = value;
+ p.firePropertyChange("<%=attrName%>", oldValue, value);
+ }*/
+ );
+
+ op = addOperation(result, getterName, attrType, ObjectModelJavaModifier.PUBLIC);
+ setOperationBody(op, ""
+/*{
+ return <%=attrName%>;
+ }*/
+ );
+
+ } else {
+
+ op = addOperation(result, setterName, "void", ObjectModelJavaModifier.PUBLIC);
+ addParameter(op, attrType+"[]", "values");
+ setOperationBody(op, ""
+/*{
+ <%=attrType%>[] oldValues = this.<%=attrName%>;
+ this.<%=attrName%> = values;
+ p.firePropertyChange("<%=attrName%>", oldValues, values);
+ }*/
+ );
+
+ op = addOperation(result, getterName, attrType+"[]", ObjectModelJavaModifier.PUBLIC);
+ setOperationBody(op, ""
+/*{
+ return <%=attrName%>;
+ }*/
+ );
+ }
+ } else {
+ String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(attr);
+ String propertyName = GeneratorUtil.toLowerCaseFirstLetter(assocAttrName);
+ String assocClassFQN = attr.getAssociationClass().getQualifiedName();
+ String setterName = getJavaBeanMethodName("set", assocAttrName);
+ String getterName = getJavaBeanMethodName("get", assocAttrName);
+ if (!GeneratorUtil.isNMultiplicity(attr)) {
+ op = addOperation(result, setterName, "void", ObjectModelJavaModifier.PUBLIC);
+ addParameter(op, assocClassFQN + "DTO", "association");
+ setOperationBody(op, ""
+/*{
+ <%=assocClassFQN%>DTO oldAssocation= this.<%=propertyName%>;
+ this.<%=propertyName%> = association;
+ p.firePropertyChange("<%=attrName%>", oldAssocation, assocation);
+ }*/
+ );
+
+ op = addOperation(result, getterName, assocClassFQN + "DTO", ObjectModelJavaModifier.PUBLIC);
+ setOperationBody(op, ""
+/*{
+ return <%=propertyName%>;
+ }*/
+ );
+
+ } else {
+ op = addOperation(result, setterName, "void", ObjectModelJavaModifier.PUBLIC);
+ addParameter(op, assocClassFQN + "DTO[]", "values");
+ setOperationBody(op, ""
+/*{
+ <%=assocClassFQN%>DTO[] oldValues = this.<%=propertyName%>;
+ this.<%=propertyName%> = values;
+ p.firePropertyChange("<%=attrName%>", oldValues, values);
+ }*/
+ );
+
+ op = addOperation(result, getterName, assocClassFQN + "DTO[]", ObjectModelJavaModifier.PUBLIC);
+ setOperationBody(op, ""
+/*{
+ return this.<%=propertyName%>;
+ }*/
+ );
+ }
+ }
+ }
+
+ op = addOperation(result,"toString",String.class, ObjectModelJavaModifier.PUBLIC);
+ StringBuilder buffer = new StringBuilder();
+
+ buffer.append(""
+/*{
+ String result = new ToStringBuilder(this).
+}*/
+ );
+
+ for (Object o : clazz.getAttributes()) {
+ ObjectModelAttribute attr = (ObjectModelAttribute) o;
+ //FIXME possibilité de boucles (non directes)
+ ObjectModelClass attrEntity = null;
+ if (model.hasClass(attr.getType())) {
+ attrEntity = model.getClass(attr.getType());
+ }
+ boolean isEntity = attrEntity != null && TopiaGeneratorUtil.isEntity(attrEntity);
+ ObjectModelAttribute reverse = attr.getReverseAttribute();
+ if (isEntity && (reverse == null || !reverse.isNavigable()) && !attr.hasAssociationClass() || !isEntity) {
+ String attrName = attr.getName();
+ buffer.append(""
+/*{ append("<%=attrName%>", this.<%=attrName%>).
+}*/
+ );
+ }
+ }
+ buffer.append(""
+/*{ toString();
+ return result;
+}*/
+ );
+ setOperationBody(op, buffer.toString());
+ }
+}
Copied: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityDaoTransformer.java (from rev 2882, trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityDaoTransformer.java)
===================================================================
--- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityDaoTransformer.java (rev 0)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityDaoTransformer.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,1138 @@
+package org.nuiton.topia.templates;
+
+/*{generator option: parentheses = false}*/
+/*{generator option: writeString = +}*/
+
+import com.google.common.base.Strings;
+import com.google.common.collect.Sets;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.eugene.GeneratorUtil;
+import org.nuiton.eugene.java.JavaGeneratorUtil;
+import org.nuiton.eugene.java.ObjectModelTransformerToJava;
+import org.nuiton.eugene.models.object.ObjectModel;
+import org.nuiton.eugene.models.object.ObjectModelAssociationClass;
+import org.nuiton.eugene.models.object.ObjectModelAttribute;
+import org.nuiton.eugene.models.object.ObjectModelClass;
+import org.nuiton.eugene.models.object.ObjectModelClassifier;
+import org.nuiton.eugene.models.object.ObjectModelDependency;
+import org.nuiton.eugene.models.object.ObjectModelInterface;
+import org.nuiton.eugene.models.object.ObjectModelJavaModifier;
+import org.nuiton.eugene.models.object.ObjectModelOperation;
+import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.persistence.TopiaEntity;
+import org.nuiton.topia.persistence.TopiaQueryBuilderAddCriteriaOrRunQueryStep;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+
+/**
+ * To generate all <code>DAO</code> related classes for a given entity.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.5.4
+ * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.templates.EntityDaoTransformer"
+ */
+public class EntityDaoTransformer extends ObjectModelTransformerToJava {
+
+ /** Logger. */
+ private static final Log log =
+ LogFactory.getLog(EntityDaoTransformer.class);
+
+ /**
+ * map of direct usages (values) for each entity (key).
+ * <p/>
+ * This map is used to generate the findUsages methods for DAOAbstract.
+ */
+ protected Map<ObjectModelClass, Set<ObjectModelClass>> usages;
+
+ /**
+ * All entities fqn of the model (used to detect if an attribute is not
+ * an entity).
+ */
+ protected Set<String> allEntitiesFqn;
+
+ /**
+ * The class of abstract dao to use.
+ * @since 2.5
+ */
+ protected Class<?> daoImplementation;
+
+ protected String entityEnumName;
+
+ protected String entityEnumPackage;
+
+ /**
+ * Map of extra operations for DAO. The key of the map is the qualified
+ * name of the entity relative to the DAO.
+ */
+ protected Map<String, Collection<ObjectModelOperation>> extraOperations =
+ new HashMap<String, Collection<ObjectModelOperation>>();
+
+ @Override
+ public void transformFromModel(ObjectModel model) {
+
+ boolean generateStandaloneEnum =
+ TopiaGeneratorUtil.shouldGenerateStandaloneEnumForDAOHelper(model);
+ String modelName = model.getName();
+
+ entityEnumName = modelName + "EntityEnum";
+
+ String packageName =
+ getOutputProperties().getProperty(PROP_DEFAULT_PACKAGE);
+
+ if (generateStandaloneEnum) {
+ entityEnumPackage = packageName + "." + entityEnumName;
+ } else {
+ String daoHelperClazzName = modelName + "DAOHelper";
+ entityEnumPackage = packageName + "." + daoHelperClazzName + "." + entityEnumName;
+ }
+
+ usages = TopiaGeneratorUtil.searchDirectUsages(model);
+
+ daoImplementation = TopiaGeneratorUtil.getDAOImplementation(model);
+
+
+ // keep all classifiers on the model which are entities
+ List<ObjectModelClass> allEntities =
+ TopiaGeneratorUtil.getEntityClasses(model, true);
+ allEntitiesFqn = new HashSet<String>(allEntities.size());
+ for (ObjectModelClass entity : allEntities) {
+ String fqn = entity.getQualifiedName();
+ allEntitiesFqn.add(fqn);
+ Collection<ObjectModelOperation> daoOperations =
+ new HashSet<ObjectModelOperation>();
+ for (ObjectModelOperation op : entity.getOperations()) {
+ if (TopiaGeneratorUtil.hasDaoStereotype(op)) {
+ daoOperations.add(op);
+ }
+ }
+
+ if (daoOperations.isEmpty()) {
+
+ // found some dao operations
+ extraOperations.put(fqn, daoOperations);
+ }
+ }
+ }
+
+ @Override
+ public void transformFromInterface(ObjectModelInterface interfacez) {
+ if (!TopiaGeneratorUtil.hasDaoStereotype(interfacez)) {
+ return;
+ }
+
+ /**
+ * EVO #636 : Manage extra operations for DAO from "dao" dependency
+ * between an interface with stereotype <<dao>> (dependency client) and
+ * a class with stereotype <<entity>> (dependency supplier).
+ */
+
+ ObjectModelDependency dependency =
+ interfacez.getDependency(TopiaGeneratorUtil.DEPENDENCIES_DAO);
+
+ if (dependency == null) {
+ if (log.isWarnEnabled()) {
+ log.warn("Could not find dependency " +
+ TopiaGeneratorUtil.DEPENDENCIES_DAO +
+ " but DAO stereotype was placed on the interface " +
+ interfacez.getName());
+ }
+ return;
+ }
+
+ ObjectModelClassifier classifier = dependency.getSupplier();
+
+ if (!TopiaGeneratorUtil.isEntity(classifier)) {
+
+ // dependency supplier is not an entity...
+ if (log.isWarnEnabled()) {
+ log.warn("Dependency supplier " +
+ classifier.getQualifiedName() +
+ " is not an entity.");
+ }
+ return;
+ }
+
+ // keep only direct operations
+ Collection<ObjectModelOperation> operations =
+ interfacez.getOperations();
+
+ if (CollectionUtils.isEmpty(operations)) {
+
+ // no operations on interface, this is not normal
+ if (log.isWarnEnabled()) {
+ log.warn("No operation found on interface with DAO " +
+ "stereotype "+classifier.getQualifiedName());
+ }
+ return;
+ }
+ if (log.isDebugEnabled()) {
+ log.debug("add "+operations.size()+" extra operation(s) for DAO");
+ }
+
+ extraOperations.put(classifier.getQualifiedName(), operations);
+ }
+
+ @Override
+ public void transformFromClass(ObjectModelClass clazz) {
+ if (!TopiaGeneratorUtil.isEntity(clazz)) {
+ // not an entity
+ return;
+ }
+ String clazzName = clazz.getName();
+ String clazzFQN = clazz.getQualifiedName();
+
+ if (isGenerateGeneratedDao(clazz)) {
+ generateGeneratedDao(clazz, clazzName, clazzFQN);
+ }
+
+ if (isGenerateAbstractDao(clazz)) {
+ generateAbstractDao(clazz, clazzName, clazzFQN);
+ }
+
+ if (isGenerateLegacyDao(clazz)) {
+ generateLegacyDao(clazz, clazzName, clazzFQN);
+ }
+
+ if (isGenerateConcreteDao(clazz)) {
+ generateConcreteDao(clazz, clazzName, clazzFQN);
+ }
+
+ }
+
+ protected boolean isGenerateLegacyDao(ObjectModelClass input) {
+
+ String daoLegacyFqn = TopiaGeneratorUtil.getLegacyDaoFqn(input);
+
+ if (isInClassPath(daoLegacyFqn)) {
+
+ // already in class-path
+ return false;
+ }
+
+ // can safely generate the dao impl
+ return true;
+ }
+
+ protected boolean isGenerateConcreteDao(ObjectModelClass input) {
+
+ String daoConcreteFqn = TopiaGeneratorUtil.getConcreteDaoFqn(input);
+
+ if (isInClassPath(daoConcreteFqn)) {
+
+ // already in class-path
+ return false;
+ }
+
+ // can safely generate the dao impl
+ return true;
+ }
+
+ protected boolean isGenerateGeneratedDao(ObjectModelClass input) {
+
+ String daoGeneratedFqn = TopiaGeneratorUtil.getGeneratedDaoFqn(input);
+
+ if (isInClassPath(daoGeneratedFqn)) {
+
+ // already in class-path
+ return false;
+ }
+
+ // can safely generate the dao impl
+ return true;
+
+ }
+
+ protected boolean isGenerateAbstractDao(ObjectModelClass input) {
+
+ String fqn = TopiaGeneratorUtil.getAbstractDaoFqn(input);
+
+ if (isInClassPath(fqn)) {
+
+ // already in class-path
+ return false;
+ }
+
+ Collection<ObjectModelOperation> moreOperations =
+ extraOperations.get(input.getQualifiedName());
+
+ if (CollectionUtils.isNotEmpty(moreOperations)) {
+
+ // no user operations, can not generate it
+ return false;
+ }
+
+ // can safely generate the dao impl
+ return true;
+
+ }
+
+ protected void generateLegacyDao(ObjectModelClass clazz, String clazzName, String clazzFQN) {
+ ObjectModelClass daoClass = createClass(TopiaGeneratorUtil.getLegacyDaoName(clazz), clazz.getPackageName());
+ addAnnotation(daoClass, daoClass, Deprecated.class);
+ setDocumentation(daoClass, "/**\n" +
+ " * Cette classe etend le DAOImpl pour parametrer la classe avec le bon type\n" +
+ " * Cette classe est marque finale car l'heritage entre les DAO se fait\n" +
+ " * sur les DOAImpl, c-a-d que DAOAbstract peut etendre le DAOImpl\n" +
+ " */");
+ setSuperClass(daoClass, TopiaGeneratorUtil.getAbstractDaoFqn(clazz) + "<" + clazzName + ">");
+ }
+
+ protected void generateConcreteDao(ObjectModelClass clazz, String clazzName, String clazzFQN) {
+ String concreteDaoName = TopiaGeneratorUtil.getConcreteDaoName(clazz);
+ ObjectModelClass daoClass = createClass(concreteDaoName, clazz.getPackageName());
+ setDocumentation(daoClass, "/**\n" +
+ " * Cette classe etend le DAOImpl pour parametrer la classe avec le bon type\n" +
+ " * Cette classe est marque finale car l'heritage entre les DAO se fait\n" +
+ " * sur les DOAImpl, c-a-d que DAOAbstract peut etendre le DAOImpl\n" +
+ " */");
+ // to support legacy dao
+ String superclassQualifiedName = TopiaGeneratorUtil.getLegacyDaoFqn(clazz);
+ // TODO brendan 04/10/13 above line should be replaced by
+// String superclassQualifiedName = TopiaGeneratorUtil.getAbstractDaoFqn(clazz) + "<" + clazzName + ">";
+ setSuperClass(daoClass, superclassQualifiedName);
+
+ // TODO AThimel 25/10/13 Remove the next lines in ToPIA 3.1
+ // Look for legacy Dao class, then warn user if found in classpath
+ String legacyConcreteDaoName = TopiaGeneratorUtil.getLegacyDaoName(clazz);
+ warnOnLegacyClassDetected(clazz.getPackageName(), legacyConcreteDaoName, concreteDaoName, null,
+ TopiaGeneratorUtil.getAbstractDaoFqn(clazz) + "<" + clazzName + ">");
+ }
+
+ protected void generateAbstractDao(ObjectModelClass clazz,
+ String clazzName,
+ String clazzFQN) {
+
+ Collection<ObjectModelOperation> moreOperations =
+ extraOperations.get(clazz.getQualifiedName());
+
+ if (CollectionUtils.isEmpty(moreOperations)) {
+
+ // no business Dao found, can safely generate the abstract Dao class
+
+ String abstractDaoName = TopiaGeneratorUtil.getAbstractDaoName(clazz);
+ String daoGenerics = "<E extends " + clazzName + ">";
+ ObjectModelClass abstractDaoClass = createClass(abstractDaoName + daoGenerics, clazz.getPackageName());
+ String documentation = String.format("/**%n" +
+ " * Implantation du Dao pour l'entité '%s'.%n" +
+ " * L'utilisateur peut remplacer cette classe par la sienne en la mettant%n" +
+ " * simplement dans ses sources. Cette classe générée sera alors simplement%n" +
+ " * ignorée à la génération suivante.%n" +
+ " */", clazzName);
+ setDocumentation(abstractDaoClass, documentation);
+ String superclassQualifiedName = TopiaGeneratorUtil.getGeneratedDaoFqn(clazz) + "<E>";
+ setSuperClass(abstractDaoClass, superclassQualifiedName);
+
+ // TODO AThimel 25/10/13 Remove the next lines in ToPIA 3.1
+ // Look for legacy Dao class, then warn user if found in classpath
+ String legacyDaoImplName = TopiaGeneratorUtil.getLegacyDaoName(clazz) + "Impl";
+ warnOnLegacyClassDetected(clazz.getPackageName(), legacyDaoImplName, abstractDaoName, daoGenerics,
+ superclassQualifiedName);
+
+ }
+ }
+
+ // TODO AThimel 25/10/13 Remove this method in ToPIA 3.1
+ protected void warnOnLegacyClassDetected(String packageName,
+ String legacyDaoName,
+ String daoName,
+ String daoGenerics,
+ String superclassQualifiedName) {
+
+ String legacyDaoFqn = String.format("%s.%s", packageName, legacyDaoName);
+
+ // AThimel 25/10/13 Not using isInClassPath(fqn) because this method logs that file won't be generated
+ if (log.isWarnEnabled() && getFileInClassPath(legacyDaoFqn) != null) {
+ String format = "public class %s%s extends %s {";
+ String superclassName = superclassQualifiedName.substring(superclassQualifiedName.lastIndexOf('.') + 1);
+ String daoDeclaration = String.format(format, daoName, Strings.nullToEmpty(daoGenerics), superclassName);
+ String warnMessage = "Legacy DAO detected : %s !%n" +
+ " - You should consider renaming '%s' to '%s'%n" +
+ " - Expected class declaration is : %s%n" +
+ "%n"; // AThimel 29/10/13 Add a new line for log clearness
+ log.warn(String.format(warnMessage, legacyDaoFqn, legacyDaoName, daoName, daoDeclaration));
+ }
+
+ }
+
+ protected void generateGeneratedDao(ObjectModelClass clazz,
+ String clazzName,
+ String clazzFQN) {
+ ObjectModelClass daoAbstractClass = createAbstractClass(TopiaGeneratorUtil.getGeneratedDaoName(clazz) + "<E extends " + clazzName + '>',
+ clazz.getPackageName());
+
+ // super class
+
+ String superClassName = null;
+ for (ObjectModelClass parent : clazz.getSuperclasses()) {
+ if (TopiaGeneratorUtil.isEntity(parent)) {
+ superClassName = TopiaGeneratorUtil.getAbstractDaoFqn(parent) + "<E>";
+ // in java no multi-inheritance
+ break;
+ }
+ }
+ if (superClassName == null) {
+ superClassName = daoImplementation.getName() + "<E>";
+ }
+ if (log.isDebugEnabled()) {
+ log.debug("super class = " + superClassName);
+ }
+ setSuperClass(daoAbstractClass, superClassName);
+
+ String prefix = getConstantPrefix(clazz, "");
+ setConstantPrefix(prefix);
+
+ // imports
+
+ Collection<ObjectModelOperation> daoOperations = getDaoOperations(clazz);
+
+ if (TopiaGeneratorUtil.isCollectionNeeded(daoOperations)) {
+ addImport(daoAbstractClass, Collection.class);
+ }
+ if (TopiaGeneratorUtil.isSetNeeded(daoOperations)) {
+ addImport(daoAbstractClass, Set.class);
+ }
+ addImport(daoAbstractClass, List.class);
+ addImport(daoAbstractClass, TopiaException.class);
+ addImport(daoAbstractClass, TopiaQueryBuilderAddCriteriaOrRunQueryStep.class);
+
+ ObjectModelOperation op;
+
+ // getEntityClass
+
+ op = addOperation(daoAbstractClass,
+ "getEntityClass",
+ "Class<E>",
+ ObjectModelJavaModifier.PUBLIC);
+ addAnnotation(daoAbstractClass, op,Override.class);
+ setOperationBody(op, ""
+/*{
+ return (Class<E>) <%=clazzName%>.class;
+ }*/
+ );
+
+ // getTopiaEntityEnum
+ addImport(daoAbstractClass, entityEnumPackage);
+ op = addOperation(daoAbstractClass,
+ "getTopiaEntityEnum",
+ entityEnumName,
+ ObjectModelJavaModifier.PUBLIC);
+ addAnnotation(daoAbstractClass, op,Override.class);
+ setOperationBody(op, ""
+/*{
+ return <%=entityEnumName%>.<%=clazzName%>;
+ }*/
+ );
+
+ generateDAOOperations(daoAbstractClass, daoOperations);
+
+ generateDelete(clazz, daoAbstractClass);
+
+ generateNaturalId(daoAbstractClass, clazz);
+
+ generateNotNull(daoAbstractClass, clazz);
+
+ for (ObjectModelAttribute attr : clazz.getAttributes()) {
+ if (!attr.isNavigable()) {
+ continue;
+ }
+
+ if (!GeneratorUtil.isNMultiplicity(attr)) {
+ generateNoNMultiplicity(clazzName, daoAbstractClass, attr, false);
+ } else {
+ generateNMultiplicity(clazzName, daoAbstractClass, attr);
+ }
+ }
+
+ if (clazz instanceof ObjectModelAssociationClass) {
+ ObjectModelAssociationClass assocClass =
+ (ObjectModelAssociationClass) clazz;
+ for (ObjectModelAttribute attr : assocClass.getParticipantsAttributes()) {
+ if (attr != null) {
+ if (!GeneratorUtil.isNMultiplicity(attr)) {
+ generateNoNMultiplicity(clazzName, daoAbstractClass, attr, true);
+ } else {
+ generateNMultiplicity(clazzName, daoAbstractClass, attr);
+ }
+ }
+ }
+ }
+
+ Set<ObjectModelClass> usagesForclass = usages.get(clazz);
+ generateFindUsages(clazz, daoAbstractClass, usagesForclass);
+ }
+
+ protected void generateDelete(ObjectModelClass clazz,
+ ObjectModelClass result) {
+
+ StringBuilder body = new StringBuilder();
+ String modelName = StringUtils.capitalize(model.getName());
+ String providerFQN = getOutputProperties().getProperty(
+ PROP_DEFAULT_PACKAGE) + '.' + modelName +
+ "DAOHelper.getImplementationClass";
+
+ for (ObjectModelAttribute attr : clazz.getAttributes()) {
+
+ String attrType = GeneratorUtil.getSimpleName(attr.getType());
+
+ String reverseAttrName = attr.getReverseAttributeName();
+ ObjectModelAttribute reverse = attr.getReverseAttribute();
+ if (attr.hasAssociationClass() ||
+ reverse == null || !reverse.isNavigable()) {
+
+ // never treate a non reverse and navigable attribute
+ // never treate an association class attribute
+ continue;
+ }
+
+ // at this point we are sure to have a attribute which is
+ // - reverse
+ // - navigable
+ // - not from an association class
+ if (!allEntitiesFqn.contains(attr.getType())) {
+
+ // this attribute is not from an entity, don't treate it
+ if (log.isDebugEnabled()) {
+ log.debug("[" + result.getName() + "] Skip attribute [" +
+ attr.getName() + "] with type " + attr.getType());
+ }
+ continue;
+ }
+
+ // At this point, the attribute type is a entity
+ if (GeneratorUtil.isNMultiplicity(attr) &&
+ GeneratorUtil.isNMultiplicity(reverse)) {
+ // On doit absolument supprimer pour les relations many-to-many
+ // le this de la collection de l'autre cote
+
+ String attrDBName = TopiaGeneratorUtil.getDbName(attr);
+ String attrClassifierDBName = TopiaGeneratorUtil.getDbName(attr.getClassifier());
+ String attrJoinTableName = TopiaGeneratorUtil.getManyToManyTableName(attr);
+ String attrReverseDBName = TopiaGeneratorUtil.getReverseDbName(attr);
+
+ //FIXME_-FC-20100413 Use a TopiaQuery (use HQLin elements)
+// // Add DAOHelper
+// String daoHelper = modelName + "DAOHelper";
+// String daoHelperFQN = getOutputProperties().
+// getProperty(PROP_DEFAULT_PACKAGE) + '.' + daoHelper;
+// addImport(result, daoHelperFQN);
+//
+// // Add import for TopiaQuery
+// addImport(result, TopiaQuery.class);
+//
+// // Entity DAO and reversePropertyName
+// String entityDAO = attrType + "DAO";
+// String reverseAttrNameProperty =
+// attrType + "." + getConstantName(reverseAttrName);
+//
+//
+// <%=entityDAO%> dao = <%=daoHelper%>.get<%=entityDAO%>(getTopiaContext());
+// TopiaQuery query = dao.createQuery("B").
+// addFrom(entity.getClass(), "A").
+// add("A", entity).
+// addInElements("A", "B." + <%=reverseAttrNameProperty%>);
+//
+// System.out.println("Query : " + query);
+// List<<%=attrType%>> list = dao.findAllByQuery(query);
+
+ String removeName = getJavaBeanMethodName("remove", reverseAttrName);
+ body.append(""
+/*{
+ {
+ List<<%=attrType%>> list = topiaHibernateSupport.getHibernateSession().createSQLQuery(
+ "SELECT main.topiaid " +
+ "from <%=attrClassifierDBName%> main, <%=attrJoinTableName%> secondary " +
+ "where main.topiaid=secondary.<%=attrDBName%>" +
+ " and secondary.<%=attrReverseDBName%>='" + entity.getTopiaId() + "'")
+ .addEntity("main", <%=providerFQN%>(<%=attrType%>.class)).list();
+
+ for (<%=attrType%> item : list) {
+ item.<%=removeName%>(entity);
+ }
+ }
+}*/
+ );
+ } else if (!GeneratorUtil.isNMultiplicity(reverse)) {
+ // On doit mettre a null les attributs qui ont cet objet sur les
+ // autres entites en one-to-*
+ // TODO peut-etre qu'hibernate est capable de faire ca tout seul ?
+ // THIMEL: J'ai remplacé reverse.getName() par reverseAttrName sans certitude
+ addImport(result, attrType);
+ addImport(result, attr.getType() + "TopiaDao"); // AThimel 30/10/13 Not using attrType because we need FQN // Can use TopiaGeneratorUtil.getConcreteDaoFqn(...) ?
+ String attrSimpleType = TopiaGeneratorUtil.getClassNameFromQualifiedName(attrType);
+ // XXX brendan 04/10/13 do not hard code concrete dao name
+ String attrConcreteDaoClassName = attrSimpleType + "TopiaDao";
+ String getName = getJavaBeanMethodName("get", reverseAttrName);
+ String setName = getJavaBeanMethodName("set", reverseAttrName);
+
+ body.append(""
+ /*{
+ {
+ <%=attrConcreteDaoClassName%> dao = topiaDaoSupplier
+ .getDao(<%=attrSimpleType%>.class, <%=attrConcreteDaoClassName%>.class);
+ List<<%=attrSimpleType%>> list = dao
+ .forProperties(<%=attrSimpleType%>.<%=getConstantName(reverseAttrName)%>, entity)
+ .findAll();
+ for (<%=attrSimpleType%> item : list) {
+
+ // sletellier : Set null only if target is concerned by deletion
+ if (entity.equals(item.<%=getName%>())) {
+ item.<%=setName%>(null);
+ }
+ }*/
+ );
+ if (attr.isAggregate()) {
+ body.append(""
+/*{
+ topiaDaoSupplier.getDao(<%=attrSimpleType%>.class).delete(item);
+}*/
+ );
+ }
+ body.append(""
+/*{
+ }
+ }
+}*/
+ );
+
+ }
+ }
+
+ if (body.length()>0) {
+ // something specific was done, need to generate the method
+ ObjectModelOperation op;
+ op = addOperation(result, "delete", "void", ObjectModelJavaModifier.PUBLIC);
+ addAnnotation(result, op,Override.class);
+ addParameter(op, "E", "entity");
+ body.append(""
+/*{
+ super.delete(entity);
+ }*/
+ );
+ setOperationBody(op, body.toString());
+ }
+
+
+
+ }
+
+ protected void generateFindUsages(ObjectModelClass clazz,
+ ObjectModelClass result,
+ Set<ObjectModelClass> usagesForclass) {
+
+ builder.addImport(result, LinkedList.class.getName());
+ builder.addImport(result, Map.class.getName());
+ builder.addImport(result, HashMap.class.getName());
+ builder.addImport(result, TopiaEntity.class.getName());
+
+ if (clazz instanceof ObjectModelAssociationClass ||
+ usagesForclass.isEmpty()) {
+ // not for an association class
+ // just let a null method
+ ObjectModelOperation operation;
+ operation = addOperation(result,
+ "findUsages",
+ "<U extends TopiaEntity> List<U>",
+ ObjectModelJavaModifier.PUBLIC);
+
+ addParameter(operation, "Class<U>", "type");
+ addParameter(operation, "E", "entity");
+ addAnnotation(result, operation, Override.class);
+ setOperationBody(operation, ""
+/*{
+ return new LinkedList<U>();
+ }*/
+ );
+
+ operation = addOperation(result,
+ "findAllUsages",
+ "Map<Class<? extends TopiaEntity>, List<? extends TopiaEntity>>",
+ ObjectModelJavaModifier.PUBLIC);
+
+ addParameter(operation, "E", "entity");
+ addAnnotation(result, operation, Override.class);
+ setOperationBody(operation, ""
+/*{
+ return new HashMap<Class<? extends TopiaEntity>, List<? extends TopiaEntity>>();
+ }*/
+ );
+
+ return;
+ }
+ List<ObjectModelClass> allEntities;
+ Map<String, ObjectModelClass> allEntitiesByFQN;
+
+ allEntities = TopiaGeneratorUtil.getEntityClasses(model, true);
+ allEntitiesByFQN = new TreeMap<String, ObjectModelClass>();
+
+ // prepare usages map and fill allEntitiesByFQN map
+ for (ObjectModelClass klass : allEntities) {
+ allEntitiesByFQN.put(klass.getQualifiedName(), klass);
+ }
+
+ ObjectModelOperation operation;
+ operation = addOperation(result,
+ "findUsages",
+ "<U extends TopiaEntity> List<U>",
+ ObjectModelJavaModifier.PUBLIC);
+
+ addParameter(operation, "Class<U>", "type");
+ addParameter(operation, "E", "entity");
+ addAnnotation(result, operation, Override.class);
+ StringBuilder buffer = new StringBuilder(300);
+ buffer.append(""
+/*{
+ List<?> result = new LinkedList();
+ List tmp;
+}*/
+ );
+
+ for (ObjectModelClass usageClass : usagesForclass) {
+ String usageType = usageClass.getQualifiedName();
+ builder.addImport(result, usageType);
+ String usageSimpleType =
+ TopiaGeneratorUtil.getClassNameFromQualifiedName(usageType);
+ String usageSimplePropertyMethod = "findAllBy" + usageSimpleType;
+ String usageCollectionPropertyMethod = "findAllContaining" + usageSimpleType;
+ for (ObjectModelAttribute attr : usageClass.getAttributes()) {
+ if (!attr.isNavigable()) {
+ // skip this case
+ continue;
+ }
+ String type;
+ String attrName = attr.getName();
+ if (attr.hasAssociationClass()) {
+ //FIXME-TC20100224 dont known how to do this ?
+ continue;
+// type = attr.getAssociationClass().getQualifiedName();
+// //FIXME-TC20100224 : this is crazy ??? must find the good name
+// // Perhaps need to make different cases?
+// attrName = attrName + "_" + TopiaGeneratorUtil.toLowerCaseFirstLetter(attr.getAssociationClass().getName());
+ } else {
+ type = attr.getType();
+ }
+ if (!allEntitiesByFQN.containsKey(type)) {
+ // not a entity, can skip for this attribute
+ continue;
+ }
+ ObjectModelClass targetEntity = allEntitiesByFQN.get(type);
+// if (!type.equals(clazz.getQualifiedName())) {
+ if (!targetEntity.equals(clazz)) {
+ // not a good attribute reference
+ continue;
+ }
+ // found something to seek
+
+ String methodName;
+ if (TopiaGeneratorUtil.isNMultiplicity(attr)) {
+ methodName = getJavaBeanMethodName("findAllContains", attrName);
+ } else {
+ methodName = getJavaBeanMethodName("findAllBy", attrName);
+ }
+ String daoName = StringUtils.capitalize(usageSimpleType) + "DAO";
+
+ builder.addImport(result, usageClass.getPackageName() + '.' + daoName);
+
+ buffer.append(""
+/*{
+ if (type == <%=usageSimpleType%>.class) {
+ <%=daoName%> dao = (<%=daoName%>)
+ topiaDaoSupplier.getDao(<%=usageSimpleType%>.class);
+ tmp = dao.<%=methodName%>(entity);
+ result.addAll(tmp);
+ }
+}*/
+ );
+ }
+ }
+
+ buffer.append(""
+/*{
+ return (List<U>) result;
+ }*/
+ );
+ setOperationBody(operation, buffer.toString());
+
+ operation = addOperation(result,
+ "findAllUsages",
+ "Map<Class<? extends TopiaEntity>, List<? extends TopiaEntity>>",
+ ObjectModelJavaModifier.PUBLIC);
+
+ addParameter(operation, "E", "entity");
+ addAnnotation(result, operation, Override.class);
+
+ buffer = new StringBuilder(300);
+ buffer.append(""
+/*{
+ Map<Class<? extends TopiaEntity>,List<? extends TopiaEntity>> result;
+ result = new HashMap<Class<? extends TopiaEntity>, List<? extends TopiaEntity>>(<%=usagesForclass.size()%>);
+
+ List<? extends TopiaEntity> list;
+}*/
+ );
+ for (ObjectModelClass usageClass : usagesForclass) {
+
+ String fqn = usageClass.getName();
+ buffer.append(""
+/*{
+ list = findUsages(<%=fqn%>.class, entity);
+ if (!list.isEmpty()) {
+ result.put(<%=fqn%>.class, list);
+ }
+}*/
+ );
+
+ }
+ buffer.append(""
+/*{
+ return result;
+ }*/
+ );
+
+ setOperationBody(operation, buffer.toString());
+ }
+
+ /**
+ * Generation of DAO operations signatures from class. These operations are
+ * abstract and identified by <<dao>> stereotype in the model. The
+ * developper must defined these methods in the DAOImpl associated to this
+ * DAOAbstract.
+ *
+ * @param result clazz where to add operations
+ * @param operations operations to generate
+ * @deprecated will be removed ASAP in topia 3.0
+ */
+ @Deprecated
+ protected void generateDAOOperations(ObjectModelClass result,
+ Collection<ObjectModelOperation>
+ operations) {
+ if (CollectionUtils.isEmpty(operations)) {
+
+ // no extra operations to generate
+ return;
+ }
+
+ for (ObjectModelOperation op : operations) {
+
+ Set<String> exceptions = op.getExceptions();
+ cloneOperation(op,
+ result,
+ true,
+ ObjectModelJavaModifier.ABSTRACT,
+ ObjectModelJavaModifier.fromVisibility(op.getVisibility())
+ );
+ }
+ }
+
+
+ protected void generateNoNMultiplicity(String clazzName,
+ ObjectModelClass result,
+ ObjectModelAttribute attr,
+ boolean isAssoc) {
+ String attrName = attr.getName();
+ String attrType = attr.getType();
+ String propertyName = clazzName + "." + getConstantName(attrName);
+
+ String attrTypeForGeneric;
+ if (JavaGeneratorUtil.isPrimitiveType(attrType)) {
+ attrTypeForGeneric = TopiaGeneratorUtil.getClassForPrimitiveType(attr);
+ } else {
+ attrTypeForGeneric = attrType;
+ }
+
+ if (!isAssoc && attr.hasAssociationClass()) {
+ String assocClassName = attr.getAssociationClass().getName();
+ String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(attr);
+ // It is about transitivity : use the property to access the
+ // associationClass + '.' + the property to access the expected
+ // attribute
+ // <class>.<attrAssoc> + '.' + <assocClass>.<attr>
+ propertyName =
+ clazzName + '.' + getConstantName(assocAttrName) +
+ " + '.' + " +
+ assocClassName + '.' + getConstantName(attrName);
+ }
+
+ ObjectModelOperation op;
+ op = addOperation(result,
+ getJavaBeanMethodName("for", attrName, "In"),
+ "TopiaQueryBuilderAddCriteriaOrRunQueryStep<E>",
+ ObjectModelJavaModifier.PUBLIC);
+ addParameter(op, "Iterable<" + attrTypeForGeneric + ">", "v");
+ setOperationBody(op, ""
+/*{
+ TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> result = forIn(<%=propertyName%>, (Iterable) v);
+ return result;
+ }*/
+ );
+
+ op = addOperation(result,
+ getJavaBeanMethodName("for", attrName, "Equals"),
+ "TopiaQueryBuilderAddCriteriaOrRunQueryStep<E>",
+ ObjectModelJavaModifier.PUBLIC);
+ addParameter(op, attrType, "v");
+ setOperationBody(op, ""
+/*{
+ TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> result = forEquals(<%=propertyName%>, v);
+ return result;
+ }*/
+ );
+
+ String methodToDelegateName = op.getName();
+
+ op = addOperation(result,
+ getJavaBeanMethodName("findBy", attrName),
+ "E",
+ ObjectModelJavaModifier.PUBLIC);
+ addParameter(op, attrType, "v");
+ setOperationBody(op, ""
+/*{
+ return <%=methodToDelegateName%>(v).findAnyOrNull();
+ }*/
+ );
+
+ addAnnotation(result, op, Deprecated.class);
+
+ op = addOperation(result,
+ getJavaBeanMethodName("findAllBy", attrName),
+ "List<E>",
+ ObjectModelJavaModifier.PUBLIC);
+ addParameter(op, attrType, "v");
+ setOperationBody(op, ""
+/*{
+ return <%=methodToDelegateName%>(v).findAll();
+ }*/
+ );
+
+ addAnnotation(result, op, Deprecated.class);
+
+ if (!isAssoc && attr.hasAssociationClass()) {
+ String assocClassName = attr.getAssociationClass().getName();
+ String assocClassFQN = attr.getAssociationClass().getQualifiedName();
+ String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(attr);
+ String assocPropertyConstantName = getConstantName(assocAttrName);
+ op = addOperation(result,
+ getJavaBeanMethodName("findBy", assocClassName),
+ "E",
+ ObjectModelJavaModifier.PUBLIC);
+ addParameter(op, assocClassFQN, "value");
+ setOperationBody(op, ""
+/*{
+ E result = findByProperty(<%=clazzName + "." + assocPropertyConstantName%>, value);
+ return result;
+ }*/
+ );
+
+ op = addOperation(result,
+ getJavaBeanMethodName("findAllBy", assocClassName),
+ "List<E>",
+ ObjectModelJavaModifier.PUBLIC);
+ addParameter(op, assocClassFQN, "value");
+ setOperationBody(op, ""
+/*{
+ List<E> result = findAllByProperty(<%=clazzName + "." + assocPropertyConstantName%>, value);
+ return result;
+ }*/
+ );
+ }
+ }
+
+ protected void generateNMultiplicity(String clazzName,
+ ObjectModelClass result,
+ ObjectModelAttribute attr) {
+ String attrName = attr.getName();
+ String attrType = attr.getType();
+ if (attr.hasAssociationClass()) {
+ // do nothing for association class, too complex...
+ return;
+ }
+ ObjectModelOperation op;
+
+ op = addOperation(result,
+ getJavaBeanMethodName("for", attrName, "Contains"),
+ "TopiaQueryBuilderAddCriteriaOrRunQueryStep<E>",
+ ObjectModelJavaModifier.PUBLIC);
+ addParameter(op, attrType, "v");
+ setOperationBody(op, ""
+/*{
+ return forContains(<%=clazzName + "." + getConstantName(attrName)%>, v);
+ }*/
+ );
+
+ String methodToDelegateName = op.getName();
+
+ op = addOperation(result,
+ getJavaBeanMethodName("findContains", attrName),
+ "E",
+ ObjectModelJavaModifier.PUBLIC);
+ addParameter(op, attrType, "v");
+ setOperationBody(op, ""
+/*{
+ return <%=methodToDelegateName%>(v).findAnyOrNull();
+ }*/
+ );
+
+ addAnnotation(result, op, Deprecated.class);
+
+ op = addOperation(result,
+ getJavaBeanMethodName("findAllContains", attrName),
+ "List<E>",
+ ObjectModelJavaModifier.PUBLIC);
+ addParameter(op, attrType, "v");
+ setOperationBody(op, ""
+/*{
+ return <%=methodToDelegateName%>(v).findAll();
+ }*/
+ );
+
+ addAnnotation(result, op, Deprecated.class);
+
+ }
+
+
+ /**
+ * Obtain business operations of the DAO.
+ *
+ * This operations can not be generated, but must be written by developper.
+ *
+ * @param clazz the clazz to test.
+ * @return collections of extra operations, or empty collection if none found.
+ * @deprecated Dao operation will not be generated anymore in a very close future
+ */
+ @Deprecated
+ public Collection<ObjectModelOperation> getDaoOperations(
+ ObjectModelClass clazz) {
+
+// // Note : this collection will contains extra operations for DAO.
+// // Overriding existing generated methods is not managed yet
+// Collection<ObjectModelOperation> results =
+// new ArrayList<ObjectModelOperation>();
+
+// // This code will be deprecated
+// for (ObjectModelOperation op : clazz.getOperations()) {
+// if (TopiaGeneratorUtil.hasDaoStereotype(op)) {
+// results.add(op);
+// }
+// }
+
+ Collection<ObjectModelOperation> extra =
+ extraOperations.get(clazz.getQualifiedName());
+ if (extra != null && !extra.isEmpty() && log.isWarnEnabled()) {
+ log.warn("Dao contract in model will not be supported in topia 3.0");
+ }
+ return extra;
+// if (extra != null) {
+// for (ObjectModelOperation op : extra) {
+// results.add(op);
+// }
+// }
+
+// return results;
+ }
+
+ private void generateNaturalId(ObjectModelClass result,
+ ObjectModelClass clazz) {
+ Set<ObjectModelAttribute> props =
+ TopiaGeneratorUtil.getNaturalIdAttributes(clazz);
+
+ if (!props.isEmpty()) {
+
+ if (log.isDebugEnabled()) {
+ log.debug("generateNaturalId for " + props);
+ }
+ ObjectModelOperation findByNaturalId = addOperation(result,
+ "findByNaturalId", "E", ObjectModelJavaModifier.PUBLIC);
+
+ ObjectModelOperation existByNaturalId = addOperation(result,
+ "existByNaturalId", "boolean", ObjectModelJavaModifier.PUBLIC);
+
+ ObjectModelOperation createByNaturalId = addOperation(result,
+ "createByNaturalId", "E", ObjectModelJavaModifier.PUBLIC);
+
+ Set<String> properties = Sets.newLinkedHashSet();
+ String clazzName = clazz.getName();
+
+ for (ObjectModelAttribute attr : props) {
+
+ String propName = attr.getName();
+ String type = attr.getType();
+
+ addParameter(findByNaturalId, type, propName);
+ addParameter(existByNaturalId, type, propName);
+ addParameter(createByNaturalId, type, propName);
+
+ String property = clazzName + '.' + getConstantName(propName) + ", " + propName;
+ properties.add(property);
+
+ }
+
+ String arguments = StringUtils.join(properties, ", ");
+
+ setOperationBody(findByNaturalId, ""
+/*{
+ return forProperties(<%=arguments%>).findUnique();
+ }*/
+ );
+
+ setOperationBody(existByNaturalId, ""
+/*{
+ return forProperties(<%=arguments%>).exists();
+ }*/
+ );
+
+ setOperationBody(createByNaturalId, ""
+/*{
+ return create(<%=arguments%>);
+ }*/
+ );
+ }
+ }
+
+ protected void generateNotNull(ObjectModelClass result,
+ ObjectModelClass clazz) {
+
+ Set<ObjectModelAttribute> props =
+ TopiaGeneratorUtil.getNotNullAttributes(clazz);
+
+ if (!props.isEmpty()) {
+
+ if (log.isDebugEnabled()) {
+ log.debug("generateNotNull for " + props);
+ }
+
+ ObjectModelOperation createByNotNull = addOperation(result,
+ "createByNotNull", "E", ObjectModelJavaModifier.PUBLIC);
+
+ String createProperties = "";
+// String params = "";
+ String clazzName = clazz.getName();
+ for (ObjectModelAttribute attr : props) {
+ String propName = attr.getName();
+ // add property as param in both methods
+ addParameter(createByNotNull, attr.getType(), propName);
+
+ createProperties +=
+ ", " + clazzName + '.' + getConstantName(propName) +
+ ", " + propName;
+ //params += ", " + propName;
+ }
+ createProperties = createProperties.substring(2);
+ //params = params.substring(2);
+
+ setOperationBody(createByNotNull, ""
+/*{
+ return create(<%=createProperties%>);
+ }*/
+ );
+ }
+ }
+}
Copied: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityHibernateMappingGenerator.java (from rev 2882, trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityHibernateMappingGenerator.java)
===================================================================
--- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityHibernateMappingGenerator.java (rev 0)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityHibernateMappingGenerator.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,743 @@
+/*{generator option: parentheses = true}*/
+/*{generator option: writeString = output.write}*/
+
+/* *
+* EntityHibernateMappingGenerator.java
+*
+* Created: 12 déc. 2005
+*
+* @author Arnaud Thimel <thimel(a)codelutin.com>
+* @version $Revision$
+*
+*/
+
+package org.nuiton.topia.templates;
+
+import org.apache.commons.lang3.BooleanUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.eugene.models.object.ObjectModelAssociationClass;
+import org.nuiton.eugene.models.object.ObjectModelAttribute;
+import org.nuiton.eugene.models.object.ObjectModelClass;
+import org.nuiton.eugene.models.object.ObjectModelGenerator;
+
+import java.beans.Introspector;
+import java.io.File;
+import java.io.IOException;
+import java.io.Writer;
+import java.sql.Types;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+
+import static org.nuiton.topia.templates.TopiaGeneratorUtil.hasUnidirectionalRelationOnAbstractType;
+
+/**
+ *
+ * @author poussin <poussin(a)codelutin.com>
+ * @version $Id$
+ * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.templates.EntityHibernateMappingGenerator"
+ */
+public class EntityHibernateMappingGenerator extends ObjectModelGenerator {
+
+ /**
+ * Logger.
+ */
+ private static final Log log = LogFactory
+ .getLog(EntityHibernateMappingGenerator.class);
+
+ private static final String HIBERNATE_ATTRIBUTE_DEFAULT = "default";
+
+ private static final String HIBERNATE_ATTRIBUTE_SQL_TYPE = "sql-type";
+
+ private static final String HIBERNATE_ATTRIBUTE_NAME = "name";
+
+ private Map<String, String[]> columnNamesMap = new HashMap<String, String[]>();
+
+ public static final String HIBERNATE_ATTRIBUTE_LAZY = "lazy";
+
+ public static final String HIBERNATE_ATTRIBUTE_FETCH = "fetch";
+
+ public static final String HIBERNATE_ATTRIBUTE_NOT_NULL = "not-null";
+
+ public static final String HIBERNATE_ATTRIBUTE_SCHEMA = "schema";
+
+ public static final String HIBERNATE_ATTRIBUTE_INDEX = "index";
+
+ public static final String HIBERNATE_ATTRIBUTE_UNIQUE = "unique";
+
+ public static final String HIBERNATE_ATTRIBUTE_LENGTH = "length";
+
+ public static final String HIBERNATE_ATTRIBUTE_ORDER_BY = "order-by";
+
+ @Override
+ public String getFilenameForClass(ObjectModelClass clazz) {
+ String DOName = TopiaGeneratorUtil.getDOType(clazz, model);
+ return DOName.replace('.', File.separatorChar) + ".hbm.xml";
+ }
+
+ @Override
+ public void generateFromClass(Writer output,
+ ObjectModelClass input) throws IOException {
+ String persistenceType = TopiaGeneratorUtil.getPersistenceType(input);
+ if (!TopiaGeneratorUtil.isEntity(input) &&
+ TopiaGeneratorUtil.PERSISTENCE_TYPE_HIBERNATE.equals(persistenceType)) {
+ return;
+ }
+/*{<?xml version="1.0" encoding="UTF-8"?>
+<hibernate-mapping xmlns="http://www.hibernate.org/xsd/hibernate-mapping"
+ xsi:schemaLocation="http://www.hibernate.org/xsd/hibernate-mapping classpath://org/hibernate/hibernate-mapping-4.0.xsd"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ default-access="field" auto-import="true" package="<%=input.getPackageName()%>">
+}*/
+ boolean haveSuper = input.getSuperclasses().size() > 0;
+ // la liste des attributs faisant parti de la clef metier
+ List<ObjectModelAttribute> naturalAttributes = new ArrayList<ObjectModelAttribute>();
+ // la liste des autres attributs
+ List<ObjectModelAttribute> noneNaturalAttributes = new ArrayList<ObjectModelAttribute>();
+
+ String clazzDOType = TopiaGeneratorUtil.getDOType(input, model);
+ String tableName = TopiaGeneratorUtil.getDbName(input);
+ String isAbstract = BooleanUtils.toStringTrueFalse(input.isAbstract());
+ String clazzFQN = input.getQualifiedName();
+
+ String optionalAttributes = "";
+ String schema = TopiaGeneratorUtil.getDbSchemaNameTagValue(input, model);
+ if (schema != null) {
+ optionalAttributes += "schema=\"" + schema + "\" ";
+ }
+
+ //On précise au proxy de quelle interface hérite l'objet
+ String proxyTagValue = TopiaGeneratorUtil.getProxyInterfaceTagValue(input, model);
+ if (StringUtils.isEmpty(proxyTagValue) || !proxyTagValue.equals("none")) {
+ optionalAttributes += "proxy=\"" + clazzFQN + "\" ";
+ }
+
+ String inheritanceStrategy = null;
+ if (haveSuper) {
+ ObjectModelClass superClass = input.getSuperclasses().iterator().next();
+ String superClassname = superClass.getQualifiedName();
+ if (log.isDebugEnabled()) {
+ log.debug("superClass for " + input.getQualifiedName() + " is " + superClassname);
+ }
+ String superClassDOType = TopiaGeneratorUtil.getDOType(superClassname, model);
+ inheritanceStrategy = TopiaGeneratorUtil.getInheritanceStrategyTagValue(superClass);
+ if ("joined-subclass".equals(inheritanceStrategy) || "union-subclass".equals(inheritanceStrategy)) {
+ optionalAttributes += "table=\"" + tableName + "\"";
+ }
+ if ("subclass".equals(inheritanceStrategy)) {
+ optionalAttributes += "discriminator-value=\"" + clazzDOType + "\"";
+ }
+/*{ <<%=inheritanceStrategy%> name="<%=clazzDOType%>" extends="<%=superClassDOType%>" node="<%=clazzDOType%>" abstract="<%=isAbstract%>" <%=optionalAttributes%>>
+}*/
+ if ("joined-subclass".equals(inheritanceStrategy)) {
+/*{ <key column="topiaId" />
+}*/
+ }
+ // FIXME mieux gerer le cas haveSuper
+ noneNaturalAttributes.addAll(input.getAttributes());
+ } else {
+/*{ <class name="<%=clazzDOType%>" table="<%=tableName%>" node="<%=clazzDOType%>" abstract="<%=isAbstract%>" <%=optionalAttributes%>>
+ <id name="topiaId" type="string" length="255" node="@topiaId"/>
+}*/
+ // cas où on defini la super class, il faut un discriminator seulement dans le cas de
+ // la strategy subclass
+ String currentInheritanceStrategy = TopiaGeneratorUtil.getInheritanceStrategyTagValue(input);
+ if ("subclass".equals(currentInheritanceStrategy)) {
+/*{ <discriminator column="topiaDiscriminator" type="string" />
+}*/
+ }
+
+ // on detecte les attributs des clef metiers
+ for (ObjectModelAttribute attr : input.getAttributes()) {
+ if (TopiaGeneratorUtil.isNaturalId(attr)) {
+ // attribut metier
+ naturalAttributes.add(attr);
+ } else {
+ // attribut normal
+ noneNaturalAttributes.add(attr);
+ }
+ }
+ if (!naturalAttributes.isEmpty()) {
+ // generation de la clef metier
+ boolean mutable = TopiaGeneratorUtil.isNaturalIdMutable(input);
+ String mutableStr = mutable ? " mutable=\"true\"" : "";
+ if (log.isDebugEnabled()) {
+ log.debug("natural-id detected for class " + input.getName() + " (" + mutableStr + ") attributes : " + naturalAttributes);
+ }
+/*{ <natural-id<%=mutableStr%>>
+}*/
+ generateAttributes(output, input, naturalAttributes, " ");
+/*{ </natural-id>
+}*/
+ }
+/*{ <version name="topiaVersion" type="long" node="@topiaVersion"/>
+ <property name="topiaCreateDate" type="timestamp" node="@topiaCreateDate"/>
+}*/
+ }
+
+ generateAttributes(output, input, noneNaturalAttributes, "");
+
+ if (haveSuper) {
+/*{ </<%=inheritanceStrategy%>>
+}*/
+ } else {
+/*{ </class>
+}*/
+ }
+
+ generateDatabaseObjects(output, input, naturalAttributes);
+ generateDatabaseObjects(output, input, noneNaturalAttributes);
+
+/*{</hibernate-mapping>
+}*/
+ }
+
+ protected void generateDatabaseObjects(Writer output,
+ ObjectModelClass clazz,
+ List<ObjectModelAttribute> attributes) throws IOException {
+
+ for (ObjectModelAttribute attribute : attributes) {
+ if (!attribute.isNavigable() ||
+ attribute.hasAssociationClass() ||
+ !TopiaGeneratorUtil.isNMultiplicity(attribute) ||
+ attribute.getClassifier() == null ||
+ !TopiaGeneratorUtil.isEntity(attribute.getClassifier())
+ ) {
+
+ // skip for this case (not a nm-multiplicity attribute)
+ continue;
+ }
+
+ String indexForeignKeys =
+ TopiaGeneratorUtil.getIndexForeignKeys(attribute, model);
+
+ if (StringUtils.isEmpty(indexForeignKeys) || !Boolean.valueOf(indexForeignKeys)) {
+
+ // no index to put of the attribute.
+ continue;
+ }
+
+ // add database-object to create and drop index
+
+ String tableName;
+ String indexName = "idx_" + clazz.getName() + "_" + attribute.getName();
+ String propertyName;
+
+
+ if (TopiaGeneratorUtil.isNMultiplicity(attribute.getReverseMaxMultiplicity())) {
+
+ // many to many
+ tableName = TopiaGeneratorUtil.getManyToManyTableName(attribute);
+ propertyName = TopiaGeneratorUtil.getDbName(attribute.getReverseAttribute());
+ } else {
+
+ // one to many
+ tableName =TopiaGeneratorUtil.getDbName(attribute.getClassifier());
+ propertyName = TopiaGeneratorUtil.getDbName(attribute.getReverseAttribute());
+ }
+
+ // add schema if exist (http://nuiton.org/issues/2052)
+ String schema = TopiaGeneratorUtil.getDbSchemaNameTagValue(clazz, model);
+ if (StringUtils.isNotEmpty(schema)) {
+ tableName = schema + "." + tableName;
+ }
+/*{ <database-object>
+ <create>CREATE INDEX <%=indexName%> ON <%=tableName%>(<%=propertyName%>)</create>
+ <drop>DROP INDEX <%=indexName%></drop>
+ </database-object>
+}*/
+
+ }
+ }
+ protected void generateAttributes(Writer output,
+ ObjectModelClass clazz,
+ List<ObjectModelAttribute> attributes,
+ String prefix) throws IOException {
+ for (ObjectModelAttribute attr : attributes) {
+ ObjectModelAttribute reverse = attr.getReverseAttribute();
+
+ // pour les asso quoi qu'il arrive il faut les lier des 2 cotes
+ // pour pouvoir supprimer en cascade l'asso lors de la suppression
+ // d'un des cotes
+ if (attr.isNavigable()
+ || hasUnidirectionalRelationOnAbstractType(reverse, model)
+ || attr.hasAssociationClass()) {
+ if (!TopiaGeneratorUtil.isNMultiplicity(attr)) {
+ if (attr.getClassifier() != null && TopiaGeneratorUtil.isEntity(attr.getClassifier())) {
+ if (TopiaGeneratorUtil.isNMultiplicity(attr.getReverseMaxMultiplicity()) && !attr.hasAssociationClass()) {
+ generateHibernateManyToOne(output, attr, prefix);
+ } else {
+ generateHibernateOneToOne(output, attr, prefix);
+ }
+ } else {
+ generateHibernateProperty(output, attr, prefix);
+ }
+ } else {
+ if (attr.getClassifier() != null && TopiaGeneratorUtil.isEntity(attr.getClassifier())) {
+ if (TopiaGeneratorUtil.isNMultiplicity(attr.getReverseMaxMultiplicity()) && !attr.hasAssociationClass()) {
+ generateHibernateManyToMany(output, attr, prefix);
+ } else {
+ generateHibernateOneToMany(output, attr, prefix);
+ }
+ } else {
+ generateHibernateMany(output, attr, prefix);
+ }
+ }
+ }
+ }
+
+ //Attributs pour les classes d'association
+ if (clazz instanceof ObjectModelAssociationClass) {
+ ObjectModelAssociationClass assoc = (ObjectModelAssociationClass)clazz;
+ for (ObjectModelAttribute attr : assoc.getParticipantsAttributes()) {
+ if (attr != null) {
+
+// Note(poussin) pour moi quoi qu'il arrive sur la classe d'association il faut
+// un many-to-one, sinon on a des problemes.
+// if ((!attr.getReverseAttribute().isNavigable()) || !Util.isNMultiplicity(attr.getReverseAttribute())) {
+// / *{ <one-to-one name="<%=getName(attr, true)%>" class="<%=getType(attr, true)%>"<%=(TopiaGeneratorUtil.notEmpty(attr.getTagValue(TopiaGeneratorUtil.TAG_LENGTH))?(" length=\"" + attr.getTagValue(TopiaGeneratorUtil.TAG_LENGTH) + "\""):"")%><%=(attr.isComposite()?" cascade=\"delete\"":"")%>/>
+// } */
+// } else {
+ String notNull = " " + generateFromTagValue(HIBERNATE_ATTRIBUTE_NOT_NULL, TopiaGeneratorUtil.getNotNullTagValue(attr));
+ String attrName = getName(attr, true);
+ String attrType = getType(attr, true);
+ String lazy = generateFromTagValue(HIBERNATE_ATTRIBUTE_LAZY, TopiaGeneratorUtil.getLazyTagValue(attr));
+ String attrColumn = TopiaGeneratorUtil.getDbName(attr);
+/*{<%=prefix%> <many-to-one name="<%=attrName%>" class="<%=attrType%>" <%=lazy%>column="<%=attrColumn%>" node="<%=attrName%>/@topiaId" <%=notNull%>/>
+}*/
+// }
+ //Ne sert plus grâce à l'utilisation de la navigabilité
+// if (!attr.getReverseAttribute().isNavigable()) {
+// String type = TopiaGeneratorUtil.getDOType(((ObjectModelClassifier)attr.getDeclaringElement()).getQualifiedName(), model);
+// String name = Util.toLowerCaseFirstLetter(attr.getDeclaringElement().getName());
+// if (log.isTraceEnabled()) {log.trace("reverse: " + type + " " + name);}
+// if (!Util.isNMultiplicity(attr)) {
+//{<!-- <one-to-one name="<%=name%>" class="<%=type%>"/>
+//}
+// } else {
+//{ <many-to-one name="<%=name%>" class="<%=type%>" column="<%=name.toLowerCase()%>"/> -->
+//}
+// }
+// }
+ }
+ }
+ }
+ }
+
+ protected String getName(ObjectModelAttribute attr) {
+ return getName(attr, false);
+ }
+
+ protected String getName(ObjectModelAttribute attr, boolean isAssoc) {
+ String result = Introspector.decapitalize(attr.getName());
+ if (attr.hasAssociationClass() && !isAssoc) {
+ result = TopiaGeneratorUtil.getAssocAttrName(attr);
+ }
+ return result;
+ }
+
+ protected String getType(ObjectModelAttribute attr) {
+ return getType(attr, false);
+ }
+
+ protected String getType(ObjectModelAttribute attr, boolean isAssoc) {
+ String type = attr.getType();
+ String attrType = TopiaGeneratorUtil.getTypeTagValue(attr);
+ if (StringUtils.isNotEmpty(attrType)) {
+
+ // tag value detected of the attribute
+ type = attrType;
+ } else {
+
+ String modelType = model.getTagValue(type);
+ if (StringUtils.isNotEmpty(modelType)) {
+
+ // tag value detected of the model
+
+ //TODO tchemit 20100507 Explain What todes it do ? Dont understand the story of columnNamesMap
+ int bracketIndex = modelType.indexOf('(');
+ if (bracketIndex != -1) {
+ type = modelType.substring(0, bracketIndex);
+ int bracketEndIndex = modelType.indexOf(')', bracketIndex + 1);
+ String colmunList;
+ if (bracketEndIndex != -1) {
+ colmunList = modelType.substring(bracketIndex + 1, bracketEndIndex);
+ } else {
+ colmunList = modelType.substring(bracketIndex);
+ }
+ columnNamesMap.put(type, colmunList.split(","));
+ } else {
+ type = modelType;
+ }
+ }
+ }
+ if (attr.hasAssociationClass() && !isAssoc) {
+ type = attr.getAssociationClass().getQualifiedName();
+ }
+ return TopiaGeneratorUtil.getDOType(type, model);
+ }
+
+ protected void generateHibernateProperty(Writer output,
+ ObjectModelAttribute attr,
+ String prefix) throws IOException {
+ String attrType = getType(attr);
+
+ String accessField = "field";
+ String tagValue = TopiaGeneratorUtil.getAccessTagValue(attr);
+ if (StringUtils.isNotEmpty(tagValue)) {
+ accessField = tagValue;
+ }
+ String attrName = attr.getName();
+ String declaringElementDBName = TopiaGeneratorUtil.getDbName(attr.getDeclaringElement());
+ String tableName = declaringElementDBName + "_" + attrName;
+
+ boolean attrIsEnumeration = attr.getClassifier() != null
+ && attr.getClassifier().isEnum();
+
+ if (attrType.trim().endsWith("[]")) {
+ attrType = attrType.trim().substring(0, attrType.trim().length()-2);
+
+ String optionalAttributes = "";
+ String schema = TopiaGeneratorUtil.getDbSchemaNameTagValue(attr, model);
+ if (schema != null) {
+ optionalAttributes += generateFromTagValue(HIBERNATE_ATTRIBUTE_SCHEMA, schema);
+// optionalAttributes += "schema=\"" + schema + "\" ";
+ }
+
+ if (TopiaGeneratorUtil.hasIndexedStereotype(attr)) {
+ String indexName = tableName + "_idx";
+ optionalAttributes += generateFromTagValue(HIBERNATE_ATTRIBUTE_INDEX, indexName);
+// optionalAttributes += "index=\"" + indexName + "\" ";
+ }
+
+/*{<%=prefix%> <primitive-array name="<%=attrName%>" table="<%=tableName%>" access="<%=accessField%>" <%=optionalAttributes%>>
+<%=prefix%> <key column="<%=declaringElementDBName%>"/>
+<%=prefix%> <list-index column="<%=attrName%>_idx"/>
+<%=prefix%> <element type="<%=attrType%>"/>
+<%=prefix%> </primitive-array>
+}*/
+ } else {
+ String optionalAttributes = "";
+ if (TopiaGeneratorUtil.hasIndexedStereotype(attr)) {
+ String indexName = tableName + "_idx";
+ optionalAttributes += generateFromTagValue(HIBERNATE_ATTRIBUTE_INDEX, indexName);
+// optionalAttributes += "index=\"" + indexName + "\"";
+ }
+
+ if (TopiaGeneratorUtil.hasUniqueStereotype(attr)) {
+ // the trim method is called on optionalAttributes after this set to suppress unusual space if no index is set on this attribute
+ optionalAttributes += generateFromTagValue(HIBERNATE_ATTRIBUTE_UNIQUE, "true");
+// optionalAttributes += " unique=\"true\"";
+ }
+ optionalAttributes += generateFromTagValue(HIBERNATE_ATTRIBUTE_NOT_NULL, TopiaGeneratorUtil.getNotNullTagValue(attr));
+/*{<%=prefix%> <property name="<%=attrName%>" access="<%=accessField%>"}*/
+ if ( ! attrIsEnumeration) {
+/*{ type="<%=attrType%>"}*/
+ }
+ optionalAttributes = optionalAttributes.trim();
+ String[] columnNames = columnNamesMap.get(attrType);
+
+ // contains all required attributes for a column node
+ Map<String,String> columnAttributes = new TreeMap<String, String>();
+ if (StringUtils.isNotEmpty(attr.getDefaultValue())) {
+ //TC-20100129 with a default value we must use the column child tag
+
+ String defaultValue = attr.getDefaultValue().trim();
+ columnAttributes.put(HIBERNATE_ATTRIBUTE_DEFAULT, defaultValue);
+ }
+ String sqlType = TopiaGeneratorUtil.getSqlTypeTagValue(attr);
+ if (!StringUtils.isEmpty(sqlType)) {
+
+ // an specific sql type was specified for the attribute, use it
+ columnAttributes.put(HIBERNATE_ATTRIBUTE_SQL_TYPE, sqlType);
+ }
+
+ // add length attribute if required
+ String lengthTagValue = TopiaGeneratorUtil.getLengthTagValue(attr);
+ if (!StringUtils.isEmpty(lengthTagValue)) {
+
+ optionalAttributes += generateFromTagValue(HIBERNATE_ATTRIBUTE_LENGTH, lengthTagValue);
+ }
+
+ optionalAttributes = optionalAttributes.trim();
+ if (StringUtils.isNotEmpty(optionalAttributes)) {
+ optionalAttributes = " " + optionalAttributes;
+ }
+
+ // to know if specific column name mapping is given
+ boolean noSpecifiedColumn = columnNames == null || columnNames.length == 0;
+
+ if (noSpecifiedColumn) {
+
+ String attrColumn = TopiaGeneratorUtil.getDbName(attr);
+
+ if (columnAttributes.isEmpty()) {
+
+ // simple case with no column node to generate
+
+/*{ column="<%=attrColumn%>" node="<%=attrName%>"<%=optionalAttributes%>}*/
+ if (attrIsEnumeration) {
+/*{>
+<%=prefix%> <type name="org.hibernate.type.EnumType">
+<%=prefix%> <param name="<%=org.hibernate.type.EnumType.ENUM%>"><%=attrType%></param>}*/
+
+ // if the user tuned the model to use name instead of
+ // ordinal to store the values, we must add a clause
+ boolean useEnumerationName = TopiaGeneratorUtil.hasUseEnumerationNameTagValue(attr, model);
+ if (useEnumerationName) {
+ String enumSQLType = String.valueOf(Types.VARCHAR);
+/*{
+<%=prefix%> <!-- using name instead of ordinal to store enumeration value -->
+<%=prefix%> <param name="<%=org.hibernate.type.EnumType.TYPE%>"><%=enumSQLType%></param>}*/
+ }
+
+/*{
+<%=prefix%> </type>
+<%=prefix%> </property>
+}*/
+ } else {
+/*{/>
+}*/
+ }
+ } else {
+
+ // there is some attributes to write for the column node
+
+ columnAttributes.put(HIBERNATE_ATTRIBUTE_NAME, attrColumn);
+
+ String columnAttributesAsString ="";
+ for (Map.Entry<String, String> entry :
+ columnAttributes.entrySet()) {
+ String name = entry.getKey();
+ String value = entry.getValue();
+ columnAttributesAsString += generateFromTagValue(name, value, null);
+ }
+ columnAttributesAsString = " " + columnAttributesAsString.trim();
+/*{<%=optionalAttributes%>>
+<%=prefix%> <column<%=columnAttributesAsString%>/>
+<%=prefix%> </property>
+}*/
+ }
+ } else {
+
+ // there is a colum name mapping specified, must use it
+ //FIXME tchemit 2010-12-29 Really don't know how to apply columnAttributes for multi-columns...
+/*{<%=optionalAttributes%>>
+}*/
+ for (String columnName : columnNames) {
+ columnName = attrName + "_" + columnName.trim();
+/*{<%=prefix%> <column name="<%=columnName%>"/>
+}*/
+ }
+/*{<%=prefix%> </property>
+}*/
+ }
+ }
+ }
+
+ protected void generateHibernateOneToOne(Writer output,
+ ObjectModelAttribute attr,
+ String prefix) throws IOException {
+// boolean accessField = hasUnidirectionalRelationOnAbstractType(attr.getReverseAttribute(), model);
+/// *{ <one-to-one name="<%=getName(attr)%>" class="<%=getType(attr)%>"<%=(TopiaGeneratorUtil.notEmpty(attr.getTagValue(TopiaGeneratorUtil.TAG_LENGTH))?(" length=\"" + attr.getTagValue(TopiaGeneratorUtil.TAG_LENGTH) + "\""):"")%><%=((attr.isComposite() || attr.hasAssociationClass())?" cascade=\"delete\"":"")%><%=((accessField)?" access=\"field\"":"")%> node="<%=getName(attr)%>/@topiaId" />
+//} */
+
+ // for hibernate many-to-one with unique="true" => one-to-one
+ // but if it is one-to-zero-or-one unique contraints is violated
+ // with null values
+ boolean unique = TopiaGeneratorUtil.isOneMultiplicity(attr);
+ generateHibernateManyToOne(output, attr, unique, prefix);
+
+ }
+
+ protected void generateHibernateOneToMany(Writer output,
+ ObjectModelAttribute attr,
+ String prefix) throws IOException {
+ boolean needsIndex = TopiaGeneratorUtil.hasIndexedStereotype(attr);
+ boolean isInverse = attr.getReverseAttribute().isNavigable();
+ isInverse |= hasUnidirectionalRelationOnAbstractType(attr, model);
+
+ String attrName = getName(attr); // ???
+ String attrType = getType(attr);
+ String reverseAttrDBName = TopiaGeneratorUtil.getReverseDbName(attr);
+ String orderBy = generateFromTagValue(HIBERNATE_ATTRIBUTE_ORDER_BY, TopiaGeneratorUtil.getOrderByTagValue(attr));
+
+ String cascade = "";
+ if (attr.isComposite() || attr.hasAssociationClass()) {
+ cascade += "cascade=\"all,delete-orphan\" ";
+ }
+
+ String lazy = generateFromTagValue(HIBERNATE_ATTRIBUTE_LAZY, TopiaGeneratorUtil.getLazyTagValue(attr), "true");
+
+ String fetch = generateFromTagValue(HIBERNATE_ATTRIBUTE_FETCH, TopiaGeneratorUtil.getFetchTagValue(attr));
+
+ String collType = TopiaGeneratorUtil.getNMultiplicityHibernateType(attr);
+ String inverse = "";
+ if (isInverse) {
+ inverse = "inverse=\"true\" ";
+ }
+ if (needsIndex) {
+/*{<%=prefix%> <<%=collType%> name="<%=attrName%>" <%=inverse%><%=lazy%><%=cascade%>node="<%=attrName%>">
+<%=prefix%> <key column="<%=reverseAttrDBName%>"/>
+<%=prefix%> <list-index column="<%=reverseAttrDBName%>_idx"/>
+<%=prefix%> <one-to-many class="<%=attrType%>" node="topiaId"/>
+<%=prefix%> </<%=collType%>>
+}*/
+ }else {
+/*{<%=prefix%> <<%=collType%> name="<%=attrName%>" <%=inverse%><%=orderBy%><%=fetch%><%=lazy%><%=cascade%>node="<%=attrName%>">
+<%=prefix%> <key column="<%=reverseAttrDBName%>"/>
+<%=prefix%> <one-to-many class="<%=attrType%>" node="topiaId"/>
+<%=prefix%> </<%=collType%>>
+}*/
+ }
+ }
+
+ private String generateFromTagValue(String attributeName, String tagValue) {
+ return generateFromTagValue(attributeName, tagValue, null);
+ }
+
+ /**
+ * Generate hibernate xml attribute with a final space.
+ * @param attributeName
+ * @param tagValue
+ * @param defaultValue
+ * @return
+ */
+ private String generateFromTagValue(String attributeName, String tagValue, String defaultValue) {
+ String result = "";
+ if (StringUtils.isNotEmpty(tagValue)) {
+ result+= attributeName + "=\"" + tagValue+"\" ";
+ } else if (defaultValue != null) {
+ result+= attributeName + "=\"" + defaultValue +"\" ";
+ }
+// if (attr.hasTagValue(tagName) || defaultValue != null) {
+// result+= attributeName + "=\"";
+// if (attr.hasTagValue(tagName)) {
+// result += attr.getTagValue(tagName);
+// } else {
+// result += defaultValue;
+// }
+// result += "\" ";
+// }
+ return result;
+ }
+
+ protected void generateHibernateMany(Writer output,
+ ObjectModelAttribute attr,
+ String prefix) throws IOException {
+ boolean needsIndex = TopiaGeneratorUtil.hasIndexedStereotype(attr);
+ String attrName = getName(attr);
+ String attrType = getType(attr);
+ String collType = TopiaGeneratorUtil.getNMultiplicityHibernateType(attr);
+ String lazy = generateFromTagValue(HIBERNATE_ATTRIBUTE_LAZY, TopiaGeneratorUtil.getLazyTagValue(attr));
+ String attrColumn = TopiaGeneratorUtil.getDbName(attr);
+
+/*{<%=prefix%> <<%=collType%> name="<%=attrName%>" <%=lazy%>node="<%=attrName%>">
+<%=prefix%> <key column="OWNER"/>
+}*/
+ if (needsIndex) {
+/*{<%=prefix%> <list-index/>
+}*/
+ }
+/*{<%=prefix%> <element type="<%=attrType%>" column="<%=attrColumn%>" node="id"/>
+<%=prefix%> </<%=collType%>>
+}*/
+ }
+
+ protected void generateHibernateManyToOne(Writer output,
+ ObjectModelAttribute attr,
+ String prefix) throws IOException {
+ generateHibernateManyToOne(output, attr, false, prefix);
+ }
+
+ protected void generateHibernateManyToOne(Writer output,
+ ObjectModelAttribute attr,
+ boolean isUnique,
+ String prefix) throws IOException {
+ String attrName = getName(attr);
+ String attrType = getType(attr);
+ String attrColumn = TopiaGeneratorUtil.getDbName(attr);
+/*{<%=prefix%> <many-to-one name="<%=attrName%>" class="<%=attrType%>" column="<%=attrColumn%>" }*/
+ if (attr.isComposite() || attr.hasAssociationClass()) {
+/*{cascade="delete" }*/
+ }
+ // Pour le test suivant, on verifie d'abord que l'attribut a un reverse.
+ // S'il n'en a pas, cela signifie qu'il ne s'agit pas d'un entite
+ // (au sens stereotype entity), donc a donc pas besoin de faire un access=field.
+ if (attr.getReverseAttribute() != null && hasUnidirectionalRelationOnAbstractType(attr.getReverseAttribute(), model)) {
+/*{access="field" }*/
+ }
+ // vérifier si le tag lazy est defini par defaut dans le fichier de proprietes
+ String lazy = generateFromTagValue(HIBERNATE_ATTRIBUTE_LAZY, TopiaGeneratorUtil.getLazyTagValue(attr));
+/*{<%=lazy%>}*/
+ String notNull = generateFromTagValue(HIBERNATE_ATTRIBUTE_NOT_NULL, TopiaGeneratorUtil.getNotNullTagValue(attr));
+/*{<%=notNull%>}*/
+ if (isUnique) {
+/*{unique="true" }*/
+ }
+/*{node="<%=attrName%>/@topiaId"}*/
+
+/*{/>
+}*/
+ }
+
+ protected void generateHibernateManyToMany(Writer output,
+ ObjectModelAttribute attr,
+ String prefix) throws IOException {
+ // On ne met le inverse="true" uniquement pour un seul coté de la relation.
+ // Dans le cas contraire, les modifications dans la relation ne seront
+ // pas sauvegardées. Ceci n'est vrai que si les deux coté sont navigable
+ boolean isInverse = attr.isNavigable() && attr.getReverseAttribute().isNavigable();
+ //isInverse |= !Util.isFirstAttribute(attr);
+ //isInverse = false; // 20070117 poussin: pour du many, jamais de inverse
+
+ // Modification FD-2010-04-01 :
+ // Le tagvalue "inverse" permet de spécifier qui possède le
+ // inverse="true". Il est impératif de l'utiliser sur les deux
+ // extrémités pour ne pas avoir de surprise.
+ String inverseValue = TopiaGeneratorUtil.getInverseTagValue(attr);
+ if (StringUtils.isNotEmpty(inverseValue)) {
+ isInverse &= Boolean.parseBoolean(inverseValue);
+ // Si aucun tagvalue n'est défini, le choix est arbitraire : le
+ // premier attribut dans l'ordre alphabétique sera choisi pour porter le
+ // inverse="true"
+ } else {
+ isInverse &= TopiaGeneratorUtil.isFirstAttribute(attr);
+ }
+
+ boolean needsIndex = TopiaGeneratorUtil.hasIndexedStereotype(attr);
+ String cascade = "";
+ if (attr.isComposite() || attr.hasAssociationClass()) {
+ cascade = " cascade=\"delete,delete-orphan\"";
+ }
+
+ String attrType = getType(attr);
+ String attrName = getName(attr);
+ String attrColumn = TopiaGeneratorUtil.getDbName(attr);
+ String lazy = generateFromTagValue(HIBERNATE_ATTRIBUTE_LAZY, TopiaGeneratorUtil.getLazyTagValue(attr), "true");
+ String orderBy = generateFromTagValue(HIBERNATE_ATTRIBUTE_ORDER_BY, TopiaGeneratorUtil.getOrderByTagValue(attr));
+ String collType = TopiaGeneratorUtil.getNMultiplicityHibernateType(attr);
+ String tableName = TopiaGeneratorUtil.getManyToManyTableName(attr);
+ String inverse = "";
+ if (isInverse) {
+ inverse = "inverse=\"true\" ";
+ }
+ String reverseAttrDBName = TopiaGeneratorUtil.getReverseDbName(attr);
+
+/*{<%=prefix%> <<%=collType%> name="<%=attrName%>" table="<%=tableName%>" <%=inverse%><%=lazy%><%=cascade%> node="<%=attrName%>">
+<%=prefix%> <key column="<%=reverseAttrDBName%>"/>
+}*/
+ if (needsIndex) {
+/*{<%=prefix%> <list-index column="<%=reverseAttrDBName%>_idx"/>
+}*/
+ }
+/*{<%=prefix%> <many-to-many class="<%=attrType%>" column="<%=attrColumn%>" <%=orderBy%>node="topiaId"/>
+<%=prefix%> </<%=collType%>>
+}*/
+ }
+
+} //EntityHibernateMappingGenerator
Copied: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityTransformer.java (from rev 2882, trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityTransformer.java)
===================================================================
--- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityTransformer.java (rev 0)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityTransformer.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,1630 @@
+package org.nuiton.topia.templates;
+
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.builder.ToStringBuilder;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.eugene.EugeneTagValues;
+import org.nuiton.eugene.java.ObjectModelTransformerToJava;
+import org.nuiton.eugene.models.object.ObjectModelAssociationClass;
+import org.nuiton.eugene.models.object.ObjectModelAttribute;
+import org.nuiton.eugene.models.object.ObjectModelClass;
+import org.nuiton.eugene.models.object.ObjectModelClassifier;
+import org.nuiton.eugene.models.object.ObjectModelInterface;
+import org.nuiton.eugene.models.object.ObjectModelJavaModifier;
+import org.nuiton.eugene.models.object.ObjectModelModifier;
+import org.nuiton.eugene.models.object.ObjectModelOperation;
+import org.nuiton.eugene.models.object.ObjectModelParameter;
+import org.nuiton.topia.TopiaDaoSupplier;
+import org.nuiton.topia.TopiaException;
+import org.nuiton.topia.persistence.EntityVisitor;
+import org.nuiton.topia.persistence.TopiaEntity;
+import org.nuiton.topia.persistence.TopiaEntityAbstract;
+import org.nuiton.topia.persistence.TopiaEntityContextable;
+import org.nuiton.topia.persistence.util.TopiaEntityHelper;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Set;
+
+import static org.nuiton.topia.templates.TopiaGeneratorUtil.hasUnidirectionalRelationOnAbstractType;
+
+
+
+/*{generator option: parentheses = false}*/
+/*{generator option: writeString = +}*/
+
+/**
+ * A template to generate all the {@link TopiaEntity} api for all classifier
+ * with a {@code entity} stereotype.
+ *
+ * For example, given a {@code House} entity, it will generates :
+ * <ul>
+ * <li>{@code House} : contract of entity</li>
+ * <li>{@code AbstractHouse} : default abstract implementation of entity</li>
+ * <li>{@code HouseImpl} : default impl of abstract entity</li>
+ * </ul>
+ *
+ * <b>Note: </b> The impl will ony be generated in these cases :
+ * <ul>
+ * <li>There is no abstract method</li>
+ * <li>There is no already defined such class in class-path</li>
+ * </ul>
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.3.4
+ * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.templates.EntityTransformer"
+ */
+public class EntityTransformer extends ObjectModelTransformerToJava {
+
+ /** Logger */
+ private static final Log log = LogFactory.getLog(EntityTransformer.class);
+
+ protected ObjectModelInterface outputInterface;
+
+ protected ObjectModelClass outputAbstract;
+
+ protected ObjectModelClass outputImpl;
+
+ private boolean associationClass;
+
+ protected boolean generateInterface;
+
+ protected boolean generateAbstract;
+
+ protected boolean generateImpl;
+
+ protected boolean generateBooleanGetMethods;
+
+ protected void clean() {
+ outputInterface = null;
+ outputAbstract = null;
+ outputImpl = null;
+ }
+
+ @Override
+ public void transformFromClass(ObjectModelClass input) {
+
+ if (!TopiaGeneratorUtil.isEntity(input)) {
+
+ // not an entity, skip class.
+ return;
+ }
+
+ if (log.isDebugEnabled()) {
+ log.debug("for entity : " + input.getQualifiedName());
+ log.debug("Will use classLoader " + getClassLoader());
+ }
+
+ // fix once for all the constant prefix to use
+ String prefix = getConstantPrefix(input, "");
+ if (StringUtils.isEmpty(prefix)) {
+
+ // no specific prefix, so no prefix
+ if (log.isWarnEnabled()) {
+ log.warn("[" + input.getName() + "] Will generate constants with NO prefix, not a good idea... \n" +
+ "Use '" + EugeneTagValues.TAG_CONSTANT_PREFIX +
+ "' tagvalue in your xmi properties. For example " +
+ "for all the model : model.tagvalue." + EugeneTagValues.TAG_CONSTANT_PREFIX + "=PROPERTY_");
+ }
+ }
+ setConstantPrefix(prefix);
+
+ generateInterface = isGenerateInterface(input);
+ generateAbstract = isGenerateAbstract(input);
+ generateImpl = isGenerateImpl(input);
+
+ generateBooleanGetMethods = TopiaGeneratorUtil.isDoNotGenerateBooleanGetMethods(model, input);
+
+ if (generateInterface) {
+
+ // Create Entity Interface and its header
+ createEntityInterface(input);
+ }
+
+ if (generateAbstract) {
+
+ // Create Entity Abstract class and its header
+ createEntityAbstractClass(input);
+ }
+
+ // Generate i18n block
+ String i18nPrefix = TopiaGeneratorUtil.getI18nPrefixTagValue(input, model);
+ if (!StringUtils.isEmpty(i18nPrefix)) {
+ generateI18nBlock(input, outputAbstract, i18nPrefix);
+ }
+
+ // Create accept operation, will be updated during property generation
+ createAcceptOperation();
+
+ // Add constant, attribute and operations for each property
+ generateProperties(input.getAttributes());
+
+ // Case of association class : properties from participants/extremities
+ // of the association class.
+ if (input instanceof ObjectModelAssociationClass) {
+ ObjectModelAssociationClass association =
+ (ObjectModelAssociationClass)input;
+ associationClass = true;
+ generateProperties(association.getParticipantsAttributes());
+ associationClass = false;
+ }
+
+ closeAcceptOperation();
+
+ // Add extra constants (from uml dependency)
+ generateExtraConstants(input);
+
+ // Add extra operations (defined on the entity)
+ generateExtraOperations(input);
+
+ // Implement aggregate and composite operations
+ generateAggregateOperation(input);
+ generateCompositeOperation(input);
+
+ // Implement toString operation
+ if (TopiaGeneratorUtil.generateToString(input, model)) {
+ generateToStringOperation(input);
+ }
+
+ // Generate serialVersionUID on abstract class
+ generateSerialVersionUID(input, outputAbstract);
+
+ // Generate Entity Implementation class
+ if (generateImpl) {
+ generateImpl(input);
+ generateSerialVersionUID(input, outputImpl);
+ }
+
+
+
+ // Clean data output after transformation
+ clean();
+ }
+
+ protected void generateSerialVersionUID(ObjectModelClass input,
+ ObjectModelClass ouput) {
+
+ // serialVersionUID
+ String svUID = TopiaGeneratorUtil.findTagValue(TopiaGeneratorUtil.SERIAL_VERSION_UID,
+ input,
+ model
+ );
+ if (svUID == null) {
+
+ // use a default one
+ svUID = TopiaGeneratorUtil.generateSerialVersionUID(ouput) + "L";
+ }
+ addConstant(ouput, TopiaGeneratorUtil.SERIAL_VERSION_UID, long.class, svUID,
+ ObjectModelJavaModifier.PRIVATE);
+ }
+
+ protected void createEntityInterface(ObjectModelClass input) {
+
+ outputInterface = createInterface(input.getName(),
+ input.getPackageName());
+
+ // Documentation
+ if (TopiaGeneratorUtil.hasDocumentation(input)) {
+ setDocumentation(outputInterface, input.getDocumentation());
+ }
+
+ if (log.isTraceEnabled()) {
+ log.trace("Will add interfaces on " +
+ outputInterface.getQualifiedName());
+ }
+
+ List<String> interfaceAlreadyDone = new LinkedList<String> ();
+ // Extends
+ for (ObjectModelClassifier parent : input.getInterfaces()) {
+ addInterface(interfaceAlreadyDone, outputInterface, parent);
+ }
+
+ // Extends from inheritance
+ boolean needTopiaEntity = true;
+ for (ObjectModelClassifier parent : input.getSuperclasses()) {
+ if (TopiaGeneratorUtil.isEntity(parent)) {
+ addInterface(interfaceAlreadyDone, outputInterface, parent);
+ needTopiaEntity = false;
+ break;
+ }
+ }
+
+ // Extends TopiaEntity (only if hasn't parent entity)
+ if (needTopiaEntity) {
+
+ Class<?> interfaze = TopiaEntity.class;
+
+ if (TopiaGeneratorUtil.isContextable(input)) {
+ interfaze = TopiaEntityContextable.class;
+ }
+
+ addInterface(interfaceAlreadyDone,
+ outputInterface,
+ interfaze);
+
+ } else if (TopiaGeneratorUtil.isContextable(input)) {
+ // Even if there is no need to implement TopiaEntity, it might be
+ // necessary to implement TopiaEntityContextable
+ addInterface(interfaceAlreadyDone,
+ outputInterface,
+ TopiaEntityContextable.class);
+ }
+ }
+
+ protected void createEntityAbstractClass(ObjectModelClass input) {
+
+ outputAbstract = createAbstractClass(input.getName() + "Abstract",
+ input.getPackageName());
+
+ // Documentation
+ StringBuilder doc = new StringBuilder();
+ doc.append("Implantation POJO pour l'entité {@link ");
+ doc.append(StringUtils.capitalize(outputInterface.getName()));
+ doc.append("}\n");
+
+ String dbName = TopiaGeneratorUtil.getDbName(input);
+ if (dbName != null) {
+ doc.append("<p>Nom de l'entité en BD : ");
+ doc.append(dbName);
+ doc.append(".</p>");
+ }
+
+ setDocumentation(outputAbstract, doc.toString());
+
+ // Implements
+ addInterface(outputAbstract, outputInterface.getName());
+
+ // Extends
+ for (ObjectModelClass parent : input.getSuperclasses()) {
+ //tchemit-2011-09-12 What ever abstract or not, we alwyas use an Impl, moreover use the util method instead
+ String extendClass = TopiaGeneratorUtil.getDOType(parent, model);
+// String extendClass = parent.getQualifiedName();
+// //Si une des classes parentes définies des méthodes abstraites, son
+// // impl ne sera pas créé
+// boolean abstractParent = TopiaGeneratorUtil.shouldBeAbstract(parent);
+// if (TopiaGeneratorUtil.isEntity(parent)) {
+// if (abstractParent) {
+// extendClass += "Abstract";
+// } else {
+// extendClass += "Impl";
+// }
+// }
+ setSuperClass(outputAbstract, extendClass);
+ }
+
+ // Extends TopiaEntityAbstract (only if hasn't parent entity)
+ if (outputAbstract.getSuperclasses().isEmpty()) {
+ setSuperClass(outputAbstract, TopiaEntityAbstract.class);
+ }
+
+ addContextableMethods(input, outputAbstract);
+ }
+
+ /**
+ * Ajout les methodes necessaire à l'interface {@link TopiaEntityContextable}
+ * si le tagValue {@link TopiaTagValues#TAG_CONTEXTABLE} est renseigné.
+ * @param input
+ * @param outputAbstract
+ */
+ protected void addContextableMethods(ObjectModelClass input,
+ ObjectModelClass outputAbstract) {
+
+ if (TopiaGeneratorUtil.isContextable(input)) {
+
+ addImport(outputAbstract, TopiaDaoSupplier.class);
+
+ // topiaContext attribute
+ ObjectModelAttribute topiaContextAttribute = addAttribute(
+ outputAbstract, "topiaDaoSupplier", TopiaDaoSupplier.class, null,
+ ObjectModelJavaModifier.PROTECTED, ObjectModelJavaModifier.TRANSIENT);
+ setDocumentation(topiaContextAttribute,
+ "TopiaDAO instance associated with the current \n" +
+ "instance. For internal usage only");
+
+ ObjectModelOperation op = addOperation(outputAbstract,
+ "getTopiaDAOSupplier", TopiaDaoSupplier.class,
+ ObjectModelJavaModifier.PUBLIC);
+ setDocumentation(op,"@since 3.0");
+ addAnnotation(outputAbstract, op, Override.class);
+ setOperationBody(op, ""
+/*{
+ return topiaDaoSupplier;
+ }*/
+ );
+
+ op = addOperation(outputAbstract,
+ "setTopiaDAOSupplier", "void",
+ ObjectModelJavaModifier.PUBLIC);
+ addException(op, TopiaException.class);
+ addParameter(op, TopiaDaoSupplier.class, "topiaDaoSupplier");
+ setDocumentation(op,
+// "@param context The context to set.\n" +
+// "@throws TopiaException if trying to replace a context\n" +
+ "@since 3.0");
+ addAnnotation(outputAbstract, op, Override.class);
+ setOperationBody(op, ""
+/*{
+ if (this.topiaDaoSupplier == null) {
+ this.topiaDaoSupplier = topiaDaoSupplier;
+// } else {
+// throw new TopiaException("TopiaContext replacement is forbidden");
+ }
+ }*/
+ );
+
+ op = addOperation(outputAbstract, "update", "void",
+ ObjectModelJavaModifier.PUBLIC);
+ addException(op, TopiaException.class);
+// setDocumentation(op,"@since 2.5.3");
+ addAnnotation(outputAbstract, op, Override.class);
+ setOperationBody(op, ""
+/*{
+ getTopiaDAOSupplier().getDao(<%=input.getName()%>.class).update(this);
+ }*/
+ );
+
+ op = addOperation(outputAbstract, "delete", "void", ObjectModelJavaModifier.PUBLIC);
+ addException(op, TopiaException.class);
+// setDocumentation(op,"@since 2.5.3");
+ addAnnotation(outputAbstract, op, Override.class);
+ setOperationBody(op, ""
+/*{
+ getTopiaDAOSupplier().getDao(<%=input.getName()%>.class).delete(this);
+ }*/
+ );
+ }
+ }
+
+ protected boolean isGenerateInterface(ObjectModelClass input) {
+
+ boolean alreadyInClassPath = !isInClassPath(input);
+ return alreadyInClassPath;
+ }
+
+ protected boolean isGenerateAbstract(ObjectModelClass input) {
+
+ String fqn = input.getQualifiedName() + " Abstract";
+ boolean alreadyInClassPath = !isInClassPath(fqn);
+ return alreadyInClassPath;
+ }
+
+ protected boolean isGenerateImpl(ObjectModelClass input) {
+
+ Collection<ObjectModelOperation> operations = input.getOperations();
+ String fqn = input.getQualifiedName() + "Impl";
+
+ boolean alreadyInClassPath = isInClassPath(fqn);
+ if (alreadyInClassPath) {
+
+ return false;
+ }
+
+ // On ne génère pas le impl si l'entité a des opérations
+ if (!operations.isEmpty()) {
+
+ log.info("Will not generate [" + fqn + "], there is some operations to manually implement");
+ return false;
+ }
+
+ //De même, on ne génère pas le impl si il y a des opérations venant des
+ // superclasses non implémentées
+ for (ObjectModelOperation otherOp : input.getAllOtherOperations(false)) {
+ if (otherOp.isAbstract()) {
+ log.info("Will not generate [" + fqn + "], there is an abstract operation [" + otherOp.getName() + "] in allOtherOperations.");
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ protected void generateImpl(ObjectModelClass input) {
+
+ String implName = input.getName() + "Impl";
+ String packageName = input.getPackageName();
+ if (isVerbose()) {
+ log.info("Will generate [" + implName + "]");
+ }
+
+ if (isAbstract(input)) {
+ outputImpl = createAbstractClass(implName, packageName);
+ } else {
+ outputImpl = createClass(implName, packageName);
+ }
+
+ setDocumentation(outputImpl, "Implantation des operations pour l'entité " +
+ input.getName() + ".");
+ setSuperClass(outputImpl, input.getQualifiedName() + "Abstract");
+ }
+
+ /**
+ * Generate extra constants if {@code input} has dependencies on
+ * enum used as constant injector.
+ *
+ * @param input Entity class to treate
+ */
+ protected void generateExtraConstants(ObjectModelClass input) {
+ Set<String> constants = addConstantsFromDependency(input, outputInterface);
+
+ if (log.isDebugEnabled()) {
+ log.debug("Add constants from dependency : " + constants);
+ }
+ }
+
+ protected void generateExtraOperations(ObjectModelClass input) {
+ for (ObjectModelOperation operation : input.getOperations()) {
+
+ String opName = operation.getName();
+ String opType = operation.getReturnType();
+ ObjectModelModifier visibility =
+ ObjectModelJavaModifier.fromVisibility(operation.getVisibility());
+
+ if (log.isDebugEnabled()) {
+ log.debug("Extra operation for : " + input.getQualifiedName() +
+ " - method : " + opName +
+ " - returnType : " + opType +
+ " - visibility : " + visibility);
+ }
+
+ // Deprecated from 2.3.4
+ // Pas de génération des signatures de méthodes pour celles à intégrer au DAO de l'entité
+ if (TopiaGeneratorUtil.hasDaoStereotype(operation)) {
+ return;
+
+ // Generate entity methods which have not a public visibility.
+ // Only in abstract entity class as abstract operation.
+ } else if (!visibility.equals(ObjectModelJavaModifier.PUBLIC)) {
+ addOperation(outputAbstract, opName, opType, visibility,
+ ObjectModelJavaModifier.ABSTRACT);
+
+ // Other operations, only in entity interface, implementations
+ // need to be done in implementation class created by developper
+ } else {
+ cloneOperationSignature(operation, outputInterface, true);
+ }
+ }
+ }
+
+ /**
+ * Generate properties from {@code attributes}. Generate
+ * constant, attribute and operations for each property.
+ *
+ * @param attributes Input attributes
+ */
+ protected void generateProperties(Collection<ObjectModelAttribute> attributes) {
+ for (ObjectModelAttribute attribute : attributes) {
+
+ if (!associationClass) {
+
+ // FIXME-fdesbois-2010-06-25 : Strange behavior to keep those links, will break hibernate, may be a problem in mapping
+ if (!attribute.isNavigable() && attribute.hasAssociationClass()) {
+ generatePropertyConstant(attribute);
+
+ generatePropertyAttribute(attribute);
+
+ updateAcceptOperation(attribute);
+ }
+
+ if (!attribute.isNavigable() &&
+ !TopiaGeneratorUtil.hasUnidirectionalRelationOnAbstractType(
+ attribute.getReverseAttribute(), model)) {
+ continue;
+ }
+ }
+
+ // constant
+ generatePropertyConstant(attribute);
+
+ // attribute
+ generatePropertyAttribute(attribute);
+
+ // operations
+ generatePropertyOperations(attribute);
+
+ // update accept body
+ updateAcceptOperation(attribute);
+ }
+ }
+
+ // -------------------------------------------------------------------------
+ // Generate for property
+ // -------------------------------------------------------------------------
+
+ /**
+ * Generate constant in interface for {@code attribute}.
+ *
+ * @param attribute Input attribute to treate
+ * @see #getPropertyName(ObjectModelAttribute)
+ */
+ protected void generatePropertyConstant(ObjectModelAttribute attribute) {
+ String attrName = getPropertyName(attribute);
+
+ if (log.isDebugEnabled()) {
+ log.debug("Generate constant for property : " + attrName);
+ }
+
+ addAttribute(outputInterface, getConstantName(attrName), String.class,
+ "\"" + attrName + "\"");
+ }
+
+ protected void generatePropertyAttribute(ObjectModelAttribute attribute) {
+
+ String attrName = getPropertyName(attribute);
+ String attrType = getPropertyType(attribute);
+ String collectionType = getCollectionType(attribute);
+
+ if (collectionType != null) {
+ attrType = collectionType + "<" + attrType + ">";
+ }
+
+ //String attrVisibility = attr.getVisibility();
+
+ // Declaration
+ ObjectModelAttribute property =
+ addAttribute(outputAbstract, attrName, attrType, null,
+ //ObjectModelJavaModifier.toValue(attrVisibility),
+ ObjectModelJavaModifier.PROTECTED
+ );
+
+ // Documentation
+ StringBuilder buffer = new StringBuilder();
+ if (TopiaGeneratorUtil.hasDocumentation(attribute)) {
+ String attrDocumentation = attribute.getDocumentation();
+ buffer.append(attrDocumentation).append('\n');
+ }
+
+ String dbName = TopiaGeneratorUtil.getDbName(attribute);
+ if (!StringUtils.isEmpty(dbName)) {
+ buffer.append("Nom de l'attribut en BD : ").append(dbName).append('\n');
+ }
+ setDocumentation(property, buffer.toString());
+
+ // Annotation
+ String annotation = TopiaGeneratorUtil.getAnnotationTagValue(attribute);
+ if (!StringUtils.isEmpty(annotation)) {
+ //FIXME Make annotation works...
+ //TODO tchemit 20100513 Test it still works
+ addAnnotation(outputAbstract, property, annotation);
+ }
+ }
+
+ /**
+ * Generation operations for {@code attributes}.
+ * One method exists for each operation to generate. Methods starting
+ * with 'addSingle' is for maxMultiplicity attribute = 1 and for collection
+ * case, methods start with 'addMultiple'. Other case are take care in each
+ * method (association class, reverse, entity reference, ...).
+ *
+ * @param attribute Input attribute to treate
+ * @see #addSingleGetOperation(ObjectModelAttribute, String, String)
+ * @see #addSingleSetOperation(ObjectModelAttribute)
+ * @see #addMultipleAddOperation(ObjectModelAttribute, String)
+ * @see #addMultipleAddAllOperation(ObjectModelAttribute, String)
+ * @see #addMultipleSetOperation(ObjectModelAttribute, String, String)
+ * @see #addMultipleRemoveOperation(ObjectModelAttribute)
+ * @see #addMultipleClearOperation(ObjectModelAttribute, String, String)
+ * @see #addMultipleGetOperation(ObjectModelAttribute, String)
+ * @see #addMultipleGetTopiaIdOperation(ObjectModelAttribute)
+ * @see #addMultipleGetOperationFromEntity(ObjectModelAttribute)
+ * @see #addMultipleSizeOperation(ObjectModelAttribute)
+ * @see #addMultipleIsEmptyOperation(ObjectModelAttribute)
+ */
+ protected void generatePropertyOperations(ObjectModelAttribute attribute) {
+
+ if (attribute.getMaxMultiplicity() == 1 || associationClass) {
+
+ // setXXX
+ addSingleSetOperation(attribute);
+
+ boolean booleanProperty =
+ TopiaGeneratorUtil.isBooleanPrimitive(attribute);
+
+ String attrType = getPropertyType(attribute);
+
+ if (booleanProperty) {
+
+ // isXXX
+ addSingleGetOperation(
+ attribute,
+ attrType,
+ TopiaGeneratorUtil.OPERATION_GETTER_BOOLEAN_PREFIX);
+ }
+
+ if (!booleanProperty || generateBooleanGetMethods) {
+
+ // getXXX
+ addSingleGetOperation(
+ attribute,
+ attrType,
+ TopiaGeneratorUtil.OPERATION_GETTER_DEFAULT_PREFIX);
+ }
+
+ } else {
+
+ // List, Set or Collection ?
+ String collectionInterface =
+ TopiaGeneratorUtil.getNMultiplicityInterfaceType(attribute);
+ String collectionImpl =
+ TopiaGeneratorUtil.getNMultiplicityObjectType(attribute);
+
+ addImport(outputInterface, collectionInterface);
+ addImport(outputAbstract, collectionInterface);
+ addImport(outputAbstract, collectionImpl);
+
+ collectionInterface =
+ TopiaGeneratorUtil.getSimpleName(collectionInterface);
+ collectionImpl =
+ TopiaGeneratorUtil.getSimpleName(collectionImpl);
+
+ // addXXX
+ addMultipleAddOperation(attribute, collectionImpl);
+
+ // addAllXXX
+ addMultipleAddAllOperation(attribute, collectionInterface);
+
+ // setXXX
+ addMultipleSetOperation(attribute, collectionInterface, collectionImpl);
+
+ // removeXXX
+ addMultipleRemoveOperation(attribute);
+
+ // clearXXX
+ addMultipleClearOperation(attribute, collectionInterface, collectionImpl);
+
+ // getXXX
+ addMultipleGetOperation(attribute, collectionInterface);
+
+ if (TopiaGeneratorUtil.isEntity(attribute, model)) {
+
+ // getXXXByTopiaId
+ addMultipleGetTopiaIdOperation(attribute);
+ }
+
+ if (attribute.hasAssociationClass()) {
+ // getXXX with entity parameter
+ addMultipleGetOperationFromEntity(attribute);
+ }
+
+ // sizeXXX
+ addMultipleSizeOperation(attribute);
+
+ // isXXXEmpty
+ addMultipleIsEmptyOperation(attribute);
+ }
+ }
+
+ protected void addSingleSetOperation(ObjectModelAttribute attribute) {
+
+ String attrName = getPropertyName(attribute);
+ String attrType = getPropertyType(attribute);
+
+ if (log.isDebugEnabled()) {
+ log.debug("Generate single 'set' operation for property : " + attrName +
+ " [" + attrType + "]");
+ }
+
+ // Interface operation
+ ObjectModelOperation interfaceOperation =
+ createPropertySetterSignature(outputInterface, attrType, attrName,
+ "");
+
+ // Implementation
+ ObjectModelOperation implOperation = createImplOperation(interfaceOperation);
+
+ attrType = TopiaGeneratorUtil.getSimpleName(attrType);
+
+ String constantName = getConstantName(attrName);
+
+ setOperationBody(implOperation, ""
+/*{
+ <%=attrType%> oldValue = this.<%=attrName%>;
+ fireOnPreWrite(<%=constantName%>, oldValue, <%=attrName%>);
+ this.<%=attrName%> = <%=attrName%>;
+ fireOnPostWrite(<%=constantName%>, oldValue, <%=attrName%>);
+ }*/
+ );
+ }
+
+ /**
+ * Add getter for simple property (neither association nor multiple).
+ * Will add two different operations for boolean case ('is' method and
+ * 'get' method). This method add the operation in both {@code
+ * outputAbstract} and {@code outputInterface}.
+ *
+ * @param attribute ObjectModelAttribute for getter operation
+ * @param attrType type of the attribute
+ * @param operationPrefix Operation prefix : 'get' by default, if prefix
+ * is null
+ */
+ protected void addSingleGetOperation(ObjectModelAttribute attribute,
+ String attrType,
+ String operationPrefix) {
+
+ String attrName = getPropertyName(attribute);
+
+ if (log.isDebugEnabled()) {
+ log.debug("Generate single '" + operationPrefix + "' operation for property : "
+ + attrName + " [" + attrType + "]");
+ }
+
+ String constantName = getConstantName(attrName);
+
+ // Interface operation
+ ObjectModelOperation interfaceOperation =
+ addOperation(outputInterface, getJavaBeanMethodName(operationPrefix, attrName),
+ attrType, ObjectModelJavaModifier.PACKAGE);
+
+ // Implementation
+ ObjectModelOperation implOperation =
+ createImplOperation(interfaceOperation);
+
+ attrType = TopiaGeneratorUtil.getSimpleName(attrType);
+
+ setOperationBody(implOperation, ""
+/*{
+ fireOnPreRead(<%=constantName%>, <%=attrName%>);
+ <%=attrType%> result = this.<%=attrName%>;
+ fireOnPostRead(<%=constantName%>, <%=attrName%>);
+ return result;
+ }*/
+ );
+ }
+
+ protected void addMultipleAddOperation(ObjectModelAttribute attribute,
+ String collectionImpl) {
+
+ String attrName = getPropertyName(attribute);
+ String attrType = getPropertyType(attribute);
+ ObjectModelAttribute reverse = attribute.getReverseAttribute();
+
+ if (log.isDebugEnabled()) {
+ log.debug("Generate multiple 'add' operation for property : " + attrName +
+ " [" + attrType + "]");
+ }
+
+ String constantName = getConstantName(attrName);
+
+ // Interface operation
+ ObjectModelOperation interfaceOperation =
+ addOperation(outputInterface, getJavaBeanMethodName("add", attrName),
+ void.class, ObjectModelJavaModifier.PACKAGE);
+ ObjectModelParameter param =
+ addParameter(interfaceOperation, attrType, attrName);
+
+ // Implementation
+ ObjectModelOperation implOperation = createImplOperation(interfaceOperation);
+
+ attrType = TopiaGeneratorUtil.getSimpleName(attrType);
+
+ StringBuilder body = new StringBuilder();
+
+ body.append(""
+/*{
+ fireOnPreWrite(<%=constantName%>, null, <%=attrName%>);
+ if (this.<%=attrName%> == null) {
+ this.<%=attrName%> = new <%=collectionImpl%><<%=attrType%>>();
+ }
+}*/
+ );
+
+ if (reverse != null && (reverse.isNavigable() ||
+ hasUnidirectionalRelationOnAbstractType(attribute, model))) {
+ String getterName = getJavaBeanMethodName("get", reverse.getName());
+ String setterName = getJavaBeanMethodName("set", reverse.getName());
+
+ String reverseAttrType = TopiaGeneratorUtil.getSimpleName(reverse.getType());
+
+ if (!TopiaGeneratorUtil.isNMultiplicity(reverse)) {
+ body.append(""
+/*{
+ <%=attrName%>.<%=setterName%>(this);
+}*/
+ );
+ // Don't manage reverse attribute add if attribute has associationClass
+ } else if (!attribute.hasAssociationClass()) {
+ body.append(""
+/*{
+ if (<%=attrName%>.<%=getterName%>() == null) {
+ <%=attrName%>.<%=setterName%>(new <%=collectionImpl%><<%=reverseAttrType%>>());
+ }
+ <%=attrName%>.<%=getterName%>().add(this);
+}*/
+ );
+ }
+ }
+ body.append(""
+/*{
+ this.<%=attrName%>.add(<%=attrName%>);
+ fireOnPostWrite(<%=constantName%>, this.<%=attrName%>.size(), null, <%=attrName%>);
+ }*/
+ );
+ setOperationBody(implOperation, body.toString());
+ }
+
+ protected void addMultipleAddAllOperation(ObjectModelAttribute attribute,
+ String collectionInterface) {
+
+ String attrName = getPropertyName(attribute);
+ String attrType = getPropertyType(attribute);
+
+ if (log.isDebugEnabled()) {
+ log.debug("Generate multiple 'addAll' operation for property : " + attrName +
+ " [" + attrType + "]");
+ }
+
+ // Interface operation
+ ObjectModelOperation interfaceOperation =
+ addOperation(outputInterface, getJavaBeanMethodName("addAll", attrName),
+ void.class, ObjectModelJavaModifier.PACKAGE);
+ ObjectModelParameter param =
+ addParameter(interfaceOperation, collectionInterface + "<" + attrType + ">", attrName);
+
+ // Implementation
+ ObjectModelOperation implOperation =
+ createImplOperation(interfaceOperation);
+
+ attrType = TopiaGeneratorUtil.getSimpleName(attrType);
+ String addMethodName = getJavaBeanMethodName("add", attrName);
+ setOperationBody(implOperation, ""
+/*{
+ if (<%=attrName%> == null) {
+ return;
+ }
+ for (<%=attrType%> item : <%=attrName%>) {
+ <%=addMethodName%>(item);
+ }
+ }*/
+ );
+ }
+
+ protected void addMultipleSetOperation(ObjectModelAttribute attribute,
+ String collectionInterface,
+ String collectionImpl) {
+
+ String attrName = getPropertyName(attribute);
+ String referenceType = getPropertyType(attribute);
+ String attrType = collectionInterface + "<" + referenceType + ">";
+ String constantName = getConstantName(attrName);
+
+ if (log.isDebugEnabled()) {
+ log.debug("Generate multiple 'set' operation for property : " + attrName +
+ " [" + attrType + "]");
+ }
+
+ // Interface operation
+ ObjectModelOperation interfaceOperation =
+ createPropertySetterSignature(outputInterface, attrType, attrName,
+ "");
+
+ ObjectModelOperation implOperation = createImplOperation(interfaceOperation);
+
+ attrType = TopiaGeneratorUtil.getSimpleName(attrType);
+ referenceType = TopiaGeneratorUtil.getSimpleName(referenceType);
+
+ // Force fire for collection
+ setOperationBody(implOperation, ""
+/*{
+ // Copy elements to keep data for fire with new reference
+ <%=attrType%> oldValue = this.<%=attrName%> != null ? new <%=collectionImpl%><<%=referenceType%>>(this.<%=attrName%>) : null;
+ fireOnPreWrite(<%=constantName%>, oldValue, <%=attrName%>);
+ this.<%=attrName%> = <%=attrName%>;
+ fireOnPostWrite(<%=constantName%>, oldValue, <%=attrName%>);
+ }*/
+ );
+ }
+
+ protected void addMultipleRemoveOperation(ObjectModelAttribute attribute) {
+
+ String attrName = getPropertyName(attribute);
+ String attrType = getPropertyType(attribute);
+ ObjectModelAttribute reverse = attribute.getReverseAttribute();
+ String constantName = getConstantName(attrName);
+
+ if (log.isDebugEnabled()) {
+ log.debug("Generate 'remove' operation for property : " + attrName +
+ " [" + attrType + "]");
+ }
+
+ // Interface operation
+ ObjectModelOperation interfaceOperation =
+ addOperation(outputInterface, getJavaBeanMethodName("remove" , attrName),
+ void.class, ObjectModelJavaModifier.PACKAGE);
+ ObjectModelParameter param =
+ addParameter(interfaceOperation, attrType, attrName);
+
+ // Implementation
+ ObjectModelOperation implOperation = createImplOperation(interfaceOperation);
+
+ attrType = TopiaGeneratorUtil.getSimpleName(attrType);
+
+ StringBuilder body = new StringBuilder();
+
+ body.append(""
+/*{
+ fireOnPreWrite(<%=constantName%>, <%=attrName%>, null);
+ if (this.<%=attrName%> == null || !this.<%=attrName%>.remove(<%=attrName%>)) {
+ throw new IllegalArgumentException("List does not contain given element");
+ }
+}*/
+ );
+
+ if (reverse != null && (reverse.isNavigable() ||
+ hasUnidirectionalRelationOnAbstractType(attribute, model))) {
+ String getterName = getJavaBeanMethodName("get", reverse.getName());
+ String setterName = getJavaBeanMethodName("set", reverse.getName());
+ if (!TopiaGeneratorUtil.isNMultiplicity(reverse)) {
+ body.append(""
+/*{
+ <%=attrName%>.<%=setterName%>(null);
+}*/
+ );
+ // Don't manage reverse attribute remove if attribute has associationClass
+ } else if (!attribute.hasAssociationClass()) {
+ body.append(""
+/*{
+ <%=attrName%>.<%=getterName%>().remove(this);
+}*/
+ );
+ }
+ }
+ body.append(""
+/*{
+ fireOnPostWrite(<%=constantName%>, this.<%=attrName%>.size() + 1, <%=attrName%>, null);
+ }*/
+ );
+ setOperationBody(implOperation, body.toString());
+ }
+
+ protected void addMultipleClearOperation(ObjectModelAttribute attribute,
+ String collectionInterface,
+ String collectionImpl) {
+
+ String attrName = getPropertyName(attribute);
+ String attrType = getPropertyType(attribute);
+ ObjectModelAttribute reverse = attribute.getReverseAttribute();
+ String constantName = getConstantName(attrName);
+
+ if (log.isDebugEnabled()) {
+ log.debug("Generate multiple 'clear' operation for property : " + attrName +
+ " [" + attrType + "]");
+ }
+
+ // Interface operation
+ ObjectModelOperation interfaceOperation =
+ addOperation(outputInterface, getJavaBeanMethodName("clear" , attrName),
+ void.class, ObjectModelJavaModifier.PACKAGE);
+
+ // Implementation
+ ObjectModelOperation implOperation = createImplOperation(interfaceOperation);
+
+ attrType = TopiaGeneratorUtil.getSimpleName(attrType);
+
+ StringBuilder body = new StringBuilder(""
+/*{
+ if (this.<%=attrName%> == null) {
+ return;
+ }
+}*/
+ );
+
+ if (reverse != null && (reverse.isNavigable() ||
+ hasUnidirectionalRelationOnAbstractType(attribute, model))) {
+ String getterName = getJavaBeanMethodName("get", reverse.getName());
+ String setterName = getJavaBeanMethodName("set", reverse.getName());
+ body.append(""
+/*{ for (<%=attrType%> item : this.<%=attrName%>) {
+}*/
+ );
+ if (!TopiaGeneratorUtil.isNMultiplicity(reverse)) {
+ body.append(""
+/*{ item.<%=setterName%>(null);
+}*/
+ );
+ // Don't manage reverse attribute remove if attribute has associationClass
+ } else if (!attribute.hasAssociationClass()) {
+ body.append(""
+/*{ item.<%=getterName%>().remove(this);
+}*/
+ );
+ }
+ body.append(""
+/*{ }
+}*/
+ );
+ }
+ body.append(""
+/*{ <%=collectionInterface%><<%=attrType%>> oldValue = new <%=collectionImpl%><<%=attrType%>>(this.<%=attrName%>);
+ fireOnPreWrite(<%=constantName%>, oldValue, this.<%=attrName%>);
+ this.<%=attrName%>.clear();
+ fireOnPostWrite(<%=constantName%>, oldValue, this.<%=attrName%>);
+ }*/
+ );
+ setOperationBody(implOperation, body.toString());
+ }
+
+ protected void addMultipleGetOperation(ObjectModelAttribute attribute,
+ String collectionInterface) {
+
+ String attrName = getPropertyName(attribute);
+ String attrType = collectionInterface + "<" + getPropertyType(attribute) + ">";
+
+ if (log.isDebugEnabled()) {
+ log.debug("Generate multiple 'get' operation for property : " + attrName +
+ " [" + attrType + "]");
+ }
+
+ // Interface operation
+ ObjectModelOperation interfaceOperation =
+ addOperation(outputInterface, getJavaBeanMethodName("get" , attrName),
+ attrType, ObjectModelJavaModifier.PACKAGE);
+
+ // Implementation
+ ObjectModelOperation implOperation = createImplOperation(interfaceOperation);
+
+ setOperationBody(implOperation, ""
+/*{
+ return <%=attrName%>;
+ }*/
+ );
+ }
+
+ protected void addMultipleGetTopiaIdOperation(ObjectModelAttribute attribute) {
+
+ String attrName = getPropertyName(attribute);
+ String attrType = getPropertyType(attribute);
+
+ if (log.isDebugEnabled()) {
+ log.debug("Generate multiple 'getByTopiaId' operation for property : " + attrName +
+ " [" + attrType + "]");
+ }
+
+ // Interface operation
+ ObjectModelOperation interfaceOperation =
+ addOperation(outputInterface, getJavaBeanMethodName("get", attrName) + "ByTopiaId",
+ attrType, ObjectModelJavaModifier.PACKAGE);
+ ObjectModelParameter param =
+ addParameter(interfaceOperation, String.class, "topiaId");
+
+ // Implementation
+ ObjectModelOperation implOperation =
+ createImplOperation(interfaceOperation);
+
+ addImport(outputAbstract, TopiaEntityHelper.class);
+
+ setOperationBody(implOperation, ""
+/*{
+ return TopiaEntityHelper.getEntityByTopiaId(<%=attrName%>, topiaId);
+ }*/
+ );
+ }
+
+ protected void addMultipleGetOperationFromEntity(ObjectModelAttribute attribute) {
+
+ // reference to the real attribute name
+ String referenceName = attribute.getName();
+ String referenceType = attribute.getType();
+
+ String referenceGetterName = getJavaBeanMethodName("get", referenceName);
+ // association attribute name
+ String attrName = getPropertyName(attribute);
+ String attrType = getPropertyType(attribute);
+
+ if (log.isDebugEnabled()) {
+ log.debug("Generate multiple 'getFromEntity' operation for property : " + attrName +
+ " [" + attrType + "]");
+ }
+
+ // Interface operation
+ ObjectModelOperation interfaceOperation =
+ addOperation(outputInterface,
+ getJavaBeanMethodName("get", attrName), attrType);
+
+ addParameter(interfaceOperation, referenceType, referenceName);
+
+ // Implementation
+ ObjectModelOperation implOperation = createImplOperation(interfaceOperation);
+
+ attrType = TopiaGeneratorUtil.getSimpleName(attrType);
+
+ setOperationBody(implOperation, ""
+/*{
+ if (<%=referenceName%> == null || this.<%=attrName%> == null) {
+ return null;
+ }
+ for (<%=attrType%> item : this.<%=attrName%>) {
+ if (<%=referenceName%>.equals(item.<%=referenceGetterName%>())) {
+ return item;
+ }
+ }
+ return null;
+ }*/
+ );
+ }
+
+ protected void addMultipleSizeOperation(ObjectModelAttribute attribute) {
+
+ String attrName = getPropertyName(attribute);
+
+ if (log.isDebugEnabled()) {
+ log.debug("Generate multiple 'size' operation for property : " + attrName);
+ }
+
+ // Interface operation
+ ObjectModelOperation interfaceOperation =
+ addOperation(outputInterface, getJavaBeanMethodName("size", attrName),
+ int.class, ObjectModelJavaModifier.PACKAGE);
+
+ // Implementation
+ ObjectModelOperation implOperation = createImplOperation(interfaceOperation);
+
+ setOperationBody(implOperation, ""
+/*{
+ if (<%=attrName%> == null) {
+ return 0;
+ }
+ return <%=attrName%>.size();
+ }*/
+ );
+ }
+
+ protected void addMultipleIsEmptyOperation(ObjectModelAttribute attribute) {
+
+ String attrName = getPropertyName(attribute);
+
+ if (log.isDebugEnabled()) {
+ log.debug("Generate multiple 'isEmpty' operation for property : " + attrName);
+ }
+
+ String sizeMethodName = getJavaBeanMethodName("size", attrName);
+ // Interface operation
+ ObjectModelOperation interfaceOperation =
+ addOperation(outputInterface, getJavaBeanMethodName("is", attrName)+ "Empty",
+ boolean.class, ObjectModelJavaModifier.PACKAGE);
+
+ // Implementation
+ ObjectModelOperation implOperation = createImplOperation(interfaceOperation);
+
+ setOperationBody(implOperation, ""
+/*{
+ int size = <%=sizeMethodName%>();
+ return size == 0;
+ }*/
+ );
+ }
+
+ // -------------------------------------------------------------------------
+ // Generate util operations
+ // -------------------------------------------------------------------------
+
+ private ObjectModelOperation acceptOperation;
+
+ private StringBuilder acceptOperationBody;
+
+ protected void createAcceptOperation() {
+
+ // Declaration
+ acceptOperation = addOperation(outputAbstract, "accept", void.class);
+ addAnnotation(outputAbstract, acceptOperation , Override.class);
+ ObjectModelParameter param =
+ addParameter(acceptOperation, EntityVisitor.class, "visitor");
+
+ addException(acceptOperation, TopiaException.class);
+
+ // Body init
+ acceptOperationBody = new StringBuilder(""
+/*{
+ visitor.start(this);
+}*/
+ );
+ }
+
+ protected void updateAcceptOperation(ObjectModelAttribute attribute) {
+ String attrName =
+ TopiaGeneratorUtil.getSimpleName(getPropertyName(attribute));
+ String attrType =
+ TopiaGeneratorUtil.getSimpleName(getPropertyType(attribute));
+ String collectionType = getCollectionType(attribute);
+ String constantName = getConstantName(attrName);
+ if (collectionType != null) {
+ collectionType = TopiaGeneratorUtil.getSimpleName(collectionType);
+ acceptOperationBody.append(""
+/*{ visitor.visit(this, <%=constantName%>, <%=collectionType%>.class, <%=attrType%>.class, <%=attrName%>);
+}*/
+ );
+ } else {
+ acceptOperationBody.append(""
+/*{ visitor.visit(this, <%=constantName%>, <%=attrType%>.class, <%=attrName%>);
+}*/
+ );
+ }
+ }
+
+ protected void closeAcceptOperation() {
+ acceptOperationBody.append(""
+/*{ visitor.end(this);
+ }*/
+ );
+ setOperationBody(acceptOperation, acceptOperationBody.length() == 0 ?
+ " " : acceptOperationBody.toString());
+ }
+
+ protected void generateToStringOperation(ObjectModelClass input) {
+
+ if (log.isDebugEnabled()) {
+ log.debug("generate toString method for entity " +
+ outputInterface.getQualifiedName());
+ }
+ ObjectModelOperation operation =
+ addOperation(outputAbstract, "toString", String.class);
+
+ addAnnotation(outputAbstract, operation, Override.class);
+
+ addImport(outputAbstract, ToStringBuilder.class);
+
+ StringBuilder body = new StringBuilder(""
+/*{
+ String result = new ToStringBuilder(this).
+}*/
+ );
+ for (ObjectModelAttribute attr : input.getAttributes()) {
+
+ //FIXME possibilité de boucles (non directes)
+
+ ObjectModelClass attrEntity = null;
+
+ if (model.hasClass(attr.getType())) {
+ attrEntity = model.getClass(attr.getType());
+ }
+
+ boolean isEntity = attrEntity != null &&
+ TopiaGeneratorUtil.isEntity(attrEntity);
+
+ ObjectModelAttribute reverse = attr.getReverseAttribute();
+ if (isEntity && (reverse == null || !reverse.isNavigable())
+ && !attr.hasAssociationClass() || !isEntity) {
+ String attrName = attr.getName();
+ String constantName = getConstantName(attrName);
+ body.append(""
+/*{ append(<%=constantName%>, this.<%=attrName%>).
+}*/
+ );
+ }
+ }
+ body.append(""
+/*{ toString();
+ return result;
+ }*/
+ );
+ setOperationBody(operation, body.length() == 0 ? " " : body.toString());
+
+ }
+
+ protected void generateCompositeOperation(ObjectModelClass input) {
+
+ ObjectModelOperation operation =
+ addOperation(outputAbstract, "getComposite",
+ List.class.getName() + '<' + TopiaEntity.class.getName() + '>');
+
+ addException(operation, TopiaException.class);
+ addAnnotation(outputAbstract, operation, Override.class);
+
+ StringBuilder body;
+ if (!TopiaGeneratorUtil.isContextable(input)) {
+ body = new StringBuilder(""
+/*{
+ throw new UnsupportedOperationException("Since ToPIA 3.0, 'getComposite' is only available for contextable entities");
+ }*/
+ );
+ } else {
+ addImport(outputAbstract, ArrayList.class);
+ addImport(outputAbstract, List.class);
+
+ body = new StringBuilder(""
+/*{
+ List<TopiaEntity> tmp = new ArrayList<TopiaEntity>();
+
+ // pour tous les attributs rechecher les composites et les class d'asso
+ // on les ajoute dans tmp
+}*/
+ );
+ for (ObjectModelAttribute attr : input.getAttributes()) {
+
+ if (attr.referenceClassifier() &&
+ TopiaGeneratorUtil.isEntity(attr.getClassifier())) {
+
+ if (attr.isComposite()) {
+ String attrName = attr.getName();
+ String getterName = getJavaBeanMethodName("get", attrName);
+ if (TopiaGeneratorUtil.isNMultiplicity(attr)) {
+ body.append(""
+/*{ if (<%=getterName%>() != null) {
+ tmp.addAll(<%=getterName%>());
+ }
+}*/
+ );
+ } else {
+ body.append(""
+/*{ tmp.add(<%=getterName%>());
+}*/
+ );
+ }
+ } else if (attr.hasAssociationClass()) {
+ String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(
+ attr);
+ String assocClassFQN = TopiaGeneratorUtil.getSimpleName(
+ attr.getAssociationClass().getQualifiedName());
+ String ref = "this." + TopiaGeneratorUtil.toLowerCaseFirstLetter(
+ assocAttrName);
+ if (!TopiaGeneratorUtil.isNMultiplicity(attr)) {
+ body.append(""
+/*{
+ if (<%=ref%> != null) {
+ tmp.add(<%=ref%>);
+ }
+}*/
+ );
+ } else {
+ ObjectModelAttribute reverse = attr.getReverseAttribute();
+ String reverseAttrName = reverse.getName();
+ // On utilise pas l'attribut car il est potentiellement
+ // pas a jour, car pour les asso avec cardinalité
+ // personne ne fait de add. Ce qui est normal, mais
+ // pour pouvoir faire tout de meme des delete en cascade
+ // sur les asso, le champs est dans le mapping
+ // hibernate et donc il le faut aussi dans la classe
+ // sinon hibernate rale lorsqu'il charge l'objet
+ // if (<%=ref%> != null) {
+ // tmp.addAll(<%=ref%>);
+ // }
+
+ body.append(""
+/*{
+ {
+ org.nuiton.topia.persistence.TopiaDAO<<%=assocClassFQN%>> dao = getTopiaContext().getDao(<%=assocClassFQN%>.class);
+ List<<%=assocClassFQN%>> findAllByProperties = dao.findAllByProperties("<%=reverseAttrName%>", this);
+ if (findAllByProperties != null) {
+ tmp.addAll(findAllByProperties);
+ }
+ }
+}*/
+ );
+ }
+ }
+ }
+ }
+ body.append(""
+/*{
+ // on refait un tour sur chaque entity de tmp pour recuperer leur
+ // composite
+ List<TopiaEntity> result = new ArrayList<TopiaEntity>();
+ for (TopiaEntity entity : tmp) {
+ if (entity != null) {
+ result.add(entity);
+ result.addAll(entity.getComposite());
+ }
+ }
+ return result;
+ }*/
+ );
+ }
+
+ setOperationBody(operation, body.length() == 0 ? " " : body.toString());
+ }
+
+ protected void generateAggregateOperation(ObjectModelClass input) {
+
+ ObjectModelOperation operation =
+ addOperation(outputAbstract, "getAggregate",
+ List.class.getName() + '<' + TopiaEntity.class.getName() + '>');
+
+ addException(operation, TopiaException.class);
+ addAnnotation(outputAbstract, operation, Override.class);
+
+
+ StringBuilder body = new StringBuilder();
+ if (!TopiaGeneratorUtil.isContextable(input)) {
+ body = new StringBuilder(""
+/*{
+ throw new UnsupportedOperationException("Since ToPIA 3.0, 'getComposite' is only available for contextable entities");
+ }*/
+ );
+ } else {
+
+ addImport(outputAbstract, ArrayList.class);
+ addImport(outputAbstract, List.class);
+ body .append(""
+/*{
+ List<TopiaEntity> tmp = new ArrayList<TopiaEntity>();
+
+ // pour tous les attributs rechecher les composites et les class d'asso
+ // on les ajoute dans tmp
+}*/
+ );
+ for (ObjectModelAttribute attr : input.getAttributes()) {
+
+ if (attr.referenceClassifier() &&
+ TopiaGeneratorUtil.isEntity(attr.getClassifier()) &&
+ attr.isAggregate()) {
+
+ String attrName = attr.getName();
+ String getterName = getJavaBeanMethodName("get", attrName);
+ if (TopiaGeneratorUtil.isNMultiplicity(attr)) {
+ body.append(""
+/*{ tmp.addAll(<%=getterName%>());
+}*/
+ );
+ } else {
+ body.append(""
+/*{ tmp.add(<%=getterName%>());
+}*/
+ );
+ }
+ }
+ }
+ body.append(""
+/*{
+ // on refait un tour sur chaque entity de tmp pour recuperer leur
+ // composite
+ List<TopiaEntity> result = new ArrayList<TopiaEntity>();
+ for (TopiaEntity entity : tmp) {
+ result.add(entity);
+ result.addAll(entity.getAggregate());
+ }
+ return result;
+ }*/
+ );
+ }
+ setOperationBody(operation, body.length() == 0 ? " " : body.toString());
+ }
+
+ // -------------------------------------------------------------------------
+ // Helpers
+ // -------------------------------------------------------------------------
+
+ protected boolean isAbstract(ObjectModelClass clazz) {
+ if (clazz.isAbstract()) {
+ return true;
+ }
+
+ //Une classe peut être abstraite si elle a des méthodes définies dans
+ // ses superinterface et non implantées dans ses superclasses
+ Collection<ObjectModelOperation> allInterfaceOperations =
+ clazz.getAllInterfaceOperations(true);
+ allInterfaceOperations.removeAll(clazz.getAllOtherOperations(true));
+ for (ObjectModelOperation op : allInterfaceOperations) {
+ boolean implementationFound = false;
+ for (ObjectModelClass superClazz : clazz.getSuperclasses()) {
+ for (ObjectModelOperation matchingOp :
+ superClazz.getOperations(op.getName())) {
+ implementationFound = op.equals(matchingOp) &&
+ !matchingOp.isAbstract();
+ if (implementationFound) {
+ break;
+ }
+ }
+ if (implementationFound) {
+ break;
+ }
+ }
+ if (!implementationFound) {
+ if (log.isDebugEnabled()) {
+ log.debug(clazz.getName() + " : abstract operation " + op);
+ }
+ return true;
+ }
+ }
+ return false;
+ }
+
+ protected String getCollectionType(ObjectModelAttribute attribute) {
+ String result = null;
+ if (!associationClass && TopiaGeneratorUtil.isNMultiplicity(attribute)) {
+ result = TopiaGeneratorUtil.getNMultiplicityInterfaceType(attribute);
+ }
+ return result;
+ }
+
+ protected String getPropertyName(ObjectModelAttribute attribute) {
+ String propertyName = attribute.getName();
+ if (!associationClass && attribute.hasAssociationClass()) {
+ propertyName = TopiaGeneratorUtil.getAssocAttrName(attribute);
+ }
+ return propertyName;
+ }
+
+ protected String getPropertyType(ObjectModelAttribute attribute) {
+ String propertyType = attribute.getType();
+ if (!associationClass && attribute.hasAssociationClass()) {
+ propertyType = attribute.getAssociationClass().getQualifiedName();
+ }
+ return propertyType;
+ }
+
+ protected ObjectModelOperation createImplOperation(ObjectModelOperation interfaceOperation) {
+ ObjectModelOperation implOperation =
+ cloneOperationSignature(interfaceOperation, outputAbstract, false);
+ addAnnotation(outputAbstract, implOperation, Override.class);
+ return implOperation;
+ }
+
+ /**
+ * TODO-fdesbois-2010-06-25 : This method can be put in JavaBuilder or ObjectModelTransformerToJava
+ *
+ * This method create an set operation in {@code classifier} with
+ * {@code propertyType} as return type and {@code propertyName} used for
+ * operation name ('set[propertyName]'). {@code operationDocument} can
+ * also be added to the operation created. Only signature with default
+ * visibility will be added.
+ *
+ * @param classifier Classifier where the operation will be added
+ * @param propertyType Type of the property (better if qualified name)
+ * @param propertyName Name of the property to set
+ * @param operationDocumentation Documentation for the operation
+ * @return the created operation
+ */
+ protected ObjectModelOperation createPropertySetterSignature(ObjectModelClassifier classifier,
+ String propertyType,
+ String propertyName,
+ String operationDocumentation) {
+ // Operation
+ ObjectModelOperation operation =
+ addOperation(classifier,
+ getJavaBeanMethodName("set", propertyName), void.class);
+
+ ObjectModelParameter param =
+ addParameter(operation, propertyType, propertyName);
+
+ // Documentation
+ if (StringUtils.isNotEmpty(operationDocumentation)) {
+ setDocumentation(operation, operationDocumentation);
+ setDocumentation(param, "La valeur de l'attribut à positionner.");
+ }
+
+ return operation;
+ }
+
+ protected void addInterface(List<String> interfaceAlreadyDone,
+ ObjectModelClassifier output,
+ ObjectModelClassifier interfaze) {
+ String qualifiedName = interfaze.getQualifiedName();
+ if (!interfaceAlreadyDone.contains(qualifiedName)) {
+
+ interfaceAlreadyDone.add(qualifiedName);
+
+ if (output != null) {
+
+ // add it to output
+ addInterface(output, qualifiedName);
+
+ if (log.isTraceEnabled()) {
+ log.trace("Add interface " + qualifiedName + " on " +
+ output.getQualifiedName());
+ }
+ } else {
+ if (log.isTraceEnabled()) {
+ log.trace("Skip included interface " + qualifiedName);
+ }
+ }
+
+ // scan also all interfaces or super-classes of it
+ for (ObjectModelClassifier parent : interfaze.getInterfaces()) {
+ addInterface(interfaceAlreadyDone, null, parent);
+ }
+ }
+ }
+
+ protected void addInterface(List<String> interfaceAlreadyDone,
+ ObjectModelClassifier output,
+ Class<?> clazz) {
+ String qualifiedName = clazz.getName();
+ if (!interfaceAlreadyDone.contains(qualifiedName)) {
+
+ // add it to output
+ addInterface(output, qualifiedName);
+
+ }
+ }
+}
Copied: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/PersistenceContextTransformer.java (from rev 2882, trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/PersistenceContextTransformer.java)
===================================================================
--- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/PersistenceContextTransformer.java (rev 0)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/PersistenceContextTransformer.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,262 @@
+package org.nuiton.topia.templates;
+
+/*{generator option: parentheses = false}*/
+
+/*{generator option: writeString = +}*/
+
+import org.nuiton.eugene.java.ObjectModelTransformerToJava;
+import org.nuiton.eugene.models.object.ObjectModel;
+import org.nuiton.eugene.models.object.ObjectModelClass;
+import org.nuiton.eugene.models.object.ObjectModelJavaModifier;
+import org.nuiton.eugene.models.object.ObjectModelOperation;
+import org.nuiton.topia.AbstractTopiaPersistenceContext;
+import org.nuiton.topia.HibernateProvider;
+import org.nuiton.topia.TopiaListenableSupport;
+import org.nuiton.topia.persistence.TopiaEntity;
+import org.nuiton.topia.persistence.TopiaIdFactory;
+import org.nuiton.topia.persistence.util.EntityOperator;
+import org.nuiton.topia.persistence.util.EntityOperatorStore;
+
+import java.lang.reflect.Array;
+import java.util.List;
+
+/**
+ * To generate PersistenceHelper
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.templates.PersistenceContextTransformer"
+ * @since 3.0
+ */
+public class PersistenceContextTransformer extends ObjectModelTransformerToJava {
+
+ @Override
+ public void transformFromModel(ObjectModel input) {
+
+ String packageName = TopiaGeneratorUtil.getPersistenceContextPackage(this, model);
+
+ String entityAbstractName = TopiaGeneratorUtil.getPersistenceContextAbstractName(model);
+
+ String entityConcreteName = TopiaGeneratorUtil.getPersistenceContextConcreteName(model);
+
+ boolean generateAbstract = !isInClassPath(packageName, entityAbstractName);
+
+ boolean generateConcrete = !isInClassPath(packageName, entityConcreteName);
+
+
+ if (generateAbstract) {
+
+ generateAbstract(packageName,
+ entityAbstractName);
+ }
+
+ if (generateConcrete) {
+
+ generateImpl(packageName,
+ entityAbstractName,
+ entityConcreteName);
+ }
+
+ }
+
+ protected void generateAbstract(String packageName,
+ String className) {
+
+ // try to find a super class by tag-value
+// String superClass = TopiaGeneratorUtil.getPersistenceContextSuperClassTagValue(model);
+ String superClass = null;
+
+ if (superClass == null) {
+
+ // no super-class, use default one
+ superClass = AbstractTopiaPersistenceContext.class.getName();
+ }
+
+ ObjectModelClass output = createAbstractClass(className, packageName);
+
+ setSuperClass(output, superClass);
+
+ // detect if there is a contract to set on abstract
+ String contractName = TopiaGeneratorUtil.getPersistenceContextInterfaceName(model);
+
+// addInterface(output, TopiaPersistenceContext.class);
+
+ boolean addPersistenceContextContract = isInClassPath(packageName, contractName);
+
+ if (addPersistenceContextContract) {
+ addInterface(output, packageName + "." + contractName);
+ }
+
+ String modelName = model.getName();
+ String daoHelperClazzName = modelName + "DAOHelper";
+
+ String entityEnumName = modelName + "EntityEnum";
+
+ List<ObjectModelClass> entityClasses =
+ TopiaGeneratorUtil.getEntityClasses(model, true);
+
+ boolean generateOperator =
+ TopiaGeneratorUtil.shouldGenerateOperatorForDAOHelper(model);
+
+ boolean generateStandaloneEnum =
+ TopiaGeneratorUtil.shouldGenerateStandaloneEnumForDAOHelper(model);
+
+ if (!generateStandaloneEnum) {
+
+ addImport(output, packageName + "." + daoHelperClazzName + "." + entityEnumName);
+
+ }
+
+// addImport(output, TopiaDAO.class);
+ addImport(output, TopiaEntity.class);
+// addImport(output, TopiaContext.class);
+ addImport(output, Array.class);
+ addImport(output, Array.class);
+
+ if (generateOperator) {
+ addImport(output, EntityOperator.class);
+ addImport(output, EntityOperatorStore.class);
+ }
+
+ // add public constructor
+ ObjectModelOperation constructor = addConstructor(
+ output,
+ ObjectModelJavaModifier.PUBLIC);
+ addParameter(constructor, HibernateProvider.class, "hibernateProvider");
+ addParameter(constructor, TopiaListenableSupport.class, "listenableSupport");
+ addParameter(constructor, TopiaIdFactory.class, "topiaIdFactory");
+ setOperationBody(constructor, ""
+/*{
+ super(hibernateProvider, listenableSupport, topiaIdFactory);
+ }*/
+ );
+
+ ObjectModelOperation op;
+
+ // getModelVersion method
+ String modelVersion = model.getVersion();
+ op = addOperation(output, "getModelVersion", "String", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
+ setOperationBody(op, ""
+/*{
+ return "<%=modelVersion%>";
+ }*/
+ );
+
+ // getModelName method
+ op = addOperation(output, "getModelName", "String", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
+ setOperationBody(op, ""
+/*{
+ return "<%=modelName%>";
+ }*/
+ );
+
+ for (ObjectModelClass clazz : entityClasses) {
+ String clazzName = clazz.getName();
+
+ // TODO brendan 14/10/13 use method
+ String daoContractName = clazzName + "Dao";
+ String daoClazzName = TopiaGeneratorUtil.getConcreteDaoName(clazz);
+
+ // specialized getXXXDao method
+ op = addOperation(output, "get" + daoContractName, clazz.getPackageName() + '.' + daoClazzName);
+ addImport(output, clazz);
+ setOperationBody(op, ""
+/*{
+ <%=daoClazzName%> result = getDao(<%=clazzName%>.class, <%=daoClazzName%>.class);
+ return result;
+ }*/
+ );
+
+ }
+
+ // getContractClass method
+ op = addOperation(output, "getContractClass", "<T extends TopiaEntity> Class<T>", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
+ addParameter(op, "Class<T>", "klass");
+ setOperationBody(op, ""
+/*{
+ <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass);
+ return (Class<T>) constant.getContract();
+ }*/
+ );
+
+ // getImplementationClass method
+ op = addOperation(output, "getImplementationClass", "<T extends TopiaEntity> Class<T>", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
+ addParameter(op, "Class<T>", "klass");
+ setOperationBody(op, ""
+/*{
+ <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass);
+ return (Class<T>) constant.getImplementation();
+ }*/
+ );
+
+ // getContractClasses method
+ op = addOperation(output, "getContractClasses", "Class<? extends TopiaEntity>[]", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
+ setOperationBody(op, ""
+/*{
+ <%=entityEnumName%>[] values = <%=entityEnumName%>.values();
+ Class<? extends TopiaEntity>[] result = (Class<? extends TopiaEntity>[]) Array.newInstance(Class.class, values.length);
+ for (int i = 0; i < values.length; i++) {
+ result[i] = values[i].getContract();
+ }
+ return result;
+ }*/
+ );
+
+ // getImplementationClasses method
+ op = addOperation(output, "getImplementationClasses", "Class<? extends TopiaEntity>[]", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
+ setOperationBody(op, ""
+/*{
+ <%=entityEnumName%>[] values = <%=entityEnumName%>.values();
+ Class<? extends TopiaEntity>[] result = (Class<? extends TopiaEntity>[]) Array.newInstance(Class.class, values.length);
+ for (int i = 0; i < values.length; i++) {
+ result[i] = values[i].getImplementation();
+ }
+ return result;
+ }*/
+ );
+
+ // getContracts method
+ op = addOperation(output, "getContracts", entityEnumName + "[]", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
+ setOperationBody(op, ""
+/*{
+ return <%=entityEnumName%>.values();
+ }*/
+ );
+
+ if (generateOperator) {
+ // getOperator method
+ op = addOperation(output, "getOperator", "<T extends TopiaEntity> EntityOperator<T>", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC);
+ addParameter(op, "Class<T>", "klass");
+ setOperationBody(op, ""
+/*{
+ <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass);
+ return EntityOperatorStore.getOperator(constant);
+ }*/
+ );
+ }
+
+ }
+
+ protected ObjectModelClass generateImpl(String packageName,
+ String entityAbstractName,
+ String entityConcreteName) {
+
+ ObjectModelClass output = createClass(entityConcreteName, packageName);
+
+ setSuperClass(output, entityAbstractName);
+
+ ObjectModelOperation constructor = addConstructor(
+ output,
+ ObjectModelJavaModifier.PUBLIC);
+ addParameter(constructor, HibernateProvider.class, "hibernateProvider");
+ addParameter(constructor, TopiaListenableSupport.class, "listenableSupport");
+ addParameter(constructor, TopiaIdFactory.class, "topiaIdFactory");
+ setOperationBody(constructor, ""
+/*{
+ super(hibernateProvider, listenableSupport, topiaIdFactory);
+ }*/
+ );
+
+ return output;
+ }
+
+}
Copied: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaGeneratorUtil.java (from rev 2882, trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaGeneratorUtil.java)
===================================================================
--- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaGeneratorUtil.java (rev 0)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaGeneratorUtil.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,1687 @@
+package org.nuiton.topia.templates;
+
+import com.google.common.base.Preconditions;
+import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.eugene.AbstractGenerator;
+import org.nuiton.eugene.GeneratorUtil;
+import org.nuiton.eugene.ModelPropertiesUtil;
+import org.nuiton.eugene.java.JavaGeneratorUtil;
+import org.nuiton.eugene.java.ObjectModelTransformerToJava;
+import org.nuiton.eugene.models.object.ObjectModel;
+import org.nuiton.eugene.models.object.ObjectModelAssociationClass;
+import org.nuiton.eugene.models.object.ObjectModelAttribute;
+import org.nuiton.eugene.models.object.ObjectModelClass;
+import org.nuiton.eugene.models.object.ObjectModelClassifier;
+import org.nuiton.eugene.models.object.ObjectModelElement;
+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.TopiaDAOImpl;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+
+/**
+ * Classe regroupant divers méthodes utiles pour la génération des entités
+ * <p/>
+ * Created: 13 déc. 2005
+ *
+ * @author Arnaud Thimel <thimel(a)codelutin.com>
+ * @author tchemit <tchemit(a)codelutin.com>
+ * @author fdesbois <fdesbois(a)codelutin.com>
+ * @author chatellier <chatellier(a)codelutin.com>
+ * @version $Id$
+ */
+public class TopiaGeneratorUtil extends JavaGeneratorUtil {
+
+ /** Logger */
+ private static final Log log = LogFactory.getLog(TopiaGeneratorUtil.class);
+
+ /**
+ * dependency to add extra operations for entity dao.
+ *
+ * @since 2.3.4
+ */
+ public static final String DEPENDENCIES_DAO = "dao";
+
+ /** Type de persistence Hibernate */
+ public static final String PERSISTENCE_TYPE_HIBERNATE = "hibernate";
+
+ /** Type de persistence LDAP */
+ public static final String PERSISTENCE_TYPE_LDAP = "ldap";
+
+ /** Type de persistence par défaut (si aucun précisé) */
+ public static final String PERSISTENCE_TYPE_DEFAULT = PERSISTENCE_TYPE_HIBERNATE;
+
+ /** Propriété des générateurs indiquant le package par défaut */
+ public static final String PROPERTY_DEFAULT_PACKAGE = "defaultPackage";
+
+ /** Le package par défaut si aucun n'est spécifié */
+ public static final String DEFAULT_PACKAGE = "org.codelutin.malo";
+
+ /** Stratégie d'heritage par defaut. */
+ public static final String DEFAULT_INHERITANCE_STRATEGY = "union-subclass";
+
+ /**
+ * The Eugene provider of tag values and stereotypes.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @plexus.component role="org.nuiton.eugene.ModelPropertiesUtil$ModelPropertiesProvider" role-hint="topia"
+ * @since 2.3
+ */
+ public static class TopiaModelPropertiesProvider extends ModelPropertiesUtil.ModelPropertiesProvider {
+
+ @Override
+ public void init() throws IllegalAccessException {
+ scanStereotypeClass(TopiaStereoTypes.class);
+ scanTagValueClass(TopiaTagValues.class);
+ }
+ }
+
+ /**
+ * Renvoie le package par défaut pour le générateur donné
+ *
+ * @param generator le générateur donné
+ * @return le package par défaut du générator donné
+ */
+ public static String getDefaultPackage(AbstractGenerator<?> generator) {
+ String packageName = generator.getProperty(PROPERTY_DEFAULT_PACKAGE);
+ if (StringUtils.isBlank(packageName)) {
+ packageName = DEFAULT_PACKAGE;
+ }
+ return packageName;
+ }
+
+ public static String getApplicationContextPackage(ObjectModelTransformerToJava transformer,
+ ObjectModel model) {
+
+ String result = transformer.getDefaultPackageName();
+
+ return result;
+ }
+
+ public static String getPersistenceContextPackage(ObjectModelTransformerToJava transformer,
+ ObjectModel model) {
+
+ String result = transformer.getDefaultPackageName();
+
+ return result;
+ }
+
+ public static String getDaoPackage(ObjectModelTransformerToJava transformer,
+ ObjectModel model,
+ ObjectModelClassifier input) {
+
+ Preconditions.checkState(isEntity(input), "Cant' find dao package name for a none entity " + input);
+ String result = input.getPackageName();
+ return result;
+ }
+
+ public static String getApplicationContextInterfaceName(ObjectModel model) {
+ return model.getName() + "ApplicationContext";
+ }
+
+ public static String getApplicationContextAbstractName(ObjectModel model) {
+ return "Abstract" + model.getName() + "TopiaApplicationContext";
+ }
+
+ public static String getApplicationContextConcreteName(ObjectModel model) {
+ return model.getName() + "TopiaApplicationContext";
+ }
+
+ public static String getPersistenceContextAbstractName(ObjectModel model) {
+ return "Abstract" + model.getName() + "TopiaPersistenceContext";
+ }
+
+ public static String getPersistenceContextConcreteName(ObjectModel model) {
+ return model.getName() + "TopiaPersistenceContext";
+ }
+
+ public static String getPersistenceContextInterfaceName(ObjectModel model) {
+ return model.getName() + "PersistenceContext";
+ }
+
+ public static String getEntityAbstractName(ObjectModelClass input) {
+ return "AbstractTopia" + input.getName();
+ }
+
+ public static String getEntityConcreteName(ObjectModelClass input) {
+ return input.getName();
+ }
+
+ public static String getAbstractDaoName(ObjectModelClass input) {
+ return "Abstract" + input.getName() + "TopiaDao";
+ }
+
+ public static String getGeneratedDaoName(ObjectModelClass input) {
+ return "Generated" + input.getName() + "TopiaDao";
+ }
+
+ public static String getConcreteDaoName(ObjectModelClass input) {
+ return input.getName() + "TopiaDao";
+ }
+
+ @Deprecated
+ public static String getLegacyDaoName(ObjectModelClass input) {
+ return input.getName() + "DAO";
+ }
+
+ public static String getAbstractDaoFqn(ObjectModelClass input) {
+ return input.getPackageName() + "." + getAbstractDaoName(input);
+ }
+
+ public static String getGeneratedDaoFqn(ObjectModelClass input) {
+ return input.getPackageName() + "." + getGeneratedDaoName(input);
+ }
+
+ public static String getConcreteDaoFqn(ObjectModelClass input) {
+ return input.getPackageName() + "." + getConcreteDaoName(input);
+ }
+
+ @Deprecated
+ public static String getLegacyDaoFqn(ObjectModelClass input) {
+ return input.getPackageName() + "." + getLegacyDaoName(input);
+ }
+
+ public static String getEntityPackage(ObjectModelTransformerToJava transformer,
+ ObjectModel model,
+ ObjectModelClassifier input) {
+
+ String result = input.getPackageName();
+ return result;
+ }
+
+ /**
+ * Renvoie l'interface DAO associée à la classe passée en paramètre
+ *
+ * @param clazz la classe à tester
+ * @param model le modele utilisé
+ * @return l'interface trouvée ou null sinon
+ */
+ public static ObjectModelInterface getDAOInterface(ObjectModelClass clazz,
+ ObjectModel model) {
+ for (Object o : model.getInterfaces()) {
+ ObjectModelInterface daoInterface = (ObjectModelInterface) o;
+ if (daoInterface.getName().equals(clazz.getName() + "DAO")) {
+ if (hasDaoStereotype(daoInterface)) {
+ return daoInterface;
+ }
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Renvoie le type de persistence pour le classifier donné. Si aucun n'est
+ * trouvé, le type par défaut est utilisé
+ *
+ * @param classifier l'élément à tester
+ * @return le type de persitence pour l'élément donné.
+ * @since 2.5
+ */
+ public static String getPersistenceType(ObjectModelClassifier classifier) {
+ String tag = getPersistenceTypeTagValue(classifier);
+ if (StringUtils.isEmpty(tag)) {
+ tag = PERSISTENCE_TYPE_DEFAULT;
+ }
+ return tag;
+ }
+
+ /**
+ * Obtain the reverse db name of an attribute.
+ * <p/>
+ * If attribute has a specific reverse attribute, use his db name, otherwise
+ * suffix the db name of the attribute by {@code _id}.
+ *
+ * @param attr the attribute to seek
+ * @return the value of the reverse name
+ * @since 2.5
+ */
+ public static String getReverseDbName(ObjectModelAttribute attr) {
+ if (attr.getReverseAttribute() != null) {
+ return getDbName(attr.getReverseAttribute());
+ } else {
+ return getDbName(attr) + "_id";
+ }
+ }
+
+ /**
+ * Renvoie le nom BD de l'élement passé en paramètre. Elle se base sur le
+ * tag associé si il existe, sinon sur le nom de l'élément
+ *
+ * @param element l'élément à tester
+ * @return le nom de table
+ */
+ public static String getDbName(ObjectModelElement element) {
+ if (element == null) {
+ return null;
+ }
+ String value = getDbNameTagValue(element);
+ if (!StringUtils.isEmpty(value)) {
+ return value;
+ }
+ return toLowerCaseFirstLetter(element.getName());
+ }
+
+ /**
+ * Cherche si le tagvalue {@link TopiaTagValues#TAG_GENERATE_OPERATOR_FOR_DAO_HELPER} a été
+ * activé dans le model.
+ *
+ * @param model le modele utilisé
+ * @return {@code true} si le tag value trouvé dans le modèle, {@code false}
+ * sinon.
+ * @since 2.5
+ */
+ public static boolean shouldGenerateOperatorForDAOHelper(ObjectModel model) {
+ String tagValue = getGenerateOperatorForDAOHelperTagValue(model);
+ boolean generate = StringUtils.isNotEmpty(tagValue) &&
+ Boolean.valueOf(tagValue);
+ return generate;
+ }
+
+ /**
+ * Cherche si le tagvalue {@link TopiaTagValues#TAG_GENERATE_OPERATOR_FOR_DAO_HELPER} a été
+ * activé dans le model.
+ *
+ * @param model le modele utilisé
+ * @return {@code true} si le tag value trouvé dans le modèle, {@code false}
+ * sinon.
+ * @since 2.5
+ */
+ public static boolean shouldGenerateStandaloneEnumForDAOHelper(ObjectModel model) {
+ String tagValue = getGenerateStandaloneEnumForDAOHelperTagValue(model);
+ boolean generate = StringUtils.isNotEmpty(tagValue) &&
+ Boolean.valueOf(tagValue);
+ return generate;
+ }
+
+ /**
+ * Cherche et renvoie la liste des attributs constituant la clef metier
+ * d'une classe.
+ *
+ * @param clazz la classe à tester
+ * @return la liste des attributs de la clef métier
+ */
+ public static Set<ObjectModelAttribute> getNaturalIdAttributes(
+ ObjectModelClass clazz) {
+
+ // use {@link LinkedHashSet} to keep order and prevent duplicate natural ids found
+ Set<ObjectModelAttribute> results =
+ new LinkedHashSet<ObjectModelAttribute>();
+ for (ObjectModelAttribute attr : clazz.getAttributes()) {
+ if (isNaturalId(attr)) {
+ results.add(attr);
+ }
+ }
+
+ // sletellier : #2050 Natural id and not null attributes are not propagated on generalized entities (http://nuiton.org/issues/2050)
+ Collection<ObjectModelClass> superclasses = clazz.getSuperclasses();
+ for (ObjectModelClass superClass : superclasses) {
+ Set<ObjectModelAttribute> naturalIdsOfSuperClass = getNaturalIdAttributes(superClass);
+ results.addAll(naturalIdsOfSuperClass);
+ }
+ return results;
+ }
+
+ /**
+ * Cherche et renvoie la liste des attributs qui ne doivent pas etre null dans
+ * une classe.
+ *
+ * @param clazz la classe à tester
+ * @return la liste des attributs qui ne doivent pas etre null
+ */
+ public static Set<ObjectModelAttribute> getNotNullAttributes(
+ ObjectModelClass clazz) {
+
+ // use {@link LinkedHashSet} to keep order and prevent duplicate not null found
+ Set<ObjectModelAttribute> results =
+ new LinkedHashSet<ObjectModelAttribute>();
+ for (ObjectModelAttribute attr : clazz.getAttributes()) {
+ if (isNotNull(attr)) {
+ results.add(attr);
+ }
+ }
+
+ Collection<ObjectModelClass> superclasses = clazz.getSuperclasses();
+ for (ObjectModelClass superClass : superclasses) {
+ Set<ObjectModelAttribute> notNullOfSuperClass = getNotNullAttributes(superClass);
+ results.addAll(notNullOfSuperClass);
+ }
+
+ // Association class participants are obviously not null
+ if (clazz instanceof ObjectModelAssociationClass) {
+ List<ObjectModelAttribute> participantsAttributes = ((ObjectModelAssociationClass) clazz).getParticipantsAttributes();
+ results.addAll(participantsAttributes);
+ }
+
+ return results;
+ }
+
+ /**
+ * Test if we need to generate {@code toString} method for the given class.
+ *
+ * @param clazz class to test
+ * @param model model
+ * @return {@code true} if {@code toString} should be generated.
+ * clef métier.
+ */
+ public static boolean generateToString(ObjectModelClass clazz,
+ ObjectModel model) {
+ String value = getNotGenerateToStringTagValue(clazz, model);
+ return StringUtils.isEmpty(value);
+ }
+
+
+ /**
+ * Cherche et renvoie la liste des attributs constituant la clef metier
+ * d'une classe.
+ *
+ * @param clazz la classe à tester
+ * @param model le modele
+ * @return la liste des attributs de la clef métier ou null si pas de
+ * clef métier.
+ */
+ public static boolean sortAttribute(ObjectModelClass clazz,
+ ObjectModel model) {
+ String value = getSortAttributeTagValue(clazz, model);
+ return "true".equals(value);
+ }
+
+ /**
+ * Detecte si un attribut fait partie d'une clef metier.
+ *
+ * @param attribute l'attribut à tester
+ * @return {@code true} si l'attribut fait partie d'une clef metier,
+ * <code>false</cdoe> sinon.
+ */
+ public static boolean isNaturalId(ObjectModelAttribute attribute) {
+ String value = getNaturalIdTagValue(attribute);
+ if (StringUtils.isEmpty(value)) {
+ // valeur null, donc pas positionnee
+ return false;
+ }
+ try {
+ return Boolean.valueOf(value.trim());
+ } catch (Exception e) {
+ // on a pas reussi a convertir en boolean.
+ //todo peut-être declancher une exception ?
+ return false;
+ }
+ }
+
+ /**
+ * Detecte si un attribut est marqué comme non null.
+ * Les naturalId {@link #isNaturalId} sont not null par défaut
+ *
+ * @param attribute l'attribut à tester
+ * @return {@code true} si l'attribut doit être non null,
+ * par défaut pour les naturalId, {@code false} sinon..
+ * @since 2.6.9
+ */
+ public static boolean isNotNull(ObjectModelAttribute attribute) {
+ String value = getNotNullTagValue(attribute);
+ if (StringUtils.isEmpty(value)) {
+ // valeur null, donc pas positionnee
+ return isNaturalId(attribute);
+ }
+ try {
+ return Boolean.valueOf(value.trim());
+ } catch (Exception e) {
+ // on a pas reussi a convertir en boolean.
+ //todo peut-être declancher une exception ?
+ return false;
+ }
+ }
+
+ public static <Type extends ObjectModelElement> Collection<Type> getElementsWithStereotype(
+ Collection<Type> elements, String... stereotypes) {
+ Collection<Type> result = new ArrayList<Type>();
+ for (Type element : elements) {
+ if (hasStereotypes(element, stereotypes)) {
+ result.add(element);
+ }
+ }
+ return result;
+ }
+
+ public static boolean hasStereotypes(ObjectModelElement element,
+ String... stereotypes) {
+ for (String stereotype : stereotypes) {
+ if (!element.hasStereotype(stereotype)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ public static String getPrimaryKeyAttributesListDeclaration(
+ ObjectModelClass clazz, boolean includeName) {
+ String attributes = "";
+ Collection<ObjectModelAttribute> attributeCollection;
+ attributeCollection = getElementsWithStereotype(clazz.getAttributes(),
+ TopiaStereoTypes.STEREOTYPE_PRIMARYKAY);
+ for (ObjectModelAttribute attr : attributeCollection) {
+ attributes += attr.getType();
+ if (includeName) {
+ attributes += ' ' + attr.getName();
+ }
+ attributes += ", ";
+ }
+ if (attributes.length() > 0) {
+ attributes = attributes.substring(0, attributes.length() - 2);
+ }
+ return attributes;
+ }
+
+ public static boolean isAssociationClassDoublon(ObjectModelAttribute attr) {
+ return attr.getReverseAttribute() != null &&
+ attr.getDeclaringElement().equals(
+ attr.getReverseAttribute().getDeclaringElement()) &&
+ !GeneratorUtil.isFirstAttribute(attr);
+ }
+
+ public static String getDOType(ObjectModelElement elem, ObjectModel model) {
+ String type = elem.getName();
+ if (elem instanceof ObjectModelAttribute) {
+ type = ((ObjectModelAttribute) elem).getType();
+ }
+ if (elem instanceof ObjectModelClass) {
+ type = ((ObjectModelClass) elem).getQualifiedName();
+ }
+ return getDOType(type, model);
+ }
+
+ public static String getDOType(String type, ObjectModel model) {
+ if (!model.hasClass(type)) {
+ return type;
+ }
+ ObjectModelClass clazz = model.getClass(type);
+ if (isEntity(clazz)) {
+ //tchemit-2011-09-12 What ever abstract or not, we always use an Impl
+ type += "Impl";
+// if (shouldBeAbstract(clazz)) {
+// type += "Abstract";
+// } else {
+// type += "Impl";
+// }
+ }
+ return type;
+ }
+
+ private static final Set<String> numberTypes = new HashSet<String>();
+
+ private static final Set<String> textTypes = new HashSet<String>();
+
+ private static final Set<String> booleanTypes = new HashSet<String>();
+
+ private static final Set<String> primitiveTypes = new HashSet<String>();
+
+ private static final Map<String, String> primitiveTypeToClass = new HashMap<String, String>();
+
+ private static final String VOID_TYPE = "void";
+
+ static {
+
+ primitiveTypeToClass.put("byte", "java.lang.Byte");
+ primitiveTypeToClass.put("short", "java.lang.Short");
+ primitiveTypeToClass.put("int", "java.lang.Integer");
+ primitiveTypeToClass.put("long", "java.lang.Long");
+ primitiveTypeToClass.put("float", "java.lang.Float");
+ primitiveTypeToClass.put("double", "java.lang.Double");
+ primitiveTypeToClass.put("char", "java.lang.Char");
+ primitiveTypeToClass.put("boolean", "java.lang.Boolean");
+
+ numberTypes.add("byte");
+ numberTypes.add("java.lang.Byte");
+ numberTypes.add("Byte");
+ numberTypes.add("short");
+ numberTypes.add("java.lang.Short");
+ numberTypes.add("Short");
+ numberTypes.add("int");
+ numberTypes.add("java.lang.Integer");
+ numberTypes.add("Integer");
+ numberTypes.add("long");
+ numberTypes.add("java.lang.Long");
+ numberTypes.add("Long");
+ numberTypes.add("float");
+ numberTypes.add("java.lang.Float");
+ numberTypes.add("Float");
+ numberTypes.add("double");
+ numberTypes.add("java.lang.Double");
+ numberTypes.add("Double");
+
+ textTypes.add("char");
+ textTypes.add("java.lang.Char");
+ textTypes.add("Char");
+ textTypes.add("java.lang.String");
+ textTypes.add("String");
+
+ booleanTypes.add("boolean");
+ booleanTypes.add("java.lang.Boolean");
+ booleanTypes.add("Boolean");
+
+ primitiveTypes.addAll(numberTypes);
+ primitiveTypes.addAll(textTypes);
+ primitiveTypes.addAll(booleanTypes);
+ }
+
+ public static boolean isNumericType(ObjectModelAttribute attr) {
+ return numberTypes.contains(attr.getType());
+ }
+
+ public static boolean isTextType(ObjectModelAttribute attr) {
+ return textTypes.contains(attr.getType());
+ }
+
+ public static boolean isDateType(ObjectModelAttribute attr) {
+ return "java.util.Date".equals(attr.getType());
+ }
+
+ public static boolean isBooleanType(ObjectModelAttribute attr) {
+ return booleanTypes.contains(attr.getType());
+ }
+
+ public static boolean isPrimitiveType(ObjectModelAttribute attr) {
+ return primitiveTypes.contains(attr.getType());
+ }
+
+ public static String getClassForPrimitiveType(ObjectModelAttribute attr) {
+ Preconditions.checkState(isPrimitiveType(attr));
+ String className = primitiveTypeToClass.get(attr.getType());
+ Preconditions.checkNotNull(className);
+ return className;
+ }
+
+ /**
+ * Indique si la classe specifiee n'a aucune ou que des methodes abstraites
+ *
+ * @param clazz l'instance de ObjectModelClass
+ * @return true si la classe n'a que des operations abstraite ou aucune
+ * operation
+ */
+ public static boolean hasNothingOrAbstractMethods(ObjectModelClass clazz) {
+ boolean result = true;
+ Iterator<?> operations = clazz.getOperations().iterator();
+ while (result && operations.hasNext()) {
+ ObjectModelOperation op = (ObjectModelOperation) operations.next();
+ result = op.isAbstract();
+ }
+ return result;
+ }
+
+ /**
+ * Indique si la classe specifiee devrait etre abstraite
+ *
+ * @param clazz l'instance de ObjectModelClass
+ * @return true dans ce cas, false sinon
+ */
+ public static boolean shouldBeAbstract(ObjectModelClass clazz) {
+ return clazz != null && clazz.isAbstract() &&
+ hasNothingOrAbstractMethods(clazz);
+ }
+
+ /**
+ * <p>
+ * Cette méthode permet de détecter si
+ * - l'attribut représente une relation 1-n
+ * - cette relation est unidirectionnelle
+ * - le type de l'attribut représente un entité
+ * - cette entité a des sous-classes dans le modèle
+ * <p/>
+ * Ce cas correspond à une incompatibilité d'Hibernate qui nous oblige a
+ * adopter un comportement particulier.
+ * </p>
+ *
+ * @param attr l'attribut a tester
+ * @param model le model
+ * @return true si et seulement si il s'agit bien de ce type de relation
+ */
+ public static boolean hasUnidirectionalRelationOnAbstractType(
+ ObjectModelAttribute attr, ObjectModel model) {
+ ObjectModelAttribute reverse = attr.getReverseAttribute();
+ //relation 1-n
+ if (reverse != null && isNMultiplicity(attr) &&
+ !isNMultiplicity(reverse)) {
+ //Pas de navigabilité
+ if (!reverse.isNavigable()) {
+ //Il s'agit d'une entity
+ ObjectModelClass clazz = model.getClass(attr.getType());
+ if (clazz != null && isEntity(clazz)) {
+ //Cette classe a des sous-classes dans le modèle
+ for (ObjectModelClass subClass : model.getClasses()) {
+ if (subClass.getSuperclasses().contains(clazz)) {
+ return true;
+ }
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Renvoie le nom unique de table pour une relation ManyToMany en fonction
+ * de l'attribut <code>attr</code>
+ * <p/>
+ * Plusieurs cas de figure:
+ * <li>
+ *
+ * @param attr l'attribut servant de base au calcul du nom
+ * @return le nom de la table
+ */
+ public static String getManyToManyTableName(ObjectModelAttribute attr) {
+ String result;
+
+ if (attr.hasAssociationClass()) {
+ result = getDbName(attr.getAssociationClass());
+ } else {
+ String name = attr.getName();
+ String revers = attr.getReverseAttributeName();
+
+ if (name.compareToIgnoreCase(revers) < 0) {
+ result = name + '_' + revers;
+ } else {
+ result = revers + '_' + name;
+ }
+ }
+ return result.toLowerCase();
+ }
+
+ /**
+ * Renvoie le type d'interface à utiliser en fonction de l'attribut
+ *
+ * @param attr l'attribut a traiter
+ * @return String
+ */
+ public static String getNMultiplicityInterfaceType(
+ ObjectModelAttribute attr) {
+ if (hasUniqueStereotype(attr)) {
+ return Set.class.getName();
+ } else if (JavaGeneratorUtil.hasIndexedStereotype(attr) || attr.isOrdered()) {
+ return List.class.getName();
+ }
+ return Collection.class.getName();
+ }
+
+ /**
+ * Renvoie le type d'objet (instance) à utiliser en fonction de l'attribut
+ *
+ * @param attr l'attribut a traiter
+ * @return String
+ */
+ public static String getNMultiplicityObjectType(ObjectModelAttribute attr) {
+ if (hasUniqueStereotype(attr)) {
+ return HashSet.class.getName();
+ } else if (JavaGeneratorUtil.hasIndexedStereotype(attr) || attr.isOrdered()) {
+ //On considère qu'on ne sait pas traiter vraiment l'attribut "ordered"
+ // puisqu'on va conserver l'ordre d'insertion, et non un ordre en
+ // fonction d'un élément donné. Donc on renvoi une ArrayList
+ return ArrayList.class.getName();
+ }
+ LinkedList.class.getName();
+ return ArrayList.class.getName();
+ }
+
+ /**
+ * Renvoie le type d'interface à utiliser en fonction de l'attribut
+ *
+ * @param attr l'attribut a traiter
+ * @return String
+ */
+ public static String getNMultiplicityHibernateType(
+ ObjectModelAttribute attr) {
+ if (hasUniqueStereotype(attr)) {
+ return "set";
+ } else if (JavaGeneratorUtil.hasIndexedStereotype(attr)) {
+ return "list";
+ }
+ //attr.isOrdered() - On génère le ordered en bag
+ return "bag";
+ }
+
+ /**
+ * Obtain the list of entities classes with the possibility to sort the
+ * result.
+ *
+ * @param model the current model to scan
+ * @param sort flag to allow sort the result
+ * @return the list of filtred classes by their stereotype
+ */
+ public static List<ObjectModelClass> getEntityClasses(ObjectModel model,
+ boolean sort) {
+ return getClassesByStereotype(TopiaStereoTypes.STEREOTYPE_ENTITY, model, sort);
+ }
+
+ /**
+ * Obtain the list of classes for a given stereotype with the possibility
+ * to sort the result.
+ *
+ * @param stereotype filter stereotype
+ * @param model the current model to scan
+ * @param sort flag to allow sort the result
+ * @return the list of filtred classes by their stereotype
+ */
+ public static List<ObjectModelClass> getClassesByStereotype(
+ String stereotype, ObjectModel model, boolean sort) {
+ List<ObjectModelClass> classes = new ArrayList<ObjectModelClass>();
+ for (ObjectModelClass clazz : model.getClasses()) {
+ if (clazz.hasStereotype(stereotype)) {
+ classes.add(clazz);
+ }
+ }
+ if (sort && !classes.isEmpty()) {
+
+ Collections.sort(classes, OBJECT_MODEL_CLASS_COMPARATOR);
+ }
+ return classes;
+ }
+
+ static public final Comparator<ObjectModelClass>
+ OBJECT_MODEL_CLASS_COMPARATOR =
+ new Comparator<ObjectModelClass>() {
+
+ @Override
+ public int compare(ObjectModelClass o1,
+ ObjectModelClass o2) {
+ return o1.getQualifiedName().compareTo(
+ o2.getQualifiedName());
+ }
+ };
+
+ /**
+ * Detecte si la clef metier d'une classe est mutable ou pas.
+ * <p/>
+ * On respecte la valeur par defaut d'hibernate, à savoir que par default
+ * une clef metier est non mutable.
+ *
+ * @param clazz la classe a tester
+ * @return {@code true} si le tag value a ete positionne sur la classe
+ * via le tag {@link TopiaTagValues#TAG_NATURAL_ID_MUTABLE}, {@code false}
+ * sinon.
+ */
+ public static boolean isNaturalIdMutable(ObjectModelClass clazz) {
+ String value = getNaturalIdMutableTagValue(clazz);
+ if (StringUtils.isEmpty(value)) {
+ // valeur null, donc par default positionnee
+ return false;
+ }
+ try {
+ return Boolean.valueOf(value.trim());
+ } catch (Exception e) {
+ // on a pas reussi a convertir en boolean.
+ //todo peut-être declancher une exception ?
+ return false;
+ }
+ }
+
+ /**
+ * Retourne true si le tagValue {@link TopiaTagValues#TAG_CONTEXTABLE}
+ * à la valeur {@code true}.
+ *
+ * @param classifier classifier to test
+ * @return {@code true} si {@link TopiaTagValues#TAG_CONTEXTABLE} == {@code true}
+ */
+ public static boolean isContextable(ObjectModelClassifier classifier) {
+ boolean result = false;
+ String value = classifier.getTagValue(TopiaTagValues.TAG_CONTEXTABLE);
+ if (StringUtils.equalsIgnoreCase(value, "true")) {
+ result = true;
+ }
+ return result;
+ }
+
+ /**
+ * Obtain the list of fqn of object involed in the given class.
+ *
+ * @param aClass the clazz to inspect
+ * @param incomingFqns incoming fqns
+ * @return the list of fqn of attributes
+ */
+ public static List<String> getImports(ObjectModelClass aClass,
+ String... incomingFqns) {
+ Set<String> tmp = new HashSet<String>();
+ tmp.addAll(Arrays.asList(incomingFqns));
+ getImports(aClass, tmp);
+ List<String> result = cleanImports(aClass.getPackageName(), tmp);
+ return result;
+ }
+
+ /**
+ * Obtain the list of fqn of object involed in the given interface.
+ *
+ * @param anInterface the interface to inspect
+ * @param incomingFqns incoming fqns
+ * @return the list of fqn of attributes
+ */
+ public static List<String> getImports(ObjectModelInterface anInterface,
+ String... incomingFqns) {
+ Set<String> tmp = new HashSet<String>();
+ tmp.addAll(Arrays.asList(incomingFqns));
+ getImports(anInterface, tmp);
+ List<String> result = cleanImports(anInterface.getPackageName(), tmp);
+ return result;
+ }
+
+ /**
+ * Obtain the list of fqn of object involed in the given class.
+ *
+ * @param aClass the class to inspect
+ * @param fqns where to store found fqns
+ */
+ protected static void getImports(ObjectModelClass aClass,
+ Set<String> fqns) {
+ // scan attributes
+ for (ObjectModelAttribute attr : aClass.getAttributes()) {
+ fqns.add(attr.getType());
+ if (isNMultiplicity(attr)) {
+ String collectionType = getNMultiplicityInterfaceType(attr);
+ fqns.add(collectionType);
+ String collectionObject = getNMultiplicityObjectType(attr);
+ fqns.add(collectionObject);
+ }
+ }
+ for (ObjectModelAttribute attribute : aClass.getAllOtherAttributes()) {
+ fqns.add(attribute.getType());
+ }
+ // scan associations
+ if (aClass instanceof ObjectModelAssociationClass) {
+ ObjectModelAssociationClass assoc =
+ (ObjectModelAssociationClass) aClass;
+ for (ObjectModelAttribute attr :
+ assoc.getParticipantsAttributes()) {
+ if (attr == null) {
+ continue;
+ }
+ fqns.add(attr.getType());
+ if (isNMultiplicity(attr)) {
+ String collectionType = getNMultiplicityInterfaceType(attr);
+ fqns.add(collectionType);
+ String collectionObject = getNMultiplicityObjectType(attr);
+ fqns.add(collectionObject);
+ }
+ }
+ }
+ // scan operations
+ for (ObjectModelOperation operation : aClass.getOperations()) {
+ getImports(operation, fqns);
+ }
+ // scan super interfaces
+ for (ObjectModelInterface modelInterface : aClass.getInterfaces()) {
+ fqns.add(modelInterface.getQualifiedName());
+ getImports(modelInterface, fqns);
+ }
+ // scan super classes
+ for (ObjectModelClass modelClass : aClass.getSuperclasses()) {
+ fqns.add(modelClass.getQualifiedName());
+ getImports(modelClass);
+ }
+ }
+
+ /**
+ * Obtain the list of fqn of object involed in the given interface.
+ *
+ * @param anInterface the interface to inspect
+ * @param fqns where to store found fqns
+ */
+ protected static void getImports(ObjectModelInterface anInterface,
+ Set<String> fqns) {
+ // scan operations
+ for (ObjectModelOperation operation : anInterface.getOperations()) {
+ getImports(operation, fqns);
+ }
+ // scan super interfaces
+ for (ObjectModelInterface modelInterface : anInterface.getInterfaces()) {
+ fqns.add(modelInterface.getQualifiedName());
+ getImports(modelInterface, fqns);
+ }
+ }
+
+ /**
+ * Obtain the fqn's list of all involed type in a givne operation.
+ *
+ * @param operation operation to inspect
+ * @param fqns where to store found fqns
+ */
+ protected static void getImports(ObjectModelOperation operation,
+ Set<String> fqns) {
+ String fqn = operation.getReturnType();
+ fqns.add(fqn);
+ for (ObjectModelParameter parameter : operation.getParameters()) {
+ fqns.add(parameter.getType());
+ }
+ }
+
+ /**
+ * Clean a set of fqns, transform it into a {@link List} and sort it.
+ *
+ * @param packageName the current package name
+ * @param fqns the dirty set of fqns
+ * @return the sorted cleaned list of fqns.
+ */
+ protected static List<String> cleanImports(String packageName,
+ Set<String> fqns) {
+ fqns.removeAll(primitiveTypes);
+ fqns.remove(VOID_TYPE);
+ int packageLength = packageName.length();
+ List<String> genericType = new ArrayList<String>();
+ for (Iterator<String> it = fqns.iterator(); it.hasNext(); ) {
+ String fqn = it.next();
+ int lastIndex = fqn.lastIndexOf(".");
+ if (lastIndex == packageLength && fqn.startsWith(packageName)) {
+ // same package
+ it.remove();
+ continue;
+ }
+ int genericIndex = fqn.indexOf('<');
+ if (genericIndex != -1) {
+ genericType.add(fqn.substring(0, genericIndex));
+ it.remove();
+ }
+ }
+ fqns.addAll(genericType);
+
+ ArrayList<String> result = new ArrayList<String>(fqns);
+ Collections.sort(result);
+ return result;
+ }
+
+ /**
+ * Obtain the class to use as abstract dao.
+ * <p/>
+ * It will look after a tag value {@link TopiaTagValues#TAG_DAO_IMPLEMENTATION} in model
+ * and if not found will use the default value which is {@link TopiaDAOImpl}.
+ *
+ * @param model the model which could contains
+ * @return the type of the abstract dao to use
+ * @since 2.5
+ */
+ public static Class<?> getDAOImplementation(ObjectModel model) {
+ String daoImpl = getDaoImplementationTagValue(model);
+ Class<?> result;
+ if (StringUtils.isEmpty(daoImpl)) {
+
+ // use the default dao implementation of topia
+ result = AbstractTopiaDao.class;
+ } else {
+ try {
+ result = Class.forName(daoImpl);
+ } catch (ClassNotFoundException e) {
+ String message = "Could not find dao implementation named " + daoImpl;
+ log.error(message);
+ throw new IllegalStateException(message, e);
+ }
+ }
+ return result;
+ }
+
+ public static Map<ObjectModelClass, Set<ObjectModelClass>>
+ searchDirectUsages(ObjectModel model) {
+ List<ObjectModelClass> allEntities;
+ Map<String, ObjectModelClass> allEntitiesByFQN;
+ Map<ObjectModelClass, Set<ObjectModelClass>> usages;
+
+ allEntities = getEntityClasses(model, true);
+
+ allEntitiesByFQN = new TreeMap<String, ObjectModelClass>();
+ usages = new LinkedHashMap<ObjectModelClass, Set<ObjectModelClass>>();
+
+ // prepare usages map and fill allEntitiesByFQN map
+ for (ObjectModelClass klass : allEntities) {
+ usages.put(klass, new HashSet<ObjectModelClass>());
+ allEntitiesByFQN.put(klass.getQualifiedName(), klass);
+ }
+
+ // first pass to detect direct usages
+ for (ObjectModelClass klass : allEntities) {
+ searchDirectUsages(klass, allEntitiesByFQN, usages);
+ }
+ allEntities.clear();
+ allEntitiesByFQN.clear();
+ return usages;
+
+ }
+
+ public static void searchDirectUsages(
+ ObjectModelClass klass,
+ Map<String, ObjectModelClass> allEntitiesByFQN,
+ Map<ObjectModelClass, Set<ObjectModelClass>> usages) {
+
+ if (log.isDebugEnabled()) {
+ log.debug("for entity " + klass.getQualifiedName());
+ }
+ for (ObjectModelAttribute attr : klass.getAttributes()) {
+ if (!attr.isNavigable()) {
+ // skip this case
+ continue;
+ }
+ String type;
+ if (attr.hasAssociationClass()) {
+ type = attr.getAssociationClass().getQualifiedName();
+ } else {
+ type = attr.getType();
+ }
+ if (!allEntitiesByFQN.containsKey(type)) {
+ // not a entity, can skip for this attribute
+ continue;
+ }
+ if (log.isDebugEnabled()) {
+ log.debug(" uses " + type);
+ }
+ // register the klass as using the targetEntity
+ ObjectModelClass targetEntity = allEntitiesByFQN.get(type);
+ Set<ObjectModelClass> classes = usages.get(targetEntity);
+ classes.add(klass);
+ }
+ }
+
+ public static boolean isImportNeeded(Collection<ObjectModelOperation> operations,
+ String importName) {
+ if (CollectionUtils.isNotEmpty(operations)) {
+ for (ObjectModelOperation op : operations) {
+ if (op.getReturnType().contains(importName)) {
+ return true;
+ }
+ for (ObjectModelParameter param : op.getParameters()) {
+ if (param.getType().contains(importName)) {
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+ public static boolean isCollectionNeeded(
+ Collection<ObjectModelOperation> operations) {
+ return isImportNeeded(operations,
+ Collection.class.getSimpleName());
+ }
+
+ public static boolean isSetNeeded(Collection<ObjectModelOperation> operations) {
+ return isImportNeeded(operations,
+ Set.class.getSimpleName());
+ }
+
+ /**
+ * Check if the given classifier has the
+ * {@link TopiaStereoTypes#STEREOTYPE_ENTITY} stereotype.
+ *
+ * @param classifier classifier to test
+ * @return {@code true} if stereotype was found, {@code false} otherwise
+ * @see TopiaStereoTypes#STEREOTYPE_ENTITY
+ * @since 2.5
+ */
+ public static boolean hasEntityStereotype(ObjectModelClassifier classifier) {
+ return classifier.hasStereotype(TopiaStereoTypes.STEREOTYPE_ENTITY);
+ }
+
+ /**
+ * Check if the given attribute type is an entity.
+ *
+ * @param attribute attribute to test
+ * @param model model containing the attribute
+ * @return {@code true} if type of attribute is an entity,
+ * {@code false} otherwise
+ * @see TopiaStereoTypes#STEREOTYPE_ENTITY
+ * @since 2.7
+ */
+ public static boolean isEntity(ObjectModelAttribute attribute,
+ ObjectModel model) {
+ if (isPrimitiveType(attribute)) {
+ return false;
+ }
+ String attributeType = attribute.getType();
+ ObjectModelClassifier typeclassifier =
+ model.getClassifier(attributeType);
+ return typeclassifier != null && isEntity(typeclassifier);
+ }
+
+ /**
+ * Check if the given classifier has the
+ * {@link TopiaStereoTypes#STEREOTYPE_ENTITY} and is not an enumeration
+ *
+ * @param classifier classifier to test
+ * @return {@code true} if stereotype was found and classifier is not
+ * enumeration, {@code false} otherwise
+ * @see TopiaStereoTypes#STEREOTYPE_ENTITY
+ * @since 2.5
+ */
+ public static boolean isEntity(ObjectModelClassifier classifier) {
+ return hasEntityStereotype(classifier) && !classifier.isEnum();
+ }
+
+
+ /**
+ * Check if the given attribute has the
+ * {@link TopiaStereoTypes#STEREOTYPE_ENTITY} stereotype.
+ *
+ * @param attribute attribute to test
+ * @return {@code true} if stereotype was found, {@code false otherwise}
+ * @see TopiaStereoTypes#STEREOTYPE_ENTITY
+ * @since 2.5
+ */
+ public static boolean hasEntityStereotype(ObjectModelAttribute attribute) {
+ return attribute.hasStereotype(TopiaStereoTypes.STEREOTYPE_ENTITY);
+ }
+
+ /**
+ * Check if the given classifier has the
+ * {@link TopiaStereoTypes#STEREOTYPE_DTO} stereotype.
+ *
+ * @param classifier classifier to test
+ * @return {@code true} if stereotype was found, {@code false otherwise}
+ * @see TopiaStereoTypes#STEREOTYPE_DTO
+ * @since 2.5
+ */
+ public static boolean hasDtoStereotype(ObjectModelClassifier classifier) {
+ return classifier.hasStereotype(TopiaStereoTypes.STEREOTYPE_DTO);
+ }
+
+ /**
+ * Check if the given classifier has the
+ * {@link TopiaStereoTypes#STEREOTYPE_DAO} stereotype.
+ *
+ * @param classifier classifier to test
+ * @return {@code true} if stereotype was found, {@code false otherwise}
+ * @see TopiaStereoTypes#STEREOTYPE_DAO
+ * @since 2.5
+ */
+ public static boolean hasDaoStereotype(ObjectModelClassifier classifier) {
+ return classifier.hasStereotype(TopiaStereoTypes.STEREOTYPE_DAO);
+ }
+
+ /**
+ * Check if the given operation has the
+ * {@link TopiaStereoTypes#STEREOTYPE_DAO} stereotype.
+ *
+ * @param operation operation to test
+ * @return {@code true} if stereotype was found, {@code false otherwise}
+ * @see TopiaStereoTypes#STEREOTYPE_DAO
+ * @since 2.5
+ */
+ public static boolean hasDaoStereotype(ObjectModelOperation operation) {
+ return operation.hasStereotype(TopiaStereoTypes.STEREOTYPE_DAO);
+ }
+
+ /**
+ * Check if the given attribute has the
+ * {@link TopiaStereoTypes#STEREOTYPE_UNIQUE} stereotype.
+ *
+ * @param attribute attribute to test
+ * @return {@code true} if stereotype was found, {@code false otherwise}
+ * @see TopiaStereoTypes#STEREOTYPE_UNIQUE
+ * @since 2.5
+ */
+ public static boolean hasUniqueStereotype(ObjectModelAttribute attribute) {
+ return attribute.hasStereotype(TopiaStereoTypes.STEREOTYPE_UNIQUE);
+ }
+
+ /**
+ * Check if the given attribute has the
+ * {@link TopiaStereoTypes#STEREOTYPE_PRIMARYKAY} stereotype.
+ *
+ * @param attribute attribute to test
+ * @return {@code true} if stereotype was found, {@code false otherwise}
+ * @see TopiaStereoTypes#STEREOTYPE_PRIMARYKAY
+ * @since 2.5
+ */
+ public static boolean hasPrimaryKeyStereotype(ObjectModelAttribute attribute) {
+ return attribute.hasStereotype(TopiaStereoTypes.STEREOTYPE_PRIMARYKAY);
+ }
+
+ /**
+ * Obtain the value of the {@link TopiaTagValues#TAG_PERSISTENCE_TYPE}
+ * tag value on the given classifier.
+ *
+ * @param classifier classifier to seek
+ * @return the none empty value of the found tag value or {@code null} if not found nor empty.
+ * @see TopiaTagValues#TAG_PERSISTENCE_TYPE
+ * @since 2.5
+ */
+ public static String getPersistenceTypeTagValue(ObjectModelClassifier classifier) {
+ String value = findTagValue(TopiaTagValues.TAG_PERSISTENCE_TYPE, classifier, null);
+ return value;
+ }
+
+ /**
+ * Obtain the value of the {@link TopiaTagValues#TAG_INHERITANCE_STRATEGY}
+ * tag value on the given classifier.
+ *
+ * @param classifier classifier to seek
+ * @return the none empty value of the found tag value or {@code null} if not found nor empty.
+ * @see TopiaTagValues#TAG_INHERITANCE_STRATEGY
+ * @since 3.0
+ */
+ public static String getInheritanceStrategyTagValue(ObjectModelClassifier classifier) {
+ String value = findTagValue(TopiaTagValues.TAG_INHERITANCE_STRATEGY, classifier, null);
+ if (value == null) {
+ value = DEFAULT_INHERITANCE_STRATEGY;
+ }
+ return value;
+ }
+
+ /**
+ * Obtain the value of the {@link TopiaTagValues#TAG_DB_NAME}
+ * tag value on the given classifier.
+ *
+ * @param element classifier to seek
+ * @return the none empty value of the found tag value or {@code null} if not found nor empty.
+ * @see TopiaTagValues#TAG_DB_NAME
+ * @since 2.5
+ */
+ public static String getDbNameTagValue(ObjectModelElement element) {
+ String value = findTagValue(TopiaTagValues.TAG_DB_NAME, element, null);
+ return value;
+ }
+
+ /**
+ * Obtain the value of the {@link TopiaTagValues#TAG_SCHEMA_NAME}
+ * tag value on the given classifier.
+ *
+ * @param classifier classifier to seek
+ * @param model model to seek
+ * @return the none empty value of the found tag value or {@code null} if not found nor empty.
+ * @see TopiaTagValues#TAG_SCHEMA_NAME
+ * @since 2.5
+ */
+ public static String getDbSchemaNameTagValue(ObjectModelClassifier classifier, ObjectModel model) {
+ String value = findTagValue(TopiaTagValues.TAG_SCHEMA_NAME, classifier, model);
+ return value;
+ }
+
+ /**
+ * Obtain the value of the {@link TopiaTagValues#TAG_SCHEMA_NAME}
+ * tag value on the given attribute.
+ *
+ * @param attribute attribute to seek
+ * @param model model to seek
+ * @return the none empty value of the found tag value or {@code null} if not found nor empty.
+ * @see TopiaTagValues#TAG_SCHEMA_NAME
+ * @since 2.5
+ */
+ public static String getDbSchemaNameTagValue(ObjectModelAttribute attribute, ObjectModel model) {
+ String value = findTagValue(TopiaTagValues.TAG_SCHEMA_NAME, attribute, model);
+ return value;
+ }
+
+ /**
+ * Obtain the value of the {@link TopiaTagValues#TAG_LENGTH}
+ * tag value on the given attribute.
+ *
+ * @param attribute attribute to seek
+ * @return the none empty value of the found tag value or {@code null} if not found nor empty.
+ * @see TopiaTagValues#TAG_LENGTH
+ * @since 2.5
+ */
+ public static String getLengthTagValue(ObjectModelAttribute attribute) {
+ String value = findTagValue(TopiaTagValues.TAG_LENGTH, attribute, null);
+ return value;
+ }
+
+ /**
+ * Obtain the value of the {@link TopiaTagValues#TAG_ANNOTATION}
+ * tag value on the given attribute.
+ *
+ * @param attribute attribute to seek
+ * @return the none empty value of the found tag value or {@code null} if not found nor empty.
+ * @see TopiaTagValues#TAG_ANNOTATION
+ * @since 2.5
+ */
+ public static String getAnnotationTagValue(ObjectModelAttribute attribute) {
+ String value = findTagValue(TopiaTagValues.TAG_ANNOTATION, attribute, null);
+ return value;
+ }
+
+ /**
+ * Obtain the value of the {@link TopiaTagValues#TAG_ACCESS}
+ * tag value on the given attribute.
+ *
+ * @param attribute attribute to seek
+ * @return the none empty value of the found tag value or {@code null} if not found nor empty.
+ * @see TopiaTagValues#TAG_ACCESS
+ * @since 2.5
+ */
+ public static String getAccessTagValue(ObjectModelAttribute attribute) {
+ String value = findTagValue(TopiaTagValues.TAG_ACCESS, attribute, null);
+ return value;
+ }
+
+ /**
+ * Obtain the value of the {@link TopiaTagValues#TAG_NATURAL_ID}
+ * tag value on the given attribute.
+ *
+ * @param attribute attribute to seek
+ * @return the none empty value of the found tag value or {@code null} if not found nor empty.
+ * @see TopiaTagValues#TAG_NATURAL_ID
+ * @since 2.5
+ */
+ public static String getNaturalIdTagValue(ObjectModelAttribute attribute) {
+ String value = findTagValue(TopiaTagValues.TAG_NATURAL_ID, attribute, null);
+ return value;
+ }
+
+ /**
+ * Obtain the value of the {@link TopiaTagValues#TAG_NATURAL_ID_MUTABLE}
+ * tag value on the given classifier.
+ *
+ * @param classifier classifier to seek
+ * @return the none empty value of the found tag value or {@code null} if not found nor empty.
+ * @see TopiaTagValues#TAG_NATURAL_ID_MUTABLE
+ * @since 2.5
+ */
+ public static String getNaturalIdMutableTagValue(ObjectModelClassifier classifier) {
+ String value = findTagValue(TopiaTagValues.TAG_NATURAL_ID_MUTABLE, classifier, null);
+ return value;
+ }
+
+ /**
+ * Obtain the value of the {@link TopiaTagValues#TAG_INVERSE}
+ * tag value on the given attribute.
+ *
+ * @param attribute attribute to seek
+ * @return the none empty value of the found tag value or {@code null} if not found nor empty.
+ * @see TopiaTagValues#TAG_INVERSE
+ * @since 2.5
+ */
+ public static String getInverseTagValue(ObjectModelAttribute attribute) {
+ String value = findTagValue(TopiaTagValues.TAG_INVERSE, attribute, null);
+ return value;
+ }
+
+ /**
+ * Obtain the value of the {@link TopiaTagValues#TAG_LAZY}
+ * tag value on the given attribute.
+ *
+ * @param attribute attribute to seek
+ * @return the none empty value of the found tag value or {@code null} if not found nor empty.
+ * @see TopiaTagValues#TAG_LAZY
+ * @since 2.5
+ */
+ public static String getLazyTagValue(ObjectModelAttribute attribute) {
+ String value = findTagValue(TopiaTagValues.TAG_LAZY, attribute, null);
+ return value;
+ }
+
+ /**
+ * Obtain the value of the {@link TopiaTagValues#TAG_FETCH}
+ * tag value on the given attribute.
+ *
+ * @param attribute attribute to seek
+ * @return the none empty value of the found tag value or {@code null} if not found nor empty.
+ * @see TopiaTagValues#TAG_FETCH
+ * @since 2.5
+ */
+ public static String getFetchTagValue(ObjectModelAttribute attribute) {
+ String value = findTagValue(TopiaTagValues.TAG_FETCH, attribute, null);
+ return value;
+ }
+
+ /**
+ * Obtain the value of the {@link TopiaTagValues#TAG_ORDER_BY}
+ * tag value on the given attribute.
+ *
+ * @param attribute attribute to seek
+ * @return the none empty value of the found tag value or {@code null} if not found nor empty.
+ * @see TopiaTagValues#TAG_ORDER_BY
+ * @since 2.5
+ */
+ public static String getOrderByTagValue(ObjectModelAttribute attribute) {
+ String value = findTagValue(TopiaTagValues.TAG_ORDER_BY, attribute, null);
+ return value;
+ }
+
+ /**
+ * Obtain the value of the {@link TopiaTagValues#TAG_NOT_NULL}
+ * tag value on the given attribute.
+ *
+ * @param attribute attribute to seek
+ * @return the none empty value of the found tag value or {@code null} if not found nor empty.
+ * @see TopiaTagValues#TAG_NOT_NULL
+ * @since 2.5
+ */
+ public static String getNotNullTagValue(ObjectModelAttribute attribute) {
+ String value = findTagValue(TopiaTagValues.TAG_NOT_NULL, attribute, null);
+ return value;
+ }
+
+ /**
+ * Obtain the value of the {@link TopiaTagValues#TAG_PROXY_INTERFACE}
+ * tag value on the given classifier.
+ *
+ * @param classifier classifier to seek
+ * @param model model to seek
+ * @return the none empty value of the found tag value or {@code null} if not found nor empty.
+ * @see TopiaTagValues#TAG_PROXY_INTERFACE
+ * @since 2.5
+ */
+ public static String getProxyInterfaceTagValue(ObjectModelClassifier classifier, ObjectModel model) {
+ String value = findTagValue(TopiaTagValues.TAG_PROXY_INTERFACE, classifier, model);
+ return value;
+ }
+
+ /**
+ * Tests if the given classifier own at least one security tag value.
+ *
+ * @param classifier the classifier to test
+ * @return {@code true} if there is at least one security tag value on the given class
+ * @since 2.5
+ */
+ public static boolean isClassWithSecurity(ObjectModelClassifier classifier) {
+ return StringUtils.isNotEmpty(getSecurityCreateTagValue(classifier)) ||
+ StringUtils.isNotEmpty(getSecurityLoadTagValue(classifier)) ||
+ StringUtils.isNotEmpty(getSecurityUpdateTagValue(classifier)) ||
+ StringUtils.isNotEmpty(getSecurityDeleteTagValue(classifier));
+ }
+
+ /**
+ * Obtain the value of the {@link TopiaTagValues#TAG_SECURITY_CREATE}
+ * tag value on the given classifier.
+ *
+ * @param classifier classifier to seek
+ * @return the none empty value of the found tag value or {@code null} if not found nor empty.
+ * @see TopiaTagValues#TAG_SECURITY_CREATE
+ * @since 2.5
+ */
+ public static String getSecurityCreateTagValue(ObjectModelClassifier classifier) {
+ String value = findTagValue(TopiaTagValues.TAG_SECURITY_CREATE, classifier, null);
+ return value;
+ }
+
+ /**
+ * Obtain the value of the {@link TopiaTagValues#TAG_SECURITY_DELETE}
+ * tag value on the given classifier.
+ *
+ * @param classifier classifier to seek
+ * @return the none empty value of the found tag value or {@code null} if not found nor empty.
+ * @see TopiaTagValues#TAG_SECURITY_DELETE
+ * @since 2.5
+ */
+ public static String getSecurityDeleteTagValue(ObjectModelClassifier classifier) {
+ String value = findTagValue(TopiaTagValues.TAG_SECURITY_DELETE, classifier, null);
+ return value;
+ }
+
+ /**
+ * Obtain the value of the {@link TopiaTagValues#TAG_SECURITY_LOAD}
+ * tag value on the given classifier.
+ *
+ * @param classifier classifier to seek
+ * @return the none empty value of the found tag value or {@code null} if not found nor empty.
+ * @see TopiaTagValues#TAG_SECURITY_LOAD
+ * @since 2.5
+ */
+ public static String getSecurityLoadTagValue(ObjectModelClassifier classifier) {
+ String value = findTagValue(TopiaTagValues.TAG_SECURITY_LOAD, classifier, null);
+ return value;
+ }
+
+ /**
+ * Obtain the value of the {@link TopiaTagValues#TAG_SECURITY_UPDATE}
+ * tag value on the given classifier.
+ *
+ * @param classifier classifier to seek
+ * @return the none empty value of the found tag value or {@code null} if not found nor empty.
+ * @see TopiaTagValues#TAG_SECURITY_UPDATE
+ * @since 2.5
+ */
+ public static String getSecurityUpdateTagValue(ObjectModelClassifier classifier) {
+ String value = findTagValue(TopiaTagValues.TAG_SECURITY_UPDATE, classifier, null);
+ return value;
+ }
+
+ /**
+ * Obtain the value of the {@link TopiaTagValues#TAG_NOT_GENERATE_TO_STRING}
+ * tag value on the given class.
+ *
+ * @param clazz class to seek
+ * @param model model to seek
+ * @return the none empty value of the found tag value or {@code null} if not found nor empty.
+ * @see TopiaTagValues#TAG_NOT_GENERATE_TO_STRING
+ * @since 2.5
+ */
+ public static String getNotGenerateToStringTagValue(ObjectModelClassifier clazz, ObjectModel model) {
+ String value = findTagValue(TopiaTagValues.TAG_NOT_GENERATE_TO_STRING, clazz, model);
+ return value;
+ }
+
+ /**
+ * Obtain the value of the {@link TopiaTagValues#TAG_SORT_ATTRIBUTE}
+ * tag value on the given classifier.
+ *
+ * @param classifier classifier to seek
+ * @param model model to seek
+ * @return the none empty value of the found tag value or {@code null} if not found nor empty.
+ * @see TopiaTagValues#TAG_SORT_ATTRIBUTE
+ * @since 2.5
+ */
+ public static String getSortAttributeTagValue(ObjectModelClassifier classifier, ObjectModel model) {
+ String value = findTagValue(TopiaTagValues.TAG_SORT_ATTRIBUTE, classifier, model);
+ return value;
+ }
+
+ /**
+ * Obtain the value of the {@link TopiaTagValues#TAG_GENERATE_STANDALONE_ENUM_FOR_DAO_HELPER}
+ * tag value on the given model.
+ *
+ * @param model model to seek
+ * @return the none empty value of the found tag value or {@code null} if not found nor empty.
+ * @see TopiaTagValues#TAG_GENERATE_STANDALONE_ENUM_FOR_DAO_HELPER
+ * @since 2.5
+ */
+ public static String getGenerateStandaloneEnumForDAOHelperTagValue(ObjectModel model) {
+ String value = findTagValue(TopiaTagValues.TAG_GENERATE_STANDALONE_ENUM_FOR_DAO_HELPER, null, model);
+ return value;
+ }
+
+ /* Obtain the value of the {@link TopiaTagValues#TAG_GENERATE_OPERATOR_FOR_DAO_HELPER}
+ * tag value on the given model.
+ *
+ * @param model model to seek
+ * @return the none empty value of the found tag value or {@code null} if not found nor empty.
+ * @see TopiaTagValues#TAG_GENERATE_OPERATOR_FOR_DAO_HELPER
+ * @since 2.5
+ */
+ public static String getGenerateOperatorForDAOHelperTagValue(ObjectModel model) {
+ String value = findTagValue(TopiaTagValues.TAG_GENERATE_OPERATOR_FOR_DAO_HELPER, null, model);
+ return value;
+ }
+
+ /**
+ * Obtain the value of the {@link TopiaTagValues#TAG_TYPE}
+ * tag value on the given attribute.
+ *
+ * @param attribute attribute to seek
+ * @return the none empty value of the found tag value or {@code null} if not found nor empty.
+ * @see TopiaTagValues#TAG_TYPE
+ * @since 2.5
+ */
+ public static String getTypeTagValue(ObjectModelAttribute attribute) {
+ String value = findTagValue(TopiaTagValues.TAG_TYPE, attribute, null);
+ return value;
+ }
+
+ /**
+ * Obtain the value of the {@link TopiaTagValues#TAG_SQL_TYPE}
+ * tag value on the given attribute.
+ *
+ * @param attribute attribute to seek
+ * @return the none empty value of the found tag value or {@code null} if not found nor empty.
+ * @see TopiaTagValues#TAG_TYPE
+ * @since 2.5
+ */
+ public static String getSqlTypeTagValue(ObjectModelAttribute attribute) {
+ String value = findTagValue(TopiaTagValues.TAG_SQL_TYPE, attribute, null);
+ return value;
+ }
+
+ /**
+ * Obtains the value of the {@link TopiaTagValues#TAG_DAO_IMPLEMENTATION}
+ * tag value on the given model.
+
+ *
+ * @param model model to seek
+ * @return the none empty value of the found tag value or {@code null} if not found nor empty.
+ * @see TopiaTagValues#TAG_DAO_IMPLEMENTATION
+ * @since 2.5
+ */
+ public static String getDaoImplementationTagValue(ObjectModel model) {
+ String value = findTagValue(TopiaTagValues.TAG_DAO_IMPLEMENTATION, null, model);
+ return value;
+ }
+
+ /**
+ * Obtains the value of the tag value
+ * {@link TopiaTagValues#TAG_INDEX_FOREIGN_KEYS} on the model or on the
+ * given attribute.
+ *
+ * @param attribute attribute to test
+ * @param model model to test
+ * @return none empty value of the found tag value or {@code null} if not found nor empty.
+ * @see TopiaTagValues#TAG_INDEX_FOREIGN_KEYS
+ * @since 2.6.5
+ */
+ public static String getIndexForeignKeys(ObjectModelAttribute attribute, ObjectModel model) {
+ String value = findTagValue(TopiaTagValues.TAG_INDEX_FOREIGN_KEYS, attribute, model);
+ return value;
+ }
+
+ public static boolean hasUseEnumerationNameTagValue(ObjectModelAttribute attr, ObjectModel model) {
+ String value = findTagValue(TopiaTagValues.TAG_USE_ENUMERATION_NAME, attr, model);
+ return Boolean.parseBoolean(value);
+ }
+
+ /**
+ * Search if the TagValue {@link TopiaTagValues#TAG_GENERATE_TOPIA_ID_IN_DTO} has been
+ * activated in the model.
+ *
+ * @param classifier classifier to seek
+ * @param model model to seek
+ * @return the none empty value of the found tag value or {@code null} if not found nor empty.
+ * @see TopiaTagValues#TAG_GENERATE_TOPIA_ID_IN_DTO
+ * @since 2.6.7
+ */
+ public static boolean shouldGenerateDTOTopiaIdTagValue(ObjectModelClassifier classifier, ObjectModel model) {
+ String tagValue = findTagValue(TopiaTagValues.TAG_GENERATE_TOPIA_ID_IN_DTO, classifier, model);
+ boolean generate = StringUtils.isNotEmpty(tagValue) && Boolean.valueOf(tagValue);
+ return generate;
+ }
+
+} // TopiaGeneratorUtil
+
Copied: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaJavaValidator.java (from rev 2882, trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaJavaValidator.java)
===================================================================
--- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaJavaValidator.java (rev 0)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaJavaValidator.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,132 @@
+package org.nuiton.topia.templates;
+
+import org.apache.commons.lang3.StringUtils;
+import org.nuiton.eugene.models.object.ObjectModel;
+import org.nuiton.eugene.models.object.ObjectModelAttribute;
+import org.nuiton.eugene.models.object.ObjectModelClass;
+import org.nuiton.eugene.models.object.ObjectModelOperation;
+import org.nuiton.eugene.models.object.validator.ObjectModelValidator;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * Validateur qui valide :
+ * - les types des attributs
+ * - les nom des attributs
+ * - les duplication d'attibuts
+ *
+ * @author chatellier <chatellier(a)codelutin.com>
+ * @version $Id$
+ */
+public class TopiaJavaValidator extends ObjectModelValidator {
+
+ /**
+ * Constructor.
+ *
+ * @param model model to validate
+ */
+ public TopiaJavaValidator(ObjectModel model) {
+ super(model);
+ }
+
+ @Override
+ protected boolean validateAttribute(ObjectModelAttribute attr) {
+
+ boolean isValid = super.validateAttribute(attr);
+
+ // type null ou vide
+ if (attr.getType() == null || attr.getType().isEmpty()) {
+ isValid = false;
+
+ addError(attr, "Invalid type \"" + attr.getType() + "\"");
+ }
+
+ // name = java reserved keywords
+ if (!isJavaIdentifier(attr.getName())) {
+ isValid = false;
+
+ addError(attr, "Attribute name " + attr.getName()
+ + " is not valid java identifier");
+ }
+
+ // test sur les mots réservés ?
+
+ return isValid;
+
+ }
+
+ @Override
+ protected boolean validateClass(ObjectModelClass clazz) {
+
+ boolean isValid = super.validateClass(clazz);
+
+ // test attribute names duplication
+ Set<String> attributesName = new HashSet<String>();
+ for (ObjectModelAttribute attr : clazz.getAttributes()) {
+ if (!attr.isNavigable()) {
+
+ // not navigable, so will not use it...
+ continue;
+ }
+ String attrName = attr.getName();
+ if (!attributesName.add(attrName)) {
+ addError(attr, "Attribute name " + attrName
+ + " already exists");
+
+ isValid = false;
+ }
+ }
+
+ if (TopiaGeneratorUtil.isEntity(clazz)) {
+
+ Set<String> methodsName = new HashSet<String>();
+ for (ObjectModelAttribute attr : clazz.getAttributes()) {
+
+ String capitalizeAttrName = StringUtils.capitalize(attr.getName());
+ methodsName.add(TopiaGeneratorUtil.OPERATION_GETTER_BOOLEAN_PREFIX + capitalizeAttrName);
+ methodsName.add(TopiaGeneratorUtil.OPERATION_GETTER_DEFAULT_PREFIX + capitalizeAttrName);
+ methodsName.add("set" + capitalizeAttrName);
+ }
+
+ // test if there is a method an already reserved name
+ for (ObjectModelOperation operation : clazz.getOperations()) {
+ String operationName = operation.getName();
+ if (methodsName.contains(operationName)) {
+ addError(operation, "Operation name " + operationName
+ + " is already reserved for a getter/setter of an entity attribute");
+
+ isValid = false;
+ }
+ }
+ }
+
+ return isValid;
+ }
+
+ @Override
+ protected boolean validateModel(ObjectModel model) {
+
+ return super.validateModel(model);
+ }
+
+ /**
+ * Returns true if s is a legal Java identifier.
+ *
+ * @param s string to test
+ * @return true if s is a legal Java identifier
+ */
+ public static boolean isJavaIdentifier(String s) {
+ if (s.length() == 0 || !Character.isJavaIdentifierStart(s.charAt(0))) {
+ return false;
+ }
+ for (int i = 1; i < s.length(); i++) {
+ if (!Character.isJavaIdentifierPart(s.charAt(i))) {
+ return false;
+ }
+ }
+ return true;
+ }
+}
Copied: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaMetaTransformer.java (from rev 2882, trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaMetaTransformer.java)
===================================================================
--- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaMetaTransformer.java (rev 0)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaMetaTransformer.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,107 @@
+package org.nuiton.topia.templates;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.nuiton.eugene.AbstractMetaTransformer;
+import org.nuiton.eugene.models.object.ObjectModel;
+import org.nuiton.eugene.models.object.ObjectModelClass;
+import org.nuiton.eugene.models.object.validator.AttributeNamesValidator;
+import org.nuiton.eugene.models.object.validator.ClassNamesValidator;
+import org.nuiton.eugene.models.object.validator.ObjectModelValidator;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Created: 20 déc. 2009
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @version $Id$
+ * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.templates.TopiaMetaTransformer"
+ * @since 2.3.0
+ */
+public class TopiaMetaTransformer extends AbstractMetaTransformer<ObjectModel> {
+
+ /** Logger */
+ private static final Log log = LogFactory.getLog(TopiaMetaTransformer.class);
+
+ public TopiaMetaTransformer() {
+// super(
+// EntityTransformer.class,
+// DAOTransformer.class,
+// DAOImplTransformer.class,
+// DAOAbstractTransformer.class,
+// DAOHelperTransformer.class,
+// EntityHibernateMappingGenerator.class
+// );
+
+ setTemplateTypes(
+ ApplicationContextTransformer.class,
+ PersistenceContextTransformer.class,
+ EntityTransformer.class,
+ EntityDaoTransformer.class,
+// DAOTransformer.class,
+// DAOImplTransformer.class,
+// DAOAbstractTransformer.class,
+ DAOHelperTransformer.class,
+ EntityHibernateMappingGenerator.class
+ );
+ }
+
+ protected boolean validateModel(ObjectModel model) {
+ List<ObjectModelValidator> validators = new ArrayList<ObjectModelValidator>();
+
+ AttributeNamesValidator attrValidator = new AttributeNamesValidator(
+ model);
+ attrValidator.addNameAndReason("analyze",
+ "Le nom d'attribut \"analyze\" est incompatible avec certains SGBD");
+ attrValidator.addNameAndReason("next",
+ "Le nom d'attribut \"next\" est incompatible avec HSQL");
+ attrValidator.addNameAndReason("value",
+ "Le nom d'attribut \"value\" est incompatible avec certains SGBD");
+ attrValidator.addNameAndReason("values",
+ "Le nom d'attribut \"values\" est incompatible avec certains SGBD");
+ attrValidator.addNameAndReason("begin",
+ "Le nom d'attribut \"begin\" est incompatible avec certains SGBD");
+ attrValidator.addNameAndReason("end",
+ "Le nom d'attribut \"end\" est incompatible avec certains SGBD");
+ attrValidator.addNameAndReason("authorization",
+ "Le nom d'attribut \"authorization\" est incompatible avec certains SGBD");
+ attrValidator.addNameAndReason("order",
+ "Le nom d'attribut \"order\" est incompatible avec certains SGBD");
+ validators.add(attrValidator);
+
+ ClassNamesValidator classValidator = new ClassNamesValidator(model);
+ classValidator.addNameAndReason("constraint", "Nom de classe incompatible avec certains SGBD");
+ classValidator.addNameAndReason("user", "Nom de classe incompatible avec certains SGBD");
+ validators.add(classValidator);
+
+ validators.add(new TopiaJavaValidator(model));
+ validators.add(new TopiaRelationValidator(model));
+
+ for (ObjectModelValidator validator : validators) {
+ if (!validator.validate()) {
+ for (String error : validator.getErrors()) {
+ if (log.isWarnEnabled()) {
+ log.warn("[VALIDATION] " + error);
+ }
+ }
+ }
+ }
+
+ // test before all if there is some entities to generate
+ List<ObjectModelClass> classes = TopiaGeneratorUtil.getEntityClasses(model, true);
+
+ if (classes.isEmpty()) {
+ // no entity to generate, can stop safely
+ if (log.isWarnEnabled()) {
+ log.warn("No entity to generate, " + getClass().getName() +
+ " is skipped");
+ }
+ return false;
+ }
+ //FIXME-TC20091220 seems we still generate if there is some validation errors ? not very normal
+ return true;
+ }
+
+}
Copied: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaRelationValidator.java (from rev 2882, trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaRelationValidator.java)
===================================================================
--- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaRelationValidator.java (rev 0)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaRelationValidator.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,95 @@
+/* *
+* TopiaRelationValidator.java
+*
+* Created: 31 mars 2006
+*
+* @author Arnaud Thimel <thimel(a)codelutin.com>
+* @version $Revision$
+*
+* Mise a jour: $Date$
+* par : $Author$
+*/
+
+package org.nuiton.topia.templates;
+
+import org.nuiton.eugene.models.object.ObjectModel;
+import org.nuiton.eugene.models.object.ObjectModelAttribute;
+import org.nuiton.eugene.models.object.validator.ObjectModelValidator;
+
+/**
+ * Validateur pour les relations du modèle.
+ * Vérifie que :
+ * <ul>
+ * <li>Toutes les relations ont au moins une navigabilité</li>
+ * <li>Une relation 1-n unidirectionnelle pointant sur une classe ayant des
+ * sous-classes dans le modèle est incompatibe avec Hibernate</li>
+ * <li>Toutes les relations ont des reverseAttribute</li>
+ * </ul>
+ *
+ * @version $Id$
+ */
+public class TopiaRelationValidator extends ObjectModelValidator {
+
+ /**
+ * Constructeur de TopiaRelationValidator.
+ *
+ * @param model le modèle à valider
+ */
+ public TopiaRelationValidator(ObjectModel model) {
+ super(model);
+ }
+
+ /* (non-Javadoc)
+ * @see org.nuiton.eugene.models.object.validator.ObjectModelValidator#validateAttribute(org.nuiton.eugene.models.object.ObjectModelAttribute)
+ */
+ @Override
+ protected boolean validateAttribute(ObjectModelAttribute attr) {
+ boolean isValid = true;
+ ObjectModelAttribute reverse = attr.getReverseAttribute();
+
+ /* Relation navigabilité */
+ //Pour ne pas avoir de doublons, on ne vérifie que sur le premier
+ //attribut par ordre alphabétique
+ if (TopiaGeneratorUtil.isFirstAttribute(attr)) {
+ if (!attr.isNavigable() && !reverse.isNavigable()) {
+ addError(attr, "La relation entre " + "\"" + reverse.getType()
+ + "\"[" + attr.getName() + "] et " + "\""
+ + attr.getType() + "\"[" + reverse.getName() + "] "
+ + "n'est navigable dans aucun sens");
+ isValid = false;
+ }
+ }
+
+ /* Relation héritage */
+ if (TopiaGeneratorUtil.hasUnidirectionalRelationOnAbstractType(attr, model)) {
+ isValid = false;
+ addError(
+ attr,
+ "La relation entre "
+ + "\""
+ + reverse.getType()
+ + "\"["
+ + attr.getName()
+ + "] et "
+ + "\""
+ + attr.getType()
+ + "\"["
+ + reverse.getName()
+ + "] "
+ + "n'est navigable que dans un sens et "
+ + "la classe \""
+ + attr.getType()
+ + "\" a des sous-classes. "
+ + "Des accesseurs doivent donc etre generes pour Hibernate.");
+ }
+
+ /* Pas d'inverse */
+ if (reverse == null && model.hasClass(attr.getType())) {
+ isValid = false;
+ addError(attr, "Cet attribut n'a pas d'inverse.");
+ }
+
+ return isValid;
+ }
+
+} //TopiaRelationValidator
Copied: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaStereoTypes.java (from rev 2882, trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaStereoTypes.java)
===================================================================
--- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaStereoTypes.java (rev 0)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaStereoTypes.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,64 @@
+package org.nuiton.topia.templates;
+
+import org.nuiton.eugene.EugeneStereoTypes;
+import org.nuiton.eugene.models.object.ObjectModelAttribute;
+import org.nuiton.eugene.models.object.ObjectModelClassifier;
+import org.nuiton.eugene.models.object.ObjectModelOperation;
+
+import static org.nuiton.eugene.ModelPropertiesUtil.StereotypeDefinition;
+
+/**
+ * All extra stereotypes usable in topia generators.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.5
+ */
+public interface TopiaStereoTypes extends EugeneStereoTypes {
+
+ /**
+ * Stéréotype pour les objets devant être générées sous forme d'entités
+ *
+ * @see TopiaGeneratorUtil#isEntity(ObjectModelClassifier)
+ * @see TopiaGeneratorUtil#hasEntityStereotype(ObjectModelAttribute)
+ */
+ @StereotypeDefinition(target = {ObjectModelClassifier.class, ObjectModelAttribute.class},
+ documentation = "To specify that a class is an Entity")
+ String STEREOTYPE_ENTITY = "entity";
+
+ /**
+ * Stéréotype pour les objets devant être générées sous forme de DTO.
+ *
+ * @see TopiaGeneratorUtil#hasDtoStereotype(ObjectModelClassifier)
+ */
+ @StereotypeDefinition(target = ObjectModelClassifier.class,
+ documentation = "to specify that a class is a DTO")
+ String STEREOTYPE_DTO = "dto";
+
+ /**
+ * Stéréotype pour les interfaces devant être générées sous forme de DAO.
+ *
+ * @see TopiaGeneratorUtil#hasDaoStereotype(ObjectModelClassifier)
+ * @see TopiaGeneratorUtil#hasDaoStereotype(ObjectModelOperation)
+ */
+ @StereotypeDefinition(target = {ObjectModelClassifier.class, ObjectModelOperation.class},
+ documentation = "To Specify that a classifier or an operation should be generated as (or in) a DAO")
+ String STEREOTYPE_DAO = "dao";
+
+ /**
+ * Stéréotype pour les collections avec unicité.
+ *
+ * @see TopiaGeneratorUtil#hasUniqueStereotype(ObjectModelAttribute)
+ */
+ @StereotypeDefinition(target = ObjectModelAttribute.class,
+ documentation = "To specify that an attribute is unique (Hibernate mapping)")
+ String STEREOTYPE_UNIQUE = "unique";
+
+ /**
+ * Stéréotype pour les attributs étant des clés primaires.
+ *
+ * @see TopiaGeneratorUtil#hasPrimaryKeyStereotype(ObjectModelAttribute)
+ */
+ @StereotypeDefinition(target = ObjectModelAttribute.class,
+ documentation = "To specify that an attribute is part of a primary key (Hibernate mapping)")
+ String STEREOTYPE_PRIMARYKAY = "primaryKey";
+}
Copied: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaTagValues.java (from rev 2882, trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaTagValues.java)
===================================================================
--- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaTagValues.java (rev 0)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaTagValues.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,355 @@
+package org.nuiton.topia.templates;
+
+import org.nuiton.eugene.EugeneTagValues;
+import org.nuiton.eugene.models.object.ObjectModel;
+import org.nuiton.eugene.models.object.ObjectModelAttribute;
+import org.nuiton.eugene.models.object.ObjectModelClass;
+import org.nuiton.eugene.models.object.ObjectModelClassifier;
+import org.nuiton.eugene.models.object.ObjectModelElement;
+import org.nuiton.topia.TopiaContext;
+import org.nuiton.topia.persistence.TopiaEntityContextable;
+import org.nuiton.topia.persistence.TopiaEntityEnum;
+
+import static org.nuiton.eugene.ModelPropertiesUtil.TagValueDefinition;
+
+/**
+ * All extra tag values usable in topia generators.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.5
+ */
+public interface TopiaTagValues extends EugeneTagValues {
+
+ /**
+ * Tag pour le type de persistence.
+ *
+ * @see TopiaGeneratorUtil#getPersistenceType(ObjectModelClassifier)
+ * @see TopiaGeneratorUtil#getPersistenceTypeTagValue(ObjectModelClassifier)
+ * @since 2.5
+ */
+ @TagValueDefinition(target = {ObjectModelClassifier.class},
+ documentation = "")
+ String TAG_PERSISTENCE_TYPE = "persistenceType";
+
+ /**
+ * Tag pour que les entités etendent {@link TopiaEntityContextable} et
+ * se fasse injecter le {@link TopiaContext} par rapport aux autres
+ * entités qui ne l'ont pas.
+ *
+ * @since 2.5.3
+ */
+ @TagValueDefinition(target = {ObjectModelClassifier.class}, documentation = "")
+ String TAG_CONTEXTABLE = "contextable";
+
+ /**
+ * Tag pour le nom du champ / entité en BD.
+ *
+ * @see TopiaGeneratorUtil#getDbNameTagValue(ObjectModelElement)
+ * @see TopiaGeneratorUtil#getDbName(ObjectModelElement)
+ * @see TopiaGeneratorUtil#getReverseDbName(ObjectModelAttribute)
+ */
+ @TagValueDefinition(target = {ObjectModelElement.class},
+ documentation = "Sets the database name of an element of the model (a table or a column)")
+ String TAG_DB_NAME = "dbName";
+
+ /**
+ * Tag pour le nom du schema en BD.
+ *
+ * @see TopiaGeneratorUtil#getDbSchemaNameTagValue(ObjectModelClassifier, ObjectModel)
+ * @see TopiaGeneratorUtil#getDbSchemaNameTagValue(ObjectModelAttribute, ObjectModel)
+ * @since 2.5
+ */
+ @TagValueDefinition(target = {ObjectModel.class, ObjectModelClassifier.class, ObjectModelAttribute.class},
+ documentation = "Sets the database schema name")
+ String TAG_SCHEMA_NAME = "dbSchema";
+
+ /**
+ * Tag pour la taille du champ en BD.
+ *
+ * @see TopiaGeneratorUtil#getLengthTagValue(ObjectModelAttribute)
+ * @since 2.5
+ */
+ @TagValueDefinition(target = {ObjectModelAttribute.class},
+ documentation = "Sets the length of an attribute in database")
+ String TAG_LENGTH = "length";
+
+ /**
+ * Tag pour ajouter une annotation à un champ.
+ *
+ * @see TopiaGeneratorUtil#getAnnotationTagValue(ObjectModelAttribute)
+ * @since 2.5
+ */
+ @TagValueDefinition(target = {ObjectModelAttribute.class},
+ documentation = "Sets an annotation of an attribute")
+ String TAG_ANNOTATION = "annotation";
+
+ /**
+ * Tag pour specfier le type d'acces a un champ.
+ *
+ * @see TopiaGeneratorUtil#getAccessTagValue(ObjectModelAttribute)
+ * @since 2.5
+ */
+ @TagValueDefinition(target = {ObjectModelAttribute.class},
+ documentation = "Sets the access type of an attribute (Hibernate mapping)")
+ String TAG_ACCESS = "access";
+
+ /**
+ * Tag pour ajouter un attribut dans une clef métier.
+ *
+ * @see TopiaGeneratorUtil#getNaturalIdTagValue(ObjectModelAttribute)
+ * @see TopiaGeneratorUtil#isNaturalId(ObjectModelAttribute)
+ * @since 2.5
+ */
+ @TagValueDefinition(target = {ObjectModelAttribute.class},
+ documentation = "Sets an attribute as part of a natural id (Hibernate Mapping)")
+ String TAG_NATURAL_ID = "naturalId";
+
+ /**
+ * Tag pour specifier si une clef metier est mutable.
+ *
+ * @see TopiaGeneratorUtil#getNaturalIdMutableTagValue(ObjectModelClassifier)
+ * @see TopiaGeneratorUtil#isNaturalIdMutable(ObjectModelClass)
+ * @since 2.5
+ */
+ @TagValueDefinition(target = {ObjectModelClassifier.class},
+ documentation = "Sets if natural id of a entity is mutable (hibernate mapping)")
+ String TAG_NATURAL_ID_MUTABLE = "naturalIdMutable";
+
+ /**
+ * Tag pour permettre de choisir qui contrôle la relation N-N
+ * bidirectionnelle. A utiliser sur les deux extremités de l'association.
+ * Mettre inverse=false sur le rôle fils et inverse=true sur le rôle père.
+ * Par défaut le inverse=true est placé sur le premier rôle trouvé dans
+ * l'ordre alphabétique.
+ *
+ * @see TopiaGeneratorUtil#getInverseTagValue(ObjectModelAttribute)
+ * @since 2.5
+ */
+ @TagValueDefinition(target = {ObjectModelAttribute.class},
+ documentation = "Sets which part of a N-N relation is master (inverse=true) and slave (inverse=false) (must be put on each side on a such relation) (Hibernate mapping)")
+ String TAG_INVERSE = "inverse";
+
+ /**
+ * Tag pour spécifier la caractère lazy d'une association multiple.
+ *
+ * @see TopiaGeneratorUtil#getLazyTagValue(ObjectModelAttribute)
+ * @since 2.5
+ */
+ @TagValueDefinition(target = {ObjectModelAttribute.class},
+ documentation = "Sets if an association should be lazy (Hibernate mapping)")
+ String TAG_LAZY = "lazy";
+
+ /**
+ * Tag pour spécifier la caractère fetch d'une association multiple.
+ *
+ * @see TopiaGeneratorUtil#getFetchTagValue(ObjectModelAttribute)
+ * @since 2.5
+ */
+ @TagValueDefinition(target = {ObjectModelAttribute.class},
+ documentation = "Sets the fetch caracteristic of an attribute (Hibernate mapping)")
+ String TAG_FETCH = "fetch";
+
+ /**
+ * Tag pour spécifier la caractère order-by d'une association multiple.
+ *
+ * @see TopiaGeneratorUtil#getOrderByTagValue(ObjectModelAttribute)
+ * @since 2.5
+ */
+ @TagValueDefinition(target = {ObjectModelAttribute.class},
+ documentation = "Sets the order by propertie of an multiple association (Hibernate mapping)")
+ String TAG_ORDER_BY = "orderBy";
+
+ /**
+ * Tag pour spécifier la caractère not-null d'un attribut.
+ *
+ * @see TopiaGeneratorUtil#getNotNullTagValue(ObjectModelAttribute)
+ * @since 2.5
+ */
+ @TagValueDefinition(target = {ObjectModelAttribute.class},
+ documentation = "Sets if an attribute must be not null (Hibernate mapping)")
+ String TAG_NOT_NULL = "notNull";
+
+ /**
+ * Tag à placer sur un l'attribut d'une entité. Cet attribut est de type
+ * énumération : l'ajout de la tagValue indique qu'il faut utiliser le
+ * {@code name} de l'énumération et non l'ordinal pour stocker la valeur en
+ * base
+ */
+ @TagValueDefinition(target = {ObjectModelAttribute.class},
+ documentation = "'true' if the value of this attribute of type Enumeration should be stored with its name (instead of using ordinal)")
+ String TAG_USE_ENUMERATION_NAME = "useEnumerationName";
+
+ /**
+ * Tag pour configurer l'interface du proxy sur autre chose que l'implementation par defaut.
+ * <p/>
+ * Par defaut :
+ * null > generere le proxy sur l'interface de l'implementation
+ * Autre valeur :
+ * "none" > laisse la configuration par defaut d'hibernate
+ *
+ * @see TopiaGeneratorUtil#getPersistenceTypeTagValue(ObjectModelClassifier)
+ * @since 2.5
+ */
+ @TagValueDefinition(target = {ObjectModel.class, ObjectModelClassifier.class},
+ documentation = "Configure the proxy interface on something else than the default implementation (null to use our default implementation, none to let hibernate deal it) (Hibernate mapping)")
+ String TAG_PROXY_INTERFACE = "hibernateProxyInterface";
+
+ /**
+ * Tag pour configurer la stategie d'heritage choisie.
+ * <p/>
+ * Par defaut : union-subclass : Table per class strategy
+ * Autre valeur :
+ * "subclass" > Single table per class hierarchy strategy
+ * "joined-subclass" > Joined subclass strategy
+ *
+ * @see TopiaGeneratorUtil#getPersistenceTypeTagValue(ObjectModelClassifier)
+ * @since 3.0
+ */
+ @TagValueDefinition(target = {ObjectModel.class, ObjectModelClassifier.class},
+ documentation = "Configure the proxy interface on something else than the default implementation (null to use our default implementation, none to let hibernate deal it) (Hibernate mapping)")
+ String TAG_INHERITANCE_STRATEGY = "inheritanceStrategy";
+
+ /**
+ * Tag pour spécifier le permissions à la création.
+ *
+ * @see TopiaGeneratorUtil#getSecurityCreateTagValue(ObjectModelClassifier)
+ * @since 2.5
+ */
+ @TagValueDefinition(target = {ObjectModelClassifier.class},
+ documentation = "Sets the create permission on an entity")
+ String TAG_SECURITY_CREATE = "securityCreate";
+
+ /**
+ * Tag pour spécifier le permissions au chargement.
+ *
+ * @see TopiaGeneratorUtil#getSecurityLoadTagValue(ObjectModelClassifier)
+ * @since 2.5
+ */
+ @TagValueDefinition(target = {ObjectModelClassifier.class},
+ documentation = "Sets the load permission on an entity")
+ String TAG_SECURITY_LOAD = "securityLoad";
+
+ /**
+ * Tag pour spécifier le permissions à la mise à jour.
+ *
+ * @see TopiaGeneratorUtil#getSecurityUpdateTagValue(ObjectModelClassifier)
+ * @since 2.5
+ */
+ @TagValueDefinition(target = {ObjectModelClassifier.class},
+ documentation = "Sets the update permission on an entity")
+ String TAG_SECURITY_UPDATE = "securityUpdate";
+
+ /**
+ * Tag pour spécifier le permissions à la suppression.
+ *
+ * @see TopiaGeneratorUtil#getSecurityDeleteTagValue(ObjectModelClassifier)
+ * @since 2.5
+ */
+ @TagValueDefinition(target = {ObjectModelClassifier.class},
+ documentation = "sets the delete permission on an entity")
+ String TAG_SECURITY_DELETE = "securityDelete";
+
+ /**
+ * Tag pour specifier de ne pas generer la methode toString.
+ *
+ * @see TopiaGeneratorUtil#getNotGenerateToStringTagValue(ObjectModelClassifier, ObjectModel)
+ * @see TopiaGeneratorUtil#generateToString(ObjectModelClass, ObjectModel)
+ * @since 2.5
+ */
+ @TagValueDefinition(target = {ObjectModel.class, ObjectModelClassifier.class},
+ documentation = "To not generate the toString method on entities")
+ String TAG_NOT_GENERATE_TO_STRING = "notGenerateToString";
+
+ /**
+ * Tag pour specifier de trier les attributs par nom lors de la generation.
+ *
+ * @see TopiaGeneratorUtil#getSortAttributeTagValue(ObjectModelClassifier, ObjectModel)
+ * @see TopiaGeneratorUtil#sortAttribute(ObjectModelClass, ObjectModel)
+ * @since 2.5
+ */
+ @TagValueDefinition(target = {ObjectModel.class, ObjectModelClassifier.class},
+ documentation = "To sort attribute while generation")
+ String TAG_SORT_ATTRIBUTE = "sortAttribute";
+
+ /**
+ * Tag pour specfier si on doit générer la methode getOperator dans les daohelpers.
+ *
+ * @see TopiaGeneratorUtil#getGenerateOperatorForDAOHelperTagValue(ObjectModel)
+ * @see TopiaGeneratorUtil#shouldGenerateOperatorForDAOHelper(ObjectModel)
+ * @since 2.5
+ */
+ @TagValueDefinition(target = {ObjectModel.class},
+ documentation = "To generate EntityOperation on generated DAOHelper")
+ String TAG_GENERATE_OPERATOR_FOR_DAO_HELPER = "generateOperatorForDAOHelper";
+
+ /**
+ * Tag pour spécifier si on doit générer le {@link TopiaEntityEnum} en tant qu'inner classe
+ * du dao helper ou pas.
+ * <p/>
+ * <b>Note:</b> Par défaut, on génère en tant qu'inner classe.
+ *
+ * @see TopiaGeneratorUtil#getGenerateStandaloneEnumForDAOHelperTagValue(ObjectModel)
+ * @see TopiaGeneratorUtil#shouldGenerateStandaloneEnumForDAOHelper(ObjectModel)
+ * @since 2.5
+ */
+ @TagValueDefinition(target = {ObjectModel.class},
+ documentation = "To generate a standalon EntityEnum outside the DAOHelper")
+ String TAG_GENERATE_STANDALONE_ENUM_FOR_DAO_HELPER = "generateStandaloneEnumForDAOHelper";
+
+ /**
+ * Tag pour spécifier le type d'une propriété dans le mapping hibernate.
+ *
+ * @see TopiaGeneratorUtil#getTypeTagValue(ObjectModelAttribute)
+ * @since 2.5
+ */
+ @TagValueDefinition(target = {ObjectModelAttribute.class},
+ documentation = "Sets the hibernate type of an attribute (Hibernate mapping)")
+ String TAG_TYPE = "type";
+
+ /**
+ * Tag pour spécifier le type sql d'une propriété dans le mapping hibernate.
+ *
+ * @see TopiaGeneratorUtil#getSqlTypeTagValue(ObjectModelAttribute)
+ * @since 2.5
+ */
+ @TagValueDefinition(target = {ObjectModelAttribute.class},
+ documentation = "Sets the sql type of an attribute (Hibernate mapping)")
+ String TAG_SQL_TYPE = "sqlType";
+
+ /**
+ * To specify the abstract dao to use.
+ * <p/>
+ * If none given, will use the {@code org.nuiton.topia.persistence.TopiaDAOImpl}.
+ * <p/>
+ * Other value possible is {@code org.nuiton.topia.persistence.TopiaDAOLegacy}
+ *
+ * @see TopiaGeneratorUtil#getDaoImplementationTagValue(ObjectModel)
+ * @since 2.5
+ */
+ @TagValueDefinition(target = {ObjectModel.class},
+ documentation = "Sets the fully qualified name of the DAO implementation to use in generated DAO (default is DAOImpl (base on TopiaQuery))")
+ String TAG_DAO_IMPLEMENTATION = "daoImplementation";
+
+ /**
+ * Stéréotype pour les attributs avec multiplicité nécessitant la création d'un index.
+ *
+ * @see TopiaGeneratorUtil#getIndexForeignKeys(ObjectModelAttribute, ObjectModel)
+ * @since 2.6.5
+ */
+ @TagValueDefinition(target = {ObjectModel.class, ObjectModelAttribute.class},
+ documentation = "Specifies if an nm-multiplicity attribute (or all nm-multiplicity attributes of a given model) needs an index in db (Hibernate mapping)")
+ String TAG_INDEX_FOREIGN_KEYS = "indexForeignKeys";
+
+ /**
+ * Tag to specify if we want to add an "id" property in DTO generated by
+ * {@link EntityDTOTransformer}.
+ * <p/>
+ *
+ * @see EntityDTOTransformer
+ * @see TopiaGeneratorUtil#shouldGenerateDTOTopiaIdTagValue(ObjectModelClassifier, ObjectModel)
+ * @since 2.6.7
+ */
+ @TagValueDefinition(target = {ObjectModel.class, ObjectModelClassifier.class},
+ documentation = "Add a \"id\" property with its getter/setter on a DTO.")
+ String TAG_GENERATE_TOPIA_ID_IN_DTO = "generateDTOTopiaId";
+}
Copied: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/package-info.java (from rev 2882, trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/package-info.java)
===================================================================
--- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/package-info.java (rev 0)
+++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/package-info.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,118 @@
+/*
+ * #%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%
+ */
+/**
+ * TODO-FD20100507 : Need update this javadoc for ToPIA 2.4
+ *
+ * <h1>Les Générateurs</h1>
+ *
+ * <h2>TopiaMetaGenerator</h2>
+ *
+ * <p>TopiaMetaGenerator permet d'enchainer les différents
+ * générateurs.</p>
+ *
+ * <h2>Les DAO</h2>
+ *
+ * <p>Il il y a trois générateurs pour les DAO</p>
+ *
+ * <ul>
+ * <li>DAOHelperGenerator</li>
+ *
+ * <li>DAOAbstractGenerator</li>
+ *
+ * <li>DAOGenerator</li>
+ * </ul>
+ *
+ * <p><b><i>DAOHelperGenerator</i></b> permet de récupérer les DAOs
+ * générés spécifiquement pour l'application sans avoir besoin de passer
+ * le type de l'entité en paramètre. Cette classe contient donc une
+ * methode get par type d'entity qui permet de récupérer le DAO associé.
+ * Ces méthodes sont des méthodes statiques et prennent en paramètre un
+ * TopiaContext.</p>
+ *
+ * <p><b><i>DAOAbstractGenerator</i></b> est une classe abstraite même si
+ * elle peut implanter toutes les méthodes de l'interface TopiaDAO. De
+ * cette façon on oblige l'existance d'une classe concrète qui en hérite
+ * soit développé par le développeur soit généré par DAOGenerator.
+ * DAOAbstractGenerator contient toutes les méthodes findBy, findAllBy,
+ * ... associées aux attributs existants. La classe généré hérite
+ * directement ou indirectement de TopiaDAODelegator.</p>
+ *
+ * <p><b><i>DAOGenerator</i></b> génère une classe vide qui permet au
+ * programme de compiler, si le développeur à besoin de méthode find
+ * supplémentaire sur son DAO, il lui suffit de d'implanter cette classe
+ * dans ses sources, le processus de génération écrasera alors la classe
+ * généré par la classe développée spécifiquement.</p>
+ *
+ * <h2>Les entités</h2>
+ *
+ * <p>Les entités sont de pure POJO et ne contiennent pas de référence en
+ * interne sur le TopiaContext ou le DAO qui les à créée, elle peuvent
+ * donc facilement migrer, être utilisé dans différents context, ... le
+ * but etant qu'elle reste des classes complètement déconnecté à
+ * l'exécution du framework.</p>
+ *
+ * <p>La seul contrainte est qu'elles implante TopiaEntity</p>
+ *
+ * <p>Il il y a trois générateurs pour les entités, plus un pour le
+ * mapping hibernate</p>
+ *
+ * <ul>
+ * <li>EntityInterfaceGenerator</li>
+ *
+ * <li>EntityAbstractGenerator</li>
+ *
+ * <li>EntityImplGenerator</li>
+ *
+ * <li>EntityHibernateMappingGenerator</li>
+ * </ul>
+ *
+ * <p><b><i>EntityInterfaceGenerator</i></b> génère l'interface de
+ * l'entité avec les méthodes d'accès aux attributs et les opérations
+ * définis par l'utilisateur dans son diagrammme de classe. Elle implante
+ * TopiaEntity</p>
+ *
+ * <p><b><i>EntityAbstractGenerator</i></b> génère une classe qui
+ * implante l'interface de l'entité et étend TopiaEntityAbstract qui
+ * implante les méthodes du framework, méthode d'accès aux attributs
+ * topiaId, topiaVersion et topiaCreateDate.</p>
+ *
+ * <p><b><i>EntityImplGenerator</i></b> génère une classe vide qui permet
+ * au programme de compiler si l'entité n'a pas d'opération spécifique.
+ * Si elle a des opérations spécifiques le développeur doit implanter
+ * cette classe dans ses sources et y mettre le code pour les opérations
+ * spécifiques, le processus de génération écrasera alors la classe
+ * généré par la classe développée spécifiquement.</p>
+ *
+ * <p><b><i>EntityHibernateMappingGenerator</i></b> génère le fichier de
+ * mapping pour entité. L'interface est déclaré dans le mapping et est
+ * mappé sur une table préfixé par I. Ensuite le Impl est déclaré en
+ * union-subclass de cette interface. On a besoin de l'interface car les
+ * méthodes l'utilise dans les signatures de méthode lorsqu'il y a un
+ * lien entre deux entités.</p>
+ *
+ * @author poussin <poussin(a)codelutin.com>
+ * @version $Id$
+ */
+package org.nuiton.topia.templates;
\ No newline at end of file
Copied: trunk/topia-templates/src/main/resources/META-INF.services/org.nuiton.eugene.ModelPropertiesUtil$ModelPropertiesProvider (from rev 2882, trunk/topia-persistence/src/main/resources/META-INF/services/org.nuiton.eugene.ModelPropertiesUtil$ModelPropertiesProvider)
===================================================================
--- trunk/topia-templates/src/main/resources/META-INF.services/org.nuiton.eugene.ModelPropertiesUtil$ModelPropertiesProvider (rev 0)
+++ trunk/topia-templates/src/main/resources/META-INF.services/org.nuiton.eugene.ModelPropertiesUtil$ModelPropertiesProvider 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1 @@
+org.nuiton.topia.templates.TopiaGeneratorUtil$TopiaModelPropertiesProvider
\ No newline at end of file
Copied: trunk/topia-templates/src/test/java/org/nuiton/topia/templates/TopiaGeneratorUtilTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/TopiaGeneratorUtilTest.java)
===================================================================
--- trunk/topia-templates/src/test/java/org/nuiton/topia/templates/TopiaGeneratorUtilTest.java (rev 0)
+++ trunk/topia-templates/src/test/java/org/nuiton/topia/templates/TopiaGeneratorUtilTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,39 @@
+package org.nuiton.topia.templates;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+/** @author tchemit <chemit(a)codelutin.com> */
+public class TopiaGeneratorUtilTest {
+
+ @Deprecated
+ @Test
+ public void testConvertVariableNameToConstantName() {
+
+ String variableName = "abc";
+ String expResult = "ABC";
+ String result = TopiaGeneratorUtil.convertVariableNameToConstantName(variableName);
+ assertEquals(expResult, result);
+
+ variableName = "ABC";
+ expResult = "ABC";
+ result = TopiaGeneratorUtil.convertVariableNameToConstantName(variableName);
+ assertEquals(expResult, result);
+
+ variableName = "abC";
+ expResult = "AB_C";
+ result = TopiaGeneratorUtil.convertVariableNameToConstantName(variableName);
+ assertEquals(expResult, result);
+
+ variableName = "AbC";
+ expResult = "AB_C";
+ result = TopiaGeneratorUtil.convertVariableNameToConstantName(variableName);
+ assertEquals(expResult, result);
+
+ variableName = "AbC";
+ expResult = "AB_C";
+ result = TopiaGeneratorUtil.convertVariableNameToConstantName(variableName);
+ assertEquals(expResult, result);
+ }
+}
Copied: trunk/topia-templates/src/test/java/org/nuiton/topia/templates/TopiaModelPropertiesProviderTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/TopiaModelPropertiesProviderTest.java)
===================================================================
--- trunk/topia-templates/src/test/java/org/nuiton/topia/templates/TopiaModelPropertiesProviderTest.java (rev 0)
+++ trunk/topia-templates/src/test/java/org/nuiton/topia/templates/TopiaModelPropertiesProviderTest.java 2013-11-22 18:03:47 UTC (rev 2884)
@@ -0,0 +1,56 @@
+package org.nuiton.topia.templates;
+
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.nuiton.eugene.ModelPropertiesUtil;
+import org.nuiton.eugene.models.object.ObjectModelClassifier;
+import org.nuiton.eugene.models.object.ObjectModelOperation;
+
+/**
+ * To test {@link TopiaGeneratorUtil.TopiaModelPropertiesProvider}.
+ *
+ * @author tchemit <chemit(a)codelutin.com>
+ * @since 2.3
+ */
+public class TopiaModelPropertiesProviderTest {
+
+ protected ModelPropertiesUtil.ModelPropertiesProvider provider;
+
+ @Before
+ public void setUp() throws Exception {
+ provider = new TopiaGeneratorUtil.TopiaModelPropertiesProvider();
+ provider.init();
+ }
+
+ @Test
+ public void testGetTagValueTarget() throws Exception {
+ testTagValue(TopiaTagValues.TAG_PERSISTENCE_TYPE, ObjectModelClassifier.class);
+ //TODO Finish with other tag values...
+ }
+
+ @Test
+ public void testGetStereotypeTarget() throws Exception {
+
+ testStereotype(TopiaStereoTypes.STEREOTYPE_DAO, ObjectModelClassifier.class, ObjectModelOperation.class);
+ //TODO Finish with other stereotypes...
+ }
+
+ @Test
+ public void testGetStore() throws Exception {
+ }
+
+ protected void testStereotype(String name, Class<?>... expected) {
+ Class<?>[] classes = provider.getStereotypeTarget(name);
+ Assert.assertNotNull("Could not find target for " + name, classes);
+ Assert.assertEquals("Should have " + expected.length + " targets for " + name + " but had " + classes.length, classes.length, expected.length);
+ Assert.assertArrayEquals(expected, classes);
+ }
+
+ protected void testTagValue(String name, Class<?>... expected) {
+ Class<?>[] classes = provider.getTagValueTarget(name);
+ Assert.assertNotNull("Could not find target for " + name, classes);
+ Assert.assertEquals("Should have " + expected.length + " targets for " + name + " but had " + classes.length, classes.length, expected.length);
+ Assert.assertArrayEquals(expected, classes);
+ }
+}
1
0
r2883 - trunk/topia-persistence/src/main/java/org/nuiton/topia
by athimel@users.nuiton.org Nov. 22, 2013
by athimel@users.nuiton.org Nov. 22, 2013
Nov. 22, 2013
Author: athimel
Date: 2013-11-22 18:48:55 +0100 (Fri, 22 Nov 2013)
New Revision: 2883
Url: http://nuiton.org/projects/topia/repository/revisions/2883
Log:
fixes #2922 ApplicationContext now keeps a weak reference on child PersistenceContexts
Modified:
trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaApplicationContext.java
Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaApplicationContext.java
===================================================================
--- trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaApplicationContext.java 2013-11-22 16:38:04 UTC (rev 2882)
+++ trunk/topia-persistence/src/main/java/org/nuiton/topia/AbstractTopiaApplicationContext.java 2013-11-22 17:48:55 UTC (rev 2883)
@@ -26,16 +26,12 @@
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
-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.hibernate.HibernateException;
import org.hibernate.cfg.Configuration;
-import org.hibernate.engine.spi.SessionFactoryImplementor;
-import org.hibernate.service.jdbc.connections.spi.ConnectionProvider;
-import org.hibernate.service.spi.Stoppable;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.hbm2ddl.SchemaUpdate;
import org.nuiton.topia.event.TopiaEntitiesVetoable;
@@ -44,7 +40,6 @@
import org.nuiton.topia.event.TopiaSchemaListener;
import org.nuiton.topia.event.TopiaTransactionListener;
import org.nuiton.topia.event.TopiaTransactionVetoable;
-import org.nuiton.topia.framework.TopiaContextImplementor;
import org.nuiton.topia.framework.TopiaFiresSupport;
import org.nuiton.topia.framework.TopiaService;
import org.nuiton.topia.framework.TopiaUtil;
@@ -53,10 +48,12 @@
import org.nuiton.topia.persistence.TopiaIdFactory;
import java.beans.PropertyChangeListener;
-import java.lang.ref.WeakReference;
+import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;
+import java.util.Set;
+import java.util.WeakHashMap;
/**
* The application context is the main class in ToPIA usage. This class is a kind of equivalent of the RootTopiaContext.
@@ -82,7 +79,8 @@
protected boolean closed = false;
- protected List<WeakReference<TopiaPersistenceContext>> persistenceContexts = Lists.newArrayList(); // TODO AThimel 11/10/13 Which implementation ?
+ protected Set<TopiaPersistenceContext> persistenceContexts = Collections.newSetFromMap(
+ new WeakHashMap<TopiaPersistenceContext, Boolean>());
public abstract K newPersistenceContext();
@@ -114,7 +112,7 @@
}
protected void registerPersistenceContext(TopiaPersistenceContext persistenceContext) {
- persistenceContexts.add(new WeakReference<TopiaPersistenceContext>(persistenceContext));
+ persistenceContexts.add(persistenceContext);
}
protected HibernateProvider getHibernateProvider() {
@@ -353,17 +351,23 @@
}
public void closeContext() throws TopiaException {
+
// Throw exception if context is already closed
Preconditions.checkState(!closed, "Context was already closed");
- // TODO AThimel 11/10/13 Implement close on persistence contexts
-// // Remove all children context
-// for (TopiaPersistenceContext child : getChildContext()) {
-// // Avoid to have exception from checkClosed method on child
-// if (!child.isClosed()) {
-// child.close();
-// }
-// }
+ // Iterate over the children PersistenceContexts and close them
+ for (TopiaPersistenceContext persistenceContext : persistenceContexts) {
+ if (persistenceContext == null) {
+ if (log.isWarnEnabled()) {
+ log.warn("null TopiaPersistenceContext found in #persistenceContexts");
+ }
+ } else {
+ // Avoid to have exception from checkClosed method on child
+ if (!persistenceContext.isClosed()) {
+ persistenceContext.closeContext();
+ }
+ }
+ }
hibernateProvider.close();
closed = true;
1
0
The ToPIA team is pleased to announce the topia-3.0-alpha-5 release!
Tools for Portable and Independent Architecture :
Framework de persistance et de distribution d'application.
Documentation of the project can be found here:
http://maven-site.nuiton.org/topia
Changes
-------
Changes in this version include:
New features:
o Create contextualized exceptions Issue: 2896. Thanks to Arnaud Thimel. Resolved by athimel.
o Add addNotEquals, addNotIn, addNotContains in query API Issue: 2910. Thanks to Brendan Le Ny. Resolved by bleny.
o Add an exception on the findFirst and tryFindFirst methods of the query API if query is not ordered (as said in javadoc) Issue: 2915. Thanks to Tony Chemit. Resolved by bleny.
Downloads
---------
No release file deployed. (all files are deployed in the maven repository)
Maven artifacts
---------------
Artifacts are deployed in Maven Central Repository
http://repo1.maven.org/maven2/
Find us at
* http://search.maven.org/#artifactdetails|org.nuiton|topia|3.0-alpha-5|jar
Have fun!
-ToPIA team
1
0
r2882 - in trunk: . topia-persistence topia-service-migration topia-service-replication
by maven-release@users.nuiton.org Nov. 22, 2013
by maven-release@users.nuiton.org Nov. 22, 2013
Nov. 22, 2013
Author: maven-release
Date: 2013-11-22 17:38:04 +0100 (Fri, 22 Nov 2013)
New Revision: 2882
Url: http://nuiton.org/projects/topia/repository/revisions/2882
Log:
[maven-release-plugin] prepare for next development iteration
Modified:
trunk/pom.xml
trunk/topia-persistence/pom.xml
trunk/topia-service-migration/pom.xml
trunk/topia-service-replication/pom.xml
Modified: trunk/pom.xml
===================================================================
--- trunk/pom.xml 2013-11-22 16:38:00 UTC (rev 2881)
+++ trunk/pom.xml 2013-11-22 16:38:04 UTC (rev 2882)
@@ -33,7 +33,7 @@
</parent>
<artifactId>topia</artifactId>
- <version>3.0-alpha-5</version>
+ <version>3.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>ToPIA</name>
@@ -207,12 +207,12 @@
</modules>
<scm>
- <connection>scm:svn:http://svn.nuiton.org/svn/topia/tags/topia-3.0-alpha-5</connection>
+ <connection>scm:svn:http://svn.nuiton.org/svn/topia/trunk</connection>
<developerConnection>
- scm:svn:http://svn.nuiton.org/svn/topia/tags/topia-3.0-alpha-5
+ scm:svn:http://svn.nuiton.org/svn/topia/trunk
</developerConnection>
<url>
- http://nuiton.org/projects/topia/repository/show/tags/topia-3.0-alpha-5
+ http://nuiton.org/projects/topia/repository/show/trunk
</url>
</scm>
<distributionManagement>
Modified: trunk/topia-persistence/pom.xml
===================================================================
--- trunk/topia-persistence/pom.xml 2013-11-22 16:38:00 UTC (rev 2881)
+++ trunk/topia-persistence/pom.xml 2013-11-22 16:38:04 UTC (rev 2882)
@@ -30,7 +30,7 @@
<parent>
<groupId>org.nuiton</groupId>
<artifactId>topia</artifactId>
- <version>3.0-alpha-5</version>
+ <version>3.0-SNAPSHOT</version>
</parent>
<groupId>org.nuiton.topia</groupId>
Modified: trunk/topia-service-migration/pom.xml
===================================================================
--- trunk/topia-service-migration/pom.xml 2013-11-22 16:38:00 UTC (rev 2881)
+++ trunk/topia-service-migration/pom.xml 2013-11-22 16:38:04 UTC (rev 2882)
@@ -30,7 +30,7 @@
<parent>
<groupId>org.nuiton</groupId>
<artifactId>topia</artifactId>
- <version>3.0-alpha-5</version>
+ <version>3.0-SNAPSHOT</version>
</parent>
<groupId>org.nuiton.topia</groupId>
Modified: trunk/topia-service-replication/pom.xml
===================================================================
--- trunk/topia-service-replication/pom.xml 2013-11-22 16:38:00 UTC (rev 2881)
+++ trunk/topia-service-replication/pom.xml 2013-11-22 16:38:04 UTC (rev 2882)
@@ -30,7 +30,7 @@
<parent>
<groupId>org.nuiton</groupId>
<artifactId>topia</artifactId>
- <version>3.0-alpha-5</version>
+ <version>3.0-SNAPSHOT</version>
</parent>
<groupId>org.nuiton.topia</groupId>
1
0
Author: maven-release
Date: 2013-11-22 17:38:00 +0100 (Fri, 22 Nov 2013)
New Revision: 2881
Url: http://nuiton.org/projects/topia/repository/revisions/2881
Log:
[maven-release-plugin] copy for tag topia-3.0-alpha-5
Added:
tags/topia-3.0-alpha-5/
Property changes on: tags/topia-3.0-alpha-5
___________________________________________________________________
Added: svn:ignore
+ *.ipr
*.iws
.classpath
*.iml
.project
target
.settings
.idea
atlassian-ide-plugin.xml
Added: svn:mergeinfo
+ /branches/from2.2.2-eugene2-beta:1662-1714
/branches/topia-2.6.x:2293-2300
1
0