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@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/tru... -// } -// -// @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@codelutin.com"); Contact2 contact = contactDAO.create(Contact2.PROPERTY_CONTACT_VALUE, "jaja@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@codelutin.com> - * @author tchemit <tchemit@codelutin.com> - * @author athimel <thimel@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@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@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@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@codelutin.com> - * @author tchemit <chemit@codelutin.com> - * @author fdesbois <desbois@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.ht... - */ - @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@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@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@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@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@codelutin.com> - * @author fdesbois <fdesbois@codelutin.com> - * @author tchemit <chemit@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@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@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@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@codelutin.com> - * @author tchemit <tchemit@codelutin.com> - * @author chatellier <chatellier@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@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@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@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@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;