Author: tchemit Date: 2013-11-22 19:03:47 +0100 (Fri, 22 Nov 2013) New Revision: 2884 Url: http://nuiton.org/projects/topia/repository/revisions/2884 Log: refs #299: Refactor modules Added: trunk/topia-it/ trunk/topia-it/LICENSE.txt trunk/topia-it/README.txt trunk/topia-it/pom.xml trunk/topia-it/src/ trunk/topia-it/src/main/ trunk/topia-it/src/main/java/ trunk/topia-it/src/main/java/org/ trunk/topia-it/src/main/java/org/nuiton/ trunk/topia-it/src/main/java/org/nuiton/topia/ trunk/topia-it/src/main/java/org/nuiton/topia/it/ trunk/topia-it/src/main/xmi/ trunk/topia-it/src/test/ trunk/topia-it/src/test/java/ trunk/topia-it/src/test/java/org/ trunk/topia-it/src/test/java/org/nuiton/ trunk/topia-it/src/test/java/org/nuiton/topia/ trunk/topia-it/src/test/java/org/nuiton/topia/it/ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/AbstractEmployeTopiaDao.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/AbstractPersonneTopiaDao.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/EmployeTopiaDao.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/EmployeeDao.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/GeneratedEmployeeTopiaDao.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/GeneratedPersonneTopiaDao.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/PersonneDao.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/PersonneTopiaDao.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TestHelper.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaContextFactoryTest.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaDatabase.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaJpaSupportTest.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/EntityStateTest.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaConnectionProviderHardCoded.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaConnectionProviderTest.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextImplTest.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextReplicateTest.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaUtilTest.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/generator/ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/generator/TopiaTestCase.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/EntityVisitorExportXmlTest.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/ExportXMLVisitor.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/HqlAndParametersBuilderTest.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/NaturalIdTest.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/TopiaDAOTest.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/CollectorTest.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/EntityOperatorTest.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityBinderTest.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityHelperTest.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityRefTester.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityRefTesterTest.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/ano1882/ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/ano1882/DAOAbstractTransformerTest.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/evo1912/ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/evo1912/EntityDTOTransformerTest.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/AbstractExtraDAOEntityTopiaDao.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/EnumTest.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/Gender.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/Title.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/beangen/ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/beangen/RoueImpl.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/AbstractContact2TopiaDao.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/DeleteEntityTest.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Abstract.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Impl.hbm.xml trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Impl.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/package-info.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/FakeService.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/TestService.java trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/package-info.java trunk/topia-it/src/test/resources/ trunk/topia-it/src/test/resources/TopiaConnectionProviderHardcoded.properties trunk/topia-it/src/test/resources/TopiaContextImpl.properties trunk/topia-it/src/test/resources/log4j.properties trunk/topia-junit/ trunk/topia-junit/LICENSE.txt trunk/topia-junit/README.txt trunk/topia-junit/pom.xml trunk/topia-junit/src/ trunk/topia-junit/src/main/ trunk/topia-junit/src/main/java/ trunk/topia-junit/src/main/java/org/ trunk/topia-junit/src/main/java/org/nuiton/ trunk/topia-junit/src/main/java/org/nuiton/topia/ trunk/topia-junit/src/main/java/org/nuiton/topia/junit/ trunk/topia-templates/ trunk/topia-templates/LICENSE.txt trunk/topia-templates/README.txt trunk/topia-templates/pom.xml trunk/topia-templates/src/ trunk/topia-templates/src/main/ trunk/topia-templates/src/main/java/ trunk/topia-templates/src/main/java/org/ trunk/topia-templates/src/main/java/org/nuiton/ trunk/topia-templates/src/main/java/org/nuiton/topia/ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/ApplicationContextTransformer.java trunk/topia-templates/src/main/java/org/nuiton/topia/templates/BinderHelperTransformer.java trunk/topia-templates/src/main/java/org/nuiton/topia/templates/DAOHelperTransformer.java trunk/topia-templates/src/main/java/org/nuiton/topia/templates/DTOTransformer.java trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityDTOTransformer.java trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityDaoTransformer.java trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityHibernateMappingGenerator.java trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityTransformer.java trunk/topia-templates/src/main/java/org/nuiton/topia/templates/PersistenceContextTransformer.java trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaGeneratorUtil.java trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaJavaValidator.java trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaMetaTransformer.java trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaRelationValidator.java trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaStereoTypes.java trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaTagValues.java trunk/topia-templates/src/main/java/org/nuiton/topia/templates/package-info.java trunk/topia-templates/src/main/resources/ trunk/topia-templates/src/main/resources/META-INF.services/ trunk/topia-templates/src/main/resources/META-INF.services/org.nuiton.eugene.ModelPropertiesUtil$ModelPropertiesProvider trunk/topia-templates/src/test/ trunk/topia-templates/src/test/java/ trunk/topia-templates/src/test/java/org/ trunk/topia-templates/src/test/java/org/nuiton/ trunk/topia-templates/src/test/java/org/nuiton/topia/ trunk/topia-templates/src/test/java/org/nuiton/topia/templates/ trunk/topia-templates/src/test/java/org/nuiton/topia/templates/TopiaGeneratorUtilTest.java trunk/topia-templates/src/test/java/org/nuiton/topia/templates/TopiaModelPropertiesProviderTest.java Removed: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/ApplicationContextTransformer.java trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/BinderHelperTransformer.java trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DAOHelperTransformer.java trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DTOTransformer.java trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityDTOTransformer.java trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityDaoTransformer.java trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityHibernateMappingGenerator.java trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityTransformer.java trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/PersistenceContextTransformer.java trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaGeneratorUtil.java trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaJavaValidator.java trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaMetaTransformer.java trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaRelationValidator.java trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaStereoTypes.java trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaTagValues.java trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/package-info.java trunk/topia-persistence/src/main/resources/META-INF/services/org.nuiton.eugene.ModelPropertiesUtil$ModelPropertiesProvider trunk/topia-persistence/src/test/java/org/nuiton/topia/AbstractEmployeTopiaDao.java trunk/topia-persistence/src/test/java/org/nuiton/topia/AbstractPersonneTopiaDao.java trunk/topia-persistence/src/test/java/org/nuiton/topia/EmployeTopiaDao.java trunk/topia-persistence/src/test/java/org/nuiton/topia/EmployeeDao.java trunk/topia-persistence/src/test/java/org/nuiton/topia/GeneratedEmployeeTopiaDao.java trunk/topia-persistence/src/test/java/org/nuiton/topia/GeneratedPersonneTopiaDao.java trunk/topia-persistence/src/test/java/org/nuiton/topia/PersonneDao.java trunk/topia-persistence/src/test/java/org/nuiton/topia/PersonneTopiaDao.java trunk/topia-persistence/src/test/java/org/nuiton/topia/TestHelper.java trunk/topia-persistence/src/test/java/org/nuiton/topia/TopiaContextFactoryTest.java trunk/topia-persistence/src/test/java/org/nuiton/topia/TopiaDatabase.java trunk/topia-persistence/src/test/java/org/nuiton/topia/TopiaJpaSupportTest.java trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/EntityStateTest.java trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaConnectionProviderHardCoded.java trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaConnectionProviderTest.java trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaContextImplTest.java trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaContextReplicateTest.java trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaUtilTest.java trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/TopiaGeneratorUtilTest.java trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/TopiaModelPropertiesProviderTest.java trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/TopiaTestCase.java trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/EntityVisitorExportXmlTest.java trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/ExportXMLVisitor.java trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/HqlAndParametersBuilderTest.java trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/NaturalIdTest.java trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/TopiaDAOTest.java trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/CollectorTest.java trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/EntityOperatorTest.java trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityBinderTest.java trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityHelperTest.java trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTester.java trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTesterTest.java trunk/topia-persistence/src/test/java/org/nuiton/topia/test/ano1882/DAOAbstractTransformerTest.java trunk/topia-persistence/src/test/java/org/nuiton/topia/test/evo1912/EntityDTOTransformerTest.java trunk/topia-persistence/src/test/java/org/nuiton/topiatest/AbstractExtraDAOEntityTopiaDao.java trunk/topia-persistence/src/test/java/org/nuiton/topiatest/EnumTest.java trunk/topia-persistence/src/test/java/org/nuiton/topiatest/Gender.java trunk/topia-persistence/src/test/java/org/nuiton/topiatest/Title.java trunk/topia-persistence/src/test/java/org/nuiton/topiatest/beangen/RoueImpl.java trunk/topia-persistence/src/test/java/org/nuiton/topiatest/deletetest/AbstractContact2TopiaDao.java trunk/topia-persistence/src/test/java/org/nuiton/topiatest/deletetest/DeleteEntityTest.java trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1.java trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1Abstract.java trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1Impl.hbm.xml trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1Impl.java trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/package-info.java trunk/topia-persistence/src/test/java/org/nuiton/topiatest/service/FakeService.java trunk/topia-persistence/src/test/java/org/nuiton/topiatest/service/TestService.java trunk/topia-persistence/src/test/java/org/nuiton/topiatest/service/package-info.java trunk/topia-persistence/src/test/resources/TopiaConnectionProviderHardcoded.properties trunk/topia-persistence/src/test/resources/TopiaContextImpl.properties trunk/topia-persistence/src/test/resources/log4j.properties trunk/topia-persistence/src/test/xmi/ Modified: trunk/pom.xml trunk/topia-it/src/main/xmi/topiatest.zargo trunk/topia-persistence/pom.xml trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaEntity.java Modified: trunk/pom.xml =================================================================== --- trunk/pom.xml 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/pom.xml 2013-11-22 18:03:47 UTC (rev 2884) @@ -202,6 +202,9 @@ <modules> <module>topia-persistence</module> + <module>topia-junit</module> + <module>topia-templates</module> + <module>topia-it</module> <module>topia-service-replication</module> <module>topia-service-migration</module> </modules> Property changes on: trunk/topia-it ___________________________________________________________________ Added: svn:ignore + target .idea *.ipr *.iws *.iml Property changes on: trunk/topia-it/LICENSE.txt ___________________________________________________________________ Added: svn:keywords + Author Date Id Revision Added: svn:eol-style + native Property changes on: trunk/topia-it/README.txt ___________________________________________________________________ Added: svn:keywords + Author Date Id Revision Added: svn:eol-style + native Added: trunk/topia-it/pom.xml =================================================================== --- trunk/topia-it/pom.xml (rev 0) +++ trunk/topia-it/pom.xml 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,129 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + #%L + ToPIA :: Persistence + + $Id$ + $HeadURL: http://svn.nuiton.org/svn/topia/trunk/topia-persistence/pom.xml $ + %% + Copyright (C) 2004 - 2010 CodeLutin + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Lesser Public License for more details. + + You should have received a copy of the GNU General Lesser Public + License along with this program. If not, see + <http://www.gnu.org/licenses/lgpl-3.0.html>. + #L% + --> + +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>org.nuiton</groupId> + <artifactId>topia</artifactId> + <version>3.0-SNAPSHOT</version> + </parent> + + <groupId>org.nuiton.topia</groupId> + <artifactId>topia-it</artifactId> + <packaging>jar</packaging> + + <name>ToPIA :: IT</name> + <description>Integration tests</description> + + <dependencies> + + <dependency> + <groupId>${project.groupId}</groupId> + <artifactId>topia-persistence</artifactId> + <version>${project.version}</version> + </dependency> + + <dependency> + <groupId>${project.groupId}</groupId> + <artifactId>topia-junit</artifactId> + <version>${project.version}</version> + </dependency> + + <dependency> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-log4j12</artifactId> + </dependency> + + <!-- BD H2 for testing --> + <dependency> + <groupId>com.h2database</groupId> + <artifactId>h2</artifactId> + <scope>test</scope> + </dependency> + + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + </dependency> + + <dependency> + <groupId>org.hamcrest</groupId> + <artifactId>hamcrest-core</artifactId> + </dependency> + + <dependency> + <groupId>log4j</groupId> + <artifactId>log4j</artifactId> + <scope>test</scope> + </dependency> + + </dependencies> + + <build> + + <plugins> + + <plugin> + <groupId>org.nuiton.eugene</groupId> + <artifactId>eugene-maven-plugin</artifactId> + <configuration> + + </configuration> + <executions> + <execution> + <id>Model Generator</id> + <phase>generate-sources</phase> + <configuration> + <templates> + org.nuiton.eugene.java.JavaInterfaceTransformer, + org.nuiton.eugene.java.JavaBeanTransformer, + org.nuiton.topia.templates.TopiaMetaTransformer, + org.nuiton.topia.templates.EntityDTOTransformer, + org.nuiton.topia.templates.BinderHelperTransformer + </templates> + <fullPackagePath>org.nuiton.topia</fullPackagePath> + <defaultPackage>org.nuiton.topia</defaultPackage> + </configuration> + <goals> + <goal>generate</goal> + </goals> + </execution> + </executions> + <dependencies> + <dependency> + <groupId>${project.groupId}</groupId> + <artifactId>topia-templates</artifactId> + <version>${project.version}</version> + </dependency> + </dependencies> + </plugin> + + </plugins> + </build> + +</project> Property changes on: trunk/topia-it/pom.xml ___________________________________________________________________ Added: svn:mime-type + text/xml Added: svn:keywords + Author Date Id Revision Added: svn:eol-style + native Property changes on: trunk/topia-it/src/main/java/org ___________________________________________________________________ Added: svn:ignore + target *.ipr *.iws *.iml .idea Modified: trunk/topia-it/src/main/xmi/topiatest.zargo =================================================================== (Binary files differ) Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/AbstractEmployeTopiaDao.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/AbstractEmployeTopiaDao.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/AbstractEmployeTopiaDao.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/AbstractEmployeTopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,33 @@ +package org.nuiton.topia.it.legacy; + +/* + * #%L + * ToPIA :: Persistence + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2013 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ + +import org.nuiton.topiatest.Employe; + +/** + * @author Arnaud Thimel <thimel@codelutin.com> + */ +public abstract class AbstractEmployeTopiaDao<E extends Employe> extends GeneratedEmployeeTopiaDao<E> { +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/AbstractPersonneTopiaDao.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/AbstractPersonneTopiaDao.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/AbstractPersonneTopiaDao.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/AbstractPersonneTopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,34 @@ +package org.nuiton.topia.it.legacy; + +/* + * #%L + * ToPIA :: Persistence + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2013 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ + +import org.nuiton.topiatest.Personne; + +/** + * @author Arnaud Thimel <thimel@codelutin.com> + */ +public abstract class AbstractPersonneTopiaDao<E extends Personne> extends GeneratedPersonneTopiaDao<E> { + +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/EmployeTopiaDao.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/EmployeTopiaDao.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/EmployeTopiaDao.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/EmployeTopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,42 @@ +package org.nuiton.topia.it.legacy; + +/* + * #%L + * ToPIA :: Persistence + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2013 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ + +import java.util.List; + +import org.nuiton.topiatest.Employe; +import org.nuiton.topiatest.Personne; + +/** + * @author Arnaud Thimel <thimel@codelutin.com> + */ +public class EmployeTopiaDao extends AbstractEmployeTopiaDao<Employe> { + + @Override + public List<Personne> findAllPersonnesByXAndY(int x, int y) { + return null; + } + +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/EmployeeDao.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/EmployeeDao.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/EmployeeDao.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/EmployeeDao.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,31 @@ +package org.nuiton.topia.it.legacy; + +/* + * #%L + * ToPIA :: Persistence + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2013 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ + +/** + * @author Arnaud Thimel <thimel@codelutin.com> + */ +public interface EmployeeDao { +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/GeneratedEmployeeTopiaDao.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/GeneratedEmployeeTopiaDao.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/GeneratedEmployeeTopiaDao.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/GeneratedEmployeeTopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,33 @@ +package org.nuiton.topia.it.legacy; + +/* + * #%L + * ToPIA :: Persistence + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2013 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ + +import org.nuiton.topiatest.Employe; + +/** + * @author Arnaud Thimel <thimel@codelutin.com> + */ +public abstract class GeneratedEmployeeTopiaDao<E extends Employe> extends AbstractPersonneTopiaDao<E> { +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/GeneratedPersonneTopiaDao.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/GeneratedPersonneTopiaDao.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/GeneratedPersonneTopiaDao.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/GeneratedPersonneTopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,60 @@ +package org.nuiton.topia.it.legacy; + +/* + * #%L + * ToPIA :: Persistence + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2013 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ + +import java.util.List; +import java.util.Map; + +import org.nuiton.topia.persistence.AbstractTopiaDao; +import org.nuiton.topia.persistence.TopiaEntity; +import org.nuiton.topia.persistence.TopiaEntityEnum; +import org.nuiton.topiatest.Personne; + +/** + * @author Arnaud Thimel <thimel@codelutin.com> + */ +public abstract class GeneratedPersonneTopiaDao<E extends Personne> extends AbstractTopiaDao<E> implements PersonneDao { + + @Override + public TopiaEntityEnum getTopiaEntityEnum() { + return null; + } + + @Override + public <R extends TopiaEntity> List<R> findUsages(Class<R> type, E entity) throws TopiaException { + return null; + } + + @Override + public Map<Class<? extends TopiaEntity>, List<? extends TopiaEntity>> findAllUsages(E entity) throws TopiaException { + return null; + } + + @Override + public Class<E> getEntityClass() { + return null; + } + +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/PersonneDao.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/PersonneDao.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/PersonneDao.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/PersonneDao.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,38 @@ +package org.nuiton.topia.it.legacy; + +/* + * #%L + * ToPIA :: Persistence + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2013 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ + +import java.util.List; + +import org.nuiton.topiatest.Personne; + +/** + * @author Arnaud Thimel <thimel@codelutin.com> + */ +public interface PersonneDao { + + List<Personne> findAllPersonnesByXAndY(int x, int y); + +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/PersonneTopiaDao.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/PersonneTopiaDao.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/PersonneTopiaDao.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/PersonneTopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,41 @@ +package org.nuiton.topia.it.legacy; + +/* + * #%L + * ToPIA :: Persistence + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2013 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ + +import java.util.List; + +import org.nuiton.topiatest.Personne; + +/** + * @author Arnaud Thimel <thimel@codelutin.com> + */ +public class PersonneTopiaDao extends AbstractPersonneTopiaDao<Personne> { + + @Override + public List<Personne> findAllPersonnesByXAndY(int x, int y) { + return null; + } + +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TestHelper.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/TestHelper.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TestHelper.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TestHelper.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,160 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2010 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ +package org.nuiton.topia.it.legacy; + +import org.apache.commons.io.FileUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.hibernate.cfg.Environment; +import org.junit.Ignore; +import org.nuiton.util.FileUtil; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.Properties; + +/** + * Helper for all topia tests. + * + * @author tchemit <chemit@codelutin.com> + * @since 2.5 + */ +@Ignore +// this is not a test :) +public class TestHelper { + + private static final Log log = LogFactory.getLog(TestHelper.class); + + protected static File testBasedir; + + protected static File targetdir; + + protected static File dirDatabase; + + public static final String DEFAULT_CONFIGURATION_LOCATION = "/TopiaContextImpl.properties"; + + public static File getTestWorkdir() { + if (testBasedir == null) { + String base = System.getProperty("java.io.tmpdir"); + if (base == null || base.isEmpty()) { + base = new File("").getAbsolutePath(); + } + testBasedir = new File(base); + log.info("basedir for test " + testBasedir); + } + return testBasedir; + } + + public static File getTestBasedir(Class<?> testClass) throws IOException { + File dir = getTestWorkdir(); + File result = new File(dir, testClass.getName()); + if (result.exists()) { + + // when calling this method (always in a BeforeClass method), we wants + // to clean the directory, this is a new build + FileUtils.deleteDirectory(result); + } + + // always create the directory + FileUtil.createDirectoryIfNecessary(result); + return result; + } + + public static TopiaContext initTopiaContext(File testDirectory, + String dbname) + throws IOException, TopiaNotFoundException { + + + TopiaContext topiaContext = initTopiaContext( + testDirectory, + DEFAULT_CONFIGURATION_LOCATION, + dbname + ); + return topiaContext; + } + + public static TopiaContext initTopiaContext(File testDirectory, + String dbPropertiesPath, + String dbname) + throws IOException, TopiaNotFoundException { + + Properties configuration = initTopiaContextConfiguration( + testDirectory, + dbPropertiesPath, + dbname); + return TopiaContextFactory.getContext(configuration); + } + + public static Properties initTopiaContextConfiguration(File testDirectory, + String dbPropertiesPath, + String dbname) + throws IOException { + + Properties configuration = loadHibernateConfiguration(dbPropertiesPath); + + // make sure we always use a different directory + + String dbPath = getDbName(testDirectory, dbname); + + if (log.isInfoEnabled()) { + log.info("dbPath = " + dbPath); + } + configuration.setProperty( + Environment.URL, +// "hibernate.connection.url", + "jdbc:h2:file:" + dbPath); + + return configuration; + } + + public static Properties loadHibernateConfiguration(String dbPropertiesPath) throws IOException { + InputStream stream = TestHelper.class.getResourceAsStream(dbPropertiesPath); + + Properties configuration = new Properties(); + + configuration.load(stream); + configuration.setProperty( + TopiaContextFactory.CONFIG_PERSISTENCE_CLASSES, + TopiaTestDAOHelper.getImplementationClassesAsString()); + return configuration; + } + + public static String getDbName(File testDirectory, String dbname) { + return new File(testDirectory, + dbname + '_' + System.nanoTime()).getAbsolutePath(); + } + + public static Properties initTopiaContextConfiguration(File testDirectory, + String dbname) + throws IOException { + + return initTopiaContextConfiguration( + testDirectory, + DEFAULT_CONFIGURATION_LOCATION, + dbname + ); + } +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaContextFactoryTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/TopiaContextFactoryTest.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaContextFactoryTest.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaContextFactoryTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,189 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2010 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ +package org.nuiton.topia.it.legacy; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.nuiton.topia.framework.AbstractTopiaContext; + +import java.io.File; +import java.io.IOException; +import java.util.List; +import java.util.Properties; + +/** + * Created: 8 mai 2010 + * + * @author fdesbois <fdesbois@codelutin.com> + * @version $Id$ + */ +public class TopiaContextFactoryTest { + + private static final Log log = + LogFactory.getLog(TopiaContextFactoryTest.class); + + protected static File testBasedir; + + protected Properties properties; + + @BeforeClass + public static void init() throws IOException { + + testBasedir = TopiaDatabase.getTestSpecificDirectory(TopiaContextFactoryTest.class, "dummy"); + + } + + @Before + public void setUp() throws Exception { + properties = new Properties(); + properties.setProperty("prop1", "value1"); + properties.setProperty("prop2", "value2"); + TopiaContextFactory.contextCache.clear(); + } + + @Test + public void testGetContextOpened() throws Exception { + log.debug("## testGetContextOpened"); + + /** PREPARE DATA **/ + String databaseName = "h2data-testGetContextByPropertie"; + File dbDirectory = new File(testBasedir, databaseName); + String url = "jdbc:h2:file:" + dbDirectory; + properties.setProperty("hibernate.connection.url", url); + + AbstractTopiaContext test = new AbstractTopiaContext(properties); + TopiaContextFactory.contextCache.put(properties, test); + + /** EXEC METHOD **/ + List<String> result = TopiaContextFactory.getContextOpened(); + Assert.assertEquals(1, result.size()); + Assert.assertEquals(url, result.get(0)); + } + + @Test + public void testRemoveContext() throws Exception { + log.debug("## testRemoveContext"); + + /** PREPARE DATA **/ + AbstractTopiaContext test = new AbstractTopiaContext(properties); + TopiaContextFactory.contextCache.put(properties, test); + + /** EXEC METHOD **/ + TopiaContextFactory.removeContext(test); + Assert.assertEquals(0, TopiaContextFactory.contextCache.size()); + } + + //@Test + + public void testGetContext() throws Exception { + // TODO-fdesbois-20100508 : only used TopiaUtil.getProperties, need tests for this method + } + + @Test + public void testGetContextByProperties() throws Exception { + log.debug("## testGetContextByProperties"); + + /** PREPARE DATA **/ + Properties propertiesParent = new Properties(properties); + propertiesParent.setProperty("prop3", "value3"); + + Properties propertiesAll = new Properties(); + propertiesAll.setProperty("prop1", "value1"); + propertiesAll.setProperty("prop2", "value2"); + propertiesAll.setProperty("prop3", "value3"); + + /** EXEC METHOD **/ + + log.info("test 0 : add null properties"); + try { + TopiaContextFactory.getContext(null); + } catch (Exception eee) { + Assert.assertEquals(NullPointerException.class, eee.getClass()); + } + + log.info("test 1 : add new properties, will instantiate a new" + + " TopiaContext"); + TopiaContext test1 = TopiaContextFactory.getContext(propertiesParent); + Assert.assertNotNull(test1); + Assert.assertEquals(1, TopiaContextFactory.contextCache.size()); + + log.info("test 2 : with same properties, will retrieve existing" + + " TopiaContext"); + TopiaContext test2 = TopiaContextFactory.getContext(propertiesParent); + Assert.assertEquals(test1, test2); + Assert.assertEquals(1, TopiaContextFactory.contextCache.size()); + + log.info("test 3 : use other properties, will instantiate a different" + + "TopiaContext"); + TopiaContext test3 = TopiaContextFactory.getContext(properties); + log.debug("cache size : " + TopiaContextFactory.contextCache.size()); + log.debug("result : " + test1); + log.debug("result3 : " + test3); + Assert.assertNotSame(test1, test3); + Assert.assertEquals(2, TopiaContextFactory.contextCache.size()); + + log.info("test 4 : use other properties but equivalent to existing " + + "TopiaContext"); + // Test flating of properties + TopiaContext test4 = TopiaContextFactory.getContext(propertiesAll); + Assert.assertEquals(test1, test4); + Assert.assertEquals(2, TopiaContextFactory.contextCache.size()); + + log.info("test5a : reinstantiate new TopiaContext after one is closed."); + // TEST + // Strange behavior the closed flag of context stay true if + // hibernateFactory is not loaded from real properties +// test1.closeContext(); +// Assert.assertTrue(test1.isClosed()); + + // Add properties for Hibernate to have real opened topiaContext + String databaseName = "h2data-testGetContextByPropertie"; + File f = new File(testBasedir, databaseName); + + properties.setProperty("hibernate.connection.username", "sa"); + properties.setProperty("hibernate.connection.password", ""); + properties.setProperty("hibernate.connection.driver_class", "org.h2.Driver"); + properties.setProperty("hibernate.connection.url", + "jdbc:h2:file:" + f.getAbsolutePath()); + + + TopiaContext test5 = TopiaContextFactory.getContext(properties); + Assert.assertNotSame(test1, test5); + Assert.assertEquals(3, TopiaContextFactory.contextCache.size()); + + log.info("test5b : beginTransaction to properly close the context"); + test5.beginTransaction(); + + test5.closeContext(); + + TopiaContext result = TopiaContextFactory.getContext(properties); + Assert.assertNotSame(test5, result); + Assert.assertEquals(3, TopiaContextFactory.contextCache.size()); + } +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaDatabase.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/TopiaDatabase.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaDatabase.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaDatabase.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,210 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2012 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ +package org.nuiton.topia.it.legacy; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.hibernate.cfg.Configuration; +import org.junit.rules.TestWatcher; +import org.junit.runner.Description; +import org.nuiton.topia.HibernateProvider; +import org.nuiton.topia.TopiaContextFactory; +import org.nuiton.topia.TopiaException; + +import java.io.File; +import java.io.InputStream; +import java.util.Properties; + +/** + * Put this class as a Rule in test to obtain a new isolated db for each test. + * <p/> + * Here is a simple example of usage : + * <pre> + * public class MyTest { + * + * \@Rule + * public final TopiaDatabase db = new TopiaDatabase(); + * + * \@Test + * public void testMethod() throws TopiaException { + * + * TopiaContext tx = db.beginTransaction(); + * ... + * } + * </pre> + * The db created will be unique for each test method (and for each build also). + * <p/> + * You don't need to close any transaction, it will be done for you and the end + * of each method test. + * + * @author tchemit <chemit@codelutin.com> + * @since 2.6.8 + */ +public class TopiaDatabase extends TestWatcher { + + /** Logger. */ + private static final Log log = LogFactory.getLog(TopiaDatabase.class); + + /** A time-stamp, allow to make multiple build and keep the tests data. */ + public static final String TIMESTAMP = String.valueOf(System.nanoTime()); + + private File testBasedir; + + private Properties dbConfiguration; + + private TopiaTestTopiaApplicationContext applicationContext; + + private Configuration hibernateCfg; + + private final String configurationPath; + + public TopiaDatabase() { + this(TestHelper.DEFAULT_CONFIGURATION_LOCATION); + } + + public TopiaDatabase(String configurationPath) { + this.configurationPath = configurationPath; + } + + @Override + protected void starting(Description description) { + + // get test directory + testBasedir = getTestSpecificDirectory( + description.getTestClass(), + description.getMethodName()); + + if (log.isDebugEnabled()) { + log.debug("testBasedir = " + testBasedir); + } + + // create the root context + try { + + dbConfiguration = new Properties(); + InputStream stream = + getClass().getResourceAsStream(configurationPath); + + try { + dbConfiguration.load(stream); + } finally { + stream.close(); + } + dbConfiguration.setProperty( + TopiaContextFactory.CONFIG_PERSISTENCE_CLASSES, + TopiaTestDAOHelper.getImplementationClassesAsString()); + + // make sure we always use a different directory + + String dbPath = new File(testBasedir, "db").getAbsolutePath(); + + if (log.isDebugEnabled()) { + log.debug("dbPath = " + dbPath); + } + dbConfiguration.setProperty( + TopiaContextFactory.CONFIG_URL, "jdbc:h2:file:" + dbPath); + + onDbConfigurationCreate(dbConfiguration, testBasedir, dbPath); + +// rootCtxt = TopiaContextFactory.getContext(dbConfiguration); + applicationContext = new TopiaTestTopiaApplicationContext(dbConfiguration) { + @Override + protected HibernateProvider getHibernateProvider() { + HibernateProvider provider = super.getHibernateProvider(); + hibernateCfg = provider.getHibernateConfiguration(); + return provider; + } + }; + } catch (Exception e) { + throw new IllegalStateException( + "Could not start db at " + testBasedir, e); + } + } + + @Override + public void finished(Description description) { + + if (applicationContext != null && !applicationContext.isClosed()) { + try { + applicationContext.closeContext(); + } catch (TopiaException e) { + if (log.isErrorEnabled()) { + log.error("Could not close topia root context", e); + } + } + } + applicationContext = null; + dbConfiguration = null; + } + + public File getTestBasedir() { + return testBasedir; + } + + public Properties getDbConfiguration() { + return dbConfiguration; + } + + public TopiaTestTopiaApplicationContext getApplicationContext() { + return applicationContext; + } + + public Configuration getHibernateCfg() { + return hibernateCfg; + } + + public TopiaTestTopiaPersistenceContext beginTransaction() throws TopiaException { + return applicationContext.newPersistenceContext(); + } + + protected void onDbConfigurationCreate(Properties configuration, + File testDir, + String dbPath) { + + } + + public static File getTestSpecificDirectory(Class<?> testClassName, String methodName) { + // Trying to look for the temporary folder to store data for the test + String tempDirPath = System.getProperty("java.io.tmpdir"); + if (tempDirPath == null) { + // can this really occur ? + tempDirPath = ""; + if (log.isWarnEnabled()) { + log.warn("'\"java.io.tmpdir\" not defined"); + } + } + File tempDirFile = new File(tempDirPath); + + // create the directory to store database data + String dataBasePath = testClassName.getName() + + File.separator // a directory with the test class name + + methodName// a sub-directory with the method name + + '_' + + TIMESTAMP; // and a timestamp + File databaseFile = new File(tempDirFile, dataBasePath); + return databaseFile; + } +} + Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaJpaSupportTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/TopiaJpaSupportTest.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaJpaSupportTest.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/TopiaJpaSupportTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,161 @@ +/* + * #%L + * ToPIA :: Persistence :: Test Compatibility Kit + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2012 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ +package org.nuiton.topia.it.legacy; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.nuiton.topiatest.Address; +import org.nuiton.topiatest.AddressTopiaDao; +import org.nuiton.topiatest.Gender; +import org.nuiton.topiatest.Personne; +import org.nuiton.topiatest.PersonneTopiaDao; + +import java.util.List; + +/** + * Tests the TopiaContext#find|findAll|findUnique methods + * + * @author Arnaud Thimel <thimel@codelutin.com> + */ +public class TopiaJpaSupportTest { + + @Rule + public final TopiaDatabase db = new TopiaDatabase(); + + protected TopiaTestTopiaPersistenceContext persistenceContext; + protected TopiaJpaSupport jpaSupport; + protected AddressTopiaDao addressDAO; + protected PersonneTopiaDao personneDAO; + protected Address address; + + @Before + public void createCompanies() throws TopiaException { + persistenceContext = db.beginTransaction(); + jpaSupport = persistenceContext.jpaSupport; + + personneDAO = persistenceContext.getPersonneDao(); + addressDAO = persistenceContext.getAddressDao(); + + address = addressDAO.create( + Address.PROPERTY_ADRESS, "17 rue de la Pote Gellée, 44200 NANTES"); + + personneDAO.create( + Personne.PROPERTY_NAME, "Arnaud", + Personne.PROPERTY_GENDER, Gender.MALE); + personneDAO.create( + Personne.PROPERTY_NAME, "Charlotte", + Personne.PROPERTY_GENDER, Gender.FEMALE); + personneDAO.create( + Personne.PROPERTY_NAME, "Hortense", + Personne.PROPERTY_GENDER, Gender.FEMALE); + persistenceContext.commitTransaction(); + } + + @Test + public void testFindDAO() throws TopiaException { + Assert.assertEquals(3, personneDAO.count()); + + Assert.assertEquals(2, personneDAO.findAllByGender(Gender.FEMALE).size()); + Assert.assertNotNull(personneDAO.findByGender(Gender.FEMALE)); + Assert.assertNotNull(personneDAO.findByGender(Gender.MALE)); + Assert.assertNull(personneDAO.findByGender(null)); + + Assert.assertEquals(0, personneDAO.findAllByName("nobody").size()); + } + + @Test + public void testFindAll() throws TopiaException { + Assert.assertEquals(3, personneDAO.count()); + + String query = "from " + Personne.class.getName() + + " where " + Personne.PROPERTY_GENDER + "=:g"; + + List females = jpaSupport.findAll(query, "g", Gender.FEMALE); + Assert.assertEquals(2, females.size()); + + List males = jpaSupport.findAll(query, "g", Gender.MALE); + Assert.assertEquals(1, males.size()); + + List all = jpaSupport.findAll("from " + Personne.class.getName()); + Assert.assertEquals(3, all.size()); + + List none = jpaSupport.findAll("from " + Personne.class.getName() + + " where " + Personne.PROPERTY_NAME + "=:pax", "pax", "nobody"); + Assert.assertEquals(0, none.size()); + } + + @Test + public void testFind() throws TopiaException { + Assert.assertEquals(3, personneDAO.count()); + + String query = "from " + Personne.class.getName() + + " where " + Personne.PROPERTY_GENDER + "=:g"; + + List females = jpaSupport.find(query, 0, 100, "g", Gender.FEMALE); + Assert.assertEquals(2, females.size()); + + females = jpaSupport.find(query, 0, 0, "g", Gender.FEMALE); + Assert.assertEquals(1, females.size()); + Personne charlotte = (Personne)females.get(0); + + females = jpaSupport.find(query, 1, 1, "g", Gender.FEMALE); + Assert.assertEquals(1, females.size()); + Personne hortense = (Personne)females.get(0); + + Assert.assertFalse(hortense.equals(charlotte)); + + // endIndex = -1 not supported in ToPIA 2.6, wait for 3.0 +// females = context.find(query, 0, -1, "g", Gender.FEMALE); +// Assert.assertEquals(2, females.size()); + } + + @Test + public void testFindUnique() throws TopiaException { + Assert.assertEquals(3, personneDAO.count()); + + String query = "from " + Personne.class.getName() + + " where " + Personne.PROPERTY_GENDER + "=:g"; + + Object male = jpaSupport.findUnique(query, "g", Gender.MALE); + Assert.assertNotNull(male); + + Object none = jpaSupport.findUnique("from " + Personne.class.getName() + + " where " + Personne.PROPERTY_NAME + "=:pax", "pax", "nobody"); + Assert.assertNull(none); + } + + @Test(expected = TopiaException.class) + public void testFindUniqueOutOfBounds() throws TopiaException { + Assert.assertEquals(3, personneDAO.count()); + + String query = "from " + Personne.class.getName() + + " where " + Personne.PROPERTY_GENDER + "=:g"; + + Object female = jpaSupport.findUnique(query, "g", Gender.FEMALE); + Assert.assertNotNull(female); + } + +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/EntityStateTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/EntityStateTest.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/EntityStateTest.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/EntityStateTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,97 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2010 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ + +package org.nuiton.topia.it.legacy.framework; + +import org.junit.Assert; +import org.junit.Test; +import org.nuiton.topia.framework.EntityState; + +/** + * EntityStateTest.java + * <p/> + * Created: 22 nov. 06 12:15:11 + * + * @author poussin <poussin@codelutin.com> + * @version $Revision$ + * <p/> + * Last update: $Date$ + * by : $Author$ + */ +public class EntityStateTest { + + /** + * Test les changements d'etat de {@link EntityState}. + * + * @throws Exception + */ + @Test + public void testState() throws Exception { + EntityState state = new EntityState(); + + state.addLoad(); + Assert.assertTrue(state.isLoad()); + Assert.assertFalse(state.isRead()); + Assert.assertFalse(state.isCreate()); + Assert.assertFalse(state.isUpdate()); + Assert.assertFalse(state.isDelete()); + + state.addRead(); + Assert.assertTrue(state.isLoad()); + Assert.assertTrue(state.isRead()); + Assert.assertFalse(state.isCreate()); + Assert.assertFalse(state.isUpdate()); + Assert.assertFalse(state.isDelete()); + + //state.addRead(); + state.addCreate(); + Assert.assertTrue(state.isLoad()); + Assert.assertTrue(state.isRead()); + Assert.assertTrue(state.isCreate()); + Assert.assertFalse(state.isUpdate()); + Assert.assertFalse(state.isDelete()); + + state.addUpdate(); + Assert.assertTrue(state.isLoad()); + Assert.assertTrue(state.isRead()); + Assert.assertTrue(state.isCreate()); + Assert.assertTrue(state.isUpdate()); + Assert.assertFalse(state.isDelete()); + + state.addDelete(); + Assert.assertTrue(state.isLoad()); + Assert.assertTrue(state.isRead()); + Assert.assertTrue(state.isCreate()); + Assert.assertTrue(state.isUpdate()); + Assert.assertTrue(state.isDelete()); + + state = new EntityState(); + state.addDelete(); + Assert.assertFalse(state.isRead()); + Assert.assertFalse(state.isCreate()); + Assert.assertFalse(state.isUpdate()); + Assert.assertTrue(state.isDelete()); + } +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaConnectionProviderHardCoded.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaConnectionProviderHardCoded.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaConnectionProviderHardCoded.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaConnectionProviderHardCoded.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,210 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2011 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ +package org.nuiton.topia.it.legacy.framework; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.Map; +import java.util.Properties; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.hibernate.HibernateException; +import org.hibernate.cfg.Environment; +import org.hibernate.internal.util.ReflectHelper; +import org.hibernate.internal.util.config.ConfigurationHelper; +import org.hibernate.service.jdbc.connections.internal.ConnectionProviderInitiator; +import org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl; + +/** + * Customized connection provider. + * + * @author tchemit <chemit@codelutin.com> + * @since 2.5.3 + */ +public class TopiaConnectionProviderHardCoded extends DriverManagerConnectionProviderImpl { + + private String url; + + private Properties connectionProps; + + private Integer isolation; + + private final ArrayList pool = new ArrayList(); + + private int poolSize; + + private int checkedOut = 0; + + private boolean autocommit; + + /** Logger. */ + private static final Log log = + LogFactory.getLog(TopiaConnectionProviderHardCoded.class); + + @Override + public void configure(Map configurationValues) throws HibernateException { + String driverClass = (String)configurationValues.get(Environment.DRIVER); + + poolSize = ConfigurationHelper.getInt(Environment.POOL_SIZE, configurationValues, 20); //default pool size 20 + log.info("Using Hibernate built-in connection pool (not for production use!)"); + log.info("Hibernate connection pool size: " + poolSize); + + autocommit = ConfigurationHelper.getBoolean(Environment.AUTOCOMMIT, configurationValues); + log.info("autocommit mode: " + autocommit); + + isolation = ConfigurationHelper.getInteger(Environment.ISOLATION, configurationValues); + if (isolation != null) + log.info("JDBC isolation level: " + Environment.isolationLevelToString(isolation)); + + if (driverClass == null) { + log.warn("no JDBC Driver class was specified by property " + Environment.DRIVER); + } else { + try { + // trying via forName() first to be as close to DriverManager's semantics + Class.forName(driverClass); + } catch (ClassNotFoundException cnfe) { + try { + ReflectHelper.classForName(driverClass); + } catch (ClassNotFoundException e) { + String msg = "JDBC Driver class not found: " + driverClass; + log.error(msg, e); + throw new HibernateException(msg, e); + } + } + } + + // use a dummy directory to make sure only the connection provider knows + // the real directory where db is and then make sure hibernate always + // use the connection provider... + String directory = + (String)configurationValues.get(TopiaConnectionProviderTest.TEST_URL); + + url = directory; +// url = props.getProperty(Environment.URL); + +// if (url == null) { +// String msg = "JDBC URL was not specified by property " + Environment.URL; +// log.error(msg); +// throw new HibernateException(msg); +// } + + connectionProps = ConnectionProviderInitiator.getConnectionProperties(configurationValues); + + log.info("using driver: " + driverClass + " at URL: " + url); + // if debug level is enabled, then log the password, otherwise mask it + if (log.isDebugEnabled()) { + log.info("connection properties: " + connectionProps); + } else if (log.isInfoEnabled()) { + log.info("connection properties: " + ConfigurationHelper.maskOut(connectionProps, "password")); + } + } + + @Override + public Connection getConnection() throws SQLException { + if (log.isTraceEnabled()) + log.trace("total checked-out connections: " + checkedOut); + + synchronized (pool) { + if (!pool.isEmpty()) { + int last = pool.size() - 1; + if (log.isTraceEnabled()) { + log.trace("using pooled JDBC connection, pool size: " + last); + } + checkedOut++; + Connection pooled = (Connection) pool.remove(last); + if (isolation != null) + pooled.setTransactionIsolation(isolation.intValue()); + if (pooled.getAutoCommit() != autocommit) + pooled.setAutoCommit(autocommit); + return pooled; + } + } + + log.debug("opening new JDBC connection"); + Connection conn = DriverManager.getConnection(url, connectionProps); + if (isolation != null) conn.setTransactionIsolation(isolation); + if (conn.getAutoCommit() != autocommit) conn.setAutoCommit(autocommit); + + if (log.isDebugEnabled()) { + log.debug("created connection to: " + url + ", Isolation Level: " + conn.getTransactionIsolation()); + } +// if ( log.isTraceEnabled() ) + checkedOut++; + + return conn; + } + + @Override + public void closeConnection(Connection conn) throws SQLException { +// if ( log.isDebugEnabled() ) + checkedOut--; + + synchronized (pool) { + int currentSize = pool.size(); + if (currentSize < poolSize) { + if (log.isTraceEnabled()) { + log.trace("returning connection to pool, pool size: " + (currentSize + 1)); + } + pool.add(conn); + return; + } + } + + log.debug("closing JDBC connection"); + + conn.close(); + } + + @Override + protected void finalize() throws Throwable { + super.finalize(); + close(); + } + + public void close() { + + log.info("cleaning up connection pool: " + url); + + Iterator iter = pool.iterator(); + while (iter.hasNext()) { + try { + ((Connection) iter.next()).close(); + } catch (SQLException sqle) { + log.warn("problem closing pooled connection", sqle); + } + } + pool.clear(); + + } + + @Override + public boolean supportsAggressiveRelease() { + return false; + } +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaConnectionProviderTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaConnectionProviderTest.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaConnectionProviderTest.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaConnectionProviderTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,142 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2011 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ +package org.nuiton.topia.it.legacy.framework; + +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.nuiton.topia.TopiaContextFactory; +import org.nuiton.topia.TopiaDatabase; +import org.nuiton.topia.TopiaException; +import org.nuiton.topia.TopiaTestDAOHelper; +import org.nuiton.topia.TopiaTestTopiaPersistenceContext; +import org.nuiton.topia.framework.TopiaConnectionProvider; +import org.nuiton.topia.test.entities.Person; +import org.nuiton.topia.test.entities.PersonDAO; +import org.nuiton.topia.test.entities.PersonTopiaDao; +import org.nuiton.topiatest.Personne; + +import java.io.File; +import java.util.Locale; +import java.util.Properties; + +import static org.junit.Assert.assertNotNull; + +/** + * To test the {@link TopiaConnectionProvider} and make sure all connections + * are done from here... + * + * @author tchemit <chemit@codelutin.com> + * @since 2.5.3 + */ +public class TopiaConnectionProviderTest { + +// private static final Log log = +// LogFactory.getLog(TopiaConnectionProviderTest.class); + + public static final String TEST_URL = "testURL"; + + @Rule + public final TopiaDatabase db = + new TopiaDatabase("/TopiaConnectionProviderHardcoded.properties") { + + @Override + protected void onDbConfigurationCreate(Properties configuration, + File testdir, + String dbPath) { + + Assert.assertFalse(testdir.exists()); + + String dbPathFake = new File(testdir, "fake" + File.separator + "db").getAbsolutePath(); + + Assert.assertFalse(new File(dbPathFake).getParentFile().exists()); + + configuration.setProperty("dbPath", dbPath); + configuration.setProperty("dbPathFake", dbPathFake); + + // give the path where connection provider will create db + configuration.setProperty(TEST_URL, + "jdbc:h2:file:" + dbPath); + + // give a fake db path (we will make sure it is never create after hibernate usage). + configuration.setProperty(TopiaContextFactory.CONFIG_URL, + "jdbc:h2:file:" + dbPathFake); + } + }; + + @Test + public void testWithHardcoded() throws Exception { + +// Properties dbProperties = TestHelper.loadHibernateConfiguration( +// "/TopiaConnectionProviderHardcoded.properties"); +// +// File directory = new File(TestHelper.getDbName(testBasedir, "testWithHardcoded")); + + String dbPath = (String) db.getDbConfiguration().get("dbPath"); + String dbPathFake = (String) db.getDbConfiguration().get("dbPathFake"); + +// new File(directory, "real" + File.separator + "db").getAbsolutePath(); +// Assert.assertFalse(new File(dbPath).getParentFile().exists()); + +// String dbPathFake = new File(directory, "fake" + File.separator + "db").getAbsolutePath(); + +// Assert.assertFalse(new File(dbPathFake).getParentFile().exists()); + +// // give the path where connection provider will create db +// dbProperties.setProperty(TEST_URL, "jdbc:h2:file:" + dbPath); +// +// // give a fake db path (we will make sure it is never create after hibernate usage). +// dbProperties.setProperty(Environment.URL, "jdbc:h2:file:" + dbPathFake); +// +// root = TopiaContextFactory.getContext(dbProperties); + + Locale.setDefault(Locale.FRANCE); + + doStuffOnDb(); + + // the db file must have been created + Assert.assertTrue(new File(dbPath).getParentFile().exists()); + + // make sure the fake db path was never used + Assert.assertFalse(new File(dbPathFake).getParentFile().exists()); + } + + private void doStuffOnDb() throws TopiaException { + TopiaTestTopiaPersistenceContext transaction = db.beginTransaction(); + + try { + PersonDAO dao = TopiaTestDAOHelper.getPersonDAO(transaction); + + Person personne = dao.create(Personne.PROPERTY_NAME, "Jack Bauer"); + transaction.commitTransaction(); + String idPersonne = personne.getTopiaId(); + assertNotNull(idPersonne); + + transaction.commitTransaction(); + } finally { + transaction.closeContext(); + } + } +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextImplTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaContextImplTest.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextImplTest.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextImplTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,552 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2010 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ +package org.nuiton.topia.it.legacy.framework; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.h2.Driver; +import org.hibernate.cfg.Configuration; +import org.hibernate.mapping.PersistentClass; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.nuiton.topia.TopiaContextFactory; +import org.nuiton.topia.TopiaDatabase; +import org.nuiton.topia.TopiaNotFoundException; +import org.nuiton.topia.framework.AbstractTopiaContext; +import org.nuiton.topia.framework.TopiaContextImplementor; +import org.nuiton.topia.framework.TopiaService; +import org.nuiton.topiatest.persistence.Entity1; +import org.nuiton.topia.it.legacy.topiatest.persistence.Entity1Impl; +import org.nuiton.topiatest.service.FakeService; +import org.nuiton.topiatest.service.TestService; + +import java.io.File; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +/** + * Created: 10 mai 2010 + * + * @author fdesbois <fdesbois@codelutin.com> + * @version $Id$ + */ +public class TopiaContextImplTest { + + private static final Log log = + LogFactory.getLog(TopiaContextImplTest.class); + + protected Properties properties = new Properties(); + + static File testBasedir; + + @BeforeClass + public static void setUpClass() throws Exception { + + testBasedir = TopiaDatabase.getTestSpecificDirectory(TopiaContextImplTest.class, "dummy"); + } + + @Before + public void setUp() throws Exception { + properties.clear(); + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testLoadServices() throws Exception { + if (log.isDebugEnabled()) { + log.debug("## testLoadServices"); + } + + /** PREPARE DATA **/ + properties.setProperty("topia.service.test", + TestService.class.getName()); + + AbstractTopiaContext context = new AbstractTopiaContext(); + + /** EXEC METHOD **/ + if (log.isInfoEnabled()) { + log.info("test 1 : load a simple TestService from properties"); + } + Map<String, TopiaService> results = context.loadServices(properties); + Assert.assertEquals(1, results.size()); + Assert.assertTrue(results.containsKey("test")); + TopiaService service = results.get("test"); + Assert.assertEquals(TestService.class, service.getClass()); + + if (log.isInfoEnabled()) { + log.info("test 2 : load with wrong key : will display a WARN"); + } + properties.clear(); + + properties.setProperty("topia.service.fake", + TestService.class.getName()); + + results = context.loadServices(properties); + Assert.assertEquals(0, results.size()); + Assert.assertFalse(results.containsKey("fake")); + + if (log.isInfoEnabled()) { + log.info("test 3 : load with fake service name : will display an ERROR"); + } + properties.clear(); + + properties.setProperty("topia.service.test", "FAKE"); + + results = context.loadServices(properties); + Assert.assertEquals(0, results.size()); + Assert.assertFalse(results.containsKey("test")); + } + + @Test + public void testGetServices() throws Exception { + if (log.isDebugEnabled()) { + log.debug("## testGetServices"); + } + + /** PREPARE DATA **/ + properties.setProperty("topia.service.test", + TestService.class.getName()); + + // Calling the constructor with properties will load the services + AbstractTopiaContext context = new AbstractTopiaContext(properties); + + // Instantiate a child context and set its parent + AbstractTopiaContext child = new AbstractTopiaContext(context); + + /** EXEC METHOD **/ + if (log.isInfoEnabled()) { + log.info("test 1 : with child context"); + } + Map<String, TopiaService> test1 = child.getServices(); + Assert.assertEquals(1, test1.size()); + Assert.assertTrue(test1.containsKey("test")); + + if (log.isInfoEnabled()) { + log.info("test 2 : test serviceEnabled method"); + } + boolean test2 = child.serviceEnabled("test"); + Assert.assertTrue(test2); + + if (log.isInfoEnabled()) { + log.info("test 3 : test getService method"); + } + TopiaService test3 = child.getService("test"); + Assert.assertEquals(TestService.class, test3.getClass()); + + if (log.isInfoEnabled()) { + log.info("test 4 : test serviceEnabled from class TestService"); + } + boolean test4 = child.serviceEnabled(TestService.class); + Assert.assertTrue(test4); + + if (log.isInfoEnabled()) { + log.info("test 5 : test getService from class TestService"); + } + TestService test5 = child.getService(TestService.class); + Assert.assertNotNull(test5); + + if (log.isInfoEnabled()) { + log.info("test 6 : test serviceEnabled error with class FakeService"); + } + // FakeService doesn't contains property SERVICE_NAME used by + // serviceEnabled method + // Even it's properly loaded the serviceEnabled method will return false + properties.clear(); + properties.setProperty("topia.service.fake", + FakeService.class.getName()); + AbstractTopiaContext otherContext = new AbstractTopiaContext(properties); + + boolean test6 = otherContext.serviceEnabled(FakeService.class); + Assert.assertFalse(test6); + + if (log.isInfoEnabled()) { + log.info("test 7 : test getService with error TopiaNotFoundException" + + " : service not loaded"); + } + // TestService is not loaded in otherContext + try { + TestService test7 = otherContext.getService(TestService.class); + Assert.fail(); + } catch (TopiaNotFoundException eee) { + //log.error(eee.getClass().getSimpleName() + " : " + eee.getMessage()); + //Assert.assertEquals(TopiaNotFoundException.class, eee.getClass()); + } catch (Exception e) { + Assert.fail(); + } + } + + @Test + public void testContextHierarchy() throws Exception { + if (log.isDebugEnabled()) { + log.debug("## testContextHierarchy"); + } + + /** PREPARE DATA **/ + AbstractTopiaContext context = new AbstractTopiaContext(properties); + + /** EXEC METHODS **/ + if (log.isInfoEnabled()) { + log.info("test 1 : constructor with parent context"); + } + AbstractTopiaContext test1 = new AbstractTopiaContext(context); + Assert.assertEquals(context, test1.parentContext); + + if (log.isInfoEnabled()) { + log.info("test 2 : addChildContext"); + } + AbstractTopiaContext test2 = new AbstractTopiaContext(properties); + AbstractTopiaContext child2 = new AbstractTopiaContext(); + test2.addChildContext(child2); + Assert.assertEquals(1, test2.childContext.size()); + + if (log.isInfoEnabled()) { + log.info("test 3 : removeChildContext"); + } + AbstractTopiaContext test3 = new AbstractTopiaContext(properties); + AbstractTopiaContext child3 = new AbstractTopiaContext(test3); + test3.childContext.add(child3); + test3.removeChildContext(child3); + Assert.assertEquals(0, test3.childContext.size()); + + // No remove if context is closed + test3.childContext.add(child3); + test3.closed = true; + test3.removeChildContext(child3); + Assert.assertEquals(1, test3.childContext.size()); + + if (log.isInfoEnabled()) { + log.info("test 4 : getRootContext"); + } + TopiaContextImplementor test4 = child3.getRootContext(); + Assert.assertEquals(test3, test4); + + // Note : existing test is already done for concurrency problem on + // getChildContext(). Go to : http://www.nuiton.org/repositories/browse/sandbox/testTopiaPostgresError/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.commitTransaction(); +// +// daoSource = TopiaTestDAOHelper.getPersonDAO(txSource); +// +// personSource = daoSource.findByTopiaId(personSource.getTopiaId()); +// Assert.assertNotNull(personSource); +// +// petSource = petDAOSource.findByTopiaId(petSource.getTopiaId()); +// Assert.assertNotNull(petSource); +// Assert.assertEquals(1, personSource.sizePet()); +// Assert.assertEquals(petSource, personSource.getPet().iterator().next()); +// +// txTarget = contextTarget.beginTransaction(); +// +// txSource.replicateEntity(txTarget, petSource); +// txSource.replicateEntity(txTarget, personSource); +// +// txTarget.commitTransaction(); +// +// daoTarget = TopiaTestDAOHelper.getPersonDAO(txTarget); +// petDAOTarget = TopiaTestDAOHelper.getPetDAO(txTarget); +// +// personTarget = daoTarget.findByTopiaId(personSource.getTopiaId()); +// Assert.assertNotNull(personTarget); +// Assert.assertEquals(personSource, personTarget); +// Assert.assertEquals(1, personTarget.sizePet()); +// +// petTarget = petDAOTarget.findByTopiaId(petSource.getTopiaId()); +// Assert.assertNotNull(petTarget); +// Assert.assertEquals(petSource, petTarget); +// +// Assert.assertEquals(petTarget, personTarget.getPet().iterator().next()); +// +// +// } finally { +// closeDb(contextSource); +// closeDb(contextTarget); +// } +// +// } +// +// protected static void closeDb(TopiaContext contextSource) { +// if (contextSource != null && !contextSource.isClosed()) +// try { +// contextSource.clear(false); +// } catch (TopiaException e) { +// if (log.isErrorEnabled()) { +// log.error("Could not close db " + contextSource, e); +// } +// } +// } + + +// +// @Test +// public void testGetHibernateConfiguration() throws Exception { +// } +// +// @Test +// public void testGetDAO() throws Exception { +// } +// +// @Test +// public void testBeginTransaction() throws Exception { +// } +// +// @Test +// public void testCommitTransaction() throws Exception { +// } +// +// @Test +// public void testRollbackTransaction() throws Exception { +// } +// +// @Test +// public void testCloseContext() throws Exception { +// } +// +// @Test +// public void testIsClosed() throws Exception { +// } +// +// @Test +// public void testFindByTopiaId() throws Exception { +// } +// +// @Test +// public void testFind() throws Exception { +// } +// +// @Test +// public void testFind2() throws Exception { +// } +// +// @Test +// public void testExecute() throws Exception { +// } +// +// @Test +// public void testAdd() throws Exception { +// } +// +// @Test +// public void testImportXML() throws Exception { +// } +// +// @Test +// public void testExportXML() throws Exception { +// } +// +// +// @Test +// public void testReplicateEntity() throws Exception { +// } +// +// @Test +// public void testReplicateEntities() throws Exception { +// } +// +// @Test +// public void testGetFiresSupport() throws Exception { +// } +// +// @Test +// public void testBackup() throws Exception { +// } +// +// @Test +// public void testRestore() throws Exception { +// } +// +// @Test +// public void testClear() throws Exception { +// } +// +// @Test +// public void testGetPersistenceClasses() throws Exception { +// } +// +// @Test +// public void testIsSchemaExist() throws Exception { +// } +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextReplicateTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaContextReplicateTest.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextReplicateTest.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaContextReplicateTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,155 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2012 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ +package org.nuiton.topia.it.legacy.framework; + +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.nuiton.topia.TopiaContextFactory; +import org.nuiton.topia.TopiaDatabase; +import org.nuiton.topia.TopiaTestDAOHelper; +import org.nuiton.topia.TopiaTestTopiaPersistenceContext; +import org.nuiton.topia.test.entities.Person; +import org.nuiton.topia.test.entities.PersonDAO; +import org.nuiton.topia.test.entities.Pet; +import org.nuiton.topia.test.entities.PetDAO; + +import java.io.File; +import java.util.Properties; + +/** + * To test replication sugin TopiaContext. + * + * @author tchemit <chemit@codelutin.com> + * @since 2.6.8 + */ +public class TopiaContextReplicateTest { + + @Rule + public final TopiaDatabase dbSource = + new TopiaDatabase() { + + @Override + protected void onDbConfigurationCreate(Properties configuration, File testDir, String dbPath) { + configuration.setProperty( + TopiaContextFactory.CONFIG_URL, "jdbc:h2:file:" + dbPath + "-source"); + + } + }; + + @Rule + public final TopiaDatabase dbTarget = + new TopiaDatabase() { + + @Override + protected void onDbConfigurationCreate(Properties configuration, File testDir, String dbPath) { + configuration.setProperty( + TopiaContextFactory.CONFIG_URL, "jdbc:h2:file:" + dbPath + "-target"); + + } + }; + + @Test + public void replicateEntity() throws Exception { +// +// Properties configSource = TestHelper.initTopiaContextConfiguration( +// testBasedir, +// "/TopiaContextImpl.properties", +// "replicateSource"); +// +// Properties configTarget = TestHelper.initTopiaContextConfiguration( +// testBasedir, +// "/TopiaContextImpl.properties", +// "replicateTarget"); +// + + +// try { +// contextSource = TopiaContextFactory.getContext(configSource); +// contextTarget = TopiaContextFactory.getContext(configTarget); + + TopiaTestTopiaPersistenceContext txSource; + TopiaTestTopiaPersistenceContext txTarget; + PersonDAO daoSource, daoTarget; + PetDAO petDAOSource, petDAOTarget; + Person personSource, personTarget; + Pet petSource, petTarget; + + txSource = dbSource.beginTransaction(); + daoSource = TopiaTestDAOHelper.getPersonDAO(txSource); + petDAOSource = TopiaTestDAOHelper.getPetDAO(txSource); + + personSource = daoSource.create(Person.PROPERTY_FIRSTNAME, " firstName", + Person.PROPERTY_NAME, " name" + ); + + petSource = petDAOSource.create(Pet.PROPERTY_NAME, "name", + Pet.PROPERTY_TYPE, "type", + Pet.PROPERTY_PERSON, personSource + ); + + personSource.addPet(petSource); + + txSource.commitTransaction(); + + daoSource = TopiaTestDAOHelper.getPersonDAO(txSource); + + personSource = daoSource.findByTopiaId(personSource.getTopiaId()); + Assert.assertNotNull(personSource); + + petSource = petDAOSource.findByTopiaId(petSource.getTopiaId()); + Assert.assertNotNull(petSource); + Assert.assertEquals(1, personSource.sizePet()); + Assert.assertEquals(petSource, personSource.getPet().iterator().next()); + + txTarget = dbTarget.beginTransaction(); + + txSource.replicateEntity(txTarget, petSource); + txSource.replicateEntity(txTarget, personSource); + + txTarget.commitTransaction(); + + daoTarget = TopiaTestDAOHelper.getPersonDAO(txTarget); + petDAOTarget = TopiaTestDAOHelper.getPetDAO(txTarget); + + personTarget = daoTarget.findByTopiaId(personSource.getTopiaId()); + Assert.assertNotNull(personTarget); + Assert.assertEquals(personSource, personTarget); + Assert.assertEquals(1, personTarget.sizePet()); + + petTarget = petDAOTarget.findByTopiaId(petSource.getTopiaId()); + Assert.assertNotNull(petTarget); + Assert.assertEquals(petSource, petTarget); + + Assert.assertEquals(petTarget, personTarget.getPet().iterator().next()); + + +// } finally { +// closeDb(contextSource); +// closeDb(contextTarget); +// } + + } +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaUtilTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaUtilTest.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaUtilTest.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/framework/TopiaUtilTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,114 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2010 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ + +package org.nuiton.topia.it.legacy.framework; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.hibernate.cfg.Configuration; +import org.junit.Rule; +import org.junit.Test; +import org.nuiton.topia.TopiaDatabase; +import org.nuiton.topia.framework.TopiaUtil; +import org.nuiton.topia.test.entities.PersonImpl; +import org.nuiton.topiatest.Personne; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +/** + * Test pour les methodes de {@link TopiaUtil}. + * + * @author tchemit <chemit@codelutin.com> + * @version $Revision$ + * <p/> + * Last update: $Date$ + * by : $Author$ + */ +public class TopiaUtilTest { + + protected static final String PERSON_ID = "org.nuiton.topiatest.Personne#1226701039001#0.6502325993664224"; + + protected static final String PERSON_ID2 = "org.nuiton.topiatest.Personne#1226701039001#0.6502325993664999"; + + @Rule + public final TopiaDatabase db = new TopiaDatabase(); + + @Test + public void testGetTopiaIdPattern() throws Exception { + String expected; + String actual; + + expected = "org\\.nuiton\\.topiatest\\.Personne#(?:\\d+?)#(?:\\d+)\\.(?:\\d+)"; + actual = TopiaUtil.getTopiaIdPattern(Personne.class); + assertEquals(expected, actual); + } + + @Test + public void testGetTopiaPattern() throws Exception { + String expected; + Pattern pattern; + + expected = "(\\d+)-(org\\.nuiton\\.topiatest\\.Personne#(?:\\d+?)#(?:\\d+)\\.(?:\\d+))-(org\\.nuiton\\.topiatest\\.Personne#(?:\\d+?)#(?:\\d+)\\.(?:\\d+))(.*)"; + pattern = TopiaUtil.getTopiaPattern("(\\d+)-%1$s-%1$s(.*)", Personne.class); + assertEquals(expected, pattern.toString()); + + String expression = 123 + "-" + PERSON_ID + "-" + PERSON_ID2 + "-afterall"; + + Matcher matcher = pattern.matcher(expression); + + assertTrue(matcher.matches()); + + assertTrue(matcher.matches()); + assertEquals(4, matcher.groupCount()); + assertEquals("123", matcher.group(1)); + assertEquals(PERSON_ID, matcher.group(2)); + assertEquals(PERSON_ID2, matcher.group(3)); + assertEquals("-afterall", matcher.group(4)); + } + + @Test(expected = IllegalArgumentException.class) + public void testIsSchemaExistFailed() throws Exception { + TopiaUtil.isSchemaExist(db.getHibernateCfg(), "fake"); + } + + @Test + public void testIsSchemaExist() throws Exception { + + String personClassName = PersonImpl.class.getName(); + Configuration hibernateCfg = db.getHibernateCfg(); + + // First, test before DB is created, the table should not exist + assertFalse(TopiaUtil.isSchemaExist(hibernateCfg, personClassName)); + + // Create schema + db.getApplicationContext().createSchema(); + + // Now table should exist + assertTrue(TopiaUtil.isSchemaExist(hibernateCfg, personClassName)); + } +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/generator/TopiaTestCase.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/TopiaTestCase.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/generator/TopiaTestCase.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/generator/TopiaTestCase.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,170 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2010 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ + +package org.nuiton.topia.it.legacy.generator; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.nuiton.topia.TopiaDatabase; +import org.nuiton.topia.TopiaException; +import org.nuiton.topia.TopiaTestDAOHelper; +import org.nuiton.topia.TopiaTestTopiaPersistenceContext; +import org.nuiton.topiatest.Company; +import org.nuiton.topiatest.CompanyDAO; +import org.nuiton.topiatest.Department; +import org.nuiton.topiatest.DepartmentDAO; + +/** + * TopiaTestCase. + * + * @author chatellier + * @version $Revision$ + * <p/> + * Last update : $Date$ + * By : $Author$ + */ +public class TopiaTestCase { + + /** Logger */ + private final static Log log = LogFactory.getLog(TopiaTestCase.class); + + @Rule + public final TopiaDatabase db = new TopiaDatabase(); + +// /** Proprietes */ +// protected static Properties config; +// +// /** TopiaContext */ +// protected static TopiaContext context; + +// /** +// * Init les proprietes de connection a la base +// * +// * @throws IOException for any IO error while getting configuration. +// */ +// @BeforeClass +// public static void init() throws IOException { +// +// File testBasedir = TestHelper.getTestBasedir(TopiaTestCase.class); +// +// config = TestHelper.initTopiaContextConfiguration( +// testBasedir, +// "/TopiaContextImpl.properties", +// "TopiaTestCaseDb"); +//// config = new Properties(); +//// config.setProperty("topia.persistence.classes", TopiaTestDAOHelper.getImplementationClassesAsString()); +//// +//// config.setProperty(Environment.USER, "sa"); +//// config.setProperty(Environment.PASS, ""); +//// config.setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread"); +//// config.setProperty(Environment.DIALECT, "org.hibernate.dialect.H2Dialect"); +//// config.setProperty(Environment.DRIVER, "org.h2.Driver"); +//// config.setProperty(Environment.URL, "jdbc:h2:file:" + testBasedir + "/db/data_" + System.currentTimeMillis()); +// } +// +// @AfterClass +// public static void after() throws TopiaException { +// // destroy database +// context.clear(false); +// } + +// /** Create base with schema created. */ +// @Before +// public void setUp() { +// +// if (log.isDebugEnabled()) { +// log.debug("Junit beforeTest"); +// } +// +// try { +// context = TopiaContextFactory.getContext(config); +// +// try { +// context.createSchema(); +// } catch (TopiaException e) { +// log.error("Erreur à la creation du schema", e); +// } +// } catch (TopiaNotFoundException e) { +// log.error("Erreur à la creation du topia context", e); +// } +// } + + @Test + public void testCompositeAssociations() throws TopiaException { + if (log.isDebugEnabled()) { + log.debug("Junit Test testCompositeAssociations"); + } + +// try { + TopiaTestTopiaPersistenceContext newContext = db.beginTransaction(); + + CompanyDAO companyDAO = newContext.getCompanyDao(); + DepartmentDAO departmentDAO = newContext.getDepartmentDao(); + + Company company = companyDAO.create(); + company.setName("Ma société"); + + + Department dep1 = departmentDAO.create(); + dep1.setName("Departement 1"); + Department dep2 = departmentDAO.create(); + dep2.setName("Departement 2"); + Department dep3 = departmentDAO.create(); + dep3.setName("Departement 3"); + Department dep4 = departmentDAO.create(); + dep4.setName("Departement 7"); + + departmentDAO.update(dep1); + departmentDAO.update(dep2); + departmentDAO.update(dep3); + departmentDAO.update(dep4); + + company.addDepartment(dep1); + company.addDepartment(dep2); + company.addDepartment(dep3); + company.addDepartment(dep4); + + companyDAO.update(company); + newContext.commitTransaction(); + + newContext = db.beginTransaction(); + + companyDAO = TopiaTestDAOHelper.getCompanyDAO(newContext); + + company = companyDAO.findByTopiaId(company.getTopiaId()); + + Assert.assertEquals(company.getName(), "Ma société"); + Assert.assertEquals(company.getDepartment().size(), 4); + + newContext.commitTransaction(); +// newContext.closeContext(); +// } catch (TopiaException e) { +// log.error("Erreur pendant le test testCompositeAssociations", e); +// } + } +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/EntityVisitorExportXmlTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/EntityVisitorExportXmlTest.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/EntityVisitorExportXmlTest.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/EntityVisitorExportXmlTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,131 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2010 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ + +package org.nuiton.topia.persistence; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.nuiton.topia.TopiaDatabase; +import org.nuiton.topia.TopiaException; +import org.nuiton.topia.TopiaTestTopiaPersistenceContext; +import org.nuiton.topiatest.Address; +import org.nuiton.topiatest.AddressTopiaDao; +import org.nuiton.topiatest.Company; +import org.nuiton.topiatest.CompanyTopiaDao; +import org.nuiton.topiatest.Department; +import org.nuiton.topiatest.DepartmentTopiaDao; +import org.nuiton.topiatest.Employe; +import org.nuiton.topiatest.EmployeTopiaDao; + +/** + * Test de visitor. + * + * @author chatellier + * @version $Revision$ + * <p/> + * Last update : $Date$ + * By : $Author$ + */ +public class EntityVisitorExportXmlTest { + + private static final Log log = + LogFactory.getLog(EntityVisitorExportXmlTest.class); + + @Rule + public final TopiaDatabase db = new TopiaDatabase(); + + /** + * Prepare test. + * <p/> + * Add all tests commons data + * + * @throws TopiaException if could not create datas + */ + @Before + public void setUp() throws TopiaException { + + TopiaTestTopiaPersistenceContext newContext = db.beginTransaction(); + try { + // company + CompanyTopiaDao companyDAO = newContext.getCompanyDao(); + Company clCompany = companyDAO.create(Company.PROPERTY_NAME, "CodeLutin"); + + // employe + EmployeTopiaDao employeDAO = newContext.getEmployeDao(); + Employe empl1 = employeDAO.create(Employe.PROPERTY_NAME, "boss", Employe.PROPERTY_SALARY, 30000); + + AddressTopiaDao adressDAO = newContext.getAddressDao(); + Address addr1 = adressDAO.create(Address.PROPERTY_CITY, "Nantes", Address.PROPERTY_ADRESS, "12 Avenue Jules Vernes"); + empl1.setAddress(addr1); + + Employe empl2 = employeDAO.create(Employe.PROPERTY_NAME, "boss2", Employe.PROPERTY_SALARY, 29000); + Address addr2 = adressDAO.create(Address.PROPERTY_CITY, "Nantes", Address.PROPERTY_ADRESS, "12 Avenue Jules Vernes"); + empl2.setAddress(addr2); + + // departement + DepartmentTopiaDao departmentDAO = newContext.getDepartmentDao(); + Department depComm = departmentDAO.create(Department.PROPERTY_NAME, "Commercial"); + depComm.setLeader(empl1); + + Department depDev = departmentDAO.create(Department.PROPERTY_NAME, "Dev"); + depDev.setLeader(empl2); + clCompany.addDepartment(depComm); + clCompany.addDepartment(depDev); + + newContext.commitTransaction(); + } finally { + + newContext.closeContext(); + } + } + + + /** + * Test l'export XML via un visiteur. + * <p/> + * Parcourt en profondeur. + * + * @throws TopiaException + */ + @Test + public void testExportXMLDepth() throws TopiaException { + + TopiaTestTopiaPersistenceContext context = db.beginTransaction(); + + CompanyTopiaDao companyDAO = context.getCompanyDao(); + Company clCompany = companyDAO.findByName("CodeLutin"); + + EntityVisitor delegateVisitor = new ExportXMLVisitor(); + EntityVisitor visitor = new DepthEntityVisitor(delegateVisitor); + clCompany.accept(visitor); + + if (log.isInfoEnabled()) { + log.info("Export XML = \n" + delegateVisitor.toString()); + } + } +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/ExportXMLVisitor.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/ExportXMLVisitor.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/ExportXMLVisitor.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/ExportXMLVisitor.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,107 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2010 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ + +package org.nuiton.topia.persistence; + + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.junit.Ignore; + +/** + * Visitor pour export xml. + * + * @author chatellier + * @version $Revision$ + * <p/> + * Last update : $Date$ + * By : $Author$ + */ +@Ignore +public class ExportXMLVisitor implements EntityVisitor { + + /** log. */ + private static Log log = LogFactory.getLog(ExportXMLVisitor.class); + + protected StringBuffer buffer; + + public ExportXMLVisitor() { + buffer = new StringBuffer(); + } + + @Override + public void start(TopiaEntity e) { + if (log.isDebugEnabled()) { + log.debug("start : " + e); + } + + buffer.append("<").append(e.getClass().getName()); + buffer.append(" topiaId=\"").append(e.getTopiaId()).append("\""); + buffer.append(" topiaCreateDate=\"").append(e.getTopiaCreateDate()).append("\""); + buffer.append(" topiaVersion=\"").append(e.getTopiaVersion()).append("\""); + buffer.append(">\n"); + } + + @Override + public void visit(TopiaEntity e, String name, Class<?> type, Object value) { + if (log.isDebugEnabled()) { + log.debug("visit : " + e); + } + + buffer.append("<").append(type.getName()).append(">").append(value).append("</").append(type.getName()).append(">\n"); + } + + @Override + public void visit(TopiaEntity e, String name, Class<?> collectionType, Class<?> type, + Object value) { + } + + @Override + public void visit(TopiaEntity e, String name, Class<?> collectionType, Class<?> type, int index, Object value) { + visit(e, name, type, value); + } + + @Override + public void end(TopiaEntity e) { + if (log.isDebugEnabled()) { + log.debug("end : " + e); + } + + buffer.append("</").append(e.getClass().getName()).append(">\n"); + } + + @Override + public String toString() { + String content = buffer.toString(); + return content; + } + + @Override + public void clear() { + // do nothing + } + + +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/HqlAndParametersBuilderTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/HqlAndParametersBuilderTest.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/HqlAndParametersBuilderTest.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/HqlAndParametersBuilderTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,118 @@ +package org.nuiton.topia.it.legacy.persistence; + +/* + * #%L + * ToPIA :: Persistence + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2013 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.Lists; +import org.junit.Assert; +import org.junit.Test; +import org.nuiton.topia.persistence.HqlAndParametersBuilder; +import org.nuiton.topia.persistence.TopiaEntity; + +import java.util.Collection; + +public class HqlAndParametersBuilderTest { + + protected HqlAndParametersBuilder hqlAndParametersBuilder = + new HqlAndParametersBuilder(TopiaEntity.class); + + protected static final Collection<String> SOME_VALUES = + Lists.newArrayList("value1", "value2", "value3"); + + protected static final Collection<String> SOME_VALUES_WITH_NULL = + Lists.newArrayList("value1", "value2", null, "value3"); + + @Test + public void testFindAvailableHqlParameterName() { + + String availableHqlParameterName1 = hqlAndParametersBuilder.putHqlParameterWithAvailableName("survey.topiaId", "topiaId1"); + String availableHqlParameterName2 = hqlAndParametersBuilder.putHqlParameterWithAvailableName("survey.topiaId", "topiaId1"); + + Assert.assertNotEquals(availableHqlParameterName1, availableHqlParameterName2); + Assert.assertFalse(availableHqlParameterName1.contains(".")); + Assert.assertFalse(availableHqlParameterName2.contains(".")); + + } + + @Test + public void testEqualsNull() { + + hqlAndParametersBuilder.addEquals("myProp", null); + + String actualHql = hqlAndParametersBuilder.getHql(); + + Assert.assertFalse(actualHql.contains("myProp = null")); + Assert.assertTrue(actualHql.contains("myProp is null")); + + } + + @Test + public void testAddInWithNull() { + + hqlAndParametersBuilder.addIn("myProp", SOME_VALUES_WITH_NULL); + + String actualHql = hqlAndParametersBuilder.getHql(); + + Assert.assertTrue(actualHql.contains("myProp is null or topiaEntity_.myProp in (")); + Assert.assertEquals( + SOME_VALUES_WITH_NULL.size() - 1, // there should be as many argument as in collection minus 1 because null is removed + hqlAndParametersBuilder.getHqlParameters().size()); + + } + + @Test + public void testAddNotEqualsToValue() { + + hqlAndParametersBuilder.addNotEquals("myProp", "value"); + + String actualHql = hqlAndParametersBuilder.getHql(); + + Assert.assertTrue(actualHql.contains("myProp != ")); + Assert.assertFalse(actualHql.contains("myProp = ")); + + } + + @Test + public void testAddNotEqualsToNull() { + + hqlAndParametersBuilder.addNotEquals("myProp", null); + + String actualHql = hqlAndParametersBuilder.getHql(); + + Assert.assertTrue(actualHql.contains("myProp is not null")); + + } + + @Test + public void testAddNotInWithNull() { + + hqlAndParametersBuilder.addNotIn("myProp", SOME_VALUES_WITH_NULL); + + String actualHql = hqlAndParametersBuilder.getHql(); + + Assert.assertTrue(actualHql.contains("myProp is not null and ")); + + } + +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/NaturalIdTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/NaturalIdTest.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/NaturalIdTest.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/NaturalIdTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,185 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2010 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ + +package org.nuiton.topia.persistence; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.hibernate.PropertyValueException; +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.nuiton.topia.TopiaDatabase; +import org.nuiton.topia.TopiaException; +import org.nuiton.topia.TopiaTestDAOHelper; +import org.nuiton.topia.TopiaTestTopiaPersistenceContext; +import org.nuiton.topiatest.NaturalizedEntity; +import org.nuiton.topiatest.NaturalizedEntityDAO; + +/** + * NaturalIdTest + * <p/> + * Created: 18 févr. 2010 + * + * @author fdesbois + * @version $Revision$ + * <p/> + * Mise a jour: $Date$ + * par : $Author$ + */ +public class NaturalIdTest { + + private static final Log log = LogFactory.getLog(NaturalIdTest.class); + + @Rule + public final TopiaDatabase db = new TopiaDatabase(); + + @Test + public void testCreateSucessfull() throws Exception { + log.debug("Test naturalId : create succesfull"); + TopiaTestTopiaPersistenceContext persistenceContext = db.beginTransaction(); + + NaturalizedEntityDAO dao = + persistenceContext.getNaturalizedEntityDao(); + + // No exception will be thrown with the two properties + dao.createByNaturalId(5, "str"); + persistenceContext.commitTransaction(); + + // No exception will only the need property + dao.createByNotNull(3); + persistenceContext.commitTransaction(); + + // No exception will only the need property + dao.create(NaturalizedEntity.PROPERTY_NATURAL_ID_NOT_NULL, 3); + persistenceContext.commitTransaction(); + } + + @Test + public void testCreateFailed() throws Exception { + log.debug("Test naturalId : create failed"); + TopiaTestTopiaPersistenceContext persistenceContext = db.beginTransaction(); + + NaturalizedEntityDAO dao = + persistenceContext.getNaturalizedEntityDao(); + + // Exception will be throw + try { + dao.create(); + persistenceContext.commitTransaction(); + + // Note : this is possible to create an empty entity if the type + // is primitive like 'int' which have a default value of '0' + } catch (TopiaException eee) { + Assert.assertNotNull(eee.getCause()); + Assert.assertTrue(eee.getCause() instanceof PropertyValueException); + Assert.assertEquals("naturalIdNotNull", ((PropertyValueException)eee.getCause()).getPropertyName()); + } +// catch (PropertyValueException eee) { +// Assert.assertEquals("naturalIdNotNull", eee.getPropertyName()); +// } + } + + @Test + public void testUpdateFailed() throws Exception { + log.debug("Test naturalId : update failed"); + + TopiaTestTopiaPersistenceContext persistenceContext = db.beginTransaction(); + + NaturalizedEntityDAO dao = + persistenceContext.getNaturalizedEntityDao(); + + NaturalizedEntity entity = + dao.createByNaturalId(5, "str"); + persistenceContext.commitTransaction(); + + // Exception will be throw : not allowed to modify a naturalId property + try { + entity.setNaturalIdNotNull(8); + persistenceContext.commitTransaction(); + } catch (TopiaException eee) { + Assert.assertEquals("org.hibernate.HibernateException", + eee.getCause().getClass().getName()); + } + } + + @Test + public void testFindByNaturalId() throws Exception { + log.debug("Test naturalId : findByNaturalId"); + TopiaTestTopiaPersistenceContext persistenceContext = db.beginTransaction(); + + + NaturalizedEntityDAO dao = + persistenceContext.getNaturalizedEntityDao(); + + NaturalizedEntity entity = + dao.createByNaturalId(5, "str"); + persistenceContext.commitTransaction(); + + NaturalizedEntity result = dao.findByNaturalId(5, "str"); + + Assert.assertEquals(entity, result); + } + + @Test + public void testExistNaturalId() throws Exception { + log.debug("Test naturalId : existNaturalId"); + TopiaTestTopiaPersistenceContext persistenceContext = db.beginTransaction(); + + + NaturalizedEntityDAO dao = + persistenceContext.getNaturalizedEntityDao(); + + dao.createByNaturalId(5, "str"); + persistenceContext.commitTransaction(); + + boolean result = dao.existByNaturalId(5, "str"); + + Assert.assertTrue(result); + + // not find with only one correct property + result = dao.existByNaturalId(8, "str"); + + Assert.assertFalse(result); + } + + @Test + public void testNaturalIdAreGeneralized() throws Exception { + + // test that natural ids are generalized + String[] generalizedNaturalizedNaturalIds = TopiaTestDAOHelper.TopiaTestEntityEnum.GeneralizedNaturalizedEntity.getNaturalIds(); + String[] naturalizedNaturalIds = TopiaTestDAOHelper.TopiaTestEntityEnum.NaturalizedEntity.getNaturalIds(); + Assert.assertArrayEquals(generalizedNaturalizedNaturalIds, naturalizedNaturalIds); + } + + @Test + public void testNotNullsAreGeneralized() throws Exception { + + // test that not nulls are generalized + String[] generalizedNaturalizedNotNulls = TopiaTestDAOHelper.TopiaTestEntityEnum.GeneralizedNaturalizedEntity.getNotNulls(); + String[] naturalizedNotNulls = TopiaTestDAOHelper.TopiaTestEntityEnum.NaturalizedEntity.getNotNulls(); + Assert.assertArrayEquals(generalizedNaturalizedNotNulls, naturalizedNotNulls); + } +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/TopiaDAOTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/TopiaDAOTest.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/TopiaDAOTest.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/TopiaDAOTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,201 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2010 CodeLutin, Chatellier Eric + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ + +package org.nuiton.topia.persistence; + +import java.util.List; + +import org.hamcrest.CoreMatchers; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.nuiton.topia.TopiaDatabase; +import org.nuiton.topia.TopiaException; +import org.nuiton.topia.TopiaTestTopiaPersistenceContext; +import org.nuiton.topia.test.entities.Person; +import org.nuiton.topia.test.entities.PersonDAO; + +import com.google.common.collect.Lists; + +/** + * Test on {@link TopiaDAO}. + * <p/> + * Last update : $Date$ + * By : $Author$ + * + * @author chatellier + * @version $Revision$ + */ +public class TopiaDAOTest { + + @Rule + public final TopiaDatabase db = new TopiaDatabase(); + + protected TopiaTestTopiaPersistenceContext context; + + protected PersonDAO dao; + + @Before + public void setup() throws TopiaException { + + context = db.beginTransaction(); + dao = context.getPersonDao(); + } + + /** + * Test de creer une entité et de verifier qu'elle est + * présente dans la persistence au sein de la transaction. + * + * @throws Exception if any exception while test + */ + @Test + public void testCreateAndFindInTransaction() throws Exception { + + // appel 1 find all + createPerson("toto"); + List<Person> allPerson = dao.findAll(); + Assert.assertEquals(1, allPerson.size()); + context.commitTransaction(); + + // recherce la personne créée dans la même transaction + Person person2 = createPerson("titi"); + allPerson = dao.findAll(); + Assert.assertEquals(2, allPerson.size()); + Assert.assertThat(allPerson, CoreMatchers.hasItem(person2)); + + context.rollbackTransaction(); + + // meme test apres roolback + Person person3 = createPerson("tata"); + allPerson = dao.findAll(); + Assert.assertEquals(2, allPerson.size()); + Assert.assertThat(allPerson, CoreMatchers.hasItem(person3)); + + context.commitTransaction(); + } + + @Test + public void findAllLazyByQuery() throws TopiaException { + + Assert.assertEquals(dao.count(), 0); + + createPersons(101); + + Iterable<Person> allByLazy = dao.findAllLazyByQuery( + 100, + "FROM " + dao.getTopiaEntityEnum().getImplementationFQN() + " ORDER BY id"); + + List<Person> actual = Lists.newArrayList(); + + for (Person person : allByLazy) { + actual.add(person); + } + Assert.assertEquals(dao.count(), actual.size()); + + allByLazy = dao.findAllLazyByQuery( + 54, + "FROM " + dao.getTopiaEntityEnum().getImplementationFQN() + " ORDER BY id"); + + actual = Lists.newArrayList(); + + for (Person person : allByLazy) { + actual.add(person); + } + Assert.assertEquals(dao.count(), actual.size()); + + allByLazy = dao.findAllLazyByQuery( + 49, + "FROM " + dao.getTopiaEntityEnum().getImplementationFQN() + " ORDER BY id"); + + actual = Lists.newArrayList(); + + for (Person person : allByLazy) { + actual.add(person); + } + Assert.assertEquals(dao.count(), actual.size()); + + allByLazy = dao.findAllLazyByQuery( + 101, + "FROM " + dao.getTopiaEntityEnum().getImplementationFQN() + " ORDER BY id"); + + actual = Lists.newArrayList(); + + for (Person person : allByLazy) { + actual.add(person); + } + Assert.assertEquals(dao.count(), actual.size()); + + allByLazy = dao.findAllLazyByQuery( + 102, + "FROM " + dao.getTopiaEntityEnum().getImplementationFQN() + " ORDER BY id"); + + actual = Lists.newArrayList(); + + for (Person person : allByLazy) { + actual.add(person); + } + Assert.assertEquals(dao.count(), actual.size()); + } + + @Test + public void iterateOnTopiaDAO() throws TopiaException { + + createPersons(1999); + + List<Person> excepted = dao.findAll(); + + List<Person> actual = Lists.newArrayList(); + + for (Person person : dao) { + Assert.assertThat(excepted, CoreMatchers.hasItem(person)); + actual.add(person); + } + Assert.assertEquals(excepted.size(), actual.size()); + + dao.setBatchSize(54); + + actual = Lists.newArrayList(); + + for (Person person : dao) { + Assert.assertThat(excepted, CoreMatchers.hasItem(person)); + actual.add(person); + } + Assert.assertEquals(excepted.size(), actual.size()); + + } + + protected void createPersons(int number) throws TopiaException { + for (int i = 0; i < number; i++) { + createPerson("toto" + i); + } + + context.commitTransaction(); + } + + protected Person createPerson(String name) throws TopiaException { + return dao.create(Person.PROPERTY_NAME, name); + } +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/CollectorTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/CollectorTest.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/CollectorTest.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/CollectorTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,124 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2010 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ + +package org.nuiton.topia.persistence.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.nuiton.topia.TopiaException; +import org.nuiton.topia.TopiaTestDAOHelper; +import org.nuiton.topia.persistence.TopiaEntity; +import org.nuiton.topia.persistence.TopiaEntityEnum; +import org.nuiton.topiatest.Company; +import org.nuiton.topiatest.CompanyImpl; +import org.nuiton.topiatest.Department; +import org.nuiton.topiatest.DepartmentImpl; +import org.nuiton.topiatest.EmployeImpl; + +/** @author tchemit <chemit@codelutin.com> */ +public class CollectorTest { + + + private static Log log = LogFactory.getLog(CollectorTest.class); + + + static TopiaEntityEnum[] contracts; + + @BeforeClass + public static void setUpClass() throws Exception { + contracts = TopiaTestDAOHelper.getContracts(); + } + + @AfterClass + public static void tearDownClass() throws Exception { + contracts = null; + } + + @Test + public void testCollector() throws Exception { + + Collector<Integer> detector = new Collector<Integer>(contracts) { + + int hits; + + @Override + protected void beforeAll(CollectorVisitor visitor, TopiaEntity... entities) { + super.beforeAll(visitor, entities); + hits = 0; + } + + @Override + protected Integer afterAll(CollectorVisitor visitor, TopiaEntity... entities) { + return hits; + } + + @Override + protected void onStarted(TopiaEntity e, boolean enter) { + super.onStarted(e, enter); + int level = stackSize(); + log.info(String.format("(%1$2d) %2$" + level * 2 + "s %3$s", level, ">>", getStack())); + + hits++; + } + + @Override + protected void onEnded(TopiaEntity e, boolean enter) { + super.onEnded(e, enter); + int level = stackSize() + 1; + log.info(String.format("(%1$2d) %2$" + level * 2 + "s %3$s", level, "<<", getStack())); + } + }; + + Company company = new CompanyImpl(); + EmployeImpl employe = new EmployeImpl(); + Department department = new DepartmentImpl(); + + detect(detector, 1, company); + + company.addEmploye(employe); + detect(detector, 2, company); + + company.addDepartment(department); + detect(detector, 3, company); + + company.removeEmploye(employe); + detect(detector, 2, company); + + company.removeDepartment(department); + detect(detector, 1, company); + } + + protected void detect(Collector<Integer> detector, + int expectedResult, + TopiaEntity... entities) throws TopiaException { + Integer result = detector.detect(entities); + Assert.assertNotNull(result); + Assert.assertEquals(expectedResult, result.intValue()); + } +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/EntityOperatorTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/EntityOperatorTest.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/EntityOperatorTest.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/EntityOperatorTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,238 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2010 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ + +package org.nuiton.topia.persistence.util; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.nuiton.topia.TopiaTestDAOHelper; +import org.nuiton.topiatest.Company; +import org.nuiton.topiatest.CompanyImpl; +import org.nuiton.topiatest.Department; +import org.nuiton.topiatest.DepartmentImpl; +import org.nuiton.topiatest.Employe; +import org.nuiton.topiatest.EmployeImpl; +import org.nuiton.topiatest.Personne; +import org.nuiton.topiatest.PersonneImpl; + +import java.util.Collection; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +/** @author tchemit <chemit@codelutin.com> */ +public class EntityOperatorTest { + + public EntityOperatorTest() { + } + + static EntityOperator<Company> operationC; + + static EntityOperator<Employe> operationE; + + static EntityOperator<Personne> operationP; + + static EntityOperator<Department> operationD; + + Company c; + + Department d; + + Employe e; + + Personne p; + + @BeforeClass + public static void setUpClass() throws Exception { + operationC = TopiaTestDAOHelper.getOperator(Company.class); + operationE = TopiaTestDAOHelper.getOperator(Employe.class); + operationP = TopiaTestDAOHelper.getOperator(Personne.class); + operationD = TopiaTestDAOHelper.getOperator(Department.class); + } + + @AfterClass + public static void tearDownClass() throws Throwable { + operationC.finalize(); + operationE.finalize(); + operationP.finalize(); + operationD.finalize(); + } + + @Before + public void setUp() { + c = new CompanyImpl(); + d = new DepartmentImpl(); + e = new EmployeImpl(); + p = new PersonneImpl(); + } + + @After + public void tearDown() { + c = null; + d = null; + e = null; + p = null; + } + + /** Test of newOperator method, of class EntityOperator. */ + @Test + public void testGet() { + + Object actual; + String name; + + e.setName(name = "name"); + actual = operationE.get(Employe.PROPERTY_NAME, e); + assertEquals(name, actual); + + actual = operationP.get(Employe.PROPERTY_NAME, e); + assertEquals(name, actual); + + actual = operationD.get(Department.PROPERTY_COMPANY, d); + assertNull(actual); + + d.setCompany(c); + actual = operationD.get(Department.PROPERTY_COMPANY, d); + assertNotNull(actual); + assertEquals(c, actual); + + actual = operationC.get(Company.PROPERTY_DEPARTMENT, c); + assertNull(actual); + + c.addDepartment(d); + actual = operationC.get(Company.PROPERTY_DEPARTMENT, c); + assertNotNull(actual); + assertFalse(((Collection<?>) actual).isEmpty()); + } + + /** Test of set method, of class EntityOperator. */ + @Test + public void testSet() { + + String name; + + operationE.set(Employe.PROPERTY_NAME, e, name = "name"); + assertEquals(name, e.getName()); + + operationP.set(Employe.PROPERTY_NAME, e, name = "name2"); + assertEquals(name, e.getName()); + } + + /** Test of getChild method, of class EntityOperator. */ + @Test + public void testGetChild() { + Object actual; + String topiaId; + + topiaId = "0"; + + actual = operationC.get(Company.PROPERTY_DEPARTMENT, c); + assertNull(actual); + + actual = operationC.getChild(Company.PROPERTY_DEPARTMENT, c, topiaId); + assertNull(actual); + + c.addDepartment(d); + + actual = operationC.get(Company.PROPERTY_DEPARTMENT, c); + assertNotNull(actual); + assertFalse(((Collection<?>) actual).isEmpty()); + + actual = operationC.getChild(Company.PROPERTY_DEPARTMENT, c, topiaId); + assertNull(actual); + + d.setTopiaId(topiaId); + actual = operationC.getChild(Company.PROPERTY_DEPARTMENT, c, topiaId); + assertNotNull(actual); + assertEquals(d, actual); + + } + + /** Test of addChild method, of class EntityOperator. */ + @Test + public void testAddChild() { + + assertTrue(c.isDepartmentEmpty()); + + operationC.addChild(Company.PROPERTY_DEPARTMENT, c, d); + assertFalse(c.isDepartmentEmpty()); + assertEquals(d, c.getDepartment().iterator().next()); + } + + /** Test of isChildEmpty method, of class EntityOperator. */ + @Test + public void testIsChildEmpty() { + + assertTrue(c.isDepartmentEmpty()); + + boolean actual = operationC.isChildEmpty(Company.PROPERTY_DEPARTMENT, c); + assertTrue(actual); + + c.addDepartment(d); + + actual = operationC.isChildEmpty(Company.PROPERTY_DEPARTMENT, c); + assertFalse(actual); + } + + /** Test of sizeChild method, of class EntityOperator. */ + @Test + public void testChildSize() { + + assertTrue(c.isDepartmentEmpty()); + + int actual = operationC.sizeChild(Company.PROPERTY_DEPARTMENT, c); + assertEquals(0, actual); + + c.addDepartment(d); + + actual = operationC.sizeChild(Company.PROPERTY_DEPARTMENT, c); + assertEquals(1, actual); + c.clearDepartment(); + + actual = operationC.sizeChild(Company.PROPERTY_DEPARTMENT, c); + assertEquals(0, actual); + } + + /** Test of removeChild method, of class EntityOperator. */ + @Test + public void testRemoveChild() { + + assertTrue(c.isDepartmentEmpty()); + + c.addDepartment(d); + + assertFalse(c.isDepartmentEmpty()); + + operationC.removeChild(Company.PROPERTY_DEPARTMENT, c, d); + + assertTrue(c.isDepartmentEmpty()); + } +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityBinderTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityBinderTest.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityBinderTest.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityBinderTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,105 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2010 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ + +package org.nuiton.topia.persistence.util; + +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.nuiton.topia.TopiaTestDAOHelper; +import org.nuiton.topia.persistence.TopiaEntity; +import org.nuiton.topia.persistence.TopiaEntityEnum; +import org.nuiton.topiatest.Company; +import org.nuiton.util.beans.Binder; +import org.nuiton.util.beans.BinderFactory; +import org.nuiton.util.beans.BinderModelBuilder; + +public class TopiaEntityBinderTest { + + static TopiaEntityEnum[] contracts; + + @BeforeClass + public static void setUpClass() throws Exception { + contracts = TopiaTestDAOHelper.getContracts(); + } + + public static class CompanyDTO { + + protected String name; + + protected int siret; + + protected String id; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getSiret() { + return siret; + } + + public void setSiret(int siret) { + this.siret = siret; + } + + public String getTopiaId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + } + + @Before + public void setUp() { + BinderFactory.clear(); + } + + @AfterClass + public static void afterClass() { + BinderFactory.clear(); + } + + @Test + public void testBinder() { + + BinderModelBuilder<Company, CompanyDTO> builder = BinderModelBuilder.newEmptyBuilder(Company.class, CompanyDTO.class); + builder.addSimpleProperties(Company.PROPERTY_NAME, Company.PROPERTY_SIRET); + builder.addProperties(TopiaEntity.PROPERTY_TOPIA_ID, "id"); + BinderFactory.registerBinderModel(builder); + + Binder<Company, CompanyDTO> binder = + BinderFactory.newBinder(Company.class, CompanyDTO.class); + Assert.assertNotNull(binder); + } +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityHelperTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityHelperTest.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityHelperTest.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityHelperTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,282 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2010 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ + +package org.nuiton.topia.persistence.util; + +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; +import org.nuiton.topia.TopiaException; +import org.nuiton.topia.TopiaTestDAOHelper; +import org.nuiton.topia.persistence.DefaultTopiaIdFactory; +import org.nuiton.topia.persistence.TopiaEntity; +import org.nuiton.topia.persistence.TopiaEntityEnum; +import org.nuiton.topia.persistence.TopiaIdFactory; +import org.nuiton.topiatest.Company; +import org.nuiton.topiatest.CompanyImpl; +import org.nuiton.topiatest.Department; +import org.nuiton.topiatest.DepartmentImpl; +import org.nuiton.topiatest.Employe; +import org.nuiton.topiatest.EmployeAbstract; +import org.nuiton.topiatest.EmployeImpl; +import org.nuiton.topiatest.Personne; +import org.nuiton.topiatest.PersonneAbstract; +import org.nuiton.topiatest.PersonneImpl; + +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +/** @author tchemit <chemit@codelutin.com> */ +public class TopiaEntityHelperTest { + + protected static TopiaIdFactory topiaIdFactory = new DefaultTopiaIdFactory(); + + protected static TopiaEntityEnum[] contracts; + + protected final Set<Class<? extends TopiaEntity>> contractsClass; + + public TopiaEntityHelperTest() { + contractsClass = new HashSet<Class<? extends TopiaEntity>>(); + contractsClass.add(Company.class); + contractsClass.add(Employe.class); + contractsClass.add(Department.class); + } + + @BeforeClass + public static void setUpClass() throws Exception { + contracts = TopiaTestDAOHelper.getContracts(); + } + + @AfterClass + public static void tearDownClass() throws Exception { + contracts = null; + } + + /** Test of getContractClass method, of class TopiaEntityHelper. */ + @Test + public void testgetContract() { + + Class<?> result = TopiaEntityHelper.getContractClass(null, Company.class); + assertNull(result); + + Class<? extends TopiaEntity> expResult; + + expResult = Employe.class; + + getContractClass(expResult, EmployeImpl.class); + getContractClass(expResult, EmployeAbstract.class); + getContractClass(expResult, Employe.class); + + expResult = Personne.class; + + getContractClass(expResult, PersonneImpl.class); + getContractClass(expResult, PersonneAbstract.class); + getContractClass(expResult, Personne.class); + } + + /** Test of retainContracts method, of class TopiaEntityHelper. */ + @Test + public void testRetainContracts() { + Set<Class<? extends TopiaEntity>> classes = new HashSet<Class<? extends TopiaEntity>>(); + Set<Class<? extends TopiaEntity>> result = TopiaEntityHelper.retainContracts(contracts, classes); + + assertTrue(result.isEmpty()); + + classes.add(PersonneImpl.class); + result = TopiaEntityHelper.retainContracts(contracts, classes); + assertEquals(1, result.size()); + assertTrue(result.contains(Personne.class)); + + classes.add(PersonneAbstract.class); + result = TopiaEntityHelper.retainContracts(contracts, classes); + assertEquals(1, result.size()); + assertTrue(result.contains(Personne.class)); + + classes.add(Personne.class); + result = TopiaEntityHelper.retainContracts(contracts, classes); + assertEquals(1, result.size()); + assertTrue(result.contains(Personne.class)); + + classes.clear(); + classes.add(EmployeImpl.class); + result = TopiaEntityHelper.retainContracts(contracts, classes); + assertEquals(1, result.size()); + assertTrue(result.contains(Employe.class)); + + classes.add(PersonneImpl.class); + result = TopiaEntityHelper.retainContracts(contracts, classes); + assertEquals(2, result.size()); + assertTrue(result.contains(Personne.class)); + assertTrue(result.contains(Employe.class)); + + } + + /** + * Test of detectTypes method, of class TopiaEntityHelper. + * + * @throws TopiaException + */ + @Test + public void testDetectTypes() throws TopiaException { + Company company = new CompanyImpl(); + EmployeImpl employe = new EmployeImpl(); + Department departmnet = new DepartmentImpl(); + + detectTypes(new Class<?>[]{Company.class, Employe.class, Department.class}, company, employe, departmnet); + + company.addEmploye(employe); + detectTypes(new Class<?>[]{Company.class, Employe.class}, company); + + company.addDepartment(departmnet); + departmnet.setCompany(company); + detectTypes(new Class<?>[]{Company.class, Employe.class, Department.class}, company); + + company.removeEmploye(employe); + company.removeDepartment(departmnet); + detectTypes(new Class<?>[]{Company.class}, company); + } + + @Test + public void testDetector() throws Exception { + + Company company = new CompanyImpl(); + company.setTopiaId(topiaIdFactory.newTopiaId(Company.class, company)); + Employe employe = new EmployeImpl(); + employe.setTopiaId(topiaIdFactory.newTopiaId(Employe.class, employe)); + Department department = new DepartmentImpl(); + department.setTopiaId(topiaIdFactory.newTopiaId(Department.class, department)); + + detectEntities(new Class<?>[]{Company.class, Employe.class, Department.class}, new int[]{1, 1, 1}, company, employe, department); + detectEntityIds(new Class<?>[]{Company.class, Employe.class, Department.class}, new int[]{1, 1, 1}, company, employe, department); + + company.addEmploye(employe); + detectEntities(new Class<?>[]{Company.class, Employe.class}, new int[]{1, 1, 1}, company); + detectEntityIds(new Class<?>[]{Company.class, Employe.class}, new int[]{1, 1, 1}, company); + + company.addDepartment(department); + department.setCompany(company); + + detectEntities(new Class<?>[]{Company.class, Employe.class, Department.class}, new int[]{1, 1, 1}, company); + detectEntityIds(new Class<?>[]{Company.class, Employe.class, Department.class}, new int[]{1, 1, 1}, company); + + company.removeEmploye(employe); + company.removeDepartment(department); + + + detectEntities(new Class<?>[]{Company.class}, new int[]{1}, company); + detectEntityIds(new Class<?>[]{Company.class}, new int[]{1}, company); + + detectEntities(new Class<?>[]{Company.class}, new int[]{2}, company, new CompanyImpl()); + detectEntityIds(new Class<?>[]{Company.class}, new int[]{2}, company, new CompanyImpl()); + + department.setCompany(company); + + detectEntities(new Class<?>[]{Company.class, Department.class}, new int[]{1, 1}, department); + detectEntityIds(new Class<?>[]{Company.class, Department.class}, new int[]{1, 1}, department); + + //TODO faire des tests avec des entites avec cycles + } + + protected void detectEntities(Class<?>[] expected, + int[] sizes, + TopiaEntity... data) throws TopiaException { + + Map<Class<? extends TopiaEntity>, List<TopiaEntity>> actual = null; + + try { + actual = TopiaEntityHelper.detectEntities(contracts, contractsClass, data); + + Assert.assertEquals(expected.length, actual.size()); + int index = 0; + for (Class<?> c : expected) { + List<TopiaEntity> value = actual.get(c); + int expectedSize = sizes[index++]; + Assert.assertEquals(expectedSize, value.size()); + } + } finally { + if (actual != null) { + actual.clear(); + } + } + } + + protected void detectEntityIds(Class<?>[] expected, + int[] sizes, + TopiaEntity... data) throws TopiaException { + + TopiaEntityIdsMap actual = null; + + try { + actual = TopiaEntityHelper.detectEntityIds(contracts, + contractsClass, + data + ); + + Assert.assertEquals(expected.length, actual.size()); + int index = 0; + for (Class<?> c : expected) { + List<String> value = actual.get(c); + int expectedSize = sizes[index++]; + Assert.assertEquals(expectedSize, value.size()); + } + } finally { + if (actual != null) { + actual.clear(); + } + } + } + + protected void detectTypes(Class<?>[] expected, TopiaEntity... data) throws TopiaException { + Set<String> fqns = new HashSet<String>(expected.length); + Set<Class<? extends TopiaEntity>> actual = null; + for (Class<?> c : expected) { + fqns.add(c.getName()); + } + try { + actual = TopiaEntityHelper.detectTypes(contracts, data); + Assert.assertEquals(expected.length, actual.size()); + for (Class<? extends TopiaEntity> c : actual) { + Assert.assertTrue(fqns.contains(c.getName())); + } + } finally { + fqns.clear(); + if (actual != null) { + actual.clear(); + } + } + } + + protected void getContractClass(Class<?> expected, Class<? extends TopiaEntity> klass) { + Class<?> result = TopiaEntityHelper.getContractClass(contracts, klass); + assertEquals(expected, result); + } +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityRefTester.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTester.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityRefTester.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityRefTester.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,331 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2010 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ + +package org.nuiton.topia.persistence.util; + +import org.junit.After; +import org.junit.Assert; +import org.nuiton.topia.TopiaException; +import org.nuiton.topia.persistence.TopiaEntity; +import org.nuiton.topia.persistence.TopiaEntityEnum; + +import java.util.Collection; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import java.util.SortedMap; + +import static java.util.Map.Entry; + +/** + * A abstract class to help testing {@link TopiaEntityRef} as detectes types, or + * detects or references. + * <p/> + * An example of use if given in the test {@link TopiaEntityRefTesterTest}. + * + * @author tchemit <chemit@codelutin.com> + * @since 2.3.1 + */ +public abstract class TopiaEntityRefTester<T extends TopiaEntityEnum> { + + protected SortedMap<TopiaEntity, List<TopiaEntityRef>> detected; + + protected Iterator<Entry<TopiaEntity, List<TopiaEntityRef>>> itr; + + protected Entry<TopiaEntity, List<TopiaEntityRef>> entry; + + protected List<TopiaEntityRef> refs; + + protected T[] contracts; + + protected int index; + + protected T[] getContracts() { + if (contracts == null) { + contracts = getContracts0(); + } + return contracts; + } + + /** @return all the {@link TopiaEntityEnum} to be used */ + protected abstract T[] getContracts0(); + + @After + public void after() { + itr = null; + entry = null; + refs = null; + detected = null; + index = 0; + } + + /** + * Creates a new entity with the given {@code topiaId} (will use the {@link + * TopiaEntityEnum#getImplementation()} class). + * + * @param constant the constant defining the entity + * @param topiaId the topia to assign + * @param <T> the type of entity + * @return the new entity + * @throws IllegalAccessException if can no access entity constructor + * @throws InstantiationException if can no instanciate the entity + */ + protected <T extends TopiaEntity> T newEntity( + TopiaEntityEnum constant, String topiaId) throws + IllegalAccessException, + InstantiationException { + Class<? extends TopiaEntity> impl = constant.getImplementation(); + TopiaEntity topiaEntity = impl.newInstance(); + topiaEntity.setTopiaId(topiaId); + return (T) topiaEntity; + } + + /** + * Obtain the reference of an association for a given entity. + * <p/> + * Example, to obtain the Pet 'pudding' on a Person : + * <pre>pet[@topiaId='pudding']</pre> + * invoke + * <pre>getAssociationRef('pet',pet);</pre> + * + * @param associationName the name of the association + * @param e the required entity + * @return the reference of the association + */ + protected String getAssociationRef(String associationName, TopiaEntity e) { + return getAssociationRef(associationName, e.getTopiaId()); + } + + /** + * Obtain the reference of an association for a given id. + * <p/> + * Example to obtain the Pet 'pudding' on a Person : + * <pre>pet[@topiaId='pudding']</pre> + * invoke + * <pre>getAssociationRef('pet','pudding');</pre> + * + * @param associationName the name of the association + * @param e the id + * @return the reference of the association + */ + protected String getAssociationRef(String associationName, String e) { + String s = String.format( + TopiaEntityHelper.ASSOCIATION_PATTERN, + associationName, + e + ); + return s; + } + + /** + * Obtain the next entry from the iterator. + * <p/> + * As a side-effect, it will increment the state {@link #index}. + */ + protected void nextEntry() { + if (!itr.hasNext()) { + throw new IllegalStateException("no more entry to get..."); + } + entry = itr.next(); + index = 0; + } + + /** + * Detects the references from the given {@code entity} which have their + * topiaId in the given list of {@code ids}. + * <p/> + * As a side-effect, it will update the states {@code detected} and set the + * iterator {@code itr} to the first position on detected entries. + * + * @param entity the entity to seek + * @param nb the required number of entries + * @param ids the ids to seek + * @throws TopiaException if any pb while visiting entities + */ + protected void detectReferences( + TopiaEntity entity, int nb, String... ids) throws TopiaException { + detected = TopiaEntityHelper.detectReferences( + getContracts(), ids, entity); + assertDetected(nb); + + } + + /** + * Detects the references from the given {@code entity} which have their + * topiaId in the given list of {@code ids}. + * <p/> + * As a side-effect, it will update the states {@code detected} and set the + * iterator {@code itr} to the first position on detected entries. + * + * @param entity the entity to seek + * @param nb the required number of entries + * @param ids the ids to seek + * @throws TopiaException if any pb while visiting entities + */ + protected void detectReferences( + Collection<? extends TopiaEntity> entity, + int nb, String... ids) throws TopiaException { + detected = TopiaEntityHelper.detectReferences( + getContracts(), ids, entity); + assertDetected(nb); + } + + /** + * Detects the type of entities fro the given {@code data}. + * + * @param expected the array of expected types + * @param data the data to seek + * @throws TopiaException if any pb while visiting data + */ + protected void detectTypes(Class<?>[] expected, + TopiaEntity... data) throws TopiaException { + Set<String> fqns = new HashSet<String>(expected.length); + Set<Class<? extends TopiaEntity>> actual = null; + for (Class<?> c : expected) { + fqns.add(c.getName()); + } + try { + actual = TopiaEntityHelper.detectTypes(getContracts(), data); + Assert.assertEquals(expected.length, actual.size()); + for (Class<? extends TopiaEntity> c : actual) { + Assert.assertTrue(fqns.contains(c.getName())); + } + } finally { + fqns.clear(); + if (actual != null) { + actual.clear(); + } + } + } + + /** + * Asserts if the given entry definition is equals to the next entry + * references on internal state state {@code entry}. + * + * @param invoker the invoker of the reference + * @param invokerProperty the access path of the reference + * @param expected the expected topia entities path to access + * reference target + */ + protected void assertNextEntityRef(TopiaEntity invoker, + String invokerProperty, + TopiaEntity... expected) { + assertEntityRef(index, invoker, invokerProperty, expected); + index++; + } + + /** + * Asserts if the given entry definition (of an association) is equals to + * the next entry reference on internal state {@code entry}. + * + * @param invoker the invoker of the reference + * @param association the association name + * @param id the id of the association ( see {@link + * #getAssociationRef(String, TopiaEntity)} + * @param expected the expected topia entities path to access reference + * target + */ + protected void assertNextAssociationEntityRef(TopiaEntity invoker, + String association, + String id, + TopiaEntity... expected) { + String invokerProperty = getAssociationRef(association, id); + assertNextEntityRef(invoker, invokerProperty, expected); + } + + /** + * Asserts if the given entry definition is equals to the reference entry at + * position {@code index} on internal state {@code entry}. + * + * @param index the index of the reference to test in {@code + * entry} + * @param invoker the invoker of the reference + * @param invokerProperty the path of the reference + * @param expected th expected topia entities path to access + * reference target + */ + protected void assertEntityRef(int index, + TopiaEntity invoker, + String invokerProperty, + TopiaEntity... expected) { + Assert.assertNotNull(refs); + Assert.assertTrue("no index [" + index + "] in refs of size " + + refs.size(), index < refs.size()); + TopiaEntityRef actual = refs.get(index); + Assert.assertEquals(actual.getInvoker(), invoker); + Assert.assertEquals(actual.getInvokerProperty(), invokerProperty); + + TopiaEntity[] path = actual.getPath(); + Assert.assertEquals(expected.length, path.length); + for (int i = 0; i < expected.length; i++) { + Assert.assertEquals(expected[i].getTopiaId(), path[i].getTopiaId()); + } + } + + /** + * Asserts if the given {@code expected} entity is equals to the source of + * the internal state {@code entry}. + * + * @param expected the required source of the entry + * @param nbPath the expected number of references of the given entry + */ + protected void assertCurrentEntry(TopiaEntity expected, + int nbPath) { + assertEntry(expected, nbPath, entry); + } + + /** + * Asserts if the given {@code entry} has a good source and a good number of + * references. + * + * @param expected the expected entry source + * @param nbPath the expected number of reference of the entry + * @param entry the entry to test + */ + private void assertEntry(TopiaEntity expected, + int nbPath, + Entry<TopiaEntity, List<TopiaEntityRef>> entry) { + Assert.assertNotNull(entry); + Assert.assertEquals(expected, entry.getKey()); + refs = entry.getValue(); + Assert.assertEquals(nbPath, refs.size()); + } + + /** + * Asserts that the number of detected entries (store in internal state + * {@code detected}) is ok. + * <p/> + * As a side-effect, it will reset the internal state {@code itr} on the + * first entry of the {@code detected} list. + * + * @param size the expected number of detected entries + */ + protected void assertDetected(int size) { + Assert.assertNotNull(detected); + Assert.assertEquals(size, detected.size()); + itr = detected.entrySet().iterator(); + } +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityRefTesterTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTesterTest.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityRefTesterTest.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/persistence/util/TopiaEntityRefTesterTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,155 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2010 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ + +package org.nuiton.topia.persistence.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.junit.Test; +import org.nuiton.topia.TopiaTestDAOHelper.TopiaTestEntityEnum; +import org.nuiton.topia.test.entities.Person; +import org.nuiton.topia.test.entities.Pet; +import org.nuiton.topia.test.entities.Race; + +/** + * Test the {@link TopiaEntityRefTester} on + * <p/> + * <ul> <li>{@link Pet}</li> <li>{@link Race}</li> <li>{@link Person}</li> + * </ul> + * + * @author tchemit <chemit@codelutin.com> + * @since 2.3.1 + */ +public class TopiaEntityRefTesterTest extends TopiaEntityRefTester<TopiaTestEntityEnum> { + + /** Logger */ + private static final Log log = + LogFactory.getLog(TopiaEntityRefTesterTest.class); + + private static final String PET1 = "pet1"; + + private static final String PET2 = "pet2"; + + private static final String RACE1 = "race1"; + + private static final String PERSON1 = "person1"; + + @Override + protected TopiaTestEntityEnum[] getContracts0() { + return new TopiaTestEntityEnum[]{ + TopiaTestEntityEnum.Pet, + TopiaTestEntityEnum.Person, + TopiaTestEntityEnum.Race, + }; + } + + @Test + public void testNoReferences() throws Exception { + + Pet pet = newEntity(TopiaTestEntityEnum.Pet, PET1); + + detectReferences(pet, 0); + + Race race = newEntity(TopiaTestEntityEnum.Race, RACE1); + + detectReferences(race, 0); + + Person person = newEntity(TopiaTestEntityEnum.Person, PERSON1); + + detectReferences(person, 0); + + } + + @Test + public void testReferences() throws Exception { + + Pet pet = newEntity(TopiaTestEntityEnum.Pet, PET1); + Race race = newEntity(TopiaTestEntityEnum.Race, RACE1); + pet.setRace(race); + Person person = newEntity(TopiaTestEntityEnum.Person, PERSON1); + + detectReferences(pet, 1, RACE1); + + nextEntry(); + assertCurrentEntry(race, 1); + assertNextEntityRef(pet, Pet.PROPERTY_RACE, pet, race); + + pet.setPerson(person); + + detectReferences(pet, 2, RACE1, PERSON1); + + nextEntry(); + assertCurrentEntry(person, 1); + assertNextEntityRef(pet, Pet.PROPERTY_PERSON, pet, person); + + nextEntry(); + assertCurrentEntry(race, 1); + assertNextEntityRef(pet, Pet.PROPERTY_RACE, pet, race); + + person.addPet(pet); + + detectReferences(person, 1, PET1); + + nextEntry(); + assertCurrentEntry(pet, 1); + assertNextAssociationEntityRef(person, Person.PROPERTY_PET, PET1, person, pet); + + Pet pet2 = newEntity(TopiaTestEntityEnum.Pet, PET2); + + person.addPet(pet2); + + detectReferences(person, 3, PET1, PET2, RACE1); + + nextEntry(); + assertCurrentEntry(pet, 1); + assertNextAssociationEntityRef(person, Person.PROPERTY_PET, PET1, person, pet); + + nextEntry(); + assertCurrentEntry(pet2, 1); + assertNextAssociationEntityRef(person, Person.PROPERTY_PET, PET2, person, pet2); + + nextEntry(); + assertCurrentEntry(race, 1); + assertNextEntityRef(pet, Pet.PROPERTY_RACE, person, pet, race); + + pet2.setRace(race); + + detectReferences(person, 3, PET1, PET2, RACE1); + + nextEntry(); + assertCurrentEntry(pet, 1); + assertNextAssociationEntityRef(person, Person.PROPERTY_PET, PET1, person, pet); + + nextEntry(); + assertCurrentEntry(pet2, 1); + assertNextAssociationEntityRef(person, Person.PROPERTY_PET, PET2, person, pet2); + + nextEntry(); + assertCurrentEntry(race, 2); + assertNextEntityRef(pet, Pet.PROPERTY_RACE, person, pet, race); + assertNextEntityRef(pet2, Pet.PROPERTY_RACE, person, pet2, race); + + } +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/ano1882/DAOAbstractTransformerTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/test/ano1882/DAOAbstractTransformerTest.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/ano1882/DAOAbstractTransformerTest.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/ano1882/DAOAbstractTransformerTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,57 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2012 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ +package org.nuiton.topia.test.ano1882; + +import org.junit.Rule; +import org.junit.Test; +import org.nuiton.topia.TopiaDatabase; +import org.nuiton.topia.TopiaTestDAOHelper; +import org.nuiton.topia.TopiaTestTopiaPersistenceContext; + +import java.util.Arrays; + +public class DAOAbstractTransformerTest { + + @Rule + public final TopiaDatabase db = new TopiaDatabase(); + + @Test + public void testAno1882() throws Exception { + TopiaTestTopiaPersistenceContext transaction = db.beginTransaction(); + + FrenchCompanyDAO dao = TopiaTestDAOHelper.getFrenchCompanyDAO(transaction); + SIRETDAO siretDAO = TopiaTestDAOHelper.getSIRETDAO(transaction); + SIRET siret = siretDAO.create(); + FrenchCompany entity = + dao.create( + FrenchCompany.PROPERTY_S_IREN, null, + FrenchCompany.PROPERTY_SIREN2, null, + FrenchCompany.PROPERTY_S_IRET, Arrays.asList(siret), + FrenchCompany.PROPERTY_SIRET2, null); + transaction.commitTransaction(); + dao.delete(entity); + transaction.commitTransaction(); + } +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/evo1912/EntityDTOTransformerTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/test/evo1912/EntityDTOTransformerTest.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/evo1912/EntityDTOTransformerTest.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/test/evo1912/EntityDTOTransformerTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,46 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2012 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ +package org.nuiton.topia.test.evo1912; + +import org.junit.Assert; +import org.junit.Test; +import org.nuiton.topiatest.CompanyDTO; + +/** @author ymartel <martel@codelutin.com> */ +public class EntityDTOTransformerTest { + + @Test + public void testEvo1912() throws Exception { + // simply test the getter/setter on id property : with the tagValue, they should be generated + CompanyDTO companyDTO = new CompanyDTO(); + String originalId = companyDTO.getTopiaId(); + Assert.assertNull(originalId); + String wantedId = "mycompany"; + companyDTO.setTopiaId(wantedId); + String updatedId = companyDTO.getTopiaId(); + Assert.assertEquals(wantedId, updatedId); + } + +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/AbstractExtraDAOEntityTopiaDao.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topiatest/AbstractExtraDAOEntityTopiaDao.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/AbstractExtraDAOEntityTopiaDao.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/AbstractExtraDAOEntityTopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,40 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2010 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ +package org.nuiton.topiatest; + +import org.nuiton.topia.TopiaException; + +/** + * Created: 26 mai 2010 + * + * @author fdesbois <fdesbois@codelutin.com> + * @version $Id$ + */ +public class AbstractExtraDAOEntityTopiaDao<E extends ExtraDAOEntity> extends GeneratedExtraDAOEntityTopiaDao<E> { + + @Override + public void extra() throws TopiaException { + } +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/EnumTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topiatest/EnumTest.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/EnumTest.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/EnumTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,75 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2011 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ +package org.nuiton.topiatest; + +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.nuiton.topia.TopiaDatabase; +import org.nuiton.topia.TopiaException; +import org.nuiton.topia.TopiaTestDAOHelper; +import org.nuiton.topia.TopiaTestTopiaPersistenceContext; + +/** + * Test the support of possibility to have an attribute of type enumeration + * in a entity + */ +public class EnumTest { + + @Rule + public final TopiaDatabase db = new TopiaDatabase(); + + /** + * Create an entity having two field of type enumeration. One is stored + * using ordinal, the other using the name. + * <p/> + * The test check that values are stored, and that find methods works + * + * @throws TopiaException if any exception with db + */ + @Test + public void storeEntityWithEnumValue() throws TopiaException { + TopiaTestTopiaPersistenceContext transaction = db.beginTransaction(); + + PersonneDAO dao = TopiaTestDAOHelper.getPersonneDAO(transaction); + Personne personne = new PersonneImpl(); + personne.setGender(Gender.FEMALE); + personne.setOtherGender(Gender.MALE); + dao.create(personne); + String topiaId = personne.getTopiaId(); + transaction.commitTransaction(); + transaction.closeContext(); + + transaction = db.beginTransaction(); + dao = TopiaTestDAOHelper.getPersonneDAO(transaction); + dao.findByTopiaId(topiaId); + Assert.assertEquals(Gender.FEMALE, personne.getGender()); + Assert.assertEquals(Gender.MALE, personne.getOtherGender()); + + Assert.assertNotNull(dao.findByGender(Gender.FEMALE)); + Assert.assertNotNull(dao.findByOtherGender(Gender.MALE)); + transaction.closeContext(); + } +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/Gender.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topiatest/Gender.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/Gender.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/Gender.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,29 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2011 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ +package org.nuiton.topiatest; + +public enum Gender { + MALE, FEMALE +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/Title.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topiatest/Title.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/Title.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/Title.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,37 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2011 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ +package org.nuiton.topiatest; + +/** + * To test http://nuiton.org/issues/1732. + * + * @author tchemit <chemit@codelutin.com> + * @since 2.6.2 + */ +public enum Title { + Mr, + Madam, + Other +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/beangen/RoueImpl.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topiatest/beangen/RoueImpl.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/beangen/RoueImpl.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/beangen/RoueImpl.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,53 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2010 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ + +package org.nuiton.topiatest.beangen; + +import org.nuiton.topiatest.Product; + +/** + * RoueImpl + * + * Created: 14 janv. 2010 + * + * @author fdesbois + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ +public class RoueImpl extends Roue { + + @Override + public void mount() { + throw new UnsupportedOperationException("Not supported yet."); + } + + @Override + public Product getModel(String id) { + throw new UnsupportedOperationException("Not supported yet."); + } + +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/AbstractContact2TopiaDao.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topiatest/deletetest/AbstractContact2TopiaDao.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/AbstractContact2TopiaDao.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/AbstractContact2TopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,51 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2010 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ + +package org.nuiton.topiatest.deletetest; + + +import org.nuiton.topia.TopiaException; +import org.nuiton.topiatest.Company; +import org.nuiton.topiatest.Employe; + +import java.util.Set; +import java.util.TreeSet; + +/** + * + * @author desbois + */ +public class AbstractContact2TopiaDao<E extends Contact2> extends GeneratedContact2TopiaDao<E> { + + @Override + public Set<Contact2> findAllByCompany(Company company) throws TopiaException { + Set<Contact2> contacts = new TreeSet<Contact2>(); + for (Employe e : company.getEmploye()) { + contacts.addAll(e.getContacts()); + } + return contacts; + } + +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/DeleteEntityTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topiatest/deletetest/DeleteEntityTest.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/DeleteEntityTest.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/deletetest/DeleteEntityTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,206 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2010 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ + + +/** + * DeleteEntityTest.java + * + * Created: 4 juin 2009 + * + * @author Florian Desbois <fdesbois@codelutin.com> + * @version $Revision$ + * + * Mise a jour: $Date$ + * par : $Author$ + */ + +package org.nuiton.topiatest.deletetest; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.junit.Assert; +import org.junit.Rule; +import org.junit.Test; +import org.nuiton.topia.TopiaDatabase; +import org.nuiton.topia.TopiaException; +import org.nuiton.topia.TopiaTestDAOHelper; +import org.nuiton.topia.TopiaTestTopiaPersistenceContext; +import org.nuiton.topiatest.Gender; +import org.nuiton.topiatest.Personne; +import org.nuiton.topiatest.PersonneDAO; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +/** + * Deleting tests with DAO and Entities generated with ToPIA (diagram + * delete-test in topiatest.zargo). Different case of deleting, with inheritance + * or NMultiplicity relationship between two entities, or both. Initiate from an + * issue with DAOAbstractGenerator delete method generation. Tests with H2 + * Database. Configuration in src/test/resources/TopiaContextImpl.properties + */ +public class DeleteEntityTest { + + private static final Log log = LogFactory.getLog(DeleteEntityTest.class); + + @Rule + public final TopiaDatabase db = new TopiaDatabase(); + + /** + * Test for deleting entities with inheritance. Delete from the DAO linked + * with the subclass entity and from the DAO linked with the superclass + * entity. In the test model, the two entities have NMultiplicity + * relationship without association class entity. + * + * @throws TopiaException if any exception while manipulating db + */ + @Test + public void testDeleteEntityWithInheritance() throws TopiaException { + log.debug("START TEST : testDeleteEntityWithInheritance"); + + TopiaTestTopiaPersistenceContext transaction = db.beginTransaction(); + + log.debug("DAO : PersonneDAO"); + PersonneDAO dao = TopiaTestDAOHelper.getPersonneDAO(transaction); + + log.debug("CREATE PERSONNE : Bob Marley"); + Personne personne = dao.create(Personne.PROPERTY_NAME, "Bob Marley"); + transaction.commitTransaction(); + String idPersonne = personne.getTopiaId(); + assertNotNull(idPersonne); + log.debug("ENTITY PERSONNE SAVED !"); + + log.debug("DELETE PERSONNE"); + dao.delete(personne); + transaction.commitTransaction(); + Personne res = dao.forTopiaIdEquals(idPersonne).findAnyOrNull(); + assertNull(res); + log.debug("ENTITY PERSONNE DELETED !"); + + log.debug("CREATE PERSONNE : Ziggy Marley"); + Personne personne2 = dao.create(Personne.PROPERTY_NAME, "Ziggy Marley"); + transaction.commitTransaction(); + String idPersonne2 = personne2.getTopiaId(); + assertNotNull(idPersonne2); + log.debug("ENTITY PERSONNE SAVED !"); + + log.debug("DAO parent (abstract) : PartyDAO"); + Party2DAO dao2 = TopiaTestDAOHelper.getParty2DAO(transaction); + + log.debug("DELETE PERSONNE with PartyDAO"); + dao2.delete(personne2); + transaction.commitTransaction(); + Party2 res2 = dao2.forTopiaIdEquals(idPersonne2).findAnyOrNull(); + assertNull(res2); + log.debug("ENTITY PERSONNE DELETED !"); + + + } + + /** + * Test for deleting entities with NMultiplicity relation without + * association class entity. Test DAO generation for deleting references + * between two entities with NMultiplicity relation. In the test model, the + * two entities have both inheritance. + * + * @throws TopiaException if any exception while manipulating db + */ + @Test + public void testDeleteEntityWithManyToManyRelation() throws TopiaException { + log.debug("START TEST : testDeleteEntityWithManyToManyRelation"); + + TopiaTestTopiaPersistenceContext transaction = db.beginTransaction(); + + PersonneDAO dao = TopiaTestDAOHelper.getPersonneDAO(transaction); + + log.debug("CREATE PERSONNE : Bob Marley"); + Personne personne = dao.create(Personne.PROPERTY_NAME, "Bob Marley"); + transaction.commitTransaction(); + String idPersonne = personne.getTopiaId(); + assertNotNull(idPersonne); + log.debug("ENTITY PERSONNE SAVED !"); + + Contact2DAO contactDAO = TopiaTestDAOHelper.getContact2DAO(transaction); + + log.debug("CREATE CONTACT : jaja@codelutin.com"); + Contact2 contact = contactDAO.create(Contact2.PROPERTY_CONTACT_VALUE, "jaja@codelutin.com"); + transaction.commitTransaction(); + String idContact = contact.getTopiaId(); + assertNotNull(idContact); + log.debug("ENTITY CONTACT SAVED !"); + + log.debug("ADD CONTACT TO PERSONNE"); + personne.addContacts(contact); + transaction.commitTransaction(); + assertEquals(1, personne.getContacts().size()); + log.debug("CONTACT ADDED !"); + + log.debug("DELETE PERSONNE"); + dao.delete(personne); + transaction.commitTransaction(); + Personne res = dao.forTopiaIdEquals(idPersonne).findAnyOrNull(); + assertNull(res); + log.debug("ENTITY PERSONNE DELETED !"); + + assertEquals(0, contact.getParty2().size()); + + log.debug("DELETE CONTACT"); + contactDAO.delete(contact); + transaction.commitTransaction(); + Contact2 res2 = contactDAO.forTopiaIdEquals(idContact).findAnyOrNull(); + assertNull(res2); + log.debug("ENTITY PERSONNE DELETED !"); + + } + + /** + * Test than deleting entities will modify isPersisted() result + */ + @Test + public void testIsPersisted() { + log.debug("START TEST : testIsPersisted"); + + TopiaTestTopiaPersistenceContext transaction = db.beginTransaction(); + + PersonneDAO dao = TopiaTestDAOHelper.getPersonneDAO(transaction); + + Personne person = dao.newInstance(); + Assert.assertNull(person.getTopiaId()); + + person.setName("Arno"); + person.setGender(Gender.MALE); + Assert.assertFalse(person.isPersisted()); + + Personne person2 = dao.create(person); + Assert.assertTrue(person.isPersisted()); + Assert.assertTrue(person2.isPersisted()); + + dao.delete(person2); + Assert.assertFalse(person.isPersisted()); + Assert.assertFalse(person2.isPersisted()); + } + +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,49 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2010 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ +package org.nuiton.topia.it.legacy.topiatest.persistence; + +import org.nuiton.topia.persistence.TopiaEntity; + +/** + * Created: 11 mai 2010 + * + * @author fdesbois <fdesbois@codelutin.com> + * @version $Id$ + */ +public interface Entity1 extends TopiaEntity { + + String ATTR_1 = "attr1"; + + String ATTR_2 = "attr2"; + + String getAttr1(); + + void setAttr1(String attr1); + + String getAttr2(); + + void setAttr2(String attr2); + +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Abstract.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1Abstract.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Abstract.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Abstract.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,83 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2010 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ +package org.nuiton.topia.it.legacy.topiatest.persistence; + +import org.nuiton.topia.TopiaException; +import org.nuiton.topia.persistence.EntityVisitor; +import org.nuiton.topia.persistence.TopiaEntityAbstract; + +/** + * Created: 11 mai 2010 + * + * @author fdesbois <fdesbois@codelutin.com> + * @version $Id$ + */ +public abstract class Entity1Abstract extends TopiaEntityAbstract + implements Entity1 { + + protected String attr1; + + protected String attr2; + + @Override + public String getAttr1() { + fireOnPreRead(ATTR_1, attr1); + String result = attr1; + fireOnPostRead(ATTR_1, attr1); + return result; + } + + @Override + public void setAttr1(String attr1) { + String _oldValue = this.attr1; + fireOnPreWrite(ATTR_1, _oldValue, attr1); + this.attr1 = attr1; + fireOnPostWrite(ATTR_1, _oldValue, attr1); + } + + @Override + public String getAttr2() { + fireOnPreRead(ATTR_2, attr2); + String result = attr2; + fireOnPostRead(ATTR_2, attr2); + return result; + } + + @Override + public void setAttr2(String attr2) { + String _oldValue = this.attr2; + fireOnPreWrite(ATTR_2, _oldValue, attr2); + this.attr2 = attr2; + fireOnPostWrite(ATTR_2, _oldValue, attr2); + } + + @Override + public void accept(EntityVisitor visitor) throws TopiaException { + visitor.start(this); + visitor.visit(this, ATTR_1, String.class, attr1); + visitor.visit(this, ATTR_2, String.class, attr2); + visitor.end(this); + } +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Impl.hbm.xml (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1Impl.hbm.xml) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Impl.hbm.xml (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Impl.hbm.xml 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,37 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + #%L + ToPIA :: Persistence + + $Id$ + $HeadURL$ + %% + Copyright (C) 2004 - 2010 CodeLutin + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Lesser Public License for more details. + + You should have received a copy of the GNU General Lesser Public + License along with this program. If not, see + <http://www.gnu.org/licenses/lgpl-3.0.html>. + #L% + --> + +<!--<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">--> +<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> +<hibernate-mapping default-access="field" auto-import="true" package="org.nuiton.topia.it.legacy.topiatest"> + <class name="org.nuiton.topia.it.legacy.topiatest.persistence.Entity1Impl" table="entity1" node="org.nuiton.topia.it.legacy.topiatest.persistence.Entity1Impl" abstract="false" proxy="org.nuiton.topia.it.legacy.topiatest.persistence.Entity1" > + <id name="topiaId" type="string" length="255" node="@topiaId"/> + <version name="topiaVersion" type="long" node="@topiaVersion"/> + <property name="topiaCreateDate" type="timestamp" node="@topiaCreateDate"/> + <property name="attr1" type="java.lang.String" access="field" column="attr1" node="attr1"/> + <property name="attr2" type="java.lang.String" access="field" column="attr2" node="attr2"/> + </class> +</hibernate-mapping> Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Impl.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1Impl.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Impl.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/Entity1Impl.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,37 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2010 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ +package org.nuiton.topia.it.legacy.topiatest.persistence; + +import org.nuiton.topia.TopiaException; +import org.nuiton.topia.persistence.EntityVisitor; + +/** + * Created: 11 mai 2010 + * + * @author fdesbois <fdesbois@codelutin.com> + * @version $Id$ + */ +public class Entity1Impl extends Entity1Abstract { +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/package-info.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/package-info.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/package-info.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/persistence/package-info.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,28 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2010 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ +/** + * Contains persistent entities for Tests. + */ +package org.nuiton.topiatest.persistence; \ No newline at end of file Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/FakeService.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topiatest/service/FakeService.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/FakeService.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/FakeService.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,63 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2010 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ +package org.nuiton.topia.it.legacy.topiatest.service; + +import org.nuiton.topia.TopiaContext; +import org.nuiton.topia.framework.TopiaContextImplTest; +import org.nuiton.topia.framework.TopiaService; + +/** + * FakeService which implements {@link TopiaService} to test existing service + * from {@link TopiaContextImplTest#testGetServices()}. This fake service + * doesn't contains property SERVICE_NAME used by {@link + * org.nuiton.topia.framework.AbstractTopiaContext#serviceEnabled(Class)}. + * <p/> + * Created: 10 mai 2010 + * + * @author fdesbois <fdesbois@codelutin.com> + * @version $Id$ + */ +public class FakeService implements TopiaService { + + @Override + public String getServiceName() { + return "fake"; + } + + @Override + public Class<?>[] getPersistenceClasses() { + return new Class<?>[0]; + } + + @Override + public boolean preInit(TopiaContext context) { + return true; + } + + @Override + public boolean postInit(TopiaContext context) { + return true; + } +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/TestService.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topiatest/service/TestService.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/TestService.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/TestService.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,66 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2010 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ +package org.nuiton.topia.it.legacy.topiatest.service; + +import org.junit.Ignore; +import org.nuiton.topia.TopiaContext; +import org.nuiton.topia.framework.TopiaContextImplTest; +import org.nuiton.topia.framework.TopiaService; + +/** + * TestService which implements {@link TopiaService} to test loading from {@link + * TopiaContextImplTest#testLoadServices()}. + * <p/> + * Created: 10 mai 2010 + * + * @author fdesbois <fdesbois@codelutin.com> + * @version $Id$ + */ +@Ignore +public class TestService implements TopiaService { + + /** Needed field to use {@link TopiaContext#serviceEnabled(Class)} * */ + public static final String SERVICE_NAME = "test"; + + @Override + public String getServiceName() { + return SERVICE_NAME; + } + + @Override + public Class<?>[] getPersistenceClasses() { + return new Class<?>[0]; + } + + @Override + public boolean preInit(TopiaContext context) { + return true; + } + + @Override + public boolean postInit(TopiaContext context) { + return true; + } +} Copied: trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/package-info.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topiatest/service/package-info.java) =================================================================== --- trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/package-info.java (rev 0) +++ trunk/topia-it/src/test/java/org/nuiton/topia/it/legacy/topiatest/service/package-info.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,29 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2010 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ +/** + * This package contains classes which implements {@link + * org.nuiton.topia.framework.TopiaService} to test services API. + */ +package org.nuiton.topia.it.legacy.topiatest.service; \ No newline at end of file Copied: trunk/topia-it/src/test/resources/TopiaConnectionProviderHardcoded.properties (from rev 2882, trunk/topia-persistence/src/test/resources/TopiaConnectionProviderHardcoded.properties) =================================================================== --- trunk/topia-it/src/test/resources/TopiaConnectionProviderHardcoded.properties (rev 0) +++ trunk/topia-it/src/test/resources/TopiaConnectionProviderHardcoded.properties 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,35 @@ +### +# #%L +# ToPIA :: Persistence +# +# $Id$ +# $HeadURL$ +# %% +# Copyright (C) 2004 - 2010 CodeLutin +# %% +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Lesser Public License for more details. +# +# You should have received a copy of the GNU General Lesser Public +# License along with this program. If not, see +# <http://www.gnu.org/licenses/lgpl-3.0.html>. +# #L% +### +# Proprietes par defaut pour une base de donnees de type H2 +hibernate.hbm2ddl.auto=update +hibernate.show_sql=false + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.connection.username=sa +hibernate.connection.password= +hibernate.connection.driver_class=org.h2.Driver +hibernate.connection.provider_class=org.nuiton.topia.it.legacy.framework.TopiaConnectionProviderHardCoded +# tchemit 2010-11-28 : comment this line, each test must define his own db path +#hibernate.connection.url=jdbc:h2:file:target/surefire-workdir/h2data \ No newline at end of file Copied: trunk/topia-it/src/test/resources/TopiaContextImpl.properties (from rev 2882, trunk/topia-persistence/src/test/resources/TopiaContextImpl.properties) =================================================================== --- trunk/topia-it/src/test/resources/TopiaContextImpl.properties (rev 0) +++ trunk/topia-it/src/test/resources/TopiaContextImpl.properties 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,34 @@ +### +# #%L +# ToPIA :: Persistence +# +# $Id$ +# $HeadURL$ +# %% +# Copyright (C) 2004 - 2010 CodeLutin +# %% +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Lesser Public License for more details. +# +# You should have received a copy of the GNU General Lesser Public +# License along with this program. If not, see +# <http://www.gnu.org/licenses/lgpl-3.0.html>. +# #L% +### +# Proprietes par defaut pour une base de donnees de type H2 +hibernate.hbm2ddl.auto=update +hibernate.show_sql=false + +hibernate.dialect=org.hibernate.dialect.H2Dialect +hibernate.connection.username=sa +hibernate.connection.password= +hibernate.connection.driver_class=org.h2.Driver +# tchemit 2010-11-28 : comment this line, each test must define his own db path +#hibernate.connection.url=jdbc:h2:file:target/surefire-workdir/h2data \ No newline at end of file Copied: trunk/topia-it/src/test/resources/log4j.properties (from rev 2882, trunk/topia-persistence/src/test/resources/log4j.properties) =================================================================== --- trunk/topia-it/src/test/resources/log4j.properties (rev 0) +++ trunk/topia-it/src/test/resources/log4j.properties 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,36 @@ +### +# #%L +# ToPIA :: Persistence +# +# $Id$ +# $HeadURL$ +# %% +# Copyright (C) 2004 - 2010 CodeLutin +# %% +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Lesser Public License for more details. +# +# You should have received a copy of the GNU General Lesser Public +# License along with this program. If not, see +# <http://www.gnu.org/licenses/lgpl-3.0.html>. +# #L% +### +#\u00a0This log is used to display trace in generation + +# Global logging configuration +log4j.rootLogger=WARN, stdout +# Console output... +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) %M - %m%n +# package level +log4j.logger.org.nuiton.topia=INFO +#log4j.logger.org.nuiton.topiatest=DEBUG +log4j.logger.org.nuiton.topia.persistence.util=INFO Property changes on: trunk/topia-junit ___________________________________________________________________ Added: svn:ignore + target *.ipr *.iws *.iml .idea Property changes on: trunk/topia-junit/LICENSE.txt ___________________________________________________________________ Added: svn:keywords + Author Date Id Revision Added: svn:eol-style + native Property changes on: trunk/topia-junit/README.txt ___________________________________________________________________ Added: svn:keywords + Author Date Id Revision Added: svn:eol-style + native Added: trunk/topia-junit/pom.xml =================================================================== --- trunk/topia-junit/pom.xml (rev 0) +++ trunk/topia-junit/pom.xml 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,112 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + #%L + ToPIA :: Persistence + + $Id$ + $HeadURL: http://svn.nuiton.org/svn/topia/trunk/topia-persistence/pom.xml $ + %% + Copyright (C) 2004 - 2010 CodeLutin + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Lesser Public License for more details. + + You should have received a copy of the GNU General Lesser Public + License along with this program. If not, see + <http://www.gnu.org/licenses/lgpl-3.0.html>. + #L% + --> + +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>org.nuiton</groupId> + <artifactId>topia</artifactId> + <version>3.0-SNAPSHOT</version> + </parent> + + <groupId>org.nuiton.topia</groupId> + <artifactId>topia-junit</artifactId> + <packaging>jar</packaging> + + <name>ToPIA :: JUnit</name> + <description>JUnit</description> + + <dependencies> + + <dependency> + <groupId>${project.groupId}</groupId> + <artifactId>topia-persistence</artifactId> + <version>${project.version}</version> + </dependency> + + <dependency> + <groupId>org.nuiton</groupId> + <artifactId>nuiton-utils</artifactId> + </dependency> + + <dependency> + <groupId>commons-collections</groupId> + <artifactId>commons-collections</artifactId> + </dependency> + + <dependency> + <groupId>commons-logging</groupId> + <artifactId>commons-logging</artifactId> + </dependency> + + <dependency> + <groupId>commons-io</groupId> + <artifactId>commons-io</artifactId> + </dependency> + + <dependency> + <groupId>org.apache.commons</groupId> + <artifactId>commons-lang3</artifactId> + </dependency> + + <dependency> + <groupId>org.hibernate</groupId> + <artifactId>hibernate-core</artifactId> + </dependency> + <dependency> + <groupId>org.hibernate</groupId> + <artifactId>hibernate-ehcache</artifactId> + </dependency> + + <dependency> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-log4j12</artifactId> + </dependency> + + <!-- BD H2 for testing --> + <dependency> + <groupId>com.h2database</groupId> + <artifactId>h2</artifactId> + </dependency> + + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + <scope>compile</scope> + </dependency> + + + </dependencies> + + <build> + + <plugins> + + </plugins> + </build> + +</project> Property changes on: trunk/topia-junit/pom.xml ___________________________________________________________________ Added: svn:mime-type + text/xml Added: svn:keywords + Author Date Id Revision Added: svn:eol-style + native Modified: trunk/topia-persistence/pom.xml =================================================================== --- trunk/topia-persistence/pom.xml 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/pom.xml 2013-11-22 18:03:47 UTC (rev 2884) @@ -64,16 +64,6 @@ </dependency> <dependency> - <groupId>org.nuiton.eugene</groupId> - <artifactId>eugene</artifactId> - </dependency> - - <dependency> - <groupId>org.nuiton.eugene</groupId> - <artifactId>eugene-java-templates</artifactId> - </dependency> - - <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> </dependency> @@ -147,141 +137,12 @@ </dependencies> <build> - <testResources> - <testResource> - <directory>${maven.gen.dir}/test-java</directory> - <includes> - <include>**/*.hbm.xml</include> - </includes> - </testResource> - - <testResource> - <directory>${maven.src.dir}/test/resources</directory> - <includes> - <include>**/*.properties</include> - </includes> - </testResource> - - <testResource> - <directory>${maven.src.dir}/test/java</directory> - <includes> - <include>**/*.hbm.xml</include> - </includes> - </testResource> - - </testResources> - <plugins> - - <plugin> - <groupId>org.nuiton.processor</groupId> - <artifactId>processor-maven-plugin</artifactId> - </plugin> - - <!-- expose new plexus components --> - <plugin> - <groupId>org.codehaus.plexus</groupId> - <artifactId>plexus-component-metadata</artifactId> - <executions> - <execution> - <goals> - <goal>generate-metadata</goal> - </goals> - </execution> - </executions> - </plugin> - - <plugin> - <groupId>org.nuiton.eugene</groupId> - <artifactId>eugene-maven-plugin</artifactId> - <configuration> - - </configuration> - <executions> - <execution> - <id>Test Generator</id> - <phase>generate-test-sources</phase> - <configuration> - <testPhase>true</testPhase> - <templates> - org.nuiton.topia.generator.TopiaMetaTransformer, - org.nuiton.eugene.java.JavaInterfaceTransformer, - org.nuiton.eugene.java.JavaBeanTransformer, - org.nuiton.topia.generator.EntityDTOTransformer, - org.nuiton.topia.generator.BinderHelperTransformer - </templates> - <fullPackagePath>org.nuiton.topia</fullPackagePath> - <defaultPackage>org.nuiton.topia</defaultPackage> - </configuration> - <goals> - <goal>generate</goal> - </goals> - </execution> - </executions> - </plugin> - - <!-- expose tests --> - <plugin> - <artifactId>maven-jar-plugin</artifactId> - <executions> - <execution> - <id>attach-test</id> - <goals> - <goal>test-jar</goal> - </goals> - </execution> - </executions> - - </plugin> - </plugins> </build> <profiles> - <!-- perform only on a release stage when using the maven-release-plugin --> <profile> - <id>release-profile</id> - <activation> - <property> - <name>performRelease</name> - <value>true</value> - </property> - </activation> - - <build> - <plugins> - - <!-- always expose tests source jar --> - <plugin> - <artifactId>maven-source-plugin</artifactId> - <executions> - <execution> - <id>attach-test-sources</id> - <goals> - <goal>test-jar</goal> - </goals> - </execution> - </executions> - </plugin> - - <!-- always expose tests javadoc jar --> - <plugin> - <artifactId>maven-javadoc-plugin</artifactId> - <executions> - <execution> - <id>attach-test-javadoc</id> - <goals> - <goal>test-jar</goal> - </goals> - </execution> - </executions> - </plugin> - - </plugins> - </build> - </profile> - - <profile> <id>run-its</id> <activation> <property> @@ -333,12 +194,6 @@ <reporting> <plugins> <plugin> - <groupId>org.codehaus.plexus</groupId> - <artifactId>plexus-maven-plugin</artifactId> - <version>${plexusPluginVersion}</version> - </plugin> - - <plugin> <artifactId>maven-invoker-plugin</artifactId> <version>${invokerPluginVersion}</version> </plugin> Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/ApplicationContextTransformer.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/ApplicationContextTransformer.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/ApplicationContextTransformer.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,294 +0,0 @@ -package org.nuiton.topia.generator; - -/* - * #%L - * ToPIA :: Persistence - * * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -/*{generator option: parentheses = false}*/ - -/*{generator option: writeString = +}*/ - -import org.nuiton.eugene.java.ObjectModelTransformerToJava; -import org.nuiton.eugene.models.object.ObjectModel; -import org.nuiton.eugene.models.object.ObjectModelClass; -import org.nuiton.eugene.models.object.ObjectModelJavaModifier; -import org.nuiton.eugene.models.object.ObjectModelOperation; -import org.nuiton.topia.AbstractTopiaApplicationContext; -import org.nuiton.topia.persistence.TopiaEntity; -import org.nuiton.topia.persistence.util.EntityOperator; -import org.nuiton.topia.persistence.util.EntityOperatorStore; - -import java.lang.reflect.Array; -import java.util.List; -import java.util.Properties; - -/** - * To generate PersistenceHelper - * - * @author tchemit <chemit@codelutin.com> - * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.generator.ApplicationContextTransformer" - * @since 3.0 - */ -public class ApplicationContextTransformer extends ObjectModelTransformerToJava { - - @Override - public void transformFromModel(ObjectModel input) { - - String packageName = TopiaGeneratorUtil.getApplicationContextPackage(this, model); - - String applicationContextAbstractName = TopiaGeneratorUtil.getApplicationContextAbstractName(model); - - String applicationContextConcreteName = TopiaGeneratorUtil.getApplicationContextConcreteName(model); - - boolean generateAbstract = !isInClassPath(packageName, applicationContextAbstractName); - - boolean generateConcrete = !isInClassPath(packageName, applicationContextConcreteName); - - - if (generateAbstract) { - - generateAbstract(packageName, - applicationContextAbstractName); - } - - if (generateConcrete) { - - generateImpl(packageName, - applicationContextAbstractName, - applicationContextConcreteName); - } - - } - - protected void generateAbstract(String packageName, - String className) { - - // try to find a super class by tag-value -// String superClass = TopiaGeneratorUtil.getPersistenceContextSuperClassTagValue(model); - String superClass = null; - - if (superClass == null) { - - // no super-class, use default one - superClass = AbstractTopiaApplicationContext.class.getName(); - } - - ObjectModelClass output = createAbstractClass(className, packageName); - - String persistenceContextConcreteName = TopiaGeneratorUtil.getPersistenceContextConcreteName(model); - setSuperClass(output, superClass + "<" + persistenceContextConcreteName + ">"); - - // detect if there is a contract to set on abstract - String contractName = TopiaGeneratorUtil.getPersistenceContextInterfaceName(model); - -// addInterface(output, TopiaPersistenceContext.class); - - boolean addPersistenceContextContract = isInClassPath(packageName, contractName); - - if (addPersistenceContextContract) { - addInterface(output, packageName + "." + contractName); - } - - String modelName = model.getName(); - String daoHelperClazzName = modelName + "DAOHelper"; - - String entityEnumName = modelName + "EntityEnum"; - - List<ObjectModelClass> entityClasses = - TopiaGeneratorUtil.getEntityClasses(model, true); - - boolean generateOperator = - TopiaGeneratorUtil.shouldGenerateOperatorForDAOHelper(model); - - boolean generateStandaloneEnum = - TopiaGeneratorUtil.shouldGenerateStandaloneEnumForDAOHelper(model); - - if (!generateStandaloneEnum) { - - addImport(output, packageName + "." + daoHelperClazzName + "." + entityEnumName); - - } - - addImport(output, TopiaEntity.class); - addImport(output, Array.class); - addImport(output, Array.class); - - if (generateOperator) { - addImport(output, EntityOperator.class); - addImport(output, EntityOperatorStore.class); - } - - // add public constructor - ObjectModelOperation constructor = addConstructor( - output, - ObjectModelJavaModifier.PUBLIC); - addParameter(constructor, Properties.class, "properties"); - setOperationBody(constructor, "" -/*{ - super(properties); - }*/ - ); - - constructor = addConstructor( - output, - ObjectModelJavaModifier.PUBLIC); - addParameter(constructor, "java.util.Map<String, String>", "configuration"); - setOperationBody(constructor, "" -/*{ - super(configuration); - }*/ - ); - - ObjectModelOperation op; - - // getModelVersion method - op = addOperation(output, "newPersistenceContext", persistenceContextConcreteName, ObjectModelJavaModifier.PUBLIC); - addAnnotation(output, op, Override.class); - setOperationBody(op, "" -/*{ - <%=persistenceContextConcreteName%> newContext = new <%=persistenceContextConcreteName%>( - getHibernateProvider(), getTopiaListenableSupport(), getTopiaIdFactory()); - registerPersistenceContext(newContext); - return newContext; - }*/ - ); - - // getModelVersion method - String modelVersion = model.getVersion(); - op = addOperation(output, "getModelVersion", "String", ObjectModelJavaModifier.PUBLIC); - setOperationBody(op, "" -/*{ - return "<%=modelVersion%>"; - }*/ - ); - - // getModelName method - op = addOperation(output, "getModelName", "String", ObjectModelJavaModifier.PUBLIC); - setOperationBody(op, "" -/*{ - return "<%=modelName%>"; - }*/ - ); - - // getContractClass method - op = addOperation(output, "getContractClass", "<T extends TopiaEntity> Class<T>", ObjectModelJavaModifier.PUBLIC); - addParameter(op, "Class<T>", "klass"); - setOperationBody(op, "" -/*{ - <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass); - return (Class<T>) constant.getContract(); - }*/ - ); - - // getImplementationClass method - op = addOperation(output, "getImplementationClass", "<T extends TopiaEntity> Class<T>", ObjectModelJavaModifier.PUBLIC); - addParameter(op, "Class<T>", "klass"); - setOperationBody(op, "" -/*{ - <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass); - return (Class<T>) constant.getImplementation(); - }*/ - ); - - // getContractClasses method - op = addOperation(output, "getContractClasses", "Class<? extends TopiaEntity>[]", ObjectModelJavaModifier.PUBLIC); - setOperationBody(op, "" -/*{ - <%=entityEnumName%>[] values = <%=entityEnumName%>.values(); - Class<? extends TopiaEntity>[] result = (Class<? extends TopiaEntity>[]) Array.newInstance(Class.class, values.length); - for (int i = 0; i < values.length; i++) { - result[i] = values[i].getContract(); - } - return result; - }*/ - ); - - // getImplementationClasses method - op = addOperation(output, "getImplementationClasses", "Class<? extends TopiaEntity>[]", ObjectModelJavaModifier.PUBLIC); - setOperationBody(op, "" -/*{ - <%=entityEnumName%>[] values = <%=entityEnumName%>.values(); - Class<? extends TopiaEntity>[] result = (Class<? extends TopiaEntity>[]) Array.newInstance(Class.class, values.length); - for (int i = 0; i < values.length; i++) { - result[i] = values[i].getImplementation(); - } - return result; - }*/ - ); - - // getContracts method - op = addOperation(output, "getContracts", entityEnumName + "[]", ObjectModelJavaModifier.PUBLIC); - setOperationBody(op, "" -/*{ - return <%=entityEnumName%>.values(); - }*/ - ); - - if (generateOperator) { - // getOperator method - op = addOperation(output, "getOperator", "<T extends TopiaEntity> EntityOperator<T>", ObjectModelJavaModifier.PUBLIC); - addParameter(op, "Class<T>", "klass"); - setOperationBody(op, "" -/*{ - <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass); - return EntityOperatorStore.getOperator(constant); - }*/ - ); - } - - } - - protected ObjectModelClass generateImpl(String packageName, - String applicationContextAbstractName, - String applicationContextConcreteName) { - - ObjectModelClass output = createClass(applicationContextConcreteName, packageName); - - setSuperClass(output, applicationContextAbstractName); - - // add public constructor - ObjectModelOperation constructor = addConstructor( - output, - ObjectModelJavaModifier.PUBLIC); - addParameter(constructor, Properties.class, "properties"); - setOperationBody(constructor, "" -/*{ - super(properties); - }*/ - ); - - constructor = addConstructor( - output, - ObjectModelJavaModifier.PUBLIC); - addParameter(constructor, "java.util.Map<String, String>", "configuration"); - setOperationBody(constructor, "" -/*{ - super(configuration); - }*/ - ); - - return output; - } - -} Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/BinderHelperTransformer.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/BinderHelperTransformer.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/BinderHelperTransformer.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,274 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.topia.generator; - -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.eugene.GeneratorUtil; -import org.nuiton.eugene.java.ObjectModelTransformerToJava; -import org.nuiton.eugene.models.object.*; -import org.nuiton.topia.persistence.TopiaEntity; -import org.nuiton.topia.persistence.util.TopiaEntityBinder; -import org.nuiton.topia.persistence.util.TopiaEntityHelper; -import org.nuiton.util.beans.BinderModelBuilder; -import org.nuiton.util.beans.BinderFactory; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - - -/*{generator option: parentheses = false}*/ -/*{generator option: writeString = +}*/ - -/** - * A template to generate a helper for {@link TopiaEntityBinder}. - * - * @author tchemit <chemit@codelutin.com> - * @version $Id$ - * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.generator.BinderHelperTransformer" - * @since 2.3.1 - */ -public class BinderHelperTransformer extends ObjectModelTransformerToJava { - - private static final Log log = - LogFactory.getLog(BinderHelperTransformer.class); - - - @Override - public void transformFromModel(ObjectModel model) { - ObjectModelClass resultClass; - - List<ObjectModelClass> classes = TopiaGeneratorUtil.getEntityClasses(model, true); - - if (CollectionUtils.isEmpty(classes)) { - - // no entity classes, so no generation - log.warn("No entity to generate, " + getClass().getName() + " is skipped"); - return; - } - - String packageName = getOutputProperties().getProperty(PROP_DEFAULT_PACKAGE); - String modelName = model.getName(); - String binderHelperClazzName = modelName + "BinderHelper"; - String daoHelperClazzName = modelName + "DAOHelper"; - - resultClass = createClass(binderHelperClazzName, packageName); - - setSuperClass(resultClass, BinderFactory.class); - - - addImport(resultClass, TopiaEntityBinder.class); - addImport(resultClass, TopiaEntityHelper.class); - addImport(resultClass, TopiaEntity.class); - addImport(resultClass, BinderModelBuilder.class); - - ObjectModelOperation op; - - op = addOperation(resultClass, - "getTopiaBinder", - "<E extends TopiaEntity> TopiaEntityBinder<E>", - ObjectModelJavaModifier.PUBLIC, - ObjectModelJavaModifier.STATIC); - addParameter(op, "Class<E>", "entityClass"); - addParameter(op, "String", "contextName"); - setOperationBody(op, "" -/*{ - return (TopiaEntityBinder<E>) newBinder(entityClass, entityClass, contextName, TopiaEntityBinder.class); - }*/ - ); - - op = addOperation(resultClass, - "getSimpleTopiaBinder", - "<E extends TopiaEntity> TopiaEntityBinder<E>", - ObjectModelJavaModifier.PUBLIC, - ObjectModelJavaModifier.STATIC); - addParameter(op, "Class<E>", "entityClass"); - setOperationBody(op, "" -/*{ - return getTopiaBinder(entityClass, "<%=modelName%>"); - }*/ - ); - - op = addOperation(resultClass, - "registerTopiaBinder", - "void", - ObjectModelJavaModifier.PUBLIC, - ObjectModelJavaModifier.STATIC); - addParameter(op, "BinderModelBuilder", "builder"); - addParameter(op, "String", "contextName"); - setOperationBody(op, "" -/*{ - registerBinderModel(builder, contextName); - }*/ - ); - - op = addOperation(resultClass, - "registerTopiaBinder", - "<E extends TopiaEntity> TopiaEntityBinder<E>", - ObjectModelJavaModifier.PUBLIC, - ObjectModelJavaModifier.STATIC); - addParameter(op, "Class<E>", "entityClass"); - addParameter(op, "BinderModelBuilder", "builder"); - addParameter(op, "String", "contextName"); - setOperationBody(op, "" -/*{ - registerBinderModel(builder, contextName); - return getTopiaBinder(entityClass, contextName); - }*/ - ); - - op = addOperation(resultClass, - "copy", - "<E extends TopiaEntity> void", - ObjectModelJavaModifier.PUBLIC, - ObjectModelJavaModifier.STATIC); - addParameter(op, "String", "contextName"); - addParameter(op, "E", "source"); - addParameter(op, "E", "target"); - addParameter(op, "boolean", "tech"); - setOperationBody(op, "" -/*{ - Class<E> entityClass = (Class<E>) TopiaEntityHelper.getContractClass(<%=daoHelperClazzName%>.getContracts(), target.getClass()); - TopiaEntityBinder<E> binder = getTopiaBinder(entityClass, contextName); - if (binder == null) { - throw new NullPointerException("could not find a simple topia binder of type : " + target.getClass()); - } - binder.load(source, target, tech); - }*/ - ); - - op = addOperation(resultClass, - "simpleCopy", - "<E extends TopiaEntity> void", - ObjectModelJavaModifier.PUBLIC, - ObjectModelJavaModifier.STATIC); - addParameter(op, "E", "source"); - addParameter(op, "E", "target"); - addParameter(op, "boolean", "tech"); - setOperationBody(op, "" -/*{ - Class<E> entityClass = (Class<E>) TopiaEntityHelper.getContractClass(<%=daoHelperClazzName%>.getContracts(), target.getClass()); - TopiaEntityBinder<E> binder = getSimpleTopiaBinder(entityClass); - if (binder == null) { - throw new NullPointerException("could not find a simple topia binder of type : " + target.getClass()); - } - binder.load(source, target, tech); - }*/ - ); - - StringBuilder initCode = new StringBuilder(); - - for (ObjectModelClass clazz : classes) { - - String prefix = getConstantPrefix(clazz, ""); - - if (StringUtils.isEmpty(prefix)) { - - // no specific prefix, so no prefix - if (log.isWarnEnabled()) { - log.warn("[" + clazz.getName() + "] Will generate constants with NO prefix, not a good idea..."); - } - } - - setConstantPrefix(prefix); - - generateBinder(modelName, clazz, resultClass, initCode); - - } - - op = addOperation(resultClass, "initBinders", "void", ObjectModelJavaModifier.PROTECTED, ObjectModelJavaModifier.STATIC); - setOperationBody(op, initCode.toString()); - - op = addOperation(resultClass, null, (String) null, ObjectModelJavaModifier.STATIC); - setOperationBody(op, "" - /*{ - initBinders(); -}*/ - ); - } - - protected void generateBinder(String modelName, - ObjectModelClass clazz, - ObjectModelClass resultClass, - StringBuilder initCode) { - - List<ObjectModelAttribute> list = new ArrayList<ObjectModelAttribute>(); - for (ObjectModelAttribute attr : clazz.getAttributes()) { - if (!attr.isNavigable()) { - continue; - } - - if (GeneratorUtil.isNMultiplicity(attr)) { - // not dealing with association - continue; - } - - list.add(attr); - } - - String clazzName = clazz.getName(); - - if (list.isEmpty()) { - // no attribute, do nothing - if (log.isDebugEnabled()) { - log.debug("no attribute to add in a binder for " + clazzName + - ", will not generate it."); - } - return; - } - - if (log.isDebugEnabled()) { - log.debug("generate simple binder for " + clazzName); - } - addImport(resultClass, clazz); - initCode.append("" -/*{ - BinderModelBuilder<<%=clazzName%>, <%=clazzName%>> builder<%=clazzName%> = - BinderModelBuilder.newEmptyBuilder(<%=clazzName%>.class); - builder<%=clazzName%>.addSimpleProperties( -}*/ - ); - Iterator<ObjectModelAttribute> itr = list.iterator(); - while (itr.hasNext()) { - ObjectModelAttribute attr = itr.next(); - String attrName = attr.getName(); - boolean hasNext = itr.hasNext(); - initCode.append("" -/*{ <%=clazzName%>.<%=getConstantName(attrName)%><%=(hasNext?",\n":"")%>}*/ - ); - } - initCode.append("" -/*{ - ); - registerTopiaBinder(builder<%=clazzName%>, "<%=modelName%>"); - }*/ - ); - } -} - Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DAOHelperTransformer.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DAOHelperTransformer.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DAOHelperTransformer.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,526 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.topia.generator; - -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.eugene.java.ObjectModelTransformerToJava; -import org.nuiton.eugene.models.object.ObjectModel; -import org.nuiton.eugene.models.object.ObjectModelAttribute; -import org.nuiton.eugene.models.object.ObjectModelClass; -import org.nuiton.eugene.models.object.ObjectModelEnumeration; -import org.nuiton.eugene.models.object.ObjectModelJavaModifier; -import org.nuiton.eugene.models.object.ObjectModelOperation; -import org.nuiton.eugene.models.object.ObjectModelType; -import org.nuiton.eugene.models.object.xml.ObjectModelAttributeImpl; -import org.nuiton.eugene.models.object.xml.ObjectModelEnumerationImpl; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaDaoSupplier; -import org.nuiton.topia.TopiaException; -import org.nuiton.topia.persistence.TopiaDAO; -import org.nuiton.topia.persistence.TopiaEntity; -import org.nuiton.topia.persistence.TopiaEntityEnum; -import org.nuiton.topia.persistence.util.EntityOperator; -import org.nuiton.topia.persistence.util.EntityOperatorStore; - -import java.lang.reflect.Array; -import java.util.Arrays; -import java.util.List; -import java.util.Set; - - -/*{generator option: parentheses = false}*/ - -/*{generator option: writeString = +}*/ - -/** - * Created: 13 nov. 2009 09:05:17 - * - * @author tchemit <chemit@codelutin.com> - * @version $Id$ - * @since 2.3.0 - * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.generator.DAOHelperTransformer" - */ -public class DAOHelperTransformer extends ObjectModelTransformerToJava { - - private static final Log log = - LogFactory.getLog(DAOHelperTransformer.class); - - @Override - public void transformFromModel(ObjectModel model) { - String packageName = - getOutputProperties().getProperty(PROP_DEFAULT_PACKAGE); - String modelName = model.getName(); - String daoHelperClazzName = modelName + "DAOHelper"; - String entityEnumName = modelName + "EntityEnum"; - - List<ObjectModelClass> classes = - TopiaGeneratorUtil.getEntityClasses(model, true); - - boolean generateOperator = - TopiaGeneratorUtil.shouldGenerateOperatorForDAOHelper(model); - - boolean generateStandaloneEnum = - TopiaGeneratorUtil.shouldGenerateStandaloneEnumForDAOHelper(model); - - ObjectModelClass daoHelper = createClass(daoHelperClazzName, - packageName); - - ObjectModelEnumeration entityEnum; - - if (generateStandaloneEnum) { - if (log.isDebugEnabled()) { - log.debug("Will generate standalone " + entityEnumName + - " in package " + packageName); - } - entityEnum = createEnumeration(entityEnumName, packageName); - addImport(entityEnum, TopiaEntity.class); - addImport(entityEnum, EntityOperatorStore.class); - addImport(entityEnum, Arrays.class); - addImport(entityEnum, ArrayUtils.class); - - } else { - entityEnum = (ObjectModelEnumerationImpl) - addInnerClassifier(daoHelper, - ObjectModelType.OBJECT_MODEL_ENUMERATION, - entityEnumName - ); - addImport(daoHelper, TopiaEntityEnum.class); - addImport(daoHelper, EntityOperatorStore.class); - addImport(daoHelper, Arrays.class); - addImport(daoHelper, ArrayUtils.class); - } - - // generate DAOHelper - createDAOHelper(model, - daoHelper, - daoHelperClazzName, - entityEnumName, - generateOperator, - classes - ); - - // generate TopiaEntityEnum - createEntityEnum(entityEnum, - daoHelperClazzName, - entityEnumName, - generateOperator, - generateStandaloneEnum, - classes - ); - } - - protected void createDAOHelper(ObjectModel model, - ObjectModelClass daoHelper, - String daoHelperClazzName, - String entityEnumName, - boolean generateOperator, - List<ObjectModelClass> classes) { - - String modelName = model.getName(); - String modelVersion = model.getVersion(); - - addImport(daoHelper, TopiaDAO.class); - addImport(daoHelper, TopiaEntity.class); - addImport(daoHelper, TopiaContext.class); - addImport(daoHelper, Array.class); - - if (generateOperator) { - addImport(daoHelper,EntityOperator.class); - addImport(daoHelper, EntityOperatorStore.class); - } - - addAnnotation(daoHelper, daoHelper, Deprecated.class); - - // add non public constructor - ObjectModelOperation constructor = - addConstructor(daoHelper, ObjectModelJavaModifier.PROTECTED); - setOperationBody(constructor," "); - - ObjectModelOperation op; - - // getModelVersion method - op = addOperation(daoHelper, "getModelVersion", "String", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); - setOperationBody(op, "" -/*{ - return "<%=modelVersion%>"; - }*/ - ); - - // getModelName method - op = addOperation(daoHelper, "getModelName", "String", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); - setOperationBody(op, "" -/*{ - return "<%=modelName%>"; - }*/ - ); - - - for (ObjectModelClass clazz : classes) { - String clazzName = clazz.getName(); - String daoClazzName = clazzName + "DAO"; - - // specialized getXXXDao method - op = addOperation(daoHelper, "get" + daoClazzName, clazz.getPackageName() + '.' + daoClazzName, ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); - addParameter(op, TopiaDaoSupplier.class, "supplier"); - addImport(daoHelper, clazz); - addException(op, TopiaException.class); - setOperationBody(op, "" -/*{ - <%=daoClazzName%> result = supplier.getDao(<%=clazzName%>.class, <%=daoClazzName%>.class); - return result; - }*/ - ); - - } - - // obsolete generic getDAO method - op = addOperation(daoHelper, "getDAO", "<T extends TopiaEntity, D extends TopiaDAO<? super T>> D", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); - addParameter(op, TopiaContext.class, "context"); - addParameter(op, "Class<T>", "klass"); - addException(op, TopiaException.class); - addAnnotation(daoHelper, op, Deprecated.class); - setOperationBody(op, "" -/*{ - D dao = getDao(context, klass); - return dao; - }*/ - ); - - // generic getDao method - op = addOperation(daoHelper, "getDao", "<T extends TopiaEntity, D extends TopiaDAO<? super T>> D", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); - addParameter(op, TopiaContext.class, "context"); - addParameter(op, "Class<T>", "klass"); - addException(op, TopiaException.class); - setOperationBody(op, "" -/*{ - <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass); - D dao = (D) context.getDao(constant.getContract()); - return dao; - }*/ - ); - - op = addOperation(daoHelper, "getDao", "<T extends TopiaEntity, D extends TopiaDAO<? super T>> D", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); - addParameter(op, TopiaContext.class, "context"); - addParameter(op, "T", "entity"); - addException(op, TopiaException.class); - setOperationBody(op, "" -/*{ - <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(entity); - D dao = (D) context.getDao(constant.getContract()); - return dao; - }*/ - ); - - // getContractClass method - op = addOperation(daoHelper, "getContractClass", "<T extends TopiaEntity> Class<T>", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); - addParameter(op, "Class<T>", "klass"); - setOperationBody(op, "" -/*{ - <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass); - return (Class<T>) constant.getContract(); - }*/ - ); - - // getImplementationClass method - op = addOperation(daoHelper, "getImplementationClass", "<T extends TopiaEntity> Class<T>", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); - addParameter(op, "Class<T>", "klass"); - setOperationBody(op, "" -/*{ - <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass); - return (Class<T>) constant.getImplementation(); - }*/ - ); - - // getContractClasses method - op = addOperation(daoHelper, "getContractClasses", "Class<? extends TopiaEntity>[]", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); - setOperationBody(op, "" -/*{ - <%=entityEnumName%>[] values = <%=entityEnumName%>.values(); - Class<? extends TopiaEntity>[] result = (Class<? extends TopiaEntity>[]) Array.newInstance(Class.class, values.length); - for (int i = 0; i < values.length; i++) { - result[i] = values[i].getContract(); - } - return result; - }*/ - ); - - // getImplementationClasses method - op = addOperation(daoHelper, "getImplementationClasses", "Class<? extends TopiaEntity>[]", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); - setOperationBody(op, "" -/*{ - <%=entityEnumName%>[] values = <%=entityEnumName%>.values(); - Class<? extends TopiaEntity>[] result = (Class<? extends TopiaEntity>[]) Array.newInstance(Class.class, values.length); - for (int i = 0; i < values.length; i++) { - result[i] = values[i].getImplementation(); - } - return result; - }*/ - ); - - // getImplementationClassesAsString method - op = addOperation(daoHelper, "getImplementationClassesAsString", "String", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); - setOperationBody(op, "" -/*{ - StringBuilder buffer = new StringBuilder(); - for (Class<? extends TopiaEntity> aClass : getImplementationClasses()) { - buffer.append(',').append(aClass.getName()); - } - return buffer.substring(1); - }*/ - ); - - // getContracts method - op = addOperation(daoHelper, "getContracts", entityEnumName+"[]", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); - setOperationBody(op, "" -/*{ - return <%=entityEnumName%>.values(); - }*/ - ); - - if (generateOperator) { - // getOperator method - op = addOperation(daoHelper, "getOperator", "<T extends TopiaEntity> EntityOperator<T>", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); - addParameter(op,"Class<T>","klass"); - setOperationBody(op, "" -/*{ - <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass); - return EntityOperatorStore.getOperator(constant); - }*/ - ); - } - } - - protected void createEntityEnum(ObjectModelEnumeration entityEnum, - String daoHelperClazzName, - String entityEnumName, - boolean generateOperator, - boolean generateStandaloneEnum, - List<ObjectModelClass> classes) { - - ObjectModelAttributeImpl attr; - ObjectModelOperation op; - - addInterface(entityEnum, TopiaEntityEnum.class); - - for (ObjectModelClass clazz : classes) { - String clazzName = clazz.getName(); - - boolean withNatural = false; - boolean withNotNull = false; - StringBuilder naturalIdsParams = new StringBuilder(); - StringBuilder notNullParams = new StringBuilder(); - - Set<ObjectModelAttribute> naturalIdsAttributes = TopiaGeneratorUtil.getNaturalIdAttributes(clazz); - for (ObjectModelAttribute attribute: naturalIdsAttributes) { - withNatural = true; - // attribut metier - naturalIdsParams.append(", \"").append(attribute.getName()).append("\""); - } - Set<ObjectModelAttribute> notNullIdsAttributes = TopiaGeneratorUtil.getNotNullAttributes(clazz); - for (ObjectModelAttribute attribute : notNullIdsAttributes) { - withNotNull = true; - // attribut not-null - notNullParams.append(", \"").append(attribute.getName()).append("\""); - } - - StringBuilder params = new StringBuilder(clazzName + ".class"); - if (withNotNull) { - params.append(", new String[]{ " + notNullParams.substring(2) + " }"); - } else { - params.append(", ArrayUtils.EMPTY_STRING_ARRAY"); - } - if (withNatural) { - params.append(", ").append(naturalIdsParams.substring(2)); - } - addLiteral(entityEnum, clazzName + '(' + params.toString() + ')'); - - if (generateStandaloneEnum) { - addImport(entityEnum, clazz); - } - } - - attr = (ObjectModelAttributeImpl) addAttribute(entityEnum, "contract", "Class<? extends TopiaEntity>"); - attr.setDocumentation("The contract of the entity."); - - attr = (ObjectModelAttributeImpl) addAttribute(entityEnum, "implementationFQN", "String"); - attr.setDocumentation("The fully qualified name of the implementation of the entity."); - - attr = (ObjectModelAttributeImpl) addAttribute(entityEnum, "implementation", "Class<? extends TopiaEntity>"); - attr.setDocumentation("The implementation class of the entity (will be lazy computed at runtime)."); - - attr = (ObjectModelAttributeImpl) addAttribute(entityEnum, "naturalIds", "String[]"); - attr.setDocumentation("The array of property involved in the natural key of the entity."); - - attr = (ObjectModelAttributeImpl) addAttribute(entityEnum, "notNulls", "String[]"); - attr.setDocumentation("The array of not null properties of the entity."); - - // constructor - op = addConstructor(entityEnum, ObjectModelJavaModifier.PACKAGE); - addParameter(op,"Class<? extends TopiaEntity >","contract"); - addParameter(op,"String[]","notNulls"); - addParameter(op,"String...","naturalIds"); - setOperationBody(op, "" -/*{ - this.contract = contract; - this.notNulls = Arrays.copyOf(notNulls, notNulls.length); - this.naturalIds = naturalIds; - implementationFQN = contract.getName() + "Impl"; - }*/ - ); - - // getContract method - op = addOperation(entityEnum, "getContract", "Class<? extends TopiaEntity>", ObjectModelJavaModifier.PUBLIC); - addAnnotation(entityEnum,op,Override.class); - setOperationBody(op, "" -/*{ - return contract; - }*/ - ); - - // getNaturalIds method - op = addOperation(entityEnum, "getNaturalIds", "String[]", ObjectModelJavaModifier.PUBLIC); - addAnnotation(entityEnum,op,Override.class); - setOperationBody(op, "" -/*{ - return naturalIds; - }*/ - ); - - // isUseNaturalIds method - op = addOperation(entityEnum, "isUseNaturalIds", "boolean", ObjectModelJavaModifier.PUBLIC); - addAnnotation(entityEnum,op,Override.class); - setOperationBody(op, "" -/*{ - return naturalIds.length > 0; - }*/ - ); - - // getNotNulls method - op = addOperation(entityEnum, "getNotNulls", "String[]", ObjectModelJavaModifier.PUBLIC); - addAnnotation(entityEnum,op,Override.class); - setOperationBody(op, "" -/*{ - return notNulls; - }*/ - ); - - // isUseNotNulls method - op = addOperation(entityEnum, "isUseNotNulls", "boolean", ObjectModelJavaModifier.PUBLIC); - addAnnotation(entityEnum,op,Override.class); - setOperationBody(op, "" -/*{ - return notNulls.length > 0; - }*/ - ); - - // getImplementationFQN method - op = addOperation(entityEnum, "getImplementationFQN","String",ObjectModelJavaModifier.PUBLIC); - addAnnotation(entityEnum, op, Override.class); - setOperationBody(op, "" -/*{ - return implementationFQN; - }*/ - ); - - // setImplementationFQN method - op = addOperation(entityEnum, "setImplementationFQN","void",ObjectModelJavaModifier.PUBLIC); - addAnnotation(entityEnum,op,Override.class); - addParameter(op,"String","implementationFQN"); - if (generateOperator) { - setOperationBody(op, "" -/*{ - this.implementationFQN = implementationFQN; - implementation = null; - // reinit the operators store - EntityOperatorStore.clear(); - }*/ - ); - } else { - setOperationBody(op, "" -/*{ - this.implementationFQN = implementationFQN; - this.implementation = null; - }*/ - ); - } - - // accept method - op = addOperation(entityEnum, "accept","boolean",ObjectModelJavaModifier.PUBLIC); - addAnnotation(entityEnum,op,Override.class); - addParameter(op,"Class<? extends TopiaEntity>","klass"); - setOperationBody(op, "" -/*{ - return <%=daoHelperClazzName%>.getContractClass(klass) == contract; - }*/ - ); - - // getImplementation method - op = addOperation(entityEnum, "getImplementation","Class<? extends TopiaEntity>",ObjectModelJavaModifier.PUBLIC); - addAnnotation(entityEnum,op,Override.class); - addImport(entityEnum, TopiaException.class); - setOperationBody(op, "" -/*{ - if (implementation == null) { - try { - implementation = (Class<? extends TopiaEntity>) Class.forName(implementationFQN); - } catch (ClassNotFoundException e) { - throw new TopiaException("could not find class " + implementationFQN, e); - } - } - return implementation; - }*/ - ); - - // valueOf method - op = addOperation(entityEnum, "valueOf", entityEnumName, ObjectModelJavaModifier.PUBLIC,ObjectModelJavaModifier.STATIC); - addParameter(op,"TopiaEntity", "entity"); - setOperationBody(op, "" -/*{ - return valueOf(entity.getClass()); - }*/ - ); - - // valueOf method - op = addOperation(entityEnum, "valueOf", entityEnumName, ObjectModelJavaModifier.PUBLIC,ObjectModelJavaModifier.STATIC); - addParameter(op,"Class<?>", "klass"); - setOperationBody(op, "" -/*{ - if (klass.isInterface()) { - return valueOf(klass.getSimpleName()); - } - for (<%=entityEnumName%> entityEnum : <%=entityEnumName%>.values()) { - if (entityEnum.getContract().isAssignableFrom(klass)) { - //todo check it works for inheritance - return entityEnum; - } - } - throw new IllegalArgumentException("no entity defined for the class " + klass + " in : " + Arrays.toString(<%=entityEnumName%>.values())); - }*/ - ); - } -} Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DTOTransformer.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DTOTransformer.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DTOTransformer.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,462 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.topia.generator; - -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.eugene.GeneratorUtil; -import org.nuiton.eugene.java.ObjectModelTransformerToJava; -import org.nuiton.eugene.models.object.*; - -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeSupport; -import java.io.Serializable; -import java.util.Collection; -import java.util.List; - - -/*{generator option: parentheses = false}*/ - -/*{generator option: writeString = +}*/ - -/** - * Created: 20 déc. 2009 - * - * @author tchemit <chemit@codelutin.com> - * @version $Id$ - * @since 2.3.0 - * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.generator.DTOTransformer" - */ -public class DTOTransformer extends ObjectModelTransformerToJava { - - /** - * Logger - */ - private static final Log log = LogFactory.getLog(DTOTransformer.class); - - @Override - public void transformFromClass(ObjectModelClass clazz) { - if (!TopiaGeneratorUtil.hasDtoStereotype(clazz)) { - return; - } - String clazzName = clazz.getName(); - ObjectModelClass result; - result = createClass(clazzName + "DTO", clazz.getPackageName()); - addImport(result, ToStringBuilder.class); - addImport(result, PropertyChangeListener.class); - - setDocumentation(result, "Implantation DTO pour l'entité " + StringUtils.capitalize(clazzName) + "."); - String extendClass = ""; - for (ObjectModelClass parent : clazz.getSuperclasses()) { - extendClass = parent.getQualifiedName() + "DTO"; - // no multi-inheritance in java - break; - } - if (extendClass.length() > 0) { - setSuperClass(result, extendClass); - } - - addInterface(result, Serializable.class); - for (ObjectModelInterface parentInterface : clazz.getInterfaces()) { - if (TopiaGeneratorUtil.hasDtoStereotype(parentInterface)) { - addInterface(result, parentInterface.getName() + "DTO"); - } else { - addInterface(result, parentInterface.getName()); - } - } - - addAttributes(result, clazz); - - addOperations(result, clazz); - } - - protected void addAttributes(ObjectModelClass result, ObjectModelClass clazz) { - - String svUID = TopiaGeneratorUtil.findTagValue("dto-serialVersionUID", clazz, model); - if (StringUtils.isNotEmpty(svUID)) { - addAttribute(result, "serialVersionUID", long.class, svUID, ObjectModelJavaModifier.FINAL, ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); - } - - addAttribute(result, "p", PropertyChangeSupport.class, null, ObjectModelJavaModifier.PROTECTED); - -/* -* Définition des attributs -*/ - ObjectModelAttribute attr2; - for (ObjectModelAttribute attr : clazz.getAttributes()) { - ObjectModelAttribute reverse = attr.getReverseAttribute(); - - String attributeName; - String attributeType; - if (!(attr.isNavigable() - || attr.hasAssociationClass())) { - continue; - } - - String attrName = attr.getName(); - String attrVisibility = attr.getVisibility(); - String attrType = attr.getType(); - if (!GeneratorUtil.isNMultiplicity(attr)) { - if (!attr.hasAssociationClass()) { - if (isDTO(attrType)) { - attrType += "DTO"; - } - attributeType = attrType; - attributeName = attrName; - } else { - String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(attr); - attributeType = attr.getAssociationClass().getQualifiedName(); - attributeName = GeneratorUtil.toLowerCaseFirstLetter(assocAttrName); - } - } else { - if (!attr.hasAssociationClass()) { - String nMultType; - if (attr.isOrdered()) { - nMultType = List.class.getName() + "<"; - } else { - nMultType = Collection.class.getName() + "<"; - } - nMultType += attrType; - if (isDTO(attrType)) { - nMultType += "DTO"; - } - nMultType += ">"; - - attributeType = nMultType; - attributeName = attrName; - } else { - String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(attr); - String assocClassFQN = attr.getAssociationClass().getQualifiedName(); - String nMultType; - if (attr.isOrdered()) { - nMultType = List.class.getName() + "<"; - } else { - nMultType = Collection.class.getName() + "<"; - } - nMultType += assocClassFQN; - if (isDTO(attrType)) { - nMultType += "DTO"; - } - nMultType += ">"; - attributeType = nMultType; - attributeName = GeneratorUtil.toLowerCaseFirstLetter(assocAttrName); - } - } - - attr2 = addAttribute(result, attributeName, attributeType, null, ObjectModelJavaModifier.PROTECTED); - - if (attr2 != null) { - if (TopiaGeneratorUtil.hasDocumentation(attr)) { - setDocumentation(attr2, attr.getDocumentation()); - } - String annotation = TopiaGeneratorUtil.getAnnotationTagValue(attr); - if (StringUtils.isNotEmpty(annotation)) { - addAnnotation(result, attr2, annotation); - } - } - } /* end for*/ - - //Déclaration des attributs d'une classe d'associations - if (clazz instanceof ObjectModelAssociationClass) { - ObjectModelAssociationClass assoc = (ObjectModelAssociationClass) clazz; - for (ObjectModelAttribute attr : assoc.getParticipantsAttributes()) { - if (attr != null) { - String attrName = attr.getName(); - String attrVisibility = attr.getVisibility(); - String attrType = attr.getType(); - if (isDTO(attrType)) { - attrType += "DTO"; - } - addAttribute(result, GeneratorUtil.toLowerCaseFirstLetter(attrName), attrType); - } - } - } - - } - - protected void addOperations(ObjectModelClass result, ObjectModelClass clazz) { - ObjectModelOperation op; - op = addOperation(result, "addPropertyChangeListener", "void", ObjectModelJavaModifier.PUBLIC); - addParameter(op, PropertyChangeListener.class, "listener"); - setOperationBody(op, "" -/*{ - p.addPropertyChangeListener(listener); - }*/ - ); - - op = addOperation(result, "addPropertyChangeListener", "void", ObjectModelJavaModifier.PUBLIC); - addParameter(op, String.class, "propertyName"); - addParameter(op, PropertyChangeListener.class, "listener"); - setOperationBody(op, "" -/*{ - p.addPropertyChangeListener(propertyName, listener); - }*/ - ); - - op = addOperation(result, "removePropertyChangeListener", "void", ObjectModelJavaModifier.PUBLIC); - addParameter(op, PropertyChangeListener.class, "listener"); - setOperationBody(op, "" -/*{ - p.removePropertyChangeListener(listener); - }*/ - ); - - op = addOperation(result, "removePropertyChangeListener", "void", ObjectModelJavaModifier.PUBLIC); - addParameter(op, String.class, "propertyName"); - addParameter(op, PropertyChangeListener.class, "listener"); - setOperationBody(op, "" -/*{ - p.removePropertyChangeListener(propertyName, listener); - }*/ - ); - /* - * Définition des getteurs et setteurs - */ - for (ObjectModelAttribute attr : clazz.getAttributes()) { - - ObjectModelAttribute reverse = attr.getReverseAttribute(); - -// if (!(attr.isNavigable() || hasUnidirectionalRelationOnAbstractType(reverse, model))) { - if (!attr.isNavigable()) { - continue; - } - - String attrName = attr.getName(); - String attrType = attr.getType(); - String attrTypeDTO = attr.getType(); - if (isDTO(attrType)) { - attrTypeDTO += "DTO"; - } - - if (!GeneratorUtil.isNMultiplicity(attr)) { - if (!attr.hasAssociationClass()) { - op = addOperation(result, "set" + StringUtils.capitalize(attrName), "void", ObjectModelJavaModifier.PUBLIC); - addParameter(op, attrTypeDTO, "value"); - setOperationBody(op, "" -/*{ - <%=attrTypeDTO%> oldValue = this.<%=attrName%>; - this.<%=attrName%> = value; - p.firePropertyChange("<%=attrName%>", oldValue, value); - }*/ - ); - - op = addOperation(result, "get" + StringUtils.capitalize(attrName), attrTypeDTO, ObjectModelJavaModifier.PUBLIC); - setOperationBody(op, "" -/*{ - return <%=attrName%>; - }*/ - ); - - } else { - String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(attr); - String assocClassFQN = attr.getAssociationClass().getQualifiedName(); - if (log.isTraceEnabled()) { - log.trace("assocAttrName: " + assocAttrName); - } - op = addOperation(result, "set" + StringUtils.capitalize(assocAttrName), "void", ObjectModelJavaModifier.PUBLIC); - addParameter(op, assocClassFQN + "DTO", "association"); - setOperationBody(op, "" -/*{ - <%=assocClassFQN%>DTO oldAssocation = this.<%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%>; - this.<%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%> = association; - p.firePropertyChange("<%=attrName%>", oldAssocation, assocation); - }*/ - ); - - op = addOperation(result, "get" + StringUtils.capitalize(assocAttrName), assocClassFQN + "DTO", ObjectModelJavaModifier.PUBLIC); - setOperationBody(op, "" -/*{ - return <%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%>; - }*/ - ); - } - } else { //NMultiplicity - if (!attr.hasAssociationClass()) { //Méthodes remplacées par des accesseurs sur les classes d'assoc - - String nMultType; - if (attr.isOrdered()) { - nMultType = List.class.getName() + "<" + attrTypeDTO + ">"; - } else { - nMultType = Collection.class.getName() + "<" + attrTypeDTO + ">"; - } - op = addOperation(result, "set" + StringUtils.capitalize(attrName), "void", ObjectModelJavaModifier.PUBLIC); - addParameter(op, nMultType, "values"); - setOperationBody(op, "" -/*{ - <%=nMultType%> oldValues = this.<%=attrName%>; - this.<%=attrName%> = values; - p.firePropertyChange("<%=attrName%>", oldValues, values); - }*/ - ); - - op = addOperation(result, "addChild" + StringUtils.capitalize(attrName), attrTypeDTO, ObjectModelJavaModifier.PUBLIC); - addParameter(op, attrTypeDTO, attrName); - StringBuilder buffercode = new StringBuilder(); - - buffercode.append("" -/*{ - this.<%=attrName%>.add(<%=attrName%>); - }*/ - ); - - if (reverse != null && reverse.isNavigable()) { - String reverseAttrName = reverse.getName(); - buffercode.append("" -/*{ <%=attrName%>.set<%=StringUtils.capitalize(reverseAttrName)%>(this); - }*/ - ); - } - buffercode.append("" -/*{ return <%=attrName%>; - }*/ - ); - setOperationBody(op, buffercode.toString()); - - op = addOperation(result, "removeChild", "void"); - addParameter(op, attrTypeDTO, attrName); - - buffercode = new StringBuilder(); - buffercode.append("" -/*{ - this.<%=attrName%>.remove(<%=attrName%>); - }*/ - ); - - if (reverse != null && reverse.isNavigable()) { - String reverseAttrName = reverse.getName(); - buffercode.append("" -/*{ <%=attrName%>.set<%=StringUtils.capitalize(reverseAttrName)%>(null); - }*/ - ); - } - setOperationBody(op, buffercode.toString()); - - } else { - String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(attr); - String assocClassFQN = attr.getAssociationClass().getQualifiedName(); - String nMultType; - if (attr.isOrdered()) { - nMultType = List.class.getName() + "<" + assocClassFQN + "DTO>"; - } else { - nMultType = Collection.class.getName() + "<" + assocClassFQN + "DTO>"; - } - if (log.isTraceEnabled()) { - log.trace("assocAttrName: " + assocAttrName); - } - op = addOperation(result, "set" + StringUtils.capitalize(assocAttrName), "void"); - addParameter(op, nMultType, "values"); - setOperationBody(op, "" -/*{ - <%=nMultType%> oldValues = this.<%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%>; - this.<%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%> = values; - p.firePropertyChange("<%=attrName%>", oldValues, values); - }*/ - ); - } - if (!attr.hasAssociationClass()) { - String nMultType; - if (attr.isOrdered()) { - nMultType = List.class.getName() + "<" + attrTypeDTO + ">"; - } else { - nMultType = Collection.class.getName() + "<" + attrTypeDTO + ">"; - } - op = addOperation(result, "get" + StringUtils.capitalize(attrName), nMultType); - setOperationBody(op, "" -/*{ - return this.<%=attrName%>; - }*/ - ); - } else { - String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(attr); - String assocClassFQN = attr.getAssociationClass().getQualifiedName(); - String nMultType; - if (attr.isOrdered()) { - nMultType = List.class.getName() + "<" + assocClassFQN + "DTO>"; - } else { - nMultType = Collection.class.getName() + "<" + assocClassFQN + "DTO>"; - } - if (log.isTraceEnabled()) { - log.trace("assocAttrName: " + assocAttrName); - } - op = addOperation(result, "get" + StringUtils.capitalize(assocAttrName), nMultType); - setOperationBody(op, "" -/*{ - return this.<%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%>; - }*/ - ); - } - } - } - - op = addOperation(result, "toString", String.class, ObjectModelJavaModifier.PUBLIC); - StringBuilder buffer = new StringBuilder(); - - buffer.append("" -/*{ - String result = new ToStringBuilder(this). -}*/ - ); - - for (Object o : clazz.getAttributes()) { - ObjectModelAttribute attr = (ObjectModelAttribute) o; - if (!(attr.isNavigable() - || attr.hasAssociationClass())) { - continue; - } - //FIXME possibilité de boucles (non directes) - ObjectModelClass attrEntity = null; - if (model.hasClass(attr.getType())) { - attrEntity = model.getClass(attr.getType()); - } - boolean isDTO = attrEntity != null && - TopiaGeneratorUtil.isEntity(attrEntity); //THIMEL : STEREOTYPE ENTITY ??? - ObjectModelAttribute reverse = attr.getReverseAttribute(); - if (isDTO && (reverse == null || !reverse.isNavigable()) && !attr.hasAssociationClass() || !isDTO) { - String attrName = attr.getName(); - buffer.append("" -/*{ append("<%=attrName%>", this.<%=attrName%>). -}*/ - ); - } - } - buffer.append("" -/*{ toString(); - return result; - }*/ - ); - setOperationBody(op, buffer.toString()); - } - - public boolean isDTO(String type) { - ObjectModelClassifier clazz = model.getClassifier(type); - return clazz != null && TopiaGeneratorUtil.hasDtoStereotype(clazz); - } - - -} - Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityDTOTransformer.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityDTOTransformer.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityDTOTransformer.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,366 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.topia.generator; - -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.nuiton.eugene.GeneratorUtil; -import org.nuiton.eugene.java.ObjectModelTransformerToJava; -import org.nuiton.eugene.models.object.ObjectModelAssociationClass; -import org.nuiton.eugene.models.object.ObjectModelAttribute; -import org.nuiton.eugene.models.object.ObjectModelClass; -import org.nuiton.eugene.models.object.ObjectModelClassifier; -import org.nuiton.eugene.models.object.ObjectModelJavaModifier; -import org.nuiton.eugene.models.object.ObjectModelModifier; -import org.nuiton.eugene.models.object.ObjectModelOperation; - -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeSupport; -import java.io.Serializable; - -import static org.nuiton.topia.generator.TopiaGeneratorUtil.hasUnidirectionalRelationOnAbstractType; -import static org.nuiton.topia.generator.TopiaGeneratorUtil.shouldGenerateDTOTopiaIdTagValue; - - -/*{generator option: parentheses = false}*/ - -/*{generator option: writeString = +}*/ - -/** - * Created: 14 déc. 2009 - * - * @author tchemit <chemit@codelutin.com> - * @version $Id$ - * @since 2.3.0 - * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.generator.EntityDTOTransformer" - * @deprecated since 3.0, will not be replaced - */ -@Deprecated -public class EntityDTOTransformer extends ObjectModelTransformerToJava { - - public boolean isEntity(String type) { - ObjectModelClassifier clazz = model.getClassifier(type); - return clazz != null && ! clazz.isEnum() - && TopiaGeneratorUtil.isEntity(clazz); - } - - @Override - public void transformFromClass(ObjectModelClass clazz) { - if (!TopiaGeneratorUtil.isEntity(clazz)) { - return; - } - String clazzName = clazz.getName(); - ObjectModelClass result; - result = createClass(clazzName + "DTO", clazz.getPackageName()); - addImport(result, ToStringBuilder.class); - addImport(result, PropertyChangeListener.class); - - setDocumentation(result, "Implantation DTO pour l'entité " + StringUtils.capitalize(clazzName) + "."); - String extendClass = ""; - for (ObjectModelClass parent : clazz.getSuperclasses()) { - extendClass = parent.getQualifiedName() + "DTO"; - // no multi-inheritance in java - break; - } - if (extendClass.length() > 0) { - setSuperClass(result, extendClass); - } - addInterface(result, Serializable.class); - - - addAttributes(result,clazz); - - addOperations(result,clazz); - - } - - protected void addAttributes(ObjectModelClass result, ObjectModelClass clazz) { - - String svUID = TopiaGeneratorUtil.findTagValue("dto-serialVersionUID", clazz, model); - if (svUID != null) { - addAttribute(result, "serialVersionUID", "long", svUID, ObjectModelJavaModifier.FINAL, ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); - } - - boolean generateDTOId = shouldGenerateDTOTopiaIdTagValue(clazz, model); - if (generateDTOId) { - addAttribute(result, "topiaId", "String"); - } - - ObjectModelAttribute attr2; - for (ObjectModelAttribute attr : clazz.getAttributes()) { - ObjectModelAttribute reverse = attr.getReverseAttribute(); - - // pour les asso quoi qu'il arrive il faut les lier des 2 cotes - // pour pouvoir supprimer en cascade l'asso lors de la suppression - // d'un des cotes - if (!(attr.isNavigable() - || hasUnidirectionalRelationOnAbstractType(reverse, model) - || attr.hasAssociationClass())) { - continue; - } - - String attrVisibility = attr.getVisibility(); - ObjectModelModifier modifier = ObjectModelJavaModifier.fromVisibility(attrVisibility); - if (!attr.hasAssociationClass()) { - String attrType = attr.getType(); - String attrName = attr.getName(); - if (isEntity(attrType)) { - attrType += "DTO"; - } - if (!GeneratorUtil.isNMultiplicity(attr)) { - attr2 = addAttribute(result, attrName, attrType, null, modifier); - } else { - attr2 = addAttribute(result, attrName, attrType + "[]", null, modifier); - } - } else { - String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(attr); - String assocClassFQN = attr.getAssociationClass().getQualifiedName(); - if (!GeneratorUtil.isNMultiplicity(attr)) { - attr2 = addAttribute(result, GeneratorUtil.toLowerCaseFirstLetter(assocAttrName), assocClassFQN + "DTO", null, modifier); - } else { - attr2 = addAttribute(result, GeneratorUtil.toLowerCaseFirstLetter(assocAttrName), assocClassFQN + "DTO[]", null, modifier); - } - } - if (attr2 != null) { - if (TopiaGeneratorUtil.hasDocumentation(attr)) { - setDocumentation(attr2, attr.getDocumentation()); - } - - String annotation = TopiaGeneratorUtil.getAnnotationTagValue(attr); - if (!StringUtils.isEmpty(annotation)) { - addAnnotation(result, attr2, annotation); - } - } - } - - //Déclaration des attributs d'une classe d'associations - if (clazz instanceof ObjectModelAssociationClass) { - ObjectModelAssociationClass assoc = (ObjectModelAssociationClass) clazz; - for (ObjectModelAttribute attr : assoc.getParticipantsAttributes()) { - if (attr != null) { - String attrVisibility = attr.getVisibility(); - ObjectModelModifier modifier = ObjectModelJavaModifier.fromVisibility(attrVisibility); - String attrType = attr.getType(); - String attrName = attr.getName(); - if (isEntity(attrType)) { - attrType += "DTO"; - } - addAttribute(result, GeneratorUtil.toLowerCaseFirstLetter(attrName), attrType, null, modifier); - } - } - } - - addAttribute(result,"p", PropertyChangeSupport.class,"new PropertyChangeSupport(this)",ObjectModelJavaModifier.PROTECTED,ObjectModelJavaModifier.FINAL); - } - - protected void addOperations(ObjectModelClass result,ObjectModelClass clazz) { - - boolean generateDTOId = shouldGenerateDTOTopiaIdTagValue(clazz, model); - ObjectModelOperation op; - if (generateDTOId) { - op = addOperation(result, "setTopiaId", "void", ObjectModelJavaModifier.PUBLIC); - addParameter(op, "String", "topiaId"); - setOperationBody(op, "" -/*{ - this.topiaId = topiaId; - }*/ - ); - - op = addOperation(result, "getTopiaId", "String", ObjectModelJavaModifier.PUBLIC); - setOperationBody(op, "" -/*{ - return topiaId; - }*/ - ); - } - - op = addOperation(result, "addPropertyChangeListener", "void"); - addParameter(op,PropertyChangeListener.class,"listener"); - setOperationBody(op,"" -/*{ - p.addPropertyChangeListener(listener); - }*/ - ); - - op = addOperation(result, "addPropertyChangeListener", "void"); - addParameter(op, String.class, "propertyName"); - addParameter(op, PropertyChangeListener.class, "listener"); - setOperationBody(op, "" -/*{ - p.addPropertyChangeListener(propertyName, listener); - }*/ - ); - - op = addOperation(result, "removePropertyChangeListener", "void"); - addParameter(op, PropertyChangeListener.class, "listener"); - setOperationBody(op, "" -/*{ - p.removePropertyChangeListener(listener); - }*/ - ); - - op = addOperation(result, "removePropertyChangeListener", "void"); - addParameter(op, String.class, "propertyName"); - addParameter(op, PropertyChangeListener.class, "listener"); - setOperationBody(op, "" -/*{ - p.removePropertyChangeListener(propertyName, listener); - }*/ - ); - - for (ObjectModelAttribute attr : clazz.getAttributes()) { - - ObjectModelAttribute reverse = attr.getReverseAttribute(); - - if (!(attr.isNavigable() || hasUnidirectionalRelationOnAbstractType(reverse, model))) { - continue; - } - - String attrName = attr.getName(); - - if (!attr.hasAssociationClass()) { - String attrType = attr.getType(); - if (isEntity(attrType)) { - attrType += "DTO"; - } - String setterName = getJavaBeanMethodName("set", attrName); - String getterName = getJavaBeanMethodName("get", attrName); - if (!GeneratorUtil.isNMultiplicity(attr)) { - op = addOperation(result, setterName, "void", ObjectModelJavaModifier.PUBLIC); - addParameter(op, attrType, "value"); - setOperationBody(op, "" -/*{ - <%=attrType%> oldValue = this.<%=attrName%>; - this.<%=attrName%> = value; - p.firePropertyChange("<%=attrName%>", oldValue, value); - }*/ - ); - - op = addOperation(result, getterName, attrType, ObjectModelJavaModifier.PUBLIC); - setOperationBody(op, "" -/*{ - return <%=attrName%>; - }*/ - ); - - } else { - - op = addOperation(result, setterName, "void", ObjectModelJavaModifier.PUBLIC); - addParameter(op, attrType+"[]", "values"); - setOperationBody(op, "" -/*{ - <%=attrType%>[] oldValues = this.<%=attrName%>; - this.<%=attrName%> = values; - p.firePropertyChange("<%=attrName%>", oldValues, values); - }*/ - ); - - op = addOperation(result, getterName, attrType+"[]", ObjectModelJavaModifier.PUBLIC); - setOperationBody(op, "" -/*{ - return <%=attrName%>; - }*/ - ); - } - } else { - String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(attr); - String propertyName = GeneratorUtil.toLowerCaseFirstLetter(assocAttrName); - String assocClassFQN = attr.getAssociationClass().getQualifiedName(); - String setterName = getJavaBeanMethodName("set", assocAttrName); - String getterName = getJavaBeanMethodName("get", assocAttrName); - if (!GeneratorUtil.isNMultiplicity(attr)) { - op = addOperation(result, setterName, "void", ObjectModelJavaModifier.PUBLIC); - addParameter(op, assocClassFQN + "DTO", "association"); - setOperationBody(op, "" -/*{ - <%=assocClassFQN%>DTO oldAssocation= this.<%=propertyName%>; - this.<%=propertyName%> = association; - p.firePropertyChange("<%=attrName%>", oldAssocation, assocation); - }*/ - ); - - op = addOperation(result, getterName, assocClassFQN + "DTO", ObjectModelJavaModifier.PUBLIC); - setOperationBody(op, "" -/*{ - return <%=propertyName%>; - }*/ - ); - - } else { - op = addOperation(result, setterName, "void", ObjectModelJavaModifier.PUBLIC); - addParameter(op, assocClassFQN + "DTO[]", "values"); - setOperationBody(op, "" -/*{ - <%=assocClassFQN%>DTO[] oldValues = this.<%=propertyName%>; - this.<%=propertyName%> = values; - p.firePropertyChange("<%=attrName%>", oldValues, values); - }*/ - ); - - op = addOperation(result, getterName, assocClassFQN + "DTO[]", ObjectModelJavaModifier.PUBLIC); - setOperationBody(op, "" -/*{ - return this.<%=propertyName%>; - }*/ - ); - } - } - } - - op = addOperation(result,"toString",String.class, ObjectModelJavaModifier.PUBLIC); - StringBuilder buffer = new StringBuilder(); - - buffer.append("" -/*{ - String result = new ToStringBuilder(this). -}*/ - ); - - for (Object o : clazz.getAttributes()) { - ObjectModelAttribute attr = (ObjectModelAttribute) o; - //FIXME possibilité de boucles (non directes) - ObjectModelClass attrEntity = null; - if (model.hasClass(attr.getType())) { - attrEntity = model.getClass(attr.getType()); - } - boolean isEntity = attrEntity != null && TopiaGeneratorUtil.isEntity(attrEntity); - ObjectModelAttribute reverse = attr.getReverseAttribute(); - if (isEntity && (reverse == null || !reverse.isNavigable()) && !attr.hasAssociationClass() || !isEntity) { - String attrName = attr.getName(); - buffer.append("" -/*{ append("<%=attrName%>", this.<%=attrName%>). -}*/ - ); - } - } - buffer.append("" -/*{ toString(); - return result; -}*/ - ); - setOperationBody(op, buffer.toString()); - } -} Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityDaoTransformer.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityDaoTransformer.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityDaoTransformer.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,1162 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2011 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.topia.generator; - -/*{generator option: parentheses = false}*/ -/*{generator option: writeString = +}*/ - -import com.google.common.base.Strings; -import com.google.common.collect.Sets; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.eugene.GeneratorUtil; -import org.nuiton.eugene.java.JavaGeneratorUtil; -import org.nuiton.eugene.java.ObjectModelTransformerToJava; -import org.nuiton.eugene.models.object.ObjectModel; -import org.nuiton.eugene.models.object.ObjectModelAssociationClass; -import org.nuiton.eugene.models.object.ObjectModelAttribute; -import org.nuiton.eugene.models.object.ObjectModelClass; -import org.nuiton.eugene.models.object.ObjectModelClassifier; -import org.nuiton.eugene.models.object.ObjectModelDependency; -import org.nuiton.eugene.models.object.ObjectModelInterface; -import org.nuiton.eugene.models.object.ObjectModelJavaModifier; -import org.nuiton.eugene.models.object.ObjectModelOperation; -import org.nuiton.topia.TopiaException; -import org.nuiton.topia.persistence.TopiaEntity; -import org.nuiton.topia.persistence.TopiaQueryBuilderAddCriteriaOrRunQueryStep; - -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; - -/** - * To generate all <code>DAO</code> related classes for a given entity. - * - * @author tchemit <chemit@codelutin.com> - * @since 2.5.4 - * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.generator.EntityDaoTransformer" - */ -public class EntityDaoTransformer extends ObjectModelTransformerToJava { - - /** Logger. */ - private static final Log log = - LogFactory.getLog(EntityDaoTransformer.class); - - /** - * map of direct usages (values) for each entity (key). - * <p/> - * This map is used to generate the findUsages methods for DAOAbstract. - */ - protected Map<ObjectModelClass, Set<ObjectModelClass>> usages; - - /** - * All entities fqn of the model (used to detect if an attribute is not - * an entity). - */ - protected Set<String> allEntitiesFqn; - - /** - * The class of abstract dao to use. - * @since 2.5 - */ - protected Class<?> daoImplementation; - - protected String entityEnumName; - - protected String entityEnumPackage; - - /** - * Map of extra operations for DAO. The key of the map is the qualified - * name of the entity relative to the DAO. - */ - protected Map<String, Collection<ObjectModelOperation>> extraOperations = - new HashMap<String, Collection<ObjectModelOperation>>(); - - @Override - public void transformFromModel(ObjectModel model) { - - boolean generateStandaloneEnum = - TopiaGeneratorUtil.shouldGenerateStandaloneEnumForDAOHelper(model); - String modelName = model.getName(); - - entityEnumName = modelName + "EntityEnum"; - - String packageName = - getOutputProperties().getProperty(PROP_DEFAULT_PACKAGE); - - if (generateStandaloneEnum) { - entityEnumPackage = packageName + "." + entityEnumName; - } else { - String daoHelperClazzName = modelName + "DAOHelper"; - entityEnumPackage = packageName + "." + daoHelperClazzName + "." + entityEnumName; - } - - usages = TopiaGeneratorUtil.searchDirectUsages(model); - - daoImplementation = TopiaGeneratorUtil.getDAOImplementation(model); - - - // keep all classifiers on the model which are entities - List<ObjectModelClass> allEntities = - TopiaGeneratorUtil.getEntityClasses(model, true); - allEntitiesFqn = new HashSet<String>(allEntities.size()); - for (ObjectModelClass entity : allEntities) { - String fqn = entity.getQualifiedName(); - allEntitiesFqn.add(fqn); - Collection<ObjectModelOperation> daoOperations = - new HashSet<ObjectModelOperation>(); - for (ObjectModelOperation op : entity.getOperations()) { - if (TopiaGeneratorUtil.hasDaoStereotype(op)) { - daoOperations.add(op); - } - } - - if (daoOperations.isEmpty()) { - - // found some dao operations - extraOperations.put(fqn, daoOperations); - } - } - } - - @Override - public void transformFromInterface(ObjectModelInterface interfacez) { - if (!TopiaGeneratorUtil.hasDaoStereotype(interfacez)) { - return; - } - - /** - * EVO #636 : Manage extra operations for DAO from "dao" dependency - * between an interface with stereotype <<dao>> (dependency client) and - * a class with stereotype <<entity>> (dependency supplier). - */ - - ObjectModelDependency dependency = - interfacez.getDependency(TopiaGeneratorUtil.DEPENDENCIES_DAO); - - if (dependency == null) { - if (log.isWarnEnabled()) { - log.warn("Could not find dependency " + - TopiaGeneratorUtil.DEPENDENCIES_DAO + - " but DAO stereotype was placed on the interface " + - interfacez.getName()); - } - return; - } - - ObjectModelClassifier classifier = dependency.getSupplier(); - - if (!TopiaGeneratorUtil.isEntity(classifier)) { - - // dependency supplier is not an entity... - if (log.isWarnEnabled()) { - log.warn("Dependency supplier " + - classifier.getQualifiedName() + - " is not an entity."); - } - return; - } - - // keep only direct operations - Collection<ObjectModelOperation> operations = - interfacez.getOperations(); - - if (CollectionUtils.isEmpty(operations)) { - - // no operations on interface, this is not normal - if (log.isWarnEnabled()) { - log.warn("No operation found on interface with DAO " + - "stereotype "+classifier.getQualifiedName()); - } - return; - } - if (log.isDebugEnabled()) { - log.debug("add "+operations.size()+" extra operation(s) for DAO"); - } - - extraOperations.put(classifier.getQualifiedName(), operations); - } - - @Override - public void transformFromClass(ObjectModelClass clazz) { - if (!TopiaGeneratorUtil.isEntity(clazz)) { - // not an entity - return; - } - String clazzName = clazz.getName(); - String clazzFQN = clazz.getQualifiedName(); - - if (isGenerateGeneratedDao(clazz)) { - generateGeneratedDao(clazz, clazzName, clazzFQN); - } - - if (isGenerateAbstractDao(clazz)) { - generateAbstractDao(clazz, clazzName, clazzFQN); - } - - if (isGenerateLegacyDao(clazz)) { - generateLegacyDao(clazz, clazzName, clazzFQN); - } - - if (isGenerateConcreteDao(clazz)) { - generateConcreteDao(clazz, clazzName, clazzFQN); - } - - } - - protected boolean isGenerateLegacyDao(ObjectModelClass input) { - - String daoLegacyFqn = TopiaGeneratorUtil.getLegacyDaoFqn(input); - - if (isInClassPath(daoLegacyFqn)) { - - // already in class-path - return false; - } - - // can safely generate the dao impl - return true; - } - - protected boolean isGenerateConcreteDao(ObjectModelClass input) { - - String daoConcreteFqn = TopiaGeneratorUtil.getConcreteDaoFqn(input); - - if (isInClassPath(daoConcreteFqn)) { - - // already in class-path - return false; - } - - // can safely generate the dao impl - return true; - } - - protected boolean isGenerateGeneratedDao(ObjectModelClass input) { - - String daoGeneratedFqn = TopiaGeneratorUtil.getGeneratedDaoFqn(input); - - if (isInClassPath(daoGeneratedFqn)) { - - // already in class-path - return false; - } - - // can safely generate the dao impl - return true; - - } - - protected boolean isGenerateAbstractDao(ObjectModelClass input) { - - String fqn = TopiaGeneratorUtil.getAbstractDaoFqn(input); - - if (isInClassPath(fqn)) { - - // already in class-path - return false; - } - - Collection<ObjectModelOperation> moreOperations = - extraOperations.get(input.getQualifiedName()); - - if (CollectionUtils.isNotEmpty(moreOperations)) { - - // no user operations, can not generate it - return false; - } - - // can safely generate the dao impl - return true; - - } - - protected void generateLegacyDao(ObjectModelClass clazz, String clazzName, String clazzFQN) { - ObjectModelClass daoClass = createClass(TopiaGeneratorUtil.getLegacyDaoName(clazz), clazz.getPackageName()); - addAnnotation(daoClass, daoClass, Deprecated.class); - setDocumentation(daoClass, "/**\n" + - " * Cette classe etend le DAOImpl pour parametrer la classe avec le bon type\n" + - " * Cette classe est marque finale car l'heritage entre les DAO se fait\n" + - " * sur les DOAImpl, c-a-d que DAOAbstract peut etendre le DAOImpl\n" + - " */"); - setSuperClass(daoClass, TopiaGeneratorUtil.getAbstractDaoFqn(clazz) + "<" + clazzName + ">"); - } - - protected void generateConcreteDao(ObjectModelClass clazz, String clazzName, String clazzFQN) { - String concreteDaoName = TopiaGeneratorUtil.getConcreteDaoName(clazz); - ObjectModelClass daoClass = createClass(concreteDaoName, clazz.getPackageName()); - setDocumentation(daoClass, "/**\n" + - " * Cette classe etend le DAOImpl pour parametrer la classe avec le bon type\n" + - " * Cette classe est marque finale car l'heritage entre les DAO se fait\n" + - " * sur les DOAImpl, c-a-d que DAOAbstract peut etendre le DAOImpl\n" + - " */"); - // to support legacy dao - String superclassQualifiedName = TopiaGeneratorUtil.getLegacyDaoFqn(clazz); - // TODO brendan 04/10/13 above line should be replaced by -// String superclassQualifiedName = TopiaGeneratorUtil.getAbstractDaoFqn(clazz) + "<" + clazzName + ">"; - setSuperClass(daoClass, superclassQualifiedName); - - // TODO AThimel 25/10/13 Remove the next lines in ToPIA 3.1 - // Look for legacy Dao class, then warn user if found in classpath - String legacyConcreteDaoName = TopiaGeneratorUtil.getLegacyDaoName(clazz); - warnOnLegacyClassDetected(clazz.getPackageName(), legacyConcreteDaoName, concreteDaoName, null, - TopiaGeneratorUtil.getAbstractDaoFqn(clazz) + "<" + clazzName + ">"); - } - - protected void generateAbstractDao(ObjectModelClass clazz, - String clazzName, - String clazzFQN) { - - Collection<ObjectModelOperation> moreOperations = - extraOperations.get(clazz.getQualifiedName()); - - if (CollectionUtils.isEmpty(moreOperations)) { - - // no business Dao found, can safely generate the abstract Dao class - - String abstractDaoName = TopiaGeneratorUtil.getAbstractDaoName(clazz); - String daoGenerics = "<E extends " + clazzName + ">"; - ObjectModelClass abstractDaoClass = createClass(abstractDaoName + daoGenerics, clazz.getPackageName()); - String documentation = String.format("/**%n" + - " * Implantation du Dao pour l'entité '%s'.%n" + - " * L'utilisateur peut remplacer cette classe par la sienne en la mettant%n" + - " * simplement dans ses sources. Cette classe générée sera alors simplement%n" + - " * ignorée à la génération suivante.%n" + - " */", clazzName); - setDocumentation(abstractDaoClass, documentation); - String superclassQualifiedName = TopiaGeneratorUtil.getGeneratedDaoFqn(clazz) + "<E>"; - setSuperClass(abstractDaoClass, superclassQualifiedName); - - // TODO AThimel 25/10/13 Remove the next lines in ToPIA 3.1 - // Look for legacy Dao class, then warn user if found in classpath - String legacyDaoImplName = TopiaGeneratorUtil.getLegacyDaoName(clazz) + "Impl"; - warnOnLegacyClassDetected(clazz.getPackageName(), legacyDaoImplName, abstractDaoName, daoGenerics, - superclassQualifiedName); - - } - } - - // TODO AThimel 25/10/13 Remove this method in ToPIA 3.1 - protected void warnOnLegacyClassDetected(String packageName, - String legacyDaoName, - String daoName, - String daoGenerics, - String superclassQualifiedName) { - - String legacyDaoFqn = String.format("%s.%s", packageName, legacyDaoName); - - // AThimel 25/10/13 Not using isInClassPath(fqn) because this method logs that file won't be generated - if (log.isWarnEnabled() && getFileInClassPath(legacyDaoFqn) != null) { - String format = "public class %s%s extends %s {"; - String superclassName = superclassQualifiedName.substring(superclassQualifiedName.lastIndexOf('.') + 1); - String daoDeclaration = String.format(format, daoName, Strings.nullToEmpty(daoGenerics), superclassName); - String warnMessage = "Legacy DAO detected : %s !%n" + - " - You should consider renaming '%s' to '%s'%n" + - " - Expected class declaration is : %s%n" + - "%n"; // AThimel 29/10/13 Add a new line for log clearness - log.warn(String.format(warnMessage, legacyDaoFqn, legacyDaoName, daoName, daoDeclaration)); - } - - } - - protected void generateGeneratedDao(ObjectModelClass clazz, - String clazzName, - String clazzFQN) { - ObjectModelClass daoAbstractClass = createAbstractClass(TopiaGeneratorUtil.getGeneratedDaoName(clazz) + "<E extends " + clazzName + '>', - clazz.getPackageName()); - - // super class - - String superClassName = null; - for (ObjectModelClass parent : clazz.getSuperclasses()) { - if (TopiaGeneratorUtil.isEntity(parent)) { - superClassName = TopiaGeneratorUtil.getAbstractDaoFqn(parent) + "<E>"; - // in java no multi-inheritance - break; - } - } - if (superClassName == null) { - superClassName = daoImplementation.getName() + "<E>"; - } - if (log.isDebugEnabled()) { - log.debug("super class = " + superClassName); - } - setSuperClass(daoAbstractClass, superClassName); - - String prefix = getConstantPrefix(clazz, ""); - setConstantPrefix(prefix); - - // imports - - Collection<ObjectModelOperation> daoOperations = getDaoOperations(clazz); - - if (TopiaGeneratorUtil.isCollectionNeeded(daoOperations)) { - addImport(daoAbstractClass, Collection.class); - } - if (TopiaGeneratorUtil.isSetNeeded(daoOperations)) { - addImport(daoAbstractClass, Set.class); - } - addImport(daoAbstractClass, List.class); - addImport(daoAbstractClass, TopiaException.class); - addImport(daoAbstractClass, TopiaQueryBuilderAddCriteriaOrRunQueryStep.class); - - ObjectModelOperation op; - - // getEntityClass - - op = addOperation(daoAbstractClass, - "getEntityClass", - "Class<E>", - ObjectModelJavaModifier.PUBLIC); - addAnnotation(daoAbstractClass, op,Override.class); - setOperationBody(op, "" -/*{ - return (Class<E>) <%=clazzName%>.class; - }*/ - ); - - // getTopiaEntityEnum - addImport(daoAbstractClass, entityEnumPackage); - op = addOperation(daoAbstractClass, - "getTopiaEntityEnum", - entityEnumName, - ObjectModelJavaModifier.PUBLIC); - addAnnotation(daoAbstractClass, op,Override.class); - setOperationBody(op, "" -/*{ - return <%=entityEnumName%>.<%=clazzName%>; - }*/ - ); - - generateDAOOperations(daoAbstractClass, daoOperations); - - generateDelete(clazz, daoAbstractClass); - - generateNaturalId(daoAbstractClass, clazz); - - generateNotNull(daoAbstractClass, clazz); - - for (ObjectModelAttribute attr : clazz.getAttributes()) { - if (!attr.isNavigable()) { - continue; - } - - if (!GeneratorUtil.isNMultiplicity(attr)) { - generateNoNMultiplicity(clazzName, daoAbstractClass, attr, false); - } else { - generateNMultiplicity(clazzName, daoAbstractClass, attr); - } - } - - if (clazz instanceof ObjectModelAssociationClass) { - ObjectModelAssociationClass assocClass = - (ObjectModelAssociationClass) clazz; - for (ObjectModelAttribute attr : assocClass.getParticipantsAttributes()) { - if (attr != null) { - if (!GeneratorUtil.isNMultiplicity(attr)) { - generateNoNMultiplicity(clazzName, daoAbstractClass, attr, true); - } else { - generateNMultiplicity(clazzName, daoAbstractClass, attr); - } - } - } - } - - Set<ObjectModelClass> usagesForclass = usages.get(clazz); - generateFindUsages(clazz, daoAbstractClass, usagesForclass); - } - - protected void generateDelete(ObjectModelClass clazz, - ObjectModelClass result) { - - StringBuilder body = new StringBuilder(); - String modelName = StringUtils.capitalize(model.getName()); - String providerFQN = getOutputProperties().getProperty( - PROP_DEFAULT_PACKAGE) + '.' + modelName + - "DAOHelper.getImplementationClass"; - - for (ObjectModelAttribute attr : clazz.getAttributes()) { - - String attrType = GeneratorUtil.getSimpleName(attr.getType()); - - String reverseAttrName = attr.getReverseAttributeName(); - ObjectModelAttribute reverse = attr.getReverseAttribute(); - if (attr.hasAssociationClass() || - reverse == null || !reverse.isNavigable()) { - - // never treate a non reverse and navigable attribute - // never treate an association class attribute - continue; - } - - // at this point we are sure to have a attribute which is - // - reverse - // - navigable - // - not from an association class - if (!allEntitiesFqn.contains(attr.getType())) { - - // this attribute is not from an entity, don't treate it - if (log.isDebugEnabled()) { - log.debug("[" + result.getName() + "] Skip attribute [" + - attr.getName() + "] with type " + attr.getType()); - } - continue; - } - - // At this point, the attribute type is a entity - if (GeneratorUtil.isNMultiplicity(attr) && - GeneratorUtil.isNMultiplicity(reverse)) { - // On doit absolument supprimer pour les relations many-to-many - // le this de la collection de l'autre cote - - String attrDBName = TopiaGeneratorUtil.getDbName(attr); - String attrClassifierDBName = TopiaGeneratorUtil.getDbName(attr.getClassifier()); - String attrJoinTableName = TopiaGeneratorUtil.getManyToManyTableName(attr); - String attrReverseDBName = TopiaGeneratorUtil.getReverseDbName(attr); - - //FIXME_-FC-20100413 Use a TopiaQuery (use HQLin elements) -// // Add DAOHelper -// String daoHelper = modelName + "DAOHelper"; -// String daoHelperFQN = getOutputProperties(). -// getProperty(PROP_DEFAULT_PACKAGE) + '.' + daoHelper; -// addImport(result, daoHelperFQN); -// -// // Add import for TopiaQuery -// addImport(result, TopiaQuery.class); -// -// // Entity DAO and reversePropertyName -// String entityDAO = attrType + "DAO"; -// String reverseAttrNameProperty = -// attrType + "." + getConstantName(reverseAttrName); -// -// -// <%=entityDAO%> dao = <%=daoHelper%>.get<%=entityDAO%>(getTopiaContext()); -// TopiaQuery query = dao.createQuery("B"). -// addFrom(entity.getClass(), "A"). -// add("A", entity). -// addInElements("A", "B." + <%=reverseAttrNameProperty%>); -// -// System.out.println("Query : " + query); -// List<<%=attrType%>> list = dao.findAllByQuery(query); - - String removeName = getJavaBeanMethodName("remove", reverseAttrName); - body.append("" -/*{ - { - List<<%=attrType%>> list = topiaHibernateSupport.getHibernateSession().createSQLQuery( - "SELECT main.topiaid " + - "from <%=attrClassifierDBName%> main, <%=attrJoinTableName%> secondary " + - "where main.topiaid=secondary.<%=attrDBName%>" + - " and secondary.<%=attrReverseDBName%>='" + entity.getTopiaId() + "'") - .addEntity("main", <%=providerFQN%>(<%=attrType%>.class)).list(); - - for (<%=attrType%> item : list) { - item.<%=removeName%>(entity); - } - } -}*/ - ); - } else if (!GeneratorUtil.isNMultiplicity(reverse)) { - // On doit mettre a null les attributs qui ont cet objet sur les - // autres entites en one-to-* - // TODO peut-etre qu'hibernate est capable de faire ca tout seul ? - // THIMEL: J'ai remplacé reverse.getName() par reverseAttrName sans certitude - addImport(result, attrType); - addImport(result, attr.getType() + "TopiaDao"); // AThimel 30/10/13 Not using attrType because we need FQN // Can use TopiaGeneratorUtil.getConcreteDaoFqn(...) ? - String attrSimpleType = TopiaGeneratorUtil.getClassNameFromQualifiedName(attrType); - // XXX brendan 04/10/13 do not hard code concrete dao name - String attrConcreteDaoClassName = attrSimpleType + "TopiaDao"; - String getName = getJavaBeanMethodName("get", reverseAttrName); - String setName = getJavaBeanMethodName("set", reverseAttrName); - - body.append("" - /*{ - { - <%=attrConcreteDaoClassName%> dao = topiaDaoSupplier - .getDao(<%=attrSimpleType%>.class, <%=attrConcreteDaoClassName%>.class); - List<<%=attrSimpleType%>> list = dao - .forProperties(<%=attrSimpleType%>.<%=getConstantName(reverseAttrName)%>, entity) - .findAll(); - for (<%=attrSimpleType%> item : list) { - - // sletellier : Set null only if target is concerned by deletion - if (entity.equals(item.<%=getName%>())) { - item.<%=setName%>(null); - } - }*/ - ); - if (attr.isAggregate()) { - body.append("" -/*{ - topiaDaoSupplier.getDao(<%=attrSimpleType%>.class).delete(item); -}*/ - ); - } - body.append("" -/*{ - } - } -}*/ - ); - - } - } - - if (body.length()>0) { - // something specific was done, need to generate the method - ObjectModelOperation op; - op = addOperation(result, "delete", "void", ObjectModelJavaModifier.PUBLIC); - addAnnotation(result, op,Override.class); - addParameter(op, "E", "entity"); - body.append("" -/*{ - super.delete(entity); - }*/ - ); - setOperationBody(op, body.toString()); - } - - - - } - - protected void generateFindUsages(ObjectModelClass clazz, - ObjectModelClass result, - Set<ObjectModelClass> usagesForclass) { - - builder.addImport(result, LinkedList.class.getName()); - builder.addImport(result, Map.class.getName()); - builder.addImport(result, HashMap.class.getName()); - builder.addImport(result, TopiaEntity.class.getName()); - - if (clazz instanceof ObjectModelAssociationClass || - usagesForclass.isEmpty()) { - // not for an association class - // just let a null method - ObjectModelOperation operation; - operation = addOperation(result, - "findUsages", - "<U extends TopiaEntity> List<U>", - ObjectModelJavaModifier.PUBLIC); - - addParameter(operation, "Class<U>", "type"); - addParameter(operation, "E", "entity"); - addAnnotation(result, operation, Override.class); - setOperationBody(operation, "" -/*{ - return new LinkedList<U>(); - }*/ - ); - - operation = addOperation(result, - "findAllUsages", - "Map<Class<? extends TopiaEntity>, List<? extends TopiaEntity>>", - ObjectModelJavaModifier.PUBLIC); - - addParameter(operation, "E", "entity"); - addAnnotation(result, operation, Override.class); - setOperationBody(operation, "" -/*{ - return new HashMap<Class<? extends TopiaEntity>, List<? extends TopiaEntity>>(); - }*/ - ); - - return; - } - List<ObjectModelClass> allEntities; - Map<String, ObjectModelClass> allEntitiesByFQN; - - allEntities = TopiaGeneratorUtil.getEntityClasses(model, true); - allEntitiesByFQN = new TreeMap<String, ObjectModelClass>(); - - // prepare usages map and fill allEntitiesByFQN map - for (ObjectModelClass klass : allEntities) { - allEntitiesByFQN.put(klass.getQualifiedName(), klass); - } - - ObjectModelOperation operation; - operation = addOperation(result, - "findUsages", - "<U extends TopiaEntity> List<U>", - ObjectModelJavaModifier.PUBLIC); - - addParameter(operation, "Class<U>", "type"); - addParameter(operation, "E", "entity"); - addAnnotation(result, operation, Override.class); - StringBuilder buffer = new StringBuilder(300); - buffer.append("" -/*{ - List<?> result = new LinkedList(); - List tmp; -}*/ - ); - - for (ObjectModelClass usageClass : usagesForclass) { - String usageType = usageClass.getQualifiedName(); - builder.addImport(result, usageType); - String usageSimpleType = - TopiaGeneratorUtil.getClassNameFromQualifiedName(usageType); - String usageSimplePropertyMethod = "findAllBy" + usageSimpleType; - String usageCollectionPropertyMethod = "findAllContaining" + usageSimpleType; - for (ObjectModelAttribute attr : usageClass.getAttributes()) { - if (!attr.isNavigable()) { - // skip this case - continue; - } - String type; - String attrName = attr.getName(); - if (attr.hasAssociationClass()) { - //FIXME-TC20100224 dont known how to do this ? - continue; -// type = attr.getAssociationClass().getQualifiedName(); -// //FIXME-TC20100224 : this is crazy ??? must find the good name -// // Perhaps need to make different cases? -// attrName = attrName + "_" + TopiaGeneratorUtil.toLowerCaseFirstLetter(attr.getAssociationClass().getName()); - } else { - type = attr.getType(); - } - if (!allEntitiesByFQN.containsKey(type)) { - // not a entity, can skip for this attribute - continue; - } - ObjectModelClass targetEntity = allEntitiesByFQN.get(type); -// if (!type.equals(clazz.getQualifiedName())) { - if (!targetEntity.equals(clazz)) { - // not a good attribute reference - continue; - } - // found something to seek - - String methodName; - if (TopiaGeneratorUtil.isNMultiplicity(attr)) { - methodName = getJavaBeanMethodName("findAllContains", attrName); - } else { - methodName = getJavaBeanMethodName("findAllBy", attrName); - } - String daoName = StringUtils.capitalize(usageSimpleType) + "DAO"; - - builder.addImport(result, usageClass.getPackageName() + '.' + daoName); - - buffer.append("" -/*{ - if (type == <%=usageSimpleType%>.class) { - <%=daoName%> dao = (<%=daoName%>) - topiaDaoSupplier.getDao(<%=usageSimpleType%>.class); - tmp = dao.<%=methodName%>(entity); - result.addAll(tmp); - } -}*/ - ); - } - } - - buffer.append("" -/*{ - return (List<U>) result; - }*/ - ); - setOperationBody(operation, buffer.toString()); - - operation = addOperation(result, - "findAllUsages", - "Map<Class<? extends TopiaEntity>, List<? extends TopiaEntity>>", - ObjectModelJavaModifier.PUBLIC); - - addParameter(operation, "E", "entity"); - addAnnotation(result, operation, Override.class); - - buffer = new StringBuilder(300); - buffer.append("" -/*{ - Map<Class<? extends TopiaEntity>,List<? extends TopiaEntity>> result; - result = new HashMap<Class<? extends TopiaEntity>, List<? extends TopiaEntity>>(<%=usagesForclass.size()%>); - - List<? extends TopiaEntity> list; -}*/ - ); - for (ObjectModelClass usageClass : usagesForclass) { - - String fqn = usageClass.getName(); - buffer.append("" -/*{ - list = findUsages(<%=fqn%>.class, entity); - if (!list.isEmpty()) { - result.put(<%=fqn%>.class, list); - } -}*/ - ); - - } - buffer.append("" -/*{ - return result; - }*/ - ); - - setOperationBody(operation, buffer.toString()); - } - - /** - * Generation of DAO operations signatures from class. These operations are - * abstract and identified by <<dao>> stereotype in the model. The - * developper must defined these methods in the DAOImpl associated to this - * DAOAbstract. - * - * @param result clazz where to add operations - * @param operations operations to generate - * @deprecated will be removed ASAP in topia 3.0 - */ - @Deprecated - protected void generateDAOOperations(ObjectModelClass result, - Collection<ObjectModelOperation> - operations) { - if (CollectionUtils.isEmpty(operations)) { - - // no extra operations to generate - return; - } - - for (ObjectModelOperation op : operations) { - - Set<String> exceptions = op.getExceptions(); - cloneOperation(op, - result, - true, - ObjectModelJavaModifier.ABSTRACT, - ObjectModelJavaModifier.fromVisibility(op.getVisibility()) - ); - } - } - - - protected void generateNoNMultiplicity(String clazzName, - ObjectModelClass result, - ObjectModelAttribute attr, - boolean isAssoc) { - String attrName = attr.getName(); - String attrType = attr.getType(); - String propertyName = clazzName + "." + getConstantName(attrName); - - String attrTypeForGeneric; - if (JavaGeneratorUtil.isPrimitiveType(attrType)) { - attrTypeForGeneric = TopiaGeneratorUtil.getClassForPrimitiveType(attr); - } else { - attrTypeForGeneric = attrType; - } - - if (!isAssoc && attr.hasAssociationClass()) { - String assocClassName = attr.getAssociationClass().getName(); - String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(attr); - // It is about transitivity : use the property to access the - // associationClass + '.' + the property to access the expected - // attribute - // <class>.<attrAssoc> + '.' + <assocClass>.<attr> - propertyName = - clazzName + '.' + getConstantName(assocAttrName) + - " + '.' + " + - assocClassName + '.' + getConstantName(attrName); - } - - ObjectModelOperation op; - op = addOperation(result, - getJavaBeanMethodName("for", attrName, "In"), - "TopiaQueryBuilderAddCriteriaOrRunQueryStep<E>", - ObjectModelJavaModifier.PUBLIC); - addParameter(op, "Iterable<" + attrTypeForGeneric + ">", "v"); - setOperationBody(op, "" -/*{ - TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> result = forIn(<%=propertyName%>, (Iterable) v); - return result; - }*/ - ); - - op = addOperation(result, - getJavaBeanMethodName("for", attrName, "Equals"), - "TopiaQueryBuilderAddCriteriaOrRunQueryStep<E>", - ObjectModelJavaModifier.PUBLIC); - addParameter(op, attrType, "v"); - setOperationBody(op, "" -/*{ - TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> result = forEquals(<%=propertyName%>, v); - return result; - }*/ - ); - - String methodToDelegateName = op.getName(); - - op = addOperation(result, - getJavaBeanMethodName("findBy", attrName), - "E", - ObjectModelJavaModifier.PUBLIC); - addParameter(op, attrType, "v"); - setOperationBody(op, "" -/*{ - return <%=methodToDelegateName%>(v).findAnyOrNull(); - }*/ - ); - - addAnnotation(result, op, Deprecated.class); - - op = addOperation(result, - getJavaBeanMethodName("findAllBy", attrName), - "List<E>", - ObjectModelJavaModifier.PUBLIC); - addParameter(op, attrType, "v"); - setOperationBody(op, "" -/*{ - return <%=methodToDelegateName%>(v).findAll(); - }*/ - ); - - addAnnotation(result, op, Deprecated.class); - - if (!isAssoc && attr.hasAssociationClass()) { - String assocClassName = attr.getAssociationClass().getName(); - String assocClassFQN = attr.getAssociationClass().getQualifiedName(); - String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(attr); - String assocPropertyConstantName = getConstantName(assocAttrName); - op = addOperation(result, - getJavaBeanMethodName("findBy", assocClassName), - "E", - ObjectModelJavaModifier.PUBLIC); - addParameter(op, assocClassFQN, "value"); - setOperationBody(op, "" -/*{ - E result = findByProperty(<%=clazzName + "." + assocPropertyConstantName%>, value); - return result; - }*/ - ); - - op = addOperation(result, - getJavaBeanMethodName("findAllBy", assocClassName), - "List<E>", - ObjectModelJavaModifier.PUBLIC); - addParameter(op, assocClassFQN, "value"); - setOperationBody(op, "" -/*{ - List<E> result = findAllByProperty(<%=clazzName + "." + assocPropertyConstantName%>, value); - return result; - }*/ - ); - } - } - - protected void generateNMultiplicity(String clazzName, - ObjectModelClass result, - ObjectModelAttribute attr) { - String attrName = attr.getName(); - String attrType = attr.getType(); - if (attr.hasAssociationClass()) { - // do nothing for association class, too complex... - return; - } - ObjectModelOperation op; - - op = addOperation(result, - getJavaBeanMethodName("for", attrName, "Contains"), - "TopiaQueryBuilderAddCriteriaOrRunQueryStep<E>", - ObjectModelJavaModifier.PUBLIC); - addParameter(op, attrType, "v"); - setOperationBody(op, "" -/*{ - return forContains(<%=clazzName + "." + getConstantName(attrName)%>, v); - }*/ - ); - - String methodToDelegateName = op.getName(); - - op = addOperation(result, - getJavaBeanMethodName("findContains", attrName), - "E", - ObjectModelJavaModifier.PUBLIC); - addParameter(op, attrType, "v"); - setOperationBody(op, "" -/*{ - return <%=methodToDelegateName%>(v).findAnyOrNull(); - }*/ - ); - - addAnnotation(result, op, Deprecated.class); - - op = addOperation(result, - getJavaBeanMethodName("findAllContains", attrName), - "List<E>", - ObjectModelJavaModifier.PUBLIC); - addParameter(op, attrType, "v"); - setOperationBody(op, "" -/*{ - return <%=methodToDelegateName%>(v).findAll(); - }*/ - ); - - addAnnotation(result, op, Deprecated.class); - - } - - - /** - * Obtain business operations of the DAO. - * - * This operations can not be generated, but must be written by developper. - * - * @param clazz the clazz to test. - * @return collections of extra operations, or empty collection if none found. - * @deprecated Dao operation will not be generated anymore in a very close future - */ - @Deprecated - public Collection<ObjectModelOperation> getDaoOperations( - ObjectModelClass clazz) { - -// // Note : this collection will contains extra operations for DAO. -// // Overriding existing generated methods is not managed yet -// Collection<ObjectModelOperation> results = -// new ArrayList<ObjectModelOperation>(); - -// // This code will be deprecated -// for (ObjectModelOperation op : clazz.getOperations()) { -// if (TopiaGeneratorUtil.hasDaoStereotype(op)) { -// results.add(op); -// } -// } - - Collection<ObjectModelOperation> extra = - extraOperations.get(clazz.getQualifiedName()); - if (extra != null && !extra.isEmpty() && log.isWarnEnabled()) { - log.warn("Dao contract in model will not be supported in topia 3.0"); - } - return extra; -// if (extra != null) { -// for (ObjectModelOperation op : extra) { -// results.add(op); -// } -// } - -// return results; - } - - private void generateNaturalId(ObjectModelClass result, - ObjectModelClass clazz) { - Set<ObjectModelAttribute> props = - TopiaGeneratorUtil.getNaturalIdAttributes(clazz); - - if (!props.isEmpty()) { - - if (log.isDebugEnabled()) { - log.debug("generateNaturalId for " + props); - } - ObjectModelOperation findByNaturalId = addOperation(result, - "findByNaturalId", "E", ObjectModelJavaModifier.PUBLIC); - - ObjectModelOperation existByNaturalId = addOperation(result, - "existByNaturalId", "boolean", ObjectModelJavaModifier.PUBLIC); - - ObjectModelOperation createByNaturalId = addOperation(result, - "createByNaturalId", "E", ObjectModelJavaModifier.PUBLIC); - - Set<String> properties = Sets.newLinkedHashSet(); - String clazzName = clazz.getName(); - - for (ObjectModelAttribute attr : props) { - - String propName = attr.getName(); - String type = attr.getType(); - - addParameter(findByNaturalId, type, propName); - addParameter(existByNaturalId, type, propName); - addParameter(createByNaturalId, type, propName); - - String property = clazzName + '.' + getConstantName(propName) + ", " + propName; - properties.add(property); - - } - - String arguments = StringUtils.join(properties, ", "); - - setOperationBody(findByNaturalId, "" -/*{ - return forProperties(<%=arguments%>).findUnique(); - }*/ - ); - - setOperationBody(existByNaturalId, "" -/*{ - return forProperties(<%=arguments%>).exists(); - }*/ - ); - - setOperationBody(createByNaturalId, "" -/*{ - return create(<%=arguments%>); - }*/ - ); - } - } - - protected void generateNotNull(ObjectModelClass result, - ObjectModelClass clazz) { - - Set<ObjectModelAttribute> props = - TopiaGeneratorUtil.getNotNullAttributes(clazz); - - if (!props.isEmpty()) { - - if (log.isDebugEnabled()) { - log.debug("generateNotNull for " + props); - } - - ObjectModelOperation createByNotNull = addOperation(result, - "createByNotNull", "E", ObjectModelJavaModifier.PUBLIC); - - String createProperties = ""; -// String params = ""; - String clazzName = clazz.getName(); - for (ObjectModelAttribute attr : props) { - String propName = attr.getName(); - // add property as param in both methods - addParameter(createByNotNull, attr.getType(), propName); - - createProperties += - ", " + clazzName + '.' + getConstantName(propName) + - ", " + propName; - //params += ", " + propName; - } - createProperties = createProperties.substring(2); - //params = params.substring(2); - - setOperationBody(createByNotNull, "" -/*{ - return create(<%=createProperties%>); - }*/ - ); - } - } -} Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityHibernateMappingGenerator.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityHibernateMappingGenerator.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityHibernateMappingGenerator.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,768 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -/*{generator option: parentheses = true}*/ -/*{generator option: writeString = output.write}*/ - -/* * -* EntityHibernateMappingGenerator.java -* -* Created: 12 déc. 2005 -* -* @author Arnaud Thimel <thimel@codelutin.com> -* @version $Revision$ -* -*/ - -package org.nuiton.topia.generator; - -import org.apache.commons.lang3.BooleanUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.eugene.models.object.ObjectModelAssociationClass; -import org.nuiton.eugene.models.object.ObjectModelAttribute; -import org.nuiton.eugene.models.object.ObjectModelClass; -import org.nuiton.eugene.models.object.ObjectModelGenerator; - -import java.beans.Introspector; -import java.io.File; -import java.io.IOException; -import java.io.Writer; -import java.sql.Types; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -import static org.nuiton.topia.generator.TopiaGeneratorUtil.hasUnidirectionalRelationOnAbstractType; - -/** - * - * @author poussin <poussin@codelutin.com> - * @version $Id$ - * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.generator.EntityHibernateMappingGenerator" - */ -public class EntityHibernateMappingGenerator extends ObjectModelGenerator { - - /** - * Logger. - */ - private static final Log log = LogFactory - .getLog(EntityHibernateMappingGenerator.class); - - private static final String HIBERNATE_ATTRIBUTE_DEFAULT = "default"; - - private static final String HIBERNATE_ATTRIBUTE_SQL_TYPE = "sql-type"; - - private static final String HIBERNATE_ATTRIBUTE_NAME = "name"; - - private Map<String, String[]> columnNamesMap = new HashMap<String, String[]>(); - - public static final String HIBERNATE_ATTRIBUTE_LAZY = "lazy"; - - public static final String HIBERNATE_ATTRIBUTE_FETCH = "fetch"; - - public static final String HIBERNATE_ATTRIBUTE_NOT_NULL = "not-null"; - - public static final String HIBERNATE_ATTRIBUTE_SCHEMA = "schema"; - - public static final String HIBERNATE_ATTRIBUTE_INDEX = "index"; - - public static final String HIBERNATE_ATTRIBUTE_UNIQUE = "unique"; - - public static final String HIBERNATE_ATTRIBUTE_LENGTH = "length"; - - public static final String HIBERNATE_ATTRIBUTE_ORDER_BY = "order-by"; - - @Override - public String getFilenameForClass(ObjectModelClass clazz) { - String DOName = TopiaGeneratorUtil.getDOType(clazz, model); - return DOName.replace('.', File.separatorChar) + ".hbm.xml"; - } - - @Override - public void generateFromClass(Writer output, - ObjectModelClass input) throws IOException { - String persistenceType = TopiaGeneratorUtil.getPersistenceType(input); - if (!TopiaGeneratorUtil.isEntity(input) && - TopiaGeneratorUtil.PERSISTENCE_TYPE_HIBERNATE.equals(persistenceType)) { - return; - } -/*{<?xml version="1.0" encoding="UTF-8"?> -<hibernate-mapping xmlns="http://www.hibernate.org/xsd/hibernate-mapping" - xsi:schemaLocation="http://www.hibernate.org/xsd/hibernate-mapping classpath://org/hibernate/hibernate-mapping-4.0.xsd" - xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - default-access="field" auto-import="true" package="<%=input.getPackageName()%>"> -}*/ - boolean haveSuper = input.getSuperclasses().size() > 0; - // la liste des attributs faisant parti de la clef metier - List<ObjectModelAttribute> naturalAttributes = new ArrayList<ObjectModelAttribute>(); - // la liste des autres attributs - List<ObjectModelAttribute> noneNaturalAttributes = new ArrayList<ObjectModelAttribute>(); - - String clazzDOType = TopiaGeneratorUtil.getDOType(input, model); - String tableName = TopiaGeneratorUtil.getDbName(input); - String isAbstract = BooleanUtils.toStringTrueFalse(input.isAbstract()); - String clazzFQN = input.getQualifiedName(); - - String optionalAttributes = ""; - String schema = TopiaGeneratorUtil.getDbSchemaNameTagValue(input, model); - if (schema != null) { - optionalAttributes += "schema=\"" + schema + "\" "; - } - - //On précise au proxy de quelle interface hérite l'objet - String proxyTagValue = TopiaGeneratorUtil.getProxyInterfaceTagValue(input, model); - if (StringUtils.isEmpty(proxyTagValue) || !proxyTagValue.equals("none")) { - optionalAttributes += "proxy=\"" + clazzFQN + "\" "; - } - - String inheritanceStrategy = null; - if (haveSuper) { - ObjectModelClass superClass = input.getSuperclasses().iterator().next(); - String superClassname = superClass.getQualifiedName(); - if (log.isDebugEnabled()) { - log.debug("superClass for " + input.getQualifiedName() + " is " + superClassname); - } - String superClassDOType = TopiaGeneratorUtil.getDOType(superClassname, model); - inheritanceStrategy = TopiaGeneratorUtil.getInheritanceStrategyTagValue(superClass); - if ("joined-subclass".equals(inheritanceStrategy) || "union-subclass".equals(inheritanceStrategy)) { - optionalAttributes += "table=\"" + tableName + "\""; - } - if ("subclass".equals(inheritanceStrategy)) { - optionalAttributes += "discriminator-value=\"" + clazzDOType + "\""; - } -/*{ <<%=inheritanceStrategy%> name="<%=clazzDOType%>" extends="<%=superClassDOType%>" node="<%=clazzDOType%>" abstract="<%=isAbstract%>" <%=optionalAttributes%>> -}*/ - if ("joined-subclass".equals(inheritanceStrategy)) { -/*{ <key column="topiaId" /> -}*/ - } - // FIXME mieux gerer le cas haveSuper - noneNaturalAttributes.addAll(input.getAttributes()); - } else { -/*{ <class name="<%=clazzDOType%>" table="<%=tableName%>" node="<%=clazzDOType%>" abstract="<%=isAbstract%>" <%=optionalAttributes%>> - <id name="topiaId" type="string" length="255" node="@topiaId"/> -}*/ - // cas où on defini la super class, il faut un discriminator seulement dans le cas de - // la strategy subclass - String currentInheritanceStrategy = TopiaGeneratorUtil.getInheritanceStrategyTagValue(input); - if ("subclass".equals(currentInheritanceStrategy)) { -/*{ <discriminator column="topiaDiscriminator" type="string" /> -}*/ - } - - // on detecte les attributs des clef metiers - for (ObjectModelAttribute attr : input.getAttributes()) { - if (TopiaGeneratorUtil.isNaturalId(attr)) { - // attribut metier - naturalAttributes.add(attr); - } else { - // attribut normal - noneNaturalAttributes.add(attr); - } - } - if (!naturalAttributes.isEmpty()) { - // generation de la clef metier - boolean mutable = TopiaGeneratorUtil.isNaturalIdMutable(input); - String mutableStr = mutable ? " mutable=\"true\"" : ""; - if (log.isDebugEnabled()) { - log.debug("natural-id detected for class " + input.getName() + " (" + mutableStr + ") attributes : " + naturalAttributes); - } -/*{ <natural-id<%=mutableStr%>> -}*/ - generateAttributes(output, input, naturalAttributes, " "); -/*{ </natural-id> -}*/ - } -/*{ <version name="topiaVersion" type="long" node="@topiaVersion"/> - <property name="topiaCreateDate" type="timestamp" node="@topiaCreateDate"/> -}*/ - } - - generateAttributes(output, input, noneNaturalAttributes, ""); - - if (haveSuper) { -/*{ </<%=inheritanceStrategy%>> -}*/ - } else { -/*{ </class> -}*/ - } - - generateDatabaseObjects(output, input, naturalAttributes); - generateDatabaseObjects(output, input, noneNaturalAttributes); - -/*{</hibernate-mapping> -}*/ - } - - protected void generateDatabaseObjects(Writer output, - ObjectModelClass clazz, - List<ObjectModelAttribute> attributes) throws IOException { - - for (ObjectModelAttribute attribute : attributes) { - if (!attribute.isNavigable() || - attribute.hasAssociationClass() || - !TopiaGeneratorUtil.isNMultiplicity(attribute) || - attribute.getClassifier() == null || - !TopiaGeneratorUtil.isEntity(attribute.getClassifier()) - ) { - - // skip for this case (not a nm-multiplicity attribute) - continue; - } - - String indexForeignKeys = - TopiaGeneratorUtil.getIndexForeignKeys(attribute, model); - - if (StringUtils.isEmpty(indexForeignKeys) || !Boolean.valueOf(indexForeignKeys)) { - - // no index to put of the attribute. - continue; - } - - // add database-object to create and drop index - - String tableName; - String indexName = "idx_" + clazz.getName() + "_" + attribute.getName(); - String propertyName; - - - if (TopiaGeneratorUtil.isNMultiplicity(attribute.getReverseMaxMultiplicity())) { - - // many to many - tableName = TopiaGeneratorUtil.getManyToManyTableName(attribute); - propertyName = TopiaGeneratorUtil.getDbName(attribute.getReverseAttribute()); - } else { - - // one to many - tableName =TopiaGeneratorUtil.getDbName(attribute.getClassifier()); - propertyName = TopiaGeneratorUtil.getDbName(attribute.getReverseAttribute()); - } - - // add schema if exist (http://nuiton.org/issues/2052) - String schema = TopiaGeneratorUtil.getDbSchemaNameTagValue(clazz, model); - if (StringUtils.isNotEmpty(schema)) { - tableName = schema + "." + tableName; - } -/*{ <database-object> - <create>CREATE INDEX <%=indexName%> ON <%=tableName%>(<%=propertyName%>)</create> - <drop>DROP INDEX <%=indexName%></drop> - </database-object> -}*/ - - } - } - protected void generateAttributes(Writer output, - ObjectModelClass clazz, - List<ObjectModelAttribute> attributes, - String prefix) throws IOException { - for (ObjectModelAttribute attr : attributes) { - ObjectModelAttribute reverse = attr.getReverseAttribute(); - - // pour les asso quoi qu'il arrive il faut les lier des 2 cotes - // pour pouvoir supprimer en cascade l'asso lors de la suppression - // d'un des cotes - if (attr.isNavigable() - || hasUnidirectionalRelationOnAbstractType(reverse, model) - || attr.hasAssociationClass()) { - if (!TopiaGeneratorUtil.isNMultiplicity(attr)) { - if (attr.getClassifier() != null && TopiaGeneratorUtil.isEntity(attr.getClassifier())) { - if (TopiaGeneratorUtil.isNMultiplicity(attr.getReverseMaxMultiplicity()) && !attr.hasAssociationClass()) { - generateHibernateManyToOne(output, attr, prefix); - } else { - generateHibernateOneToOne(output, attr, prefix); - } - } else { - generateHibernateProperty(output, attr, prefix); - } - } else { - if (attr.getClassifier() != null && TopiaGeneratorUtil.isEntity(attr.getClassifier())) { - if (TopiaGeneratorUtil.isNMultiplicity(attr.getReverseMaxMultiplicity()) && !attr.hasAssociationClass()) { - generateHibernateManyToMany(output, attr, prefix); - } else { - generateHibernateOneToMany(output, attr, prefix); - } - } else { - generateHibernateMany(output, attr, prefix); - } - } - } - } - - //Attributs pour les classes d'association - if (clazz instanceof ObjectModelAssociationClass) { - ObjectModelAssociationClass assoc = (ObjectModelAssociationClass)clazz; - for (ObjectModelAttribute attr : assoc.getParticipantsAttributes()) { - if (attr != null) { - -// Note(poussin) pour moi quoi qu'il arrive sur la classe d'association il faut -// un many-to-one, sinon on a des problemes. -// if ((!attr.getReverseAttribute().isNavigable()) || !Util.isNMultiplicity(attr.getReverseAttribute())) { -// / *{ <one-to-one name="<%=getName(attr, true)%>" class="<%=getType(attr, true)%>"<%=(TopiaGeneratorUtil.notEmpty(attr.getTagValue(TopiaGeneratorUtil.TAG_LENGTH))?(" length=\"" + attr.getTagValue(TopiaGeneratorUtil.TAG_LENGTH) + "\""):"")%><%=(attr.isComposite()?" cascade=\"delete\"":"")%>/> -// } */ -// } else { - String notNull = " " + generateFromTagValue(HIBERNATE_ATTRIBUTE_NOT_NULL, TopiaGeneratorUtil.getNotNullTagValue(attr)); - String attrName = getName(attr, true); - String attrType = getType(attr, true); - String lazy = generateFromTagValue(HIBERNATE_ATTRIBUTE_LAZY, TopiaGeneratorUtil.getLazyTagValue(attr)); - String attrColumn = TopiaGeneratorUtil.getDbName(attr); -/*{<%=prefix%> <many-to-one name="<%=attrName%>" class="<%=attrType%>" <%=lazy%>column="<%=attrColumn%>" node="<%=attrName%>/@topiaId" <%=notNull%>/> -}*/ -// } - //Ne sert plus grâce à l'utilisation de la navigabilité -// if (!attr.getReverseAttribute().isNavigable()) { -// String type = TopiaGeneratorUtil.getDOType(((ObjectModelClassifier)attr.getDeclaringElement()).getQualifiedName(), model); -// String name = Util.toLowerCaseFirstLetter(attr.getDeclaringElement().getName()); -// if (log.isTraceEnabled()) {log.trace("reverse: " + type + " " + name);} -// if (!Util.isNMultiplicity(attr)) { -//{<!-- <one-to-one name="<%=name%>" class="<%=type%>"/> -//} -// } else { -//{ <many-to-one name="<%=name%>" class="<%=type%>" column="<%=name.toLowerCase()%>"/> --> -//} -// } -// } - } - } - } - } - - protected String getName(ObjectModelAttribute attr) { - return getName(attr, false); - } - - protected String getName(ObjectModelAttribute attr, boolean isAssoc) { - String result = Introspector.decapitalize(attr.getName()); - if (attr.hasAssociationClass() && !isAssoc) { - result = TopiaGeneratorUtil.getAssocAttrName(attr); - } - return result; - } - - protected String getType(ObjectModelAttribute attr) { - return getType(attr, false); - } - - protected String getType(ObjectModelAttribute attr, boolean isAssoc) { - String type = attr.getType(); - String attrType = TopiaGeneratorUtil.getTypeTagValue(attr); - if (StringUtils.isNotEmpty(attrType)) { - - // tag value detected of the attribute - type = attrType; - } else { - - String modelType = model.getTagValue(type); - if (StringUtils.isNotEmpty(modelType)) { - - // tag value detected of the model - - //TODO tchemit 20100507 Explain What todes it do ? Dont understand the story of columnNamesMap - int bracketIndex = modelType.indexOf('('); - if (bracketIndex != -1) { - type = modelType.substring(0, bracketIndex); - int bracketEndIndex = modelType.indexOf(')', bracketIndex + 1); - String colmunList; - if (bracketEndIndex != -1) { - colmunList = modelType.substring(bracketIndex + 1, bracketEndIndex); - } else { - colmunList = modelType.substring(bracketIndex); - } - columnNamesMap.put(type, colmunList.split(",")); - } else { - type = modelType; - } - } - } - if (attr.hasAssociationClass() && !isAssoc) { - type = attr.getAssociationClass().getQualifiedName(); - } - return TopiaGeneratorUtil.getDOType(type, model); - } - - protected void generateHibernateProperty(Writer output, - ObjectModelAttribute attr, - String prefix) throws IOException { - String attrType = getType(attr); - - String accessField = "field"; - String tagValue = TopiaGeneratorUtil.getAccessTagValue(attr); - if (StringUtils.isNotEmpty(tagValue)) { - accessField = tagValue; - } - String attrName = attr.getName(); - String declaringElementDBName = TopiaGeneratorUtil.getDbName(attr.getDeclaringElement()); - String tableName = declaringElementDBName + "_" + attrName; - - boolean attrIsEnumeration = attr.getClassifier() != null - && attr.getClassifier().isEnum(); - - if (attrType.trim().endsWith("[]")) { - attrType = attrType.trim().substring(0, attrType.trim().length()-2); - - String optionalAttributes = ""; - String schema = TopiaGeneratorUtil.getDbSchemaNameTagValue(attr, model); - if (schema != null) { - optionalAttributes += generateFromTagValue(HIBERNATE_ATTRIBUTE_SCHEMA, schema); -// optionalAttributes += "schema=\"" + schema + "\" "; - } - - if (TopiaGeneratorUtil.hasIndexedStereotype(attr)) { - String indexName = tableName + "_idx"; - optionalAttributes += generateFromTagValue(HIBERNATE_ATTRIBUTE_INDEX, indexName); -// optionalAttributes += "index=\"" + indexName + "\" "; - } - -/*{<%=prefix%> <primitive-array name="<%=attrName%>" table="<%=tableName%>" access="<%=accessField%>" <%=optionalAttributes%>> -<%=prefix%> <key column="<%=declaringElementDBName%>"/> -<%=prefix%> <list-index column="<%=attrName%>_idx"/> -<%=prefix%> <element type="<%=attrType%>"/> -<%=prefix%> </primitive-array> -}*/ - } else { - String optionalAttributes = ""; - if (TopiaGeneratorUtil.hasIndexedStereotype(attr)) { - String indexName = tableName + "_idx"; - optionalAttributes += generateFromTagValue(HIBERNATE_ATTRIBUTE_INDEX, indexName); -// optionalAttributes += "index=\"" + indexName + "\""; - } - - if (TopiaGeneratorUtil.hasUniqueStereotype(attr)) { - // the trim method is called on optionalAttributes after this set to suppress unusual space if no index is set on this attribute - optionalAttributes += generateFromTagValue(HIBERNATE_ATTRIBUTE_UNIQUE, "true"); -// optionalAttributes += " unique=\"true\""; - } - optionalAttributes += generateFromTagValue(HIBERNATE_ATTRIBUTE_NOT_NULL, TopiaGeneratorUtil.getNotNullTagValue(attr)); -/*{<%=prefix%> <property name="<%=attrName%>" access="<%=accessField%>"}*/ - if ( ! attrIsEnumeration) { -/*{ type="<%=attrType%>"}*/ - } - optionalAttributes = optionalAttributes.trim(); - String[] columnNames = columnNamesMap.get(attrType); - - // contains all required attributes for a column node - Map<String,String> columnAttributes = new TreeMap<String, String>(); - if (StringUtils.isNotEmpty(attr.getDefaultValue())) { - //TC-20100129 with a default value we must use the column child tag - - String defaultValue = attr.getDefaultValue().trim(); - columnAttributes.put(HIBERNATE_ATTRIBUTE_DEFAULT, defaultValue); - } - String sqlType = TopiaGeneratorUtil.getSqlTypeTagValue(attr); - if (!StringUtils.isEmpty(sqlType)) { - - // an specific sql type was specified for the attribute, use it - columnAttributes.put(HIBERNATE_ATTRIBUTE_SQL_TYPE, sqlType); - } - - // add length attribute if required - String lengthTagValue = TopiaGeneratorUtil.getLengthTagValue(attr); - if (!StringUtils.isEmpty(lengthTagValue)) { - - optionalAttributes += generateFromTagValue(HIBERNATE_ATTRIBUTE_LENGTH, lengthTagValue); - } - - optionalAttributes = optionalAttributes.trim(); - if (StringUtils.isNotEmpty(optionalAttributes)) { - optionalAttributes = " " + optionalAttributes; - } - - // to know if specific column name mapping is given - boolean noSpecifiedColumn = columnNames == null || columnNames.length == 0; - - if (noSpecifiedColumn) { - - String attrColumn = TopiaGeneratorUtil.getDbName(attr); - - if (columnAttributes.isEmpty()) { - - // simple case with no column node to generate - -/*{ column="<%=attrColumn%>" node="<%=attrName%>"<%=optionalAttributes%>}*/ - if (attrIsEnumeration) { -/*{> -<%=prefix%> <type name="org.hibernate.type.EnumType"> -<%=prefix%> <param name="<%=org.hibernate.type.EnumType.ENUM%>"><%=attrType%></param>}*/ - - // if the user tuned the model to use name instead of - // ordinal to store the values, we must add a clause - boolean useEnumerationName = TopiaGeneratorUtil.hasUseEnumerationNameTagValue(attr, model); - if (useEnumerationName) { - String enumSQLType = String.valueOf(Types.VARCHAR); -/*{ -<%=prefix%> <!-- using name instead of ordinal to store enumeration value --> -<%=prefix%> <param name="<%=org.hibernate.type.EnumType.TYPE%>"><%=enumSQLType%></param>}*/ - } - -/*{ -<%=prefix%> </type> -<%=prefix%> </property> -}*/ - } else { -/*{/> -}*/ - } - } else { - - // there is some attributes to write for the column node - - columnAttributes.put(HIBERNATE_ATTRIBUTE_NAME, attrColumn); - - String columnAttributesAsString =""; - for (Map.Entry<String, String> entry : - columnAttributes.entrySet()) { - String name = entry.getKey(); - String value = entry.getValue(); - columnAttributesAsString += generateFromTagValue(name, value, null); - } - columnAttributesAsString = " " + columnAttributesAsString.trim(); -/*{<%=optionalAttributes%>> -<%=prefix%> <column<%=columnAttributesAsString%>/> -<%=prefix%> </property> -}*/ - } - } else { - - // there is a colum name mapping specified, must use it - //FIXME tchemit 2010-12-29 Really don't know how to apply columnAttributes for multi-columns... -/*{<%=optionalAttributes%>> -}*/ - for (String columnName : columnNames) { - columnName = attrName + "_" + columnName.trim(); -/*{<%=prefix%> <column name="<%=columnName%>"/> -}*/ - } -/*{<%=prefix%> </property> -}*/ - } - } - } - - protected void generateHibernateOneToOne(Writer output, - ObjectModelAttribute attr, - String prefix) throws IOException { -// boolean accessField = hasUnidirectionalRelationOnAbstractType(attr.getReverseAttribute(), model); -/// *{ <one-to-one name="<%=getName(attr)%>" class="<%=getType(attr)%>"<%=(TopiaGeneratorUtil.notEmpty(attr.getTagValue(TopiaGeneratorUtil.TAG_LENGTH))?(" length=\"" + attr.getTagValue(TopiaGeneratorUtil.TAG_LENGTH) + "\""):"")%><%=((attr.isComposite() || attr.hasAssociationClass())?" cascade=\"delete\"":"")%><%=((accessField)?" access=\"field\"":"")%> node="<%=getName(attr)%>/@topiaId" /> -//} */ - - // for hibernate many-to-one with unique="true" => one-to-one - // but if it is one-to-zero-or-one unique contraints is violated - // with null values - boolean unique = TopiaGeneratorUtil.isOneMultiplicity(attr); - generateHibernateManyToOne(output, attr, unique, prefix); - - } - - protected void generateHibernateOneToMany(Writer output, - ObjectModelAttribute attr, - String prefix) throws IOException { - boolean needsIndex = TopiaGeneratorUtil.hasIndexedStereotype(attr); - boolean isInverse = attr.getReverseAttribute().isNavigable(); - isInverse |= hasUnidirectionalRelationOnAbstractType(attr, model); - - String attrName = getName(attr); // ??? - String attrType = getType(attr); - String reverseAttrDBName = TopiaGeneratorUtil.getReverseDbName(attr); - String orderBy = generateFromTagValue(HIBERNATE_ATTRIBUTE_ORDER_BY, TopiaGeneratorUtil.getOrderByTagValue(attr)); - - String cascade = ""; - if (attr.isComposite() || attr.hasAssociationClass()) { - cascade += "cascade=\"all,delete-orphan\" "; - } - - String lazy = generateFromTagValue(HIBERNATE_ATTRIBUTE_LAZY, TopiaGeneratorUtil.getLazyTagValue(attr), "true"); - - String fetch = generateFromTagValue(HIBERNATE_ATTRIBUTE_FETCH, TopiaGeneratorUtil.getFetchTagValue(attr)); - - String collType = TopiaGeneratorUtil.getNMultiplicityHibernateType(attr); - String inverse = ""; - if (isInverse) { - inverse = "inverse=\"true\" "; - } - if (needsIndex) { -/*{<%=prefix%> <<%=collType%> name="<%=attrName%>" <%=inverse%><%=lazy%><%=cascade%>node="<%=attrName%>"> -<%=prefix%> <key column="<%=reverseAttrDBName%>"/> -<%=prefix%> <list-index column="<%=reverseAttrDBName%>_idx"/> -<%=prefix%> <one-to-many class="<%=attrType%>" node="topiaId"/> -<%=prefix%> </<%=collType%>> -}*/ - }else { -/*{<%=prefix%> <<%=collType%> name="<%=attrName%>" <%=inverse%><%=orderBy%><%=fetch%><%=lazy%><%=cascade%>node="<%=attrName%>"> -<%=prefix%> <key column="<%=reverseAttrDBName%>"/> -<%=prefix%> <one-to-many class="<%=attrType%>" node="topiaId"/> -<%=prefix%> </<%=collType%>> -}*/ - } - } - - private String generateFromTagValue(String attributeName, String tagValue) { - return generateFromTagValue(attributeName, tagValue, null); - } - - /** - * Generate hibernate xml attribute with a final space. - * @param attributeName - * @param tagValue - * @param defaultValue - * @return - */ - private String generateFromTagValue(String attributeName, String tagValue, String defaultValue) { - String result = ""; - if (StringUtils.isNotEmpty(tagValue)) { - result+= attributeName + "=\"" + tagValue+"\" "; - } else if (defaultValue != null) { - result+= attributeName + "=\"" + defaultValue +"\" "; - } -// if (attr.hasTagValue(tagName) || defaultValue != null) { -// result+= attributeName + "=\""; -// if (attr.hasTagValue(tagName)) { -// result += attr.getTagValue(tagName); -// } else { -// result += defaultValue; -// } -// result += "\" "; -// } - return result; - } - - protected void generateHibernateMany(Writer output, - ObjectModelAttribute attr, - String prefix) throws IOException { - boolean needsIndex = TopiaGeneratorUtil.hasIndexedStereotype(attr); - String attrName = getName(attr); - String attrType = getType(attr); - String collType = TopiaGeneratorUtil.getNMultiplicityHibernateType(attr); - String lazy = generateFromTagValue(HIBERNATE_ATTRIBUTE_LAZY, TopiaGeneratorUtil.getLazyTagValue(attr)); - String attrColumn = TopiaGeneratorUtil.getDbName(attr); - -/*{<%=prefix%> <<%=collType%> name="<%=attrName%>" <%=lazy%>node="<%=attrName%>"> -<%=prefix%> <key column="OWNER"/> -}*/ - if (needsIndex) { -/*{<%=prefix%> <list-index/> -}*/ - } -/*{<%=prefix%> <element type="<%=attrType%>" column="<%=attrColumn%>" node="id"/> -<%=prefix%> </<%=collType%>> -}*/ - } - - protected void generateHibernateManyToOne(Writer output, - ObjectModelAttribute attr, - String prefix) throws IOException { - generateHibernateManyToOne(output, attr, false, prefix); - } - - protected void generateHibernateManyToOne(Writer output, - ObjectModelAttribute attr, - boolean isUnique, - String prefix) throws IOException { - String attrName = getName(attr); - String attrType = getType(attr); - String attrColumn = TopiaGeneratorUtil.getDbName(attr); -/*{<%=prefix%> <many-to-one name="<%=attrName%>" class="<%=attrType%>" column="<%=attrColumn%>" }*/ - if (attr.isComposite() || attr.hasAssociationClass()) { -/*{cascade="delete" }*/ - } - // Pour le test suivant, on verifie d'abord que l'attribut a un reverse. - // S'il n'en a pas, cela signifie qu'il ne s'agit pas d'un entite - // (au sens stereotype entity), donc a donc pas besoin de faire un access=field. - if (attr.getReverseAttribute() != null && hasUnidirectionalRelationOnAbstractType(attr.getReverseAttribute(), model)) { -/*{access="field" }*/ - } - // vérifier si le tag lazy est defini par defaut dans le fichier de proprietes - String lazy = generateFromTagValue(HIBERNATE_ATTRIBUTE_LAZY, TopiaGeneratorUtil.getLazyTagValue(attr)); -/*{<%=lazy%>}*/ - String notNull = generateFromTagValue(HIBERNATE_ATTRIBUTE_NOT_NULL, TopiaGeneratorUtil.getNotNullTagValue(attr)); -/*{<%=notNull%>}*/ - if (isUnique) { -/*{unique="true" }*/ - } -/*{node="<%=attrName%>/@topiaId"}*/ - -/*{/> -}*/ - } - - protected void generateHibernateManyToMany(Writer output, - ObjectModelAttribute attr, - String prefix) throws IOException { - // On ne met le inverse="true" uniquement pour un seul coté de la relation. - // Dans le cas contraire, les modifications dans la relation ne seront - // pas sauvegardées. Ceci n'est vrai que si les deux coté sont navigable - boolean isInverse = attr.isNavigable() && attr.getReverseAttribute().isNavigable(); - //isInverse |= !Util.isFirstAttribute(attr); - //isInverse = false; // 20070117 poussin: pour du many, jamais de inverse - - // Modification FD-2010-04-01 : - // Le tagvalue "inverse" permet de spécifier qui possède le - // inverse="true". Il est impératif de l'utiliser sur les deux - // extrémités pour ne pas avoir de surprise. - String inverseValue = TopiaGeneratorUtil.getInverseTagValue(attr); - if (StringUtils.isNotEmpty(inverseValue)) { - isInverse &= Boolean.parseBoolean(inverseValue); - // Si aucun tagvalue n'est défini, le choix est arbitraire : le - // premier attribut dans l'ordre alphabétique sera choisi pour porter le - // inverse="true" - } else { - isInverse &= TopiaGeneratorUtil.isFirstAttribute(attr); - } - - boolean needsIndex = TopiaGeneratorUtil.hasIndexedStereotype(attr); - String cascade = ""; - if (attr.isComposite() || attr.hasAssociationClass()) { - cascade = " cascade=\"delete,delete-orphan\""; - } - - String attrType = getType(attr); - String attrName = getName(attr); - String attrColumn = TopiaGeneratorUtil.getDbName(attr); - String lazy = generateFromTagValue(HIBERNATE_ATTRIBUTE_LAZY, TopiaGeneratorUtil.getLazyTagValue(attr), "true"); - String orderBy = generateFromTagValue(HIBERNATE_ATTRIBUTE_ORDER_BY, TopiaGeneratorUtil.getOrderByTagValue(attr)); - String collType = TopiaGeneratorUtil.getNMultiplicityHibernateType(attr); - String tableName = TopiaGeneratorUtil.getManyToManyTableName(attr); - String inverse = ""; - if (isInverse) { - inverse = "inverse=\"true\" "; - } - String reverseAttrDBName = TopiaGeneratorUtil.getReverseDbName(attr); - -/*{<%=prefix%> <<%=collType%> name="<%=attrName%>" table="<%=tableName%>" <%=inverse%><%=lazy%><%=cascade%> node="<%=attrName%>"> -<%=prefix%> <key column="<%=reverseAttrDBName%>"/> -}*/ - if (needsIndex) { -/*{<%=prefix%> <list-index column="<%=reverseAttrDBName%>_idx"/> -}*/ - } -/*{<%=prefix%> <many-to-many class="<%=attrType%>" column="<%=attrColumn%>" <%=orderBy%>node="topiaId"/> -<%=prefix%> </<%=collType%>> -}*/ - } - -} //EntityHibernateMappingGenerator Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityTransformer.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityTransformer.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityTransformer.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,1654 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.topia.generator; - -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.eugene.EugeneTagValues; -import org.nuiton.eugene.java.ObjectModelTransformerToJava; -import org.nuiton.eugene.models.object.ObjectModelAssociationClass; -import org.nuiton.eugene.models.object.ObjectModelAttribute; -import org.nuiton.eugene.models.object.ObjectModelClass; -import org.nuiton.eugene.models.object.ObjectModelClassifier; -import org.nuiton.eugene.models.object.ObjectModelInterface; -import org.nuiton.eugene.models.object.ObjectModelJavaModifier; -import org.nuiton.eugene.models.object.ObjectModelModifier; -import org.nuiton.eugene.models.object.ObjectModelOperation; -import org.nuiton.eugene.models.object.ObjectModelParameter; -import org.nuiton.topia.TopiaDaoSupplier; -import org.nuiton.topia.TopiaException; -import org.nuiton.topia.persistence.EntityVisitor; -import org.nuiton.topia.persistence.TopiaEntity; -import org.nuiton.topia.persistence.TopiaEntityAbstract; -import org.nuiton.topia.persistence.TopiaEntityContextable; -import org.nuiton.topia.persistence.util.TopiaEntityHelper; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; - -import static org.nuiton.topia.generator.TopiaGeneratorUtil.hasUnidirectionalRelationOnAbstractType; - - - -/*{generator option: parentheses = false}*/ -/*{generator option: writeString = +}*/ - -/** - * A template to generate all the {@link TopiaEntity} api for all classifier - * with a {@code entity} stereotype. - * - * For example, given a {@code House} entity, it will generates : - * <ul> - * <li>{@code House} : contract of entity</li> - * <li>{@code AbstractHouse} : default abstract implementation of entity</li> - * <li>{@code HouseImpl} : default impl of abstract entity</li> - * </ul> - * - * <b>Note: </b> The impl will ony be generated in these cases : - * <ul> - * <li>There is no abstract method</li> - * <li>There is no already defined such class in class-path</li> - * </ul> - * - * @author tchemit <chemit@codelutin.com> - * @since 2.3.4 - * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.generator.EntityTransformer" - */ -public class EntityTransformer extends ObjectModelTransformerToJava { - - /** Logger */ - private static final Log log = LogFactory.getLog(EntityTransformer.class); - - protected ObjectModelInterface outputInterface; - - protected ObjectModelClass outputAbstract; - - protected ObjectModelClass outputImpl; - - private boolean associationClass; - - protected boolean generateInterface; - - protected boolean generateAbstract; - - protected boolean generateImpl; - - protected boolean generateBooleanGetMethods; - - protected void clean() { - outputInterface = null; - outputAbstract = null; - outputImpl = null; - } - - @Override - public void transformFromClass(ObjectModelClass input) { - - if (!TopiaGeneratorUtil.isEntity(input)) { - - // not an entity, skip class. - return; - } - - if (log.isDebugEnabled()) { - log.debug("for entity : " + input.getQualifiedName()); - log.debug("Will use classLoader " + getClassLoader()); - } - - // fix once for all the constant prefix to use - String prefix = getConstantPrefix(input, ""); - if (StringUtils.isEmpty(prefix)) { - - // no specific prefix, so no prefix - if (log.isWarnEnabled()) { - log.warn("[" + input.getName() + "] Will generate constants with NO prefix, not a good idea... \n" + - "Use '" + EugeneTagValues.TAG_CONSTANT_PREFIX + - "' tagvalue in your xmi properties. For example " + - "for all the model : model.tagvalue." + EugeneTagValues.TAG_CONSTANT_PREFIX + "=PROPERTY_"); - } - } - setConstantPrefix(prefix); - - generateInterface = isGenerateInterface(input); - generateAbstract = isGenerateAbstract(input); - generateImpl = isGenerateImpl(input); - - generateBooleanGetMethods = TopiaGeneratorUtil.isDoNotGenerateBooleanGetMethods(model, input); - - if (generateInterface) { - - // Create Entity Interface and its header - createEntityInterface(input); - } - - if (generateAbstract) { - - // Create Entity Abstract class and its header - createEntityAbstractClass(input); - } - - // Generate i18n block - String i18nPrefix = TopiaGeneratorUtil.getI18nPrefixTagValue(input, model); - if (!StringUtils.isEmpty(i18nPrefix)) { - generateI18nBlock(input, outputAbstract, i18nPrefix); - } - - // Create accept operation, will be updated during property generation - createAcceptOperation(); - - // Add constant, attribute and operations for each property - generateProperties(input.getAttributes()); - - // Case of association class : properties from participants/extremities - // of the association class. - if (input instanceof ObjectModelAssociationClass) { - ObjectModelAssociationClass association = - (ObjectModelAssociationClass)input; - associationClass = true; - generateProperties(association.getParticipantsAttributes()); - associationClass = false; - } - - closeAcceptOperation(); - - // Add extra constants (from uml dependency) - generateExtraConstants(input); - - // Add extra operations (defined on the entity) - generateExtraOperations(input); - - // Implement aggregate and composite operations - generateAggregateOperation(input); - generateCompositeOperation(input); - - // Implement toString operation - if (TopiaGeneratorUtil.generateToString(input, model)) { - generateToStringOperation(input); - } - - // Generate serialVersionUID on abstract class - generateSerialVersionUID(input, outputAbstract); - - // Generate Entity Implementation class - if (generateImpl) { - generateImpl(input); - generateSerialVersionUID(input, outputImpl); - } - - - - // Clean data output after transformation - clean(); - } - - protected void generateSerialVersionUID(ObjectModelClass input, - ObjectModelClass ouput) { - - // serialVersionUID - String svUID = TopiaGeneratorUtil.findTagValue(TopiaGeneratorUtil.SERIAL_VERSION_UID, - input, - model - ); - if (svUID == null) { - - // use a default one - svUID = TopiaGeneratorUtil.generateSerialVersionUID(ouput) + "L"; - } - addConstant(ouput, TopiaGeneratorUtil.SERIAL_VERSION_UID, long.class, svUID, - ObjectModelJavaModifier.PRIVATE); - } - - protected void createEntityInterface(ObjectModelClass input) { - - outputInterface = createInterface(input.getName(), - input.getPackageName()); - - // Documentation - if (TopiaGeneratorUtil.hasDocumentation(input)) { - setDocumentation(outputInterface, input.getDocumentation()); - } - - if (log.isTraceEnabled()) { - log.trace("Will add interfaces on " + - outputInterface.getQualifiedName()); - } - - List<String> interfaceAlreadyDone = new LinkedList<String> (); - // Extends - for (ObjectModelClassifier parent : input.getInterfaces()) { - addInterface(interfaceAlreadyDone, outputInterface, parent); - } - - // Extends from inheritance - boolean needTopiaEntity = true; - for (ObjectModelClassifier parent : input.getSuperclasses()) { - if (TopiaGeneratorUtil.isEntity(parent)) { - addInterface(interfaceAlreadyDone, outputInterface, parent); - needTopiaEntity = false; - break; - } - } - - // Extends TopiaEntity (only if hasn't parent entity) - if (needTopiaEntity) { - - Class<?> interfaze = TopiaEntity.class; - - if (TopiaGeneratorUtil.isContextable(input)) { - interfaze = TopiaEntityContextable.class; - } - - addInterface(interfaceAlreadyDone, - outputInterface, - interfaze); - - } else if (TopiaGeneratorUtil.isContextable(input)) { - // Even if there is no need to implement TopiaEntity, it might be - // necessary to implement TopiaEntityContextable - addInterface(interfaceAlreadyDone, - outputInterface, - TopiaEntityContextable.class); - } - } - - protected void createEntityAbstractClass(ObjectModelClass input) { - - outputAbstract = createAbstractClass(input.getName() + "Abstract", - input.getPackageName()); - - // Documentation - StringBuilder doc = new StringBuilder(); - doc.append("Implantation POJO pour l'entité {@link "); - doc.append(StringUtils.capitalize(outputInterface.getName())); - doc.append("}\n"); - - String dbName = TopiaGeneratorUtil.getDbName(input); - if (dbName != null) { - doc.append("<p>Nom de l'entité en BD : "); - doc.append(dbName); - doc.append(".</p>"); - } - - setDocumentation(outputAbstract, doc.toString()); - - // Implements - addInterface(outputAbstract, outputInterface.getName()); - - // Extends - for (ObjectModelClass parent : input.getSuperclasses()) { - //tchemit-2011-09-12 What ever abstract or not, we alwyas use an Impl, moreover use the util method instead - String extendClass = TopiaGeneratorUtil.getDOType(parent, model); -// String extendClass = parent.getQualifiedName(); -// //Si une des classes parentes définies des méthodes abstraites, son -// // impl ne sera pas créé -// boolean abstractParent = TopiaGeneratorUtil.shouldBeAbstract(parent); -// if (TopiaGeneratorUtil.isEntity(parent)) { -// if (abstractParent) { -// extendClass += "Abstract"; -// } else { -// extendClass += "Impl"; -// } -// } - setSuperClass(outputAbstract, extendClass); - } - - // Extends TopiaEntityAbstract (only if hasn't parent entity) - if (outputAbstract.getSuperclasses().isEmpty()) { - setSuperClass(outputAbstract, TopiaEntityAbstract.class); - } - - addContextableMethods(input, outputAbstract); - } - - /** - * Ajout les methodes necessaire à l'interface {@link TopiaEntityContextable} - * si le tagValue {@link TopiaTagValues#TAG_CONTEXTABLE} est renseigné. - * @param input - * @param outputAbstract - */ - protected void addContextableMethods(ObjectModelClass input, - ObjectModelClass outputAbstract) { - - if (TopiaGeneratorUtil.isContextable(input)) { - - addImport(outputAbstract, TopiaDaoSupplier.class); - - // topiaContext attribute - ObjectModelAttribute topiaContextAttribute = addAttribute( - outputAbstract, "topiaDaoSupplier", TopiaDaoSupplier.class, null, - ObjectModelJavaModifier.PROTECTED, ObjectModelJavaModifier.TRANSIENT); - setDocumentation(topiaContextAttribute, - "TopiaDAO instance associated with the current \n" + - "instance. For internal usage only"); - - ObjectModelOperation op = addOperation(outputAbstract, - "getTopiaDAOSupplier", TopiaDaoSupplier.class, - ObjectModelJavaModifier.PUBLIC); - setDocumentation(op,"@since 3.0"); - addAnnotation(outputAbstract, op, Override.class); - setOperationBody(op, "" -/*{ - return topiaDaoSupplier; - }*/ - ); - - op = addOperation(outputAbstract, - "setTopiaDAOSupplier", "void", - ObjectModelJavaModifier.PUBLIC); - addException(op, TopiaException.class); - addParameter(op, TopiaDaoSupplier.class, "topiaDaoSupplier"); - setDocumentation(op, -// "@param context The context to set.\n" + -// "@throws TopiaException if trying to replace a context\n" + - "@since 3.0"); - addAnnotation(outputAbstract, op, Override.class); - setOperationBody(op, "" -/*{ - if (this.topiaDaoSupplier == null) { - this.topiaDaoSupplier = topiaDaoSupplier; -// } else { -// throw new TopiaException("TopiaContext replacement is forbidden"); - } - }*/ - ); - - op = addOperation(outputAbstract, "update", "void", - ObjectModelJavaModifier.PUBLIC); - addException(op, TopiaException.class); -// setDocumentation(op,"@since 2.5.3"); - addAnnotation(outputAbstract, op, Override.class); - setOperationBody(op, "" -/*{ - getTopiaDAOSupplier().getDao(<%=input.getName()%>.class).update(this); - }*/ - ); - - op = addOperation(outputAbstract, "delete", "void", ObjectModelJavaModifier.PUBLIC); - addException(op, TopiaException.class); -// setDocumentation(op,"@since 2.5.3"); - addAnnotation(outputAbstract, op, Override.class); - setOperationBody(op, "" -/*{ - getTopiaDAOSupplier().getDao(<%=input.getName()%>.class).delete(this); - }*/ - ); - } - } - - protected boolean isGenerateInterface(ObjectModelClass input) { - - boolean alreadyInClassPath = !isInClassPath(input); - return alreadyInClassPath; - } - - protected boolean isGenerateAbstract(ObjectModelClass input) { - - String fqn = input.getQualifiedName() + " Abstract"; - boolean alreadyInClassPath = !isInClassPath(fqn); - return alreadyInClassPath; - } - - protected boolean isGenerateImpl(ObjectModelClass input) { - - Collection<ObjectModelOperation> operations = input.getOperations(); - String fqn = input.getQualifiedName() + "Impl"; - - boolean alreadyInClassPath = isInClassPath(fqn); - if (alreadyInClassPath) { - - return false; - } - - // On ne génère pas le impl si l'entité a des opérations - if (!operations.isEmpty()) { - - log.info("Will not generate [" + fqn + "], there is some operations to manually implement"); - return false; - } - - //De même, on ne génère pas le impl si il y a des opérations venant des - // superclasses non implémentées - for (ObjectModelOperation otherOp : input.getAllOtherOperations(false)) { - if (otherOp.isAbstract()) { - log.info("Will not generate [" + fqn + "], there is an abstract operation [" + otherOp.getName() + "] in allOtherOperations."); - return false; - } - } - - return true; - } - - protected void generateImpl(ObjectModelClass input) { - - String implName = input.getName() + "Impl"; - String packageName = input.getPackageName(); - if (isVerbose()) { - log.info("Will generate [" + implName + "]"); - } - - if (isAbstract(input)) { - outputImpl = createAbstractClass(implName, packageName); - } else { - outputImpl = createClass(implName, packageName); - } - - setDocumentation(outputImpl, "Implantation des operations pour l'entité " + - input.getName() + "."); - setSuperClass(outputImpl, input.getQualifiedName() + "Abstract"); - } - - /** - * Generate extra constants if {@code input} has dependencies on - * enum used as constant injector. - * - * @param input Entity class to treate - */ - protected void generateExtraConstants(ObjectModelClass input) { - Set<String> constants = addConstantsFromDependency(input, outputInterface); - - if (log.isDebugEnabled()) { - log.debug("Add constants from dependency : " + constants); - } - } - - protected void generateExtraOperations(ObjectModelClass input) { - for (ObjectModelOperation operation : input.getOperations()) { - - String opName = operation.getName(); - String opType = operation.getReturnType(); - ObjectModelModifier visibility = - ObjectModelJavaModifier.fromVisibility(operation.getVisibility()); - - if (log.isDebugEnabled()) { - log.debug("Extra operation for : " + input.getQualifiedName() + - " - method : " + opName + - " - returnType : " + opType + - " - visibility : " + visibility); - } - - // Deprecated from 2.3.4 - // Pas de génération des signatures de méthodes pour celles à intégrer au DAO de l'entité - if (TopiaGeneratorUtil.hasDaoStereotype(operation)) { - return; - - // Generate entity methods which have not a public visibility. - // Only in abstract entity class as abstract operation. - } else if (!visibility.equals(ObjectModelJavaModifier.PUBLIC)) { - addOperation(outputAbstract, opName, opType, visibility, - ObjectModelJavaModifier.ABSTRACT); - - // Other operations, only in entity interface, implementations - // need to be done in implementation class created by developper - } else { - cloneOperationSignature(operation, outputInterface, true); - } - } - } - - /** - * Generate properties from {@code attributes}. Generate - * constant, attribute and operations for each property. - * - * @param attributes Input attributes - */ - protected void generateProperties(Collection<ObjectModelAttribute> attributes) { - for (ObjectModelAttribute attribute : attributes) { - - if (!associationClass) { - - // FIXME-fdesbois-2010-06-25 : Strange behavior to keep those links, will break hibernate, may be a problem in mapping - if (!attribute.isNavigable() && attribute.hasAssociationClass()) { - generatePropertyConstant(attribute); - - generatePropertyAttribute(attribute); - - updateAcceptOperation(attribute); - } - - if (!attribute.isNavigable() && - !TopiaGeneratorUtil.hasUnidirectionalRelationOnAbstractType( - attribute.getReverseAttribute(), model)) { - continue; - } - } - - // constant - generatePropertyConstant(attribute); - - // attribute - generatePropertyAttribute(attribute); - - // operations - generatePropertyOperations(attribute); - - // update accept body - updateAcceptOperation(attribute); - } - } - - // ------------------------------------------------------------------------- - // Generate for property - // ------------------------------------------------------------------------- - - /** - * Generate constant in interface for {@code attribute}. - * - * @param attribute Input attribute to treate - * @see #getPropertyName(ObjectModelAttribute) - */ - protected void generatePropertyConstant(ObjectModelAttribute attribute) { - String attrName = getPropertyName(attribute); - - if (log.isDebugEnabled()) { - log.debug("Generate constant for property : " + attrName); - } - - addAttribute(outputInterface, getConstantName(attrName), String.class, - "\"" + attrName + "\""); - } - - protected void generatePropertyAttribute(ObjectModelAttribute attribute) { - - String attrName = getPropertyName(attribute); - String attrType = getPropertyType(attribute); - String collectionType = getCollectionType(attribute); - - if (collectionType != null) { - attrType = collectionType + "<" + attrType + ">"; - } - - //String attrVisibility = attr.getVisibility(); - - // Declaration - ObjectModelAttribute property = - addAttribute(outputAbstract, attrName, attrType, null, - //ObjectModelJavaModifier.toValue(attrVisibility), - ObjectModelJavaModifier.PROTECTED - ); - - // Documentation - StringBuilder buffer = new StringBuilder(); - if (TopiaGeneratorUtil.hasDocumentation(attribute)) { - String attrDocumentation = attribute.getDocumentation(); - buffer.append(attrDocumentation).append('\n'); - } - - String dbName = TopiaGeneratorUtil.getDbName(attribute); - if (!StringUtils.isEmpty(dbName)) { - buffer.append("Nom de l'attribut en BD : ").append(dbName).append('\n'); - } - setDocumentation(property, buffer.toString()); - - // Annotation - String annotation = TopiaGeneratorUtil.getAnnotationTagValue(attribute); - if (!StringUtils.isEmpty(annotation)) { - //FIXME Make annotation works... - //TODO tchemit 20100513 Test it still works - addAnnotation(outputAbstract, property, annotation); - } - } - - /** - * Generation operations for {@code attributes}. - * One method exists for each operation to generate. Methods starting - * with 'addSingle' is for maxMultiplicity attribute = 1 and for collection - * case, methods start with 'addMultiple'. Other case are take care in each - * method (association class, reverse, entity reference, ...). - * - * @param attribute Input attribute to treate - * @see #addSingleGetOperation(ObjectModelAttribute, String, String) - * @see #addSingleSetOperation(ObjectModelAttribute) - * @see #addMultipleAddOperation(ObjectModelAttribute, String) - * @see #addMultipleAddAllOperation(ObjectModelAttribute, String) - * @see #addMultipleSetOperation(ObjectModelAttribute, String, String) - * @see #addMultipleRemoveOperation(ObjectModelAttribute) - * @see #addMultipleClearOperation(ObjectModelAttribute, String, String) - * @see #addMultipleGetOperation(ObjectModelAttribute, String) - * @see #addMultipleGetTopiaIdOperation(ObjectModelAttribute) - * @see #addMultipleGetOperationFromEntity(ObjectModelAttribute) - * @see #addMultipleSizeOperation(ObjectModelAttribute) - * @see #addMultipleIsEmptyOperation(ObjectModelAttribute) - */ - protected void generatePropertyOperations(ObjectModelAttribute attribute) { - - if (attribute.getMaxMultiplicity() == 1 || associationClass) { - - // setXXX - addSingleSetOperation(attribute); - - boolean booleanProperty = - TopiaGeneratorUtil.isBooleanPrimitive(attribute); - - String attrType = getPropertyType(attribute); - - if (booleanProperty) { - - // isXXX - addSingleGetOperation( - attribute, - attrType, - TopiaGeneratorUtil.OPERATION_GETTER_BOOLEAN_PREFIX); - } - - if (!booleanProperty || generateBooleanGetMethods) { - - // getXXX - addSingleGetOperation( - attribute, - attrType, - TopiaGeneratorUtil.OPERATION_GETTER_DEFAULT_PREFIX); - } - - } else { - - // List, Set or Collection ? - String collectionInterface = - TopiaGeneratorUtil.getNMultiplicityInterfaceType(attribute); - String collectionImpl = - TopiaGeneratorUtil.getNMultiplicityObjectType(attribute); - - addImport(outputInterface, collectionInterface); - addImport(outputAbstract, collectionInterface); - addImport(outputAbstract, collectionImpl); - - collectionInterface = - TopiaGeneratorUtil.getSimpleName(collectionInterface); - collectionImpl = - TopiaGeneratorUtil.getSimpleName(collectionImpl); - - // addXXX - addMultipleAddOperation(attribute, collectionImpl); - - // addAllXXX - addMultipleAddAllOperation(attribute, collectionInterface); - - // setXXX - addMultipleSetOperation(attribute, collectionInterface, collectionImpl); - - // removeXXX - addMultipleRemoveOperation(attribute); - - // clearXXX - addMultipleClearOperation(attribute, collectionInterface, collectionImpl); - - // getXXX - addMultipleGetOperation(attribute, collectionInterface); - - if (TopiaGeneratorUtil.isEntity(attribute, model)) { - - // getXXXByTopiaId - addMultipleGetTopiaIdOperation(attribute); - } - - if (attribute.hasAssociationClass()) { - // getXXX with entity parameter - addMultipleGetOperationFromEntity(attribute); - } - - // sizeXXX - addMultipleSizeOperation(attribute); - - // isXXXEmpty - addMultipleIsEmptyOperation(attribute); - } - } - - protected void addSingleSetOperation(ObjectModelAttribute attribute) { - - String attrName = getPropertyName(attribute); - String attrType = getPropertyType(attribute); - - if (log.isDebugEnabled()) { - log.debug("Generate single 'set' operation for property : " + attrName + - " [" + attrType + "]"); - } - - // Interface operation - ObjectModelOperation interfaceOperation = - createPropertySetterSignature(outputInterface, attrType, attrName, - ""); - - // Implementation - ObjectModelOperation implOperation = createImplOperation(interfaceOperation); - - attrType = TopiaGeneratorUtil.getSimpleName(attrType); - - String constantName = getConstantName(attrName); - - setOperationBody(implOperation, "" -/*{ - <%=attrType%> oldValue = this.<%=attrName%>; - fireOnPreWrite(<%=constantName%>, oldValue, <%=attrName%>); - this.<%=attrName%> = <%=attrName%>; - fireOnPostWrite(<%=constantName%>, oldValue, <%=attrName%>); - }*/ - ); - } - - /** - * Add getter for simple property (neither association nor multiple). - * Will add two different operations for boolean case ('is' method and - * 'get' method). This method add the operation in both {@code - * outputAbstract} and {@code outputInterface}. - * - * @param attribute ObjectModelAttribute for getter operation - * @param attrType type of the attribute - * @param operationPrefix Operation prefix : 'get' by default, if prefix - * is null - */ - protected void addSingleGetOperation(ObjectModelAttribute attribute, - String attrType, - String operationPrefix) { - - String attrName = getPropertyName(attribute); - - if (log.isDebugEnabled()) { - log.debug("Generate single '" + operationPrefix + "' operation for property : " - + attrName + " [" + attrType + "]"); - } - - String constantName = getConstantName(attrName); - - // Interface operation - ObjectModelOperation interfaceOperation = - addOperation(outputInterface, getJavaBeanMethodName(operationPrefix, attrName), - attrType, ObjectModelJavaModifier.PACKAGE); - - // Implementation - ObjectModelOperation implOperation = - createImplOperation(interfaceOperation); - - attrType = TopiaGeneratorUtil.getSimpleName(attrType); - - setOperationBody(implOperation, "" -/*{ - fireOnPreRead(<%=constantName%>, <%=attrName%>); - <%=attrType%> result = this.<%=attrName%>; - fireOnPostRead(<%=constantName%>, <%=attrName%>); - return result; - }*/ - ); - } - - protected void addMultipleAddOperation(ObjectModelAttribute attribute, - String collectionImpl) { - - String attrName = getPropertyName(attribute); - String attrType = getPropertyType(attribute); - ObjectModelAttribute reverse = attribute.getReverseAttribute(); - - if (log.isDebugEnabled()) { - log.debug("Generate multiple 'add' operation for property : " + attrName + - " [" + attrType + "]"); - } - - String constantName = getConstantName(attrName); - - // Interface operation - ObjectModelOperation interfaceOperation = - addOperation(outputInterface, getJavaBeanMethodName("add", attrName), - void.class, ObjectModelJavaModifier.PACKAGE); - ObjectModelParameter param = - addParameter(interfaceOperation, attrType, attrName); - - // Implementation - ObjectModelOperation implOperation = createImplOperation(interfaceOperation); - - attrType = TopiaGeneratorUtil.getSimpleName(attrType); - - StringBuilder body = new StringBuilder(); - - body.append("" -/*{ - fireOnPreWrite(<%=constantName%>, null, <%=attrName%>); - if (this.<%=attrName%> == null) { - this.<%=attrName%> = new <%=collectionImpl%><<%=attrType%>>(); - } -}*/ - ); - - if (reverse != null && (reverse.isNavigable() || - hasUnidirectionalRelationOnAbstractType(attribute, model))) { - String getterName = getJavaBeanMethodName("get", reverse.getName()); - String setterName = getJavaBeanMethodName("set", reverse.getName()); - - String reverseAttrType = TopiaGeneratorUtil.getSimpleName(reverse.getType()); - - if (!TopiaGeneratorUtil.isNMultiplicity(reverse)) { - body.append("" -/*{ - <%=attrName%>.<%=setterName%>(this); -}*/ - ); - // Don't manage reverse attribute add if attribute has associationClass - } else if (!attribute.hasAssociationClass()) { - body.append("" -/*{ - if (<%=attrName%>.<%=getterName%>() == null) { - <%=attrName%>.<%=setterName%>(new <%=collectionImpl%><<%=reverseAttrType%>>()); - } - <%=attrName%>.<%=getterName%>().add(this); -}*/ - ); - } - } - body.append("" -/*{ - this.<%=attrName%>.add(<%=attrName%>); - fireOnPostWrite(<%=constantName%>, this.<%=attrName%>.size(), null, <%=attrName%>); - }*/ - ); - setOperationBody(implOperation, body.toString()); - } - - protected void addMultipleAddAllOperation(ObjectModelAttribute attribute, - String collectionInterface) { - - String attrName = getPropertyName(attribute); - String attrType = getPropertyType(attribute); - - if (log.isDebugEnabled()) { - log.debug("Generate multiple 'addAll' operation for property : " + attrName + - " [" + attrType + "]"); - } - - // Interface operation - ObjectModelOperation interfaceOperation = - addOperation(outputInterface, getJavaBeanMethodName("addAll", attrName), - void.class, ObjectModelJavaModifier.PACKAGE); - ObjectModelParameter param = - addParameter(interfaceOperation, collectionInterface + "<" + attrType + ">", attrName); - - // Implementation - ObjectModelOperation implOperation = - createImplOperation(interfaceOperation); - - attrType = TopiaGeneratorUtil.getSimpleName(attrType); - String addMethodName = getJavaBeanMethodName("add", attrName); - setOperationBody(implOperation, "" -/*{ - if (<%=attrName%> == null) { - return; - } - for (<%=attrType%> item : <%=attrName%>) { - <%=addMethodName%>(item); - } - }*/ - ); - } - - protected void addMultipleSetOperation(ObjectModelAttribute attribute, - String collectionInterface, - String collectionImpl) { - - String attrName = getPropertyName(attribute); - String referenceType = getPropertyType(attribute); - String attrType = collectionInterface + "<" + referenceType + ">"; - String constantName = getConstantName(attrName); - - if (log.isDebugEnabled()) { - log.debug("Generate multiple 'set' operation for property : " + attrName + - " [" + attrType + "]"); - } - - // Interface operation - ObjectModelOperation interfaceOperation = - createPropertySetterSignature(outputInterface, attrType, attrName, - ""); - - ObjectModelOperation implOperation = createImplOperation(interfaceOperation); - - attrType = TopiaGeneratorUtil.getSimpleName(attrType); - referenceType = TopiaGeneratorUtil.getSimpleName(referenceType); - - // Force fire for collection - setOperationBody(implOperation, "" -/*{ - // Copy elements to keep data for fire with new reference - <%=attrType%> oldValue = this.<%=attrName%> != null ? new <%=collectionImpl%><<%=referenceType%>>(this.<%=attrName%>) : null; - fireOnPreWrite(<%=constantName%>, oldValue, <%=attrName%>); - this.<%=attrName%> = <%=attrName%>; - fireOnPostWrite(<%=constantName%>, oldValue, <%=attrName%>); - }*/ - ); - } - - protected void addMultipleRemoveOperation(ObjectModelAttribute attribute) { - - String attrName = getPropertyName(attribute); - String attrType = getPropertyType(attribute); - ObjectModelAttribute reverse = attribute.getReverseAttribute(); - String constantName = getConstantName(attrName); - - if (log.isDebugEnabled()) { - log.debug("Generate 'remove' operation for property : " + attrName + - " [" + attrType + "]"); - } - - // Interface operation - ObjectModelOperation interfaceOperation = - addOperation(outputInterface, getJavaBeanMethodName("remove" , attrName), - void.class, ObjectModelJavaModifier.PACKAGE); - ObjectModelParameter param = - addParameter(interfaceOperation, attrType, attrName); - - // Implementation - ObjectModelOperation implOperation = createImplOperation(interfaceOperation); - - attrType = TopiaGeneratorUtil.getSimpleName(attrType); - - StringBuilder body = new StringBuilder(); - - body.append("" -/*{ - fireOnPreWrite(<%=constantName%>, <%=attrName%>, null); - if (this.<%=attrName%> == null || !this.<%=attrName%>.remove(<%=attrName%>)) { - throw new IllegalArgumentException("List does not contain given element"); - } -}*/ - ); - - if (reverse != null && (reverse.isNavigable() || - hasUnidirectionalRelationOnAbstractType(attribute, model))) { - String getterName = getJavaBeanMethodName("get", reverse.getName()); - String setterName = getJavaBeanMethodName("set", reverse.getName()); - if (!TopiaGeneratorUtil.isNMultiplicity(reverse)) { - body.append("" -/*{ - <%=attrName%>.<%=setterName%>(null); -}*/ - ); - // Don't manage reverse attribute remove if attribute has associationClass - } else if (!attribute.hasAssociationClass()) { - body.append("" -/*{ - <%=attrName%>.<%=getterName%>().remove(this); -}*/ - ); - } - } - body.append("" -/*{ - fireOnPostWrite(<%=constantName%>, this.<%=attrName%>.size() + 1, <%=attrName%>, null); - }*/ - ); - setOperationBody(implOperation, body.toString()); - } - - protected void addMultipleClearOperation(ObjectModelAttribute attribute, - String collectionInterface, - String collectionImpl) { - - String attrName = getPropertyName(attribute); - String attrType = getPropertyType(attribute); - ObjectModelAttribute reverse = attribute.getReverseAttribute(); - String constantName = getConstantName(attrName); - - if (log.isDebugEnabled()) { - log.debug("Generate multiple 'clear' operation for property : " + attrName + - " [" + attrType + "]"); - } - - // Interface operation - ObjectModelOperation interfaceOperation = - addOperation(outputInterface, getJavaBeanMethodName("clear" , attrName), - void.class, ObjectModelJavaModifier.PACKAGE); - - // Implementation - ObjectModelOperation implOperation = createImplOperation(interfaceOperation); - - attrType = TopiaGeneratorUtil.getSimpleName(attrType); - - StringBuilder body = new StringBuilder("" -/*{ - if (this.<%=attrName%> == null) { - return; - } -}*/ - ); - - if (reverse != null && (reverse.isNavigable() || - hasUnidirectionalRelationOnAbstractType(attribute, model))) { - String getterName = getJavaBeanMethodName("get", reverse.getName()); - String setterName = getJavaBeanMethodName("set", reverse.getName()); - body.append("" -/*{ for (<%=attrType%> item : this.<%=attrName%>) { -}*/ - ); - if (!TopiaGeneratorUtil.isNMultiplicity(reverse)) { - body.append("" -/*{ item.<%=setterName%>(null); -}*/ - ); - // Don't manage reverse attribute remove if attribute has associationClass - } else if (!attribute.hasAssociationClass()) { - body.append("" -/*{ item.<%=getterName%>().remove(this); -}*/ - ); - } - body.append("" -/*{ } -}*/ - ); - } - body.append("" -/*{ <%=collectionInterface%><<%=attrType%>> oldValue = new <%=collectionImpl%><<%=attrType%>>(this.<%=attrName%>); - fireOnPreWrite(<%=constantName%>, oldValue, this.<%=attrName%>); - this.<%=attrName%>.clear(); - fireOnPostWrite(<%=constantName%>, oldValue, this.<%=attrName%>); - }*/ - ); - setOperationBody(implOperation, body.toString()); - } - - protected void addMultipleGetOperation(ObjectModelAttribute attribute, - String collectionInterface) { - - String attrName = getPropertyName(attribute); - String attrType = collectionInterface + "<" + getPropertyType(attribute) + ">"; - - if (log.isDebugEnabled()) { - log.debug("Generate multiple 'get' operation for property : " + attrName + - " [" + attrType + "]"); - } - - // Interface operation - ObjectModelOperation interfaceOperation = - addOperation(outputInterface, getJavaBeanMethodName("get" , attrName), - attrType, ObjectModelJavaModifier.PACKAGE); - - // Implementation - ObjectModelOperation implOperation = createImplOperation(interfaceOperation); - - setOperationBody(implOperation, "" -/*{ - return <%=attrName%>; - }*/ - ); - } - - protected void addMultipleGetTopiaIdOperation(ObjectModelAttribute attribute) { - - String attrName = getPropertyName(attribute); - String attrType = getPropertyType(attribute); - - if (log.isDebugEnabled()) { - log.debug("Generate multiple 'getByTopiaId' operation for property : " + attrName + - " [" + attrType + "]"); - } - - // Interface operation - ObjectModelOperation interfaceOperation = - addOperation(outputInterface, getJavaBeanMethodName("get", attrName) + "ByTopiaId", - attrType, ObjectModelJavaModifier.PACKAGE); - ObjectModelParameter param = - addParameter(interfaceOperation, String.class, "topiaId"); - - // Implementation - ObjectModelOperation implOperation = - createImplOperation(interfaceOperation); - - addImport(outputAbstract, TopiaEntityHelper.class); - - setOperationBody(implOperation, "" -/*{ - return TopiaEntityHelper.getEntityByTopiaId(<%=attrName%>, topiaId); - }*/ - ); - } - - protected void addMultipleGetOperationFromEntity(ObjectModelAttribute attribute) { - - // reference to the real attribute name - String referenceName = attribute.getName(); - String referenceType = attribute.getType(); - - String referenceGetterName = getJavaBeanMethodName("get", referenceName); - // association attribute name - String attrName = getPropertyName(attribute); - String attrType = getPropertyType(attribute); - - if (log.isDebugEnabled()) { - log.debug("Generate multiple 'getFromEntity' operation for property : " + attrName + - " [" + attrType + "]"); - } - - // Interface operation - ObjectModelOperation interfaceOperation = - addOperation(outputInterface, - getJavaBeanMethodName("get", attrName), attrType); - - addParameter(interfaceOperation, referenceType, referenceName); - - // Implementation - ObjectModelOperation implOperation = createImplOperation(interfaceOperation); - - attrType = TopiaGeneratorUtil.getSimpleName(attrType); - - setOperationBody(implOperation, "" -/*{ - if (<%=referenceName%> == null || this.<%=attrName%> == null) { - return null; - } - for (<%=attrType%> item : this.<%=attrName%>) { - if (<%=referenceName%>.equals(item.<%=referenceGetterName%>())) { - return item; - } - } - return null; - }*/ - ); - } - - protected void addMultipleSizeOperation(ObjectModelAttribute attribute) { - - String attrName = getPropertyName(attribute); - - if (log.isDebugEnabled()) { - log.debug("Generate multiple 'size' operation for property : " + attrName); - } - - // Interface operation - ObjectModelOperation interfaceOperation = - addOperation(outputInterface, getJavaBeanMethodName("size", attrName), - int.class, ObjectModelJavaModifier.PACKAGE); - - // Implementation - ObjectModelOperation implOperation = createImplOperation(interfaceOperation); - - setOperationBody(implOperation, "" -/*{ - if (<%=attrName%> == null) { - return 0; - } - return <%=attrName%>.size(); - }*/ - ); - } - - protected void addMultipleIsEmptyOperation(ObjectModelAttribute attribute) { - - String attrName = getPropertyName(attribute); - - if (log.isDebugEnabled()) { - log.debug("Generate multiple 'isEmpty' operation for property : " + attrName); - } - - String sizeMethodName = getJavaBeanMethodName("size", attrName); - // Interface operation - ObjectModelOperation interfaceOperation = - addOperation(outputInterface, getJavaBeanMethodName("is", attrName)+ "Empty", - boolean.class, ObjectModelJavaModifier.PACKAGE); - - // Implementation - ObjectModelOperation implOperation = createImplOperation(interfaceOperation); - - setOperationBody(implOperation, "" -/*{ - int size = <%=sizeMethodName%>(); - return size == 0; - }*/ - ); - } - - // ------------------------------------------------------------------------- - // Generate util operations - // ------------------------------------------------------------------------- - - private ObjectModelOperation acceptOperation; - - private StringBuilder acceptOperationBody; - - protected void createAcceptOperation() { - - // Declaration - acceptOperation = addOperation(outputAbstract, "accept", void.class); - addAnnotation(outputAbstract, acceptOperation , Override.class); - ObjectModelParameter param = - addParameter(acceptOperation, EntityVisitor.class, "visitor"); - - addException(acceptOperation, TopiaException.class); - - // Body init - acceptOperationBody = new StringBuilder("" -/*{ - visitor.start(this); -}*/ - ); - } - - protected void updateAcceptOperation(ObjectModelAttribute attribute) { - String attrName = - TopiaGeneratorUtil.getSimpleName(getPropertyName(attribute)); - String attrType = - TopiaGeneratorUtil.getSimpleName(getPropertyType(attribute)); - String collectionType = getCollectionType(attribute); - String constantName = getConstantName(attrName); - if (collectionType != null) { - collectionType = TopiaGeneratorUtil.getSimpleName(collectionType); - acceptOperationBody.append("" -/*{ visitor.visit(this, <%=constantName%>, <%=collectionType%>.class, <%=attrType%>.class, <%=attrName%>); -}*/ - ); - } else { - acceptOperationBody.append("" -/*{ visitor.visit(this, <%=constantName%>, <%=attrType%>.class, <%=attrName%>); -}*/ - ); - } - } - - protected void closeAcceptOperation() { - acceptOperationBody.append("" -/*{ visitor.end(this); - }*/ - ); - setOperationBody(acceptOperation, acceptOperationBody.length() == 0 ? - " " : acceptOperationBody.toString()); - } - - protected void generateToStringOperation(ObjectModelClass input) { - - if (log.isDebugEnabled()) { - log.debug("generate toString method for entity " + - outputInterface.getQualifiedName()); - } - ObjectModelOperation operation = - addOperation(outputAbstract, "toString", String.class); - - addAnnotation(outputAbstract, operation, Override.class); - - addImport(outputAbstract, ToStringBuilder.class); - - StringBuilder body = new StringBuilder("" -/*{ - String result = new ToStringBuilder(this). -}*/ - ); - for (ObjectModelAttribute attr : input.getAttributes()) { - - //FIXME possibilité de boucles (non directes) - - ObjectModelClass attrEntity = null; - - if (model.hasClass(attr.getType())) { - attrEntity = model.getClass(attr.getType()); - } - - boolean isEntity = attrEntity != null && - TopiaGeneratorUtil.isEntity(attrEntity); - - ObjectModelAttribute reverse = attr.getReverseAttribute(); - if (isEntity && (reverse == null || !reverse.isNavigable()) - && !attr.hasAssociationClass() || !isEntity) { - String attrName = attr.getName(); - String constantName = getConstantName(attrName); - body.append("" -/*{ append(<%=constantName%>, this.<%=attrName%>). -}*/ - ); - } - } - body.append("" -/*{ toString(); - return result; - }*/ - ); - setOperationBody(operation, body.length() == 0 ? " " : body.toString()); - - } - - protected void generateCompositeOperation(ObjectModelClass input) { - - ObjectModelOperation operation = - addOperation(outputAbstract, "getComposite", - List.class.getName() + '<' + TopiaEntity.class.getName() + '>'); - - addException(operation, TopiaException.class); - addAnnotation(outputAbstract, operation, Override.class); - - StringBuilder body; - if (!TopiaGeneratorUtil.isContextable(input)) { - body = new StringBuilder("" -/*{ - throw new UnsupportedOperationException("Since ToPIA 3.0, 'getComposite' is only available for contextable entities"); - }*/ - ); - } else { - addImport(outputAbstract, ArrayList.class); - addImport(outputAbstract, List.class); - - body = new StringBuilder("" -/*{ - List<TopiaEntity> tmp = new ArrayList<TopiaEntity>(); - - // pour tous les attributs rechecher les composites et les class d'asso - // on les ajoute dans tmp -}*/ - ); - for (ObjectModelAttribute attr : input.getAttributes()) { - - if (attr.referenceClassifier() && - TopiaGeneratorUtil.isEntity(attr.getClassifier())) { - - if (attr.isComposite()) { - String attrName = attr.getName(); - String getterName = getJavaBeanMethodName("get", attrName); - if (TopiaGeneratorUtil.isNMultiplicity(attr)) { - body.append("" -/*{ if (<%=getterName%>() != null) { - tmp.addAll(<%=getterName%>()); - } -}*/ - ); - } else { - body.append("" -/*{ tmp.add(<%=getterName%>()); -}*/ - ); - } - } else if (attr.hasAssociationClass()) { - String assocAttrName = TopiaGeneratorUtil.getAssocAttrName( - attr); - String assocClassFQN = TopiaGeneratorUtil.getSimpleName( - attr.getAssociationClass().getQualifiedName()); - String ref = "this." + TopiaGeneratorUtil.toLowerCaseFirstLetter( - assocAttrName); - if (!TopiaGeneratorUtil.isNMultiplicity(attr)) { - body.append("" -/*{ - if (<%=ref%> != null) { - tmp.add(<%=ref%>); - } -}*/ - ); - } else { - ObjectModelAttribute reverse = attr.getReverseAttribute(); - String reverseAttrName = reverse.getName(); - // On utilise pas l'attribut car il est potentiellement - // pas a jour, car pour les asso avec cardinalité - // personne ne fait de add. Ce qui est normal, mais - // pour pouvoir faire tout de meme des delete en cascade - // sur les asso, le champs est dans le mapping - // hibernate et donc il le faut aussi dans la classe - // sinon hibernate rale lorsqu'il charge l'objet - // if (<%=ref%> != null) { - // tmp.addAll(<%=ref%>); - // } - - body.append("" -/*{ - { - org.nuiton.topia.persistence.TopiaDAO<<%=assocClassFQN%>> dao = getTopiaContext().getDao(<%=assocClassFQN%>.class); - List<<%=assocClassFQN%>> findAllByProperties = dao.findAllByProperties("<%=reverseAttrName%>", this); - if (findAllByProperties != null) { - tmp.addAll(findAllByProperties); - } - } -}*/ - ); - } - } - } - } - body.append("" -/*{ - // on refait un tour sur chaque entity de tmp pour recuperer leur - // composite - List<TopiaEntity> result = new ArrayList<TopiaEntity>(); - for (TopiaEntity entity : tmp) { - if (entity != null) { - result.add(entity); - result.addAll(entity.getComposite()); - } - } - return result; - }*/ - ); - } - - setOperationBody(operation, body.length() == 0 ? " " : body.toString()); - } - - protected void generateAggregateOperation(ObjectModelClass input) { - - ObjectModelOperation operation = - addOperation(outputAbstract, "getAggregate", - List.class.getName() + '<' + TopiaEntity.class.getName() + '>'); - - addException(operation, TopiaException.class); - addAnnotation(outputAbstract, operation, Override.class); - - - StringBuilder body = new StringBuilder(); - if (!TopiaGeneratorUtil.isContextable(input)) { - body = new StringBuilder("" -/*{ - throw new UnsupportedOperationException("Since ToPIA 3.0, 'getComposite' is only available for contextable entities"); - }*/ - ); - } else { - - addImport(outputAbstract, ArrayList.class); - addImport(outputAbstract, List.class); - body .append("" -/*{ - List<TopiaEntity> tmp = new ArrayList<TopiaEntity>(); - - // pour tous les attributs rechecher les composites et les class d'asso - // on les ajoute dans tmp -}*/ - ); - for (ObjectModelAttribute attr : input.getAttributes()) { - - if (attr.referenceClassifier() && - TopiaGeneratorUtil.isEntity(attr.getClassifier()) && - attr.isAggregate()) { - - String attrName = attr.getName(); - String getterName = getJavaBeanMethodName("get", attrName); - if (TopiaGeneratorUtil.isNMultiplicity(attr)) { - body.append("" -/*{ tmp.addAll(<%=getterName%>()); -}*/ - ); - } else { - body.append("" -/*{ tmp.add(<%=getterName%>()); -}*/ - ); - } - } - } - body.append("" -/*{ - // on refait un tour sur chaque entity de tmp pour recuperer leur - // composite - List<TopiaEntity> result = new ArrayList<TopiaEntity>(); - for (TopiaEntity entity : tmp) { - result.add(entity); - result.addAll(entity.getAggregate()); - } - return result; - }*/ - ); - } - setOperationBody(operation, body.length() == 0 ? " " : body.toString()); - } - - // ------------------------------------------------------------------------- - // Helpers - // ------------------------------------------------------------------------- - - protected boolean isAbstract(ObjectModelClass clazz) { - if (clazz.isAbstract()) { - return true; - } - - //Une classe peut être abstraite si elle a des méthodes définies dans - // ses superinterface et non implantées dans ses superclasses - Collection<ObjectModelOperation> allInterfaceOperations = - clazz.getAllInterfaceOperations(true); - allInterfaceOperations.removeAll(clazz.getAllOtherOperations(true)); - for (ObjectModelOperation op : allInterfaceOperations) { - boolean implementationFound = false; - for (ObjectModelClass superClazz : clazz.getSuperclasses()) { - for (ObjectModelOperation matchingOp : - superClazz.getOperations(op.getName())) { - implementationFound = op.equals(matchingOp) && - !matchingOp.isAbstract(); - if (implementationFound) { - break; - } - } - if (implementationFound) { - break; - } - } - if (!implementationFound) { - if (log.isDebugEnabled()) { - log.debug(clazz.getName() + " : abstract operation " + op); - } - return true; - } - } - return false; - } - - protected String getCollectionType(ObjectModelAttribute attribute) { - String result = null; - if (!associationClass && TopiaGeneratorUtil.isNMultiplicity(attribute)) { - result = TopiaGeneratorUtil.getNMultiplicityInterfaceType(attribute); - } - return result; - } - - protected String getPropertyName(ObjectModelAttribute attribute) { - String propertyName = attribute.getName(); - if (!associationClass && attribute.hasAssociationClass()) { - propertyName = TopiaGeneratorUtil.getAssocAttrName(attribute); - } - return propertyName; - } - - protected String getPropertyType(ObjectModelAttribute attribute) { - String propertyType = attribute.getType(); - if (!associationClass && attribute.hasAssociationClass()) { - propertyType = attribute.getAssociationClass().getQualifiedName(); - } - return propertyType; - } - - protected ObjectModelOperation createImplOperation(ObjectModelOperation interfaceOperation) { - ObjectModelOperation implOperation = - cloneOperationSignature(interfaceOperation, outputAbstract, false); - addAnnotation(outputAbstract, implOperation, Override.class); - return implOperation; - } - - /** - * TODO-fdesbois-2010-06-25 : This method can be put in JavaBuilder or ObjectModelTransformerToJava - * - * This method create an set operation in {@code classifier} with - * {@code propertyType} as return type and {@code propertyName} used for - * operation name ('set[propertyName]'). {@code operationDocument} can - * also be added to the operation created. Only signature with default - * visibility will be added. - * - * @param classifier Classifier where the operation will be added - * @param propertyType Type of the property (better if qualified name) - * @param propertyName Name of the property to set - * @param operationDocumentation Documentation for the operation - * @return the created operation - */ - protected ObjectModelOperation createPropertySetterSignature(ObjectModelClassifier classifier, - String propertyType, - String propertyName, - String operationDocumentation) { - // Operation - ObjectModelOperation operation = - addOperation(classifier, - getJavaBeanMethodName("set", propertyName), void.class); - - ObjectModelParameter param = - addParameter(operation, propertyType, propertyName); - - // Documentation - if (StringUtils.isNotEmpty(operationDocumentation)) { - setDocumentation(operation, operationDocumentation); - setDocumentation(param, "La valeur de l'attribut à positionner."); - } - - return operation; - } - - protected void addInterface(List<String> interfaceAlreadyDone, - ObjectModelClassifier output, - ObjectModelClassifier interfaze) { - String qualifiedName = interfaze.getQualifiedName(); - if (!interfaceAlreadyDone.contains(qualifiedName)) { - - interfaceAlreadyDone.add(qualifiedName); - - if (output != null) { - - // add it to output - addInterface(output, qualifiedName); - - if (log.isTraceEnabled()) { - log.trace("Add interface " + qualifiedName + " on " + - output.getQualifiedName()); - } - } else { - if (log.isTraceEnabled()) { - log.trace("Skip included interface " + qualifiedName); - } - } - - // scan also all interfaces or super-classes of it - for (ObjectModelClassifier parent : interfaze.getInterfaces()) { - addInterface(interfaceAlreadyDone, null, parent); - } - } - } - - protected void addInterface(List<String> interfaceAlreadyDone, - ObjectModelClassifier output, - Class<?> clazz) { - String qualifiedName = clazz.getName(); - if (!interfaceAlreadyDone.contains(qualifiedName)) { - - // add it to output - addInterface(output, qualifiedName); - - } - } -} Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/PersistenceContextTransformer.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/PersistenceContextTransformer.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/PersistenceContextTransformer.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,287 +0,0 @@ -package org.nuiton.topia.generator; - -/* - * #%L - * ToPIA :: Persistence - * * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -/*{generator option: parentheses = false}*/ - -/*{generator option: writeString = +}*/ - -import org.nuiton.eugene.java.ObjectModelTransformerToJava; -import org.nuiton.eugene.models.object.ObjectModel; -import org.nuiton.eugene.models.object.ObjectModelClass; -import org.nuiton.eugene.models.object.ObjectModelJavaModifier; -import org.nuiton.eugene.models.object.ObjectModelOperation; -import org.nuiton.topia.AbstractTopiaPersistenceContext; -import org.nuiton.topia.HibernateProvider; -import org.nuiton.topia.TopiaListenableSupport; -import org.nuiton.topia.persistence.TopiaEntity; -import org.nuiton.topia.persistence.TopiaIdFactory; -import org.nuiton.topia.persistence.util.EntityOperator; -import org.nuiton.topia.persistence.util.EntityOperatorStore; - -import java.lang.reflect.Array; -import java.util.List; - -/** - * To generate PersistenceHelper - * - * @author tchemit <chemit@codelutin.com> - * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.generator.PersistenceContextTransformer" - * @since 3.0 - */ -public class PersistenceContextTransformer extends ObjectModelTransformerToJava { - - @Override - public void transformFromModel(ObjectModel input) { - - String packageName = TopiaGeneratorUtil.getPersistenceContextPackage(this, model); - - String entityAbstractName = TopiaGeneratorUtil.getPersistenceContextAbstractName(model); - - String entityConcreteName = TopiaGeneratorUtil.getPersistenceContextConcreteName(model); - - boolean generateAbstract = !isInClassPath(packageName, entityAbstractName); - - boolean generateConcrete = !isInClassPath(packageName, entityConcreteName); - - - if (generateAbstract) { - - generateAbstract(packageName, - entityAbstractName); - } - - if (generateConcrete) { - - generateImpl(packageName, - entityAbstractName, - entityConcreteName); - } - - } - - protected void generateAbstract(String packageName, - String className) { - - // try to find a super class by tag-value -// String superClass = TopiaGeneratorUtil.getPersistenceContextSuperClassTagValue(model); - String superClass = null; - - if (superClass == null) { - - // no super-class, use default one - superClass = AbstractTopiaPersistenceContext.class.getName(); - } - - ObjectModelClass output = createAbstractClass(className, packageName); - - setSuperClass(output, superClass); - - // detect if there is a contract to set on abstract - String contractName = TopiaGeneratorUtil.getPersistenceContextInterfaceName(model); - -// addInterface(output, TopiaPersistenceContext.class); - - boolean addPersistenceContextContract = isInClassPath(packageName, contractName); - - if (addPersistenceContextContract) { - addInterface(output, packageName + "." + contractName); - } - - String modelName = model.getName(); - String daoHelperClazzName = modelName + "DAOHelper"; - - String entityEnumName = modelName + "EntityEnum"; - - List<ObjectModelClass> entityClasses = - TopiaGeneratorUtil.getEntityClasses(model, true); - - boolean generateOperator = - TopiaGeneratorUtil.shouldGenerateOperatorForDAOHelper(model); - - boolean generateStandaloneEnum = - TopiaGeneratorUtil.shouldGenerateStandaloneEnumForDAOHelper(model); - - if (!generateStandaloneEnum) { - - addImport(output, packageName + "." + daoHelperClazzName + "." + entityEnumName); - - } - -// addImport(output, TopiaDAO.class); - addImport(output, TopiaEntity.class); -// addImport(output, TopiaContext.class); - addImport(output, Array.class); - addImport(output, Array.class); - - if (generateOperator) { - addImport(output, EntityOperator.class); - addImport(output, EntityOperatorStore.class); - } - - // add public constructor - ObjectModelOperation constructor = addConstructor( - output, - ObjectModelJavaModifier.PUBLIC); - addParameter(constructor, HibernateProvider.class, "hibernateProvider"); - addParameter(constructor, TopiaListenableSupport.class, "listenableSupport"); - addParameter(constructor, TopiaIdFactory.class, "topiaIdFactory"); - setOperationBody(constructor, "" -/*{ - super(hibernateProvider, listenableSupport, topiaIdFactory); - }*/ - ); - - ObjectModelOperation op; - - // getModelVersion method - String modelVersion = model.getVersion(); - op = addOperation(output, "getModelVersion", "String", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); - setOperationBody(op, "" -/*{ - return "<%=modelVersion%>"; - }*/ - ); - - // getModelName method - op = addOperation(output, "getModelName", "String", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); - setOperationBody(op, "" -/*{ - return "<%=modelName%>"; - }*/ - ); - - for (ObjectModelClass clazz : entityClasses) { - String clazzName = clazz.getName(); - - // TODO brendan 14/10/13 use method - String daoContractName = clazzName + "Dao"; - String daoClazzName = TopiaGeneratorUtil.getConcreteDaoName(clazz); - - // specialized getXXXDao method - op = addOperation(output, "get" + daoContractName, clazz.getPackageName() + '.' + daoClazzName); - addImport(output, clazz); - setOperationBody(op, "" -/*{ - <%=daoClazzName%> result = getDao(<%=clazzName%>.class, <%=daoClazzName%>.class); - return result; - }*/ - ); - - } - - // getContractClass method - op = addOperation(output, "getContractClass", "<T extends TopiaEntity> Class<T>", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); - addParameter(op, "Class<T>", "klass"); - setOperationBody(op, "" -/*{ - <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass); - return (Class<T>) constant.getContract(); - }*/ - ); - - // getImplementationClass method - op = addOperation(output, "getImplementationClass", "<T extends TopiaEntity> Class<T>", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); - addParameter(op, "Class<T>", "klass"); - setOperationBody(op, "" -/*{ - <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass); - return (Class<T>) constant.getImplementation(); - }*/ - ); - - // getContractClasses method - op = addOperation(output, "getContractClasses", "Class<? extends TopiaEntity>[]", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); - setOperationBody(op, "" -/*{ - <%=entityEnumName%>[] values = <%=entityEnumName%>.values(); - Class<? extends TopiaEntity>[] result = (Class<? extends TopiaEntity>[]) Array.newInstance(Class.class, values.length); - for (int i = 0; i < values.length; i++) { - result[i] = values[i].getContract(); - } - return result; - }*/ - ); - - // getImplementationClasses method - op = addOperation(output, "getImplementationClasses", "Class<? extends TopiaEntity>[]", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); - setOperationBody(op, "" -/*{ - <%=entityEnumName%>[] values = <%=entityEnumName%>.values(); - Class<? extends TopiaEntity>[] result = (Class<? extends TopiaEntity>[]) Array.newInstance(Class.class, values.length); - for (int i = 0; i < values.length; i++) { - result[i] = values[i].getImplementation(); - } - return result; - }*/ - ); - - // getContracts method - op = addOperation(output, "getContracts", entityEnumName + "[]", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); - setOperationBody(op, "" -/*{ - return <%=entityEnumName%>.values(); - }*/ - ); - - if (generateOperator) { - // getOperator method - op = addOperation(output, "getOperator", "<T extends TopiaEntity> EntityOperator<T>", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); - addParameter(op, "Class<T>", "klass"); - setOperationBody(op, "" -/*{ - <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass); - return EntityOperatorStore.getOperator(constant); - }*/ - ); - } - - } - - protected ObjectModelClass generateImpl(String packageName, - String entityAbstractName, - String entityConcreteName) { - - ObjectModelClass output = createClass(entityConcreteName, packageName); - - setSuperClass(output, entityAbstractName); - - ObjectModelOperation constructor = addConstructor( - output, - ObjectModelJavaModifier.PUBLIC); - addParameter(constructor, HibernateProvider.class, "hibernateProvider"); - addParameter(constructor, TopiaListenableSupport.class, "listenableSupport"); - addParameter(constructor, TopiaIdFactory.class, "topiaIdFactory"); - setOperationBody(constructor, "" -/*{ - super(hibernateProvider, listenableSupport, topiaIdFactory); - }*/ - ); - - return output; - } - -} Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaGeneratorUtil.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaGeneratorUtil.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaGeneratorUtil.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,1712 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.topia.generator; - -import com.google.common.base.Preconditions; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.eugene.AbstractGenerator; -import org.nuiton.eugene.GeneratorUtil; -import org.nuiton.eugene.ModelPropertiesUtil; -import org.nuiton.eugene.java.JavaGeneratorUtil; -import org.nuiton.eugene.java.ObjectModelTransformerToJava; -import org.nuiton.eugene.models.object.ObjectModel; -import org.nuiton.eugene.models.object.ObjectModelAssociationClass; -import org.nuiton.eugene.models.object.ObjectModelAttribute; -import org.nuiton.eugene.models.object.ObjectModelClass; -import org.nuiton.eugene.models.object.ObjectModelClassifier; -import org.nuiton.eugene.models.object.ObjectModelElement; -import org.nuiton.eugene.models.object.ObjectModelInterface; -import org.nuiton.eugene.models.object.ObjectModelOperation; -import org.nuiton.eugene.models.object.ObjectModelParameter; -import org.nuiton.topia.persistence.AbstractTopiaDao; -import org.nuiton.topia.persistence.TopiaDAOImpl; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; - -/** - * Classe regroupant divers méthodes utiles pour la génération des entités - * <p/> - * Created: 13 déc. 2005 - * - * @author Arnaud Thimel <thimel@codelutin.com> - * @author tchemit <tchemit@codelutin.com> - * @author fdesbois <fdesbois@codelutin.com> - * @author chatellier <chatellier@codelutin.com> - * @version $Id$ - */ -public class TopiaGeneratorUtil extends JavaGeneratorUtil { - - /** Logger */ - private static final Log log = LogFactory.getLog(TopiaGeneratorUtil.class); - - /** - * dependency to add extra operations for entity dao. - * - * @since 2.3.4 - */ - public static final String DEPENDENCIES_DAO = "dao"; - - /** Type de persistence Hibernate */ - public static final String PERSISTENCE_TYPE_HIBERNATE = "hibernate"; - - /** Type de persistence LDAP */ - public static final String PERSISTENCE_TYPE_LDAP = "ldap"; - - /** Type de persistence par défaut (si aucun précisé) */ - public static final String PERSISTENCE_TYPE_DEFAULT = PERSISTENCE_TYPE_HIBERNATE; - - /** Propriété des générateurs indiquant le package par défaut */ - public static final String PROPERTY_DEFAULT_PACKAGE = "defaultPackage"; - - /** Le package par défaut si aucun n'est spécifié */ - public static final String DEFAULT_PACKAGE = "org.codelutin.malo"; - - /** Stratégie d'heritage par defaut. */ - public static final String DEFAULT_INHERITANCE_STRATEGY = "union-subclass"; - - /** - * The Eugene provider of tag values and stereotypes. - * - * @author tchemit <chemit@codelutin.com> - * @plexus.component role="org.nuiton.eugene.ModelPropertiesUtil$ModelPropertiesProvider" role-hint="topia" - * @since 2.3 - */ - public static class TopiaModelPropertiesProvider extends ModelPropertiesUtil.ModelPropertiesProvider { - - @Override - public void init() throws IllegalAccessException { - scanStereotypeClass(TopiaStereoTypes.class); - scanTagValueClass(TopiaTagValues.class); - } - } - - /** - * Renvoie le package par défaut pour le générateur donné - * - * @param generator le générateur donné - * @return le package par défaut du générator donné - */ - public static String getDefaultPackage(AbstractGenerator<?> generator) { - String packageName = generator.getProperty(PROPERTY_DEFAULT_PACKAGE); - if (StringUtils.isBlank(packageName)) { - packageName = DEFAULT_PACKAGE; - } - return packageName; - } - - public static String getApplicationContextPackage(ObjectModelTransformerToJava transformer, - ObjectModel model) { - - String result = transformer.getDefaultPackageName(); - - return result; - } - - public static String getPersistenceContextPackage(ObjectModelTransformerToJava transformer, - ObjectModel model) { - - String result = transformer.getDefaultPackageName(); - - return result; - } - - public static String getDaoPackage(ObjectModelTransformerToJava transformer, - ObjectModel model, - ObjectModelClassifier input) { - - Preconditions.checkState(isEntity(input), "Cant' find dao package name for a none entity " + input); - String result = input.getPackageName(); - return result; - } - - public static String getApplicationContextInterfaceName(ObjectModel model) { - return model.getName() + "ApplicationContext"; - } - - public static String getApplicationContextAbstractName(ObjectModel model) { - return "Abstract" + model.getName() + "TopiaApplicationContext"; - } - - public static String getApplicationContextConcreteName(ObjectModel model) { - return model.getName() + "TopiaApplicationContext"; - } - - public static String getPersistenceContextAbstractName(ObjectModel model) { - return "Abstract" + model.getName() + "TopiaPersistenceContext"; - } - - public static String getPersistenceContextConcreteName(ObjectModel model) { - return model.getName() + "TopiaPersistenceContext"; - } - - public static String getPersistenceContextInterfaceName(ObjectModel model) { - return model.getName() + "PersistenceContext"; - } - - public static String getEntityAbstractName(ObjectModelClass input) { - return "AbstractTopia" + input.getName(); - } - - public static String getEntityConcreteName(ObjectModelClass input) { - return input.getName(); - } - - public static String getAbstractDaoName(ObjectModelClass input) { - return "Abstract" + input.getName() + "TopiaDao"; - } - - public static String getGeneratedDaoName(ObjectModelClass input) { - return "Generated" + input.getName() + "TopiaDao"; - } - - public static String getConcreteDaoName(ObjectModelClass input) { - return input.getName() + "TopiaDao"; - } - - @Deprecated - public static String getLegacyDaoName(ObjectModelClass input) { - return input.getName() + "DAO"; - } - - public static String getAbstractDaoFqn(ObjectModelClass input) { - return input.getPackageName() + "." + getAbstractDaoName(input); - } - - public static String getGeneratedDaoFqn(ObjectModelClass input) { - return input.getPackageName() + "." + getGeneratedDaoName(input); - } - - public static String getConcreteDaoFqn(ObjectModelClass input) { - return input.getPackageName() + "." + getConcreteDaoName(input); - } - - @Deprecated - public static String getLegacyDaoFqn(ObjectModelClass input) { - return input.getPackageName() + "." + getLegacyDaoName(input); - } - - public static String getEntityPackage(ObjectModelTransformerToJava transformer, - ObjectModel model, - ObjectModelClassifier input) { - - String result = input.getPackageName(); - return result; - } - - /** - * Renvoie l'interface DAO associée à la classe passée en paramètre - * - * @param clazz la classe à tester - * @param model le modele utilisé - * @return l'interface trouvée ou null sinon - */ - public static ObjectModelInterface getDAOInterface(ObjectModelClass clazz, - ObjectModel model) { - for (Object o : model.getInterfaces()) { - ObjectModelInterface daoInterface = (ObjectModelInterface) o; - if (daoInterface.getName().equals(clazz.getName() + "DAO")) { - if (hasDaoStereotype(daoInterface)) { - return daoInterface; - } - } - } - return null; - } - - /** - * Renvoie le type de persistence pour le classifier donné. Si aucun n'est - * trouvé, le type par défaut est utilisé - * - * @param classifier l'élément à tester - * @return le type de persitence pour l'élément donné. - * @since 2.5 - */ - public static String getPersistenceType(ObjectModelClassifier classifier) { - String tag = getPersistenceTypeTagValue(classifier); - if (StringUtils.isEmpty(tag)) { - tag = PERSISTENCE_TYPE_DEFAULT; - } - return tag; - } - - /** - * Obtain the reverse db name of an attribute. - * <p/> - * If attribute has a specific reverse attribute, use his db name, otherwise - * suffix the db name of the attribute by {@code _id}. - * - * @param attr the attribute to seek - * @return the value of the reverse name - * @since 2.5 - */ - public static String getReverseDbName(ObjectModelAttribute attr) { - if (attr.getReverseAttribute() != null) { - return getDbName(attr.getReverseAttribute()); - } else { - return getDbName(attr) + "_id"; - } - } - - /** - * Renvoie le nom BD de l'élement passé en paramètre. Elle se base sur le - * tag associé si il existe, sinon sur le nom de l'élément - * - * @param element l'élément à tester - * @return le nom de table - */ - public static String getDbName(ObjectModelElement element) { - if (element == null) { - return null; - } - String value = getDbNameTagValue(element); - if (!StringUtils.isEmpty(value)) { - return value; - } - return toLowerCaseFirstLetter(element.getName()); - } - - /** - * Cherche si le tagvalue {@link TopiaTagValues#TAG_GENERATE_OPERATOR_FOR_DAO_HELPER} a été - * activé dans le model. - * - * @param model le modele utilisé - * @return {@code true} si le tag value trouvé dans le modèle, {@code false} - * sinon. - * @since 2.5 - */ - public static boolean shouldGenerateOperatorForDAOHelper(ObjectModel model) { - String tagValue = getGenerateOperatorForDAOHelperTagValue(model); - boolean generate = StringUtils.isNotEmpty(tagValue) && - Boolean.valueOf(tagValue); - return generate; - } - - /** - * Cherche si le tagvalue {@link TopiaTagValues#TAG_GENERATE_OPERATOR_FOR_DAO_HELPER} a été - * activé dans le model. - * - * @param model le modele utilisé - * @return {@code true} si le tag value trouvé dans le modèle, {@code false} - * sinon. - * @since 2.5 - */ - public static boolean shouldGenerateStandaloneEnumForDAOHelper(ObjectModel model) { - String tagValue = getGenerateStandaloneEnumForDAOHelperTagValue(model); - boolean generate = StringUtils.isNotEmpty(tagValue) && - Boolean.valueOf(tagValue); - return generate; - } - - /** - * Cherche et renvoie la liste des attributs constituant la clef metier - * d'une classe. - * - * @param clazz la classe à tester - * @return la liste des attributs de la clef métier - */ - public static Set<ObjectModelAttribute> getNaturalIdAttributes( - ObjectModelClass clazz) { - - // use {@link LinkedHashSet} to keep order and prevent duplicate natural ids found - Set<ObjectModelAttribute> results = - new LinkedHashSet<ObjectModelAttribute>(); - for (ObjectModelAttribute attr : clazz.getAttributes()) { - if (isNaturalId(attr)) { - results.add(attr); - } - } - - // sletellier : #2050 Natural id and not null attributes are not propagated on generalized entities (http://nuiton.org/issues/2050) - Collection<ObjectModelClass> superclasses = clazz.getSuperclasses(); - for (ObjectModelClass superClass : superclasses) { - Set<ObjectModelAttribute> naturalIdsOfSuperClass = getNaturalIdAttributes(superClass); - results.addAll(naturalIdsOfSuperClass); - } - return results; - } - - /** - * Cherche et renvoie la liste des attributs qui ne doivent pas etre null dans - * une classe. - * - * @param clazz la classe à tester - * @return la liste des attributs qui ne doivent pas etre null - */ - public static Set<ObjectModelAttribute> getNotNullAttributes( - ObjectModelClass clazz) { - - // use {@link LinkedHashSet} to keep order and prevent duplicate not null found - Set<ObjectModelAttribute> results = - new LinkedHashSet<ObjectModelAttribute>(); - for (ObjectModelAttribute attr : clazz.getAttributes()) { - if (isNotNull(attr)) { - results.add(attr); - } - } - - Collection<ObjectModelClass> superclasses = clazz.getSuperclasses(); - for (ObjectModelClass superClass : superclasses) { - Set<ObjectModelAttribute> notNullOfSuperClass = getNotNullAttributes(superClass); - results.addAll(notNullOfSuperClass); - } - - // Association class participants are obviously not null - if (clazz instanceof ObjectModelAssociationClass) { - List<ObjectModelAttribute> participantsAttributes = ((ObjectModelAssociationClass) clazz).getParticipantsAttributes(); - results.addAll(participantsAttributes); - } - - return results; - } - - /** - * Test if we need to generate {@code toString} method for the given class. - * - * @param clazz class to test - * @param model model - * @return {@code true} if {@code toString} should be generated. - * clef métier. - */ - public static boolean generateToString(ObjectModelClass clazz, - ObjectModel model) { - String value = getNotGenerateToStringTagValue(clazz, model); - return StringUtils.isEmpty(value); - } - - - /** - * Cherche et renvoie la liste des attributs constituant la clef metier - * d'une classe. - * - * @param clazz la classe à tester - * @param model le modele - * @return la liste des attributs de la clef métier ou null si pas de - * clef métier. - */ - public static boolean sortAttribute(ObjectModelClass clazz, - ObjectModel model) { - String value = getSortAttributeTagValue(clazz, model); - return "true".equals(value); - } - - /** - * Detecte si un attribut fait partie d'une clef metier. - * - * @param attribute l'attribut à tester - * @return {@code true} si l'attribut fait partie d'une clef metier, - * <code>false</cdoe> sinon. - */ - public static boolean isNaturalId(ObjectModelAttribute attribute) { - String value = getNaturalIdTagValue(attribute); - if (StringUtils.isEmpty(value)) { - // valeur null, donc pas positionnee - return false; - } - try { - return Boolean.valueOf(value.trim()); - } catch (Exception e) { - // on a pas reussi a convertir en boolean. - //todo peut-être declancher une exception ? - return false; - } - } - - /** - * Detecte si un attribut est marqué comme non null. - * Les naturalId {@link #isNaturalId} sont not null par défaut - * - * @param attribute l'attribut à tester - * @return {@code true} si l'attribut doit être non null, - * par défaut pour les naturalId, {@code false} sinon.. - * @since 2.6.9 - */ - public static boolean isNotNull(ObjectModelAttribute attribute) { - String value = getNotNullTagValue(attribute); - if (StringUtils.isEmpty(value)) { - // valeur null, donc pas positionnee - return isNaturalId(attribute); - } - try { - return Boolean.valueOf(value.trim()); - } catch (Exception e) { - // on a pas reussi a convertir en boolean. - //todo peut-être declancher une exception ? - return false; - } - } - - public static <Type extends ObjectModelElement> Collection<Type> getElementsWithStereotype( - Collection<Type> elements, String... stereotypes) { - Collection<Type> result = new ArrayList<Type>(); - for (Type element : elements) { - if (hasStereotypes(element, stereotypes)) { - result.add(element); - } - } - return result; - } - - public static boolean hasStereotypes(ObjectModelElement element, - String... stereotypes) { - for (String stereotype : stereotypes) { - if (!element.hasStereotype(stereotype)) { - return false; - } - } - return true; - } - - public static String getPrimaryKeyAttributesListDeclaration( - ObjectModelClass clazz, boolean includeName) { - String attributes = ""; - Collection<ObjectModelAttribute> attributeCollection; - attributeCollection = getElementsWithStereotype(clazz.getAttributes(), - TopiaStereoTypes.STEREOTYPE_PRIMARYKAY); - for (ObjectModelAttribute attr : attributeCollection) { - attributes += attr.getType(); - if (includeName) { - attributes += ' ' + attr.getName(); - } - attributes += ", "; - } - if (attributes.length() > 0) { - attributes = attributes.substring(0, attributes.length() - 2); - } - return attributes; - } - - public static boolean isAssociationClassDoublon(ObjectModelAttribute attr) { - return attr.getReverseAttribute() != null && - attr.getDeclaringElement().equals( - attr.getReverseAttribute().getDeclaringElement()) && - !GeneratorUtil.isFirstAttribute(attr); - } - - public static String getDOType(ObjectModelElement elem, ObjectModel model) { - String type = elem.getName(); - if (elem instanceof ObjectModelAttribute) { - type = ((ObjectModelAttribute) elem).getType(); - } - if (elem instanceof ObjectModelClass) { - type = ((ObjectModelClass) elem).getQualifiedName(); - } - return getDOType(type, model); - } - - public static String getDOType(String type, ObjectModel model) { - if (!model.hasClass(type)) { - return type; - } - ObjectModelClass clazz = model.getClass(type); - if (isEntity(clazz)) { - //tchemit-2011-09-12 What ever abstract or not, we always use an Impl - type += "Impl"; -// if (shouldBeAbstract(clazz)) { -// type += "Abstract"; -// } else { -// type += "Impl"; -// } - } - return type; - } - - private static final Set<String> numberTypes = new HashSet<String>(); - - private static final Set<String> textTypes = new HashSet<String>(); - - private static final Set<String> booleanTypes = new HashSet<String>(); - - private static final Set<String> primitiveTypes = new HashSet<String>(); - - private static final Map<String, String> primitiveTypeToClass = new HashMap<String, String>(); - - private static final String VOID_TYPE = "void"; - - static { - - primitiveTypeToClass.put("byte", "java.lang.Byte"); - primitiveTypeToClass.put("short", "java.lang.Short"); - primitiveTypeToClass.put("int", "java.lang.Integer"); - primitiveTypeToClass.put("long", "java.lang.Long"); - primitiveTypeToClass.put("float", "java.lang.Float"); - primitiveTypeToClass.put("double", "java.lang.Double"); - primitiveTypeToClass.put("char", "java.lang.Char"); - primitiveTypeToClass.put("boolean", "java.lang.Boolean"); - - numberTypes.add("byte"); - numberTypes.add("java.lang.Byte"); - numberTypes.add("Byte"); - numberTypes.add("short"); - numberTypes.add("java.lang.Short"); - numberTypes.add("Short"); - numberTypes.add("int"); - numberTypes.add("java.lang.Integer"); - numberTypes.add("Integer"); - numberTypes.add("long"); - numberTypes.add("java.lang.Long"); - numberTypes.add("Long"); - numberTypes.add("float"); - numberTypes.add("java.lang.Float"); - numberTypes.add("Float"); - numberTypes.add("double"); - numberTypes.add("java.lang.Double"); - numberTypes.add("Double"); - - textTypes.add("char"); - textTypes.add("java.lang.Char"); - textTypes.add("Char"); - textTypes.add("java.lang.String"); - textTypes.add("String"); - - booleanTypes.add("boolean"); - booleanTypes.add("java.lang.Boolean"); - booleanTypes.add("Boolean"); - - primitiveTypes.addAll(numberTypes); - primitiveTypes.addAll(textTypes); - primitiveTypes.addAll(booleanTypes); - } - - public static boolean isNumericType(ObjectModelAttribute attr) { - return numberTypes.contains(attr.getType()); - } - - public static boolean isTextType(ObjectModelAttribute attr) { - return textTypes.contains(attr.getType()); - } - - public static boolean isDateType(ObjectModelAttribute attr) { - return "java.util.Date".equals(attr.getType()); - } - - public static boolean isBooleanType(ObjectModelAttribute attr) { - return booleanTypes.contains(attr.getType()); - } - - public static boolean isPrimitiveType(ObjectModelAttribute attr) { - return primitiveTypes.contains(attr.getType()); - } - - public static String getClassForPrimitiveType(ObjectModelAttribute attr) { - Preconditions.checkState(isPrimitiveType(attr)); - String className = primitiveTypeToClass.get(attr.getType()); - Preconditions.checkNotNull(className); - return className; - } - - /** - * Indique si la classe specifiee n'a aucune ou que des methodes abstraites - * - * @param clazz l'instance de ObjectModelClass - * @return true si la classe n'a que des operations abstraite ou aucune - * operation - */ - public static boolean hasNothingOrAbstractMethods(ObjectModelClass clazz) { - boolean result = true; - Iterator<?> operations = clazz.getOperations().iterator(); - while (result && operations.hasNext()) { - ObjectModelOperation op = (ObjectModelOperation) operations.next(); - result = op.isAbstract(); - } - return result; - } - - /** - * Indique si la classe specifiee devrait etre abstraite - * - * @param clazz l'instance de ObjectModelClass - * @return true dans ce cas, false sinon - */ - public static boolean shouldBeAbstract(ObjectModelClass clazz) { - return clazz != null && clazz.isAbstract() && - hasNothingOrAbstractMethods(clazz); - } - - /** - * <p> - * Cette méthode permet de détecter si - * - l'attribut représente une relation 1-n - * - cette relation est unidirectionnelle - * - le type de l'attribut représente un entité - * - cette entité a des sous-classes dans le modèle - * <p/> - * Ce cas correspond à une incompatibilité d'Hibernate qui nous oblige a - * adopter un comportement particulier. - * </p> - * - * @param attr l'attribut a tester - * @param model le model - * @return true si et seulement si il s'agit bien de ce type de relation - */ - public static boolean hasUnidirectionalRelationOnAbstractType( - ObjectModelAttribute attr, ObjectModel model) { - ObjectModelAttribute reverse = attr.getReverseAttribute(); - //relation 1-n - if (reverse != null && isNMultiplicity(attr) && - !isNMultiplicity(reverse)) { - //Pas de navigabilité - if (!reverse.isNavigable()) { - //Il s'agit d'une entity - ObjectModelClass clazz = model.getClass(attr.getType()); - if (clazz != null && isEntity(clazz)) { - //Cette classe a des sous-classes dans le modèle - for (ObjectModelClass subClass : model.getClasses()) { - if (subClass.getSuperclasses().contains(clazz)) { - return true; - } - } - } - } - } - return false; - } - - /** - * Renvoie le nom unique de table pour une relation ManyToMany en fonction - * de l'attribut <code>attr</code> - * <p/> - * Plusieurs cas de figure: - * <li> - * - * @param attr l'attribut servant de base au calcul du nom - * @return le nom de la table - */ - public static String getManyToManyTableName(ObjectModelAttribute attr) { - String result; - - if (attr.hasAssociationClass()) { - result = getDbName(attr.getAssociationClass()); - } else { - String name = attr.getName(); - String revers = attr.getReverseAttributeName(); - - if (name.compareToIgnoreCase(revers) < 0) { - result = name + '_' + revers; - } else { - result = revers + '_' + name; - } - } - return result.toLowerCase(); - } - - /** - * Renvoie le type d'interface à utiliser en fonction de l'attribut - * - * @param attr l'attribut a traiter - * @return String - */ - public static String getNMultiplicityInterfaceType( - ObjectModelAttribute attr) { - if (hasUniqueStereotype(attr)) { - return Set.class.getName(); - } else if (JavaGeneratorUtil.hasIndexedStereotype(attr) || attr.isOrdered()) { - return List.class.getName(); - } - return Collection.class.getName(); - } - - /** - * Renvoie le type d'objet (instance) à utiliser en fonction de l'attribut - * - * @param attr l'attribut a traiter - * @return String - */ - public static String getNMultiplicityObjectType(ObjectModelAttribute attr) { - if (hasUniqueStereotype(attr)) { - return HashSet.class.getName(); - } else if (JavaGeneratorUtil.hasIndexedStereotype(attr) || attr.isOrdered()) { - //On considère qu'on ne sait pas traiter vraiment l'attribut "ordered" - // puisqu'on va conserver l'ordre d'insertion, et non un ordre en - // fonction d'un élément donné. Donc on renvoi une ArrayList - return ArrayList.class.getName(); - } - LinkedList.class.getName(); - return ArrayList.class.getName(); - } - - /** - * Renvoie le type d'interface à utiliser en fonction de l'attribut - * - * @param attr l'attribut a traiter - * @return String - */ - public static String getNMultiplicityHibernateType( - ObjectModelAttribute attr) { - if (hasUniqueStereotype(attr)) { - return "set"; - } else if (JavaGeneratorUtil.hasIndexedStereotype(attr)) { - return "list"; - } - //attr.isOrdered() - On génère le ordered en bag - return "bag"; - } - - /** - * Obtain the list of entities classes with the possibility to sort the - * result. - * - * @param model the current model to scan - * @param sort flag to allow sort the result - * @return the list of filtred classes by their stereotype - */ - public static List<ObjectModelClass> getEntityClasses(ObjectModel model, - boolean sort) { - return getClassesByStereotype(TopiaStereoTypes.STEREOTYPE_ENTITY, model, sort); - } - - /** - * Obtain the list of classes for a given stereotype with the possibility - * to sort the result. - * - * @param stereotype filter stereotype - * @param model the current model to scan - * @param sort flag to allow sort the result - * @return the list of filtred classes by their stereotype - */ - public static List<ObjectModelClass> getClassesByStereotype( - String stereotype, ObjectModel model, boolean sort) { - List<ObjectModelClass> classes = new ArrayList<ObjectModelClass>(); - for (ObjectModelClass clazz : model.getClasses()) { - if (clazz.hasStereotype(stereotype)) { - classes.add(clazz); - } - } - if (sort && !classes.isEmpty()) { - - Collections.sort(classes, OBJECT_MODEL_CLASS_COMPARATOR); - } - return classes; - } - - static public final Comparator<ObjectModelClass> - OBJECT_MODEL_CLASS_COMPARATOR = - new Comparator<ObjectModelClass>() { - - @Override - public int compare(ObjectModelClass o1, - ObjectModelClass o2) { - return o1.getQualifiedName().compareTo( - o2.getQualifiedName()); - } - }; - - /** - * Detecte si la clef metier d'une classe est mutable ou pas. - * <p/> - * On respecte la valeur par defaut d'hibernate, à savoir que par default - * une clef metier est non mutable. - * - * @param clazz la classe a tester - * @return {@code true} si le tag value a ete positionne sur la classe - * via le tag {@link TopiaTagValues#TAG_NATURAL_ID_MUTABLE}, {@code false} - * sinon. - */ - public static boolean isNaturalIdMutable(ObjectModelClass clazz) { - String value = getNaturalIdMutableTagValue(clazz); - if (StringUtils.isEmpty(value)) { - // valeur null, donc par default positionnee - return false; - } - try { - return Boolean.valueOf(value.trim()); - } catch (Exception e) { - // on a pas reussi a convertir en boolean. - //todo peut-être declancher une exception ? - return false; - } - } - - /** - * Retourne true si le tagValue {@link TopiaTagValues#TAG_CONTEXTABLE} - * à la valeur {@code true}. - * - * @param classifier classifier to test - * @return {@code true} si {@link TopiaTagValues#TAG_CONTEXTABLE} == {@code true} - */ - public static boolean isContextable(ObjectModelClassifier classifier) { - boolean result = false; - String value = classifier.getTagValue(TopiaTagValues.TAG_CONTEXTABLE); - if (StringUtils.equalsIgnoreCase(value, "true")) { - result = true; - } - return result; - } - - /** - * Obtain the list of fqn of object involed in the given class. - * - * @param aClass the clazz to inspect - * @param incomingFqns incoming fqns - * @return the list of fqn of attributes - */ - public static List<String> getImports(ObjectModelClass aClass, - String... incomingFqns) { - Set<String> tmp = new HashSet<String>(); - tmp.addAll(Arrays.asList(incomingFqns)); - getImports(aClass, tmp); - List<String> result = cleanImports(aClass.getPackageName(), tmp); - return result; - } - - /** - * Obtain the list of fqn of object involed in the given interface. - * - * @param anInterface the interface to inspect - * @param incomingFqns incoming fqns - * @return the list of fqn of attributes - */ - public static List<String> getImports(ObjectModelInterface anInterface, - String... incomingFqns) { - Set<String> tmp = new HashSet<String>(); - tmp.addAll(Arrays.asList(incomingFqns)); - getImports(anInterface, tmp); - List<String> result = cleanImports(anInterface.getPackageName(), tmp); - return result; - } - - /** - * Obtain the list of fqn of object involed in the given class. - * - * @param aClass the class to inspect - * @param fqns where to store found fqns - */ - protected static void getImports(ObjectModelClass aClass, - Set<String> fqns) { - // scan attributes - for (ObjectModelAttribute attr : aClass.getAttributes()) { - fqns.add(attr.getType()); - if (isNMultiplicity(attr)) { - String collectionType = getNMultiplicityInterfaceType(attr); - fqns.add(collectionType); - String collectionObject = getNMultiplicityObjectType(attr); - fqns.add(collectionObject); - } - } - for (ObjectModelAttribute attribute : aClass.getAllOtherAttributes()) { - fqns.add(attribute.getType()); - } - // scan associations - if (aClass instanceof ObjectModelAssociationClass) { - ObjectModelAssociationClass assoc = - (ObjectModelAssociationClass) aClass; - for (ObjectModelAttribute attr : - assoc.getParticipantsAttributes()) { - if (attr == null) { - continue; - } - fqns.add(attr.getType()); - if (isNMultiplicity(attr)) { - String collectionType = getNMultiplicityInterfaceType(attr); - fqns.add(collectionType); - String collectionObject = getNMultiplicityObjectType(attr); - fqns.add(collectionObject); - } - } - } - // scan operations - for (ObjectModelOperation operation : aClass.getOperations()) { - getImports(operation, fqns); - } - // scan super interfaces - for (ObjectModelInterface modelInterface : aClass.getInterfaces()) { - fqns.add(modelInterface.getQualifiedName()); - getImports(modelInterface, fqns); - } - // scan super classes - for (ObjectModelClass modelClass : aClass.getSuperclasses()) { - fqns.add(modelClass.getQualifiedName()); - getImports(modelClass); - } - } - - /** - * Obtain the list of fqn of object involed in the given interface. - * - * @param anInterface the interface to inspect - * @param fqns where to store found fqns - */ - protected static void getImports(ObjectModelInterface anInterface, - Set<String> fqns) { - // scan operations - for (ObjectModelOperation operation : anInterface.getOperations()) { - getImports(operation, fqns); - } - // scan super interfaces - for (ObjectModelInterface modelInterface : anInterface.getInterfaces()) { - fqns.add(modelInterface.getQualifiedName()); - getImports(modelInterface, fqns); - } - } - - /** - * Obtain the fqn's list of all involed type in a givne operation. - * - * @param operation operation to inspect - * @param fqns where to store found fqns - */ - protected static void getImports(ObjectModelOperation operation, - Set<String> fqns) { - String fqn = operation.getReturnType(); - fqns.add(fqn); - for (ObjectModelParameter parameter : operation.getParameters()) { - fqns.add(parameter.getType()); - } - } - - /** - * Clean a set of fqns, transform it into a {@link List} and sort it. - * - * @param packageName the current package name - * @param fqns the dirty set of fqns - * @return the sorted cleaned list of fqns. - */ - protected static List<String> cleanImports(String packageName, - Set<String> fqns) { - fqns.removeAll(primitiveTypes); - fqns.remove(VOID_TYPE); - int packageLength = packageName.length(); - List<String> genericType = new ArrayList<String>(); - for (Iterator<String> it = fqns.iterator(); it.hasNext(); ) { - String fqn = it.next(); - int lastIndex = fqn.lastIndexOf("."); - if (lastIndex == packageLength && fqn.startsWith(packageName)) { - // same package - it.remove(); - continue; - } - int genericIndex = fqn.indexOf('<'); - if (genericIndex != -1) { - genericType.add(fqn.substring(0, genericIndex)); - it.remove(); - } - } - fqns.addAll(genericType); - - ArrayList<String> result = new ArrayList<String>(fqns); - Collections.sort(result); - return result; - } - - /** - * Obtain the class to use as abstract dao. - * <p/> - * It will look after a tag value {@link TopiaTagValues#TAG_DAO_IMPLEMENTATION} in model - * and if not found will use the default value which is {@link TopiaDAOImpl}. - * - * @param model the model which could contains - * @return the type of the abstract dao to use - * @since 2.5 - */ - public static Class<?> getDAOImplementation(ObjectModel model) { - String daoImpl = getDaoImplementationTagValue(model); - Class<?> result; - if (StringUtils.isEmpty(daoImpl)) { - - // use the default dao implementation of topia - result = AbstractTopiaDao.class; - } else { - try { - result = Class.forName(daoImpl); - } catch (ClassNotFoundException e) { - String message = "Could not find dao implementation named " + daoImpl; - log.error(message); - throw new IllegalStateException(message, e); - } - } - return result; - } - - public static Map<ObjectModelClass, Set<ObjectModelClass>> - searchDirectUsages(ObjectModel model) { - List<ObjectModelClass> allEntities; - Map<String, ObjectModelClass> allEntitiesByFQN; - Map<ObjectModelClass, Set<ObjectModelClass>> usages; - - allEntities = getEntityClasses(model, true); - - allEntitiesByFQN = new TreeMap<String, ObjectModelClass>(); - usages = new LinkedHashMap<ObjectModelClass, Set<ObjectModelClass>>(); - - // prepare usages map and fill allEntitiesByFQN map - for (ObjectModelClass klass : allEntities) { - usages.put(klass, new HashSet<ObjectModelClass>()); - allEntitiesByFQN.put(klass.getQualifiedName(), klass); - } - - // first pass to detect direct usages - for (ObjectModelClass klass : allEntities) { - searchDirectUsages(klass, allEntitiesByFQN, usages); - } - allEntities.clear(); - allEntitiesByFQN.clear(); - return usages; - - } - - public static void searchDirectUsages( - ObjectModelClass klass, - Map<String, ObjectModelClass> allEntitiesByFQN, - Map<ObjectModelClass, Set<ObjectModelClass>> usages) { - - if (log.isDebugEnabled()) { - log.debug("for entity " + klass.getQualifiedName()); - } - for (ObjectModelAttribute attr : klass.getAttributes()) { - if (!attr.isNavigable()) { - // skip this case - continue; - } - String type; - if (attr.hasAssociationClass()) { - type = attr.getAssociationClass().getQualifiedName(); - } else { - type = attr.getType(); - } - if (!allEntitiesByFQN.containsKey(type)) { - // not a entity, can skip for this attribute - continue; - } - if (log.isDebugEnabled()) { - log.debug(" uses " + type); - } - // register the klass as using the targetEntity - ObjectModelClass targetEntity = allEntitiesByFQN.get(type); - Set<ObjectModelClass> classes = usages.get(targetEntity); - classes.add(klass); - } - } - - public static boolean isImportNeeded(Collection<ObjectModelOperation> operations, - String importName) { - if (CollectionUtils.isNotEmpty(operations)) { - for (ObjectModelOperation op : operations) { - if (op.getReturnType().contains(importName)) { - return true; - } - for (ObjectModelParameter param : op.getParameters()) { - if (param.getType().contains(importName)) { - return true; - } - } - } - } - return false; - } - - public static boolean isCollectionNeeded( - Collection<ObjectModelOperation> operations) { - return isImportNeeded(operations, - Collection.class.getSimpleName()); - } - - public static boolean isSetNeeded(Collection<ObjectModelOperation> operations) { - return isImportNeeded(operations, - Set.class.getSimpleName()); - } - - /** - * Check if the given classifier has the - * {@link TopiaStereoTypes#STEREOTYPE_ENTITY} stereotype. - * - * @param classifier classifier to test - * @return {@code true} if stereotype was found, {@code false} otherwise - * @see TopiaStereoTypes#STEREOTYPE_ENTITY - * @since 2.5 - */ - public static boolean hasEntityStereotype(ObjectModelClassifier classifier) { - return classifier.hasStereotype(TopiaStereoTypes.STEREOTYPE_ENTITY); - } - - /** - * Check if the given attribute type is an entity. - * - * @param attribute attribute to test - * @param model model containing the attribute - * @return {@code true} if type of attribute is an entity, - * {@code false} otherwise - * @see TopiaStereoTypes#STEREOTYPE_ENTITY - * @since 2.7 - */ - public static boolean isEntity(ObjectModelAttribute attribute, - ObjectModel model) { - if (isPrimitiveType(attribute)) { - return false; - } - String attributeType = attribute.getType(); - ObjectModelClassifier typeclassifier = - model.getClassifier(attributeType); - return typeclassifier != null && isEntity(typeclassifier); - } - - /** - * Check if the given classifier has the - * {@link TopiaStereoTypes#STEREOTYPE_ENTITY} and is not an enumeration - * - * @param classifier classifier to test - * @return {@code true} if stereotype was found and classifier is not - * enumeration, {@code false} otherwise - * @see TopiaStereoTypes#STEREOTYPE_ENTITY - * @since 2.5 - */ - public static boolean isEntity(ObjectModelClassifier classifier) { - return hasEntityStereotype(classifier) && !classifier.isEnum(); - } - - - /** - * Check if the given attribute has the - * {@link TopiaStereoTypes#STEREOTYPE_ENTITY} stereotype. - * - * @param attribute attribute to test - * @return {@code true} if stereotype was found, {@code false otherwise} - * @see TopiaStereoTypes#STEREOTYPE_ENTITY - * @since 2.5 - */ - public static boolean hasEntityStereotype(ObjectModelAttribute attribute) { - return attribute.hasStereotype(TopiaStereoTypes.STEREOTYPE_ENTITY); - } - - /** - * Check if the given classifier has the - * {@link TopiaStereoTypes#STEREOTYPE_DTO} stereotype. - * - * @param classifier classifier to test - * @return {@code true} if stereotype was found, {@code false otherwise} - * @see TopiaStereoTypes#STEREOTYPE_DTO - * @since 2.5 - */ - public static boolean hasDtoStereotype(ObjectModelClassifier classifier) { - return classifier.hasStereotype(TopiaStereoTypes.STEREOTYPE_DTO); - } - - /** - * Check if the given classifier has the - * {@link TopiaStereoTypes#STEREOTYPE_DAO} stereotype. - * - * @param classifier classifier to test - * @return {@code true} if stereotype was found, {@code false otherwise} - * @see TopiaStereoTypes#STEREOTYPE_DAO - * @since 2.5 - */ - public static boolean hasDaoStereotype(ObjectModelClassifier classifier) { - return classifier.hasStereotype(TopiaStereoTypes.STEREOTYPE_DAO); - } - - /** - * Check if the given operation has the - * {@link TopiaStereoTypes#STEREOTYPE_DAO} stereotype. - * - * @param operation operation to test - * @return {@code true} if stereotype was found, {@code false otherwise} - * @see TopiaStereoTypes#STEREOTYPE_DAO - * @since 2.5 - */ - public static boolean hasDaoStereotype(ObjectModelOperation operation) { - return operation.hasStereotype(TopiaStereoTypes.STEREOTYPE_DAO); - } - - /** - * Check if the given attribute has the - * {@link TopiaStereoTypes#STEREOTYPE_UNIQUE} stereotype. - * - * @param attribute attribute to test - * @return {@code true} if stereotype was found, {@code false otherwise} - * @see TopiaStereoTypes#STEREOTYPE_UNIQUE - * @since 2.5 - */ - public static boolean hasUniqueStereotype(ObjectModelAttribute attribute) { - return attribute.hasStereotype(TopiaStereoTypes.STEREOTYPE_UNIQUE); - } - - /** - * Check if the given attribute has the - * {@link TopiaStereoTypes#STEREOTYPE_PRIMARYKAY} stereotype. - * - * @param attribute attribute to test - * @return {@code true} if stereotype was found, {@code false otherwise} - * @see TopiaStereoTypes#STEREOTYPE_PRIMARYKAY - * @since 2.5 - */ - public static boolean hasPrimaryKeyStereotype(ObjectModelAttribute attribute) { - return attribute.hasStereotype(TopiaStereoTypes.STEREOTYPE_PRIMARYKAY); - } - - /** - * Obtain the value of the {@link TopiaTagValues#TAG_PERSISTENCE_TYPE} - * tag value on the given classifier. - * - * @param classifier classifier to seek - * @return the none empty value of the found tag value or {@code null} if not found nor empty. - * @see TopiaTagValues#TAG_PERSISTENCE_TYPE - * @since 2.5 - */ - public static String getPersistenceTypeTagValue(ObjectModelClassifier classifier) { - String value = findTagValue(TopiaTagValues.TAG_PERSISTENCE_TYPE, classifier, null); - return value; - } - - /** - * Obtain the value of the {@link TopiaTagValues#TAG_INHERITANCE_STRATEGY} - * tag value on the given classifier. - * - * @param classifier classifier to seek - * @return the none empty value of the found tag value or {@code null} if not found nor empty. - * @see TopiaTagValues#TAG_INHERITANCE_STRATEGY - * @since 3.0 - */ - public static String getInheritanceStrategyTagValue(ObjectModelClassifier classifier) { - String value = findTagValue(TopiaTagValues.TAG_INHERITANCE_STRATEGY, classifier, null); - if (value == null) { - value = DEFAULT_INHERITANCE_STRATEGY; - } - return value; - } - - /** - * Obtain the value of the {@link TopiaTagValues#TAG_DB_NAME} - * tag value on the given classifier. - * - * @param element classifier to seek - * @return the none empty value of the found tag value or {@code null} if not found nor empty. - * @see TopiaTagValues#TAG_DB_NAME - * @since 2.5 - */ - public static String getDbNameTagValue(ObjectModelElement element) { - String value = findTagValue(TopiaTagValues.TAG_DB_NAME, element, null); - return value; - } - - /** - * Obtain the value of the {@link TopiaTagValues#TAG_SCHEMA_NAME} - * tag value on the given classifier. - * - * @param classifier classifier to seek - * @param model model to seek - * @return the none empty value of the found tag value or {@code null} if not found nor empty. - * @see TopiaTagValues#TAG_SCHEMA_NAME - * @since 2.5 - */ - public static String getDbSchemaNameTagValue(ObjectModelClassifier classifier, ObjectModel model) { - String value = findTagValue(TopiaTagValues.TAG_SCHEMA_NAME, classifier, model); - return value; - } - - /** - * Obtain the value of the {@link TopiaTagValues#TAG_SCHEMA_NAME} - * tag value on the given attribute. - * - * @param attribute attribute to seek - * @param model model to seek - * @return the none empty value of the found tag value or {@code null} if not found nor empty. - * @see TopiaTagValues#TAG_SCHEMA_NAME - * @since 2.5 - */ - public static String getDbSchemaNameTagValue(ObjectModelAttribute attribute, ObjectModel model) { - String value = findTagValue(TopiaTagValues.TAG_SCHEMA_NAME, attribute, model); - return value; - } - - /** - * Obtain the value of the {@link TopiaTagValues#TAG_LENGTH} - * tag value on the given attribute. - * - * @param attribute attribute to seek - * @return the none empty value of the found tag value or {@code null} if not found nor empty. - * @see TopiaTagValues#TAG_LENGTH - * @since 2.5 - */ - public static String getLengthTagValue(ObjectModelAttribute attribute) { - String value = findTagValue(TopiaTagValues.TAG_LENGTH, attribute, null); - return value; - } - - /** - * Obtain the value of the {@link TopiaTagValues#TAG_ANNOTATION} - * tag value on the given attribute. - * - * @param attribute attribute to seek - * @return the none empty value of the found tag value or {@code null} if not found nor empty. - * @see TopiaTagValues#TAG_ANNOTATION - * @since 2.5 - */ - public static String getAnnotationTagValue(ObjectModelAttribute attribute) { - String value = findTagValue(TopiaTagValues.TAG_ANNOTATION, attribute, null); - return value; - } - - /** - * Obtain the value of the {@link TopiaTagValues#TAG_ACCESS} - * tag value on the given attribute. - * - * @param attribute attribute to seek - * @return the none empty value of the found tag value or {@code null} if not found nor empty. - * @see TopiaTagValues#TAG_ACCESS - * @since 2.5 - */ - public static String getAccessTagValue(ObjectModelAttribute attribute) { - String value = findTagValue(TopiaTagValues.TAG_ACCESS, attribute, null); - return value; - } - - /** - * Obtain the value of the {@link TopiaTagValues#TAG_NATURAL_ID} - * tag value on the given attribute. - * - * @param attribute attribute to seek - * @return the none empty value of the found tag value or {@code null} if not found nor empty. - * @see TopiaTagValues#TAG_NATURAL_ID - * @since 2.5 - */ - public static String getNaturalIdTagValue(ObjectModelAttribute attribute) { - String value = findTagValue(TopiaTagValues.TAG_NATURAL_ID, attribute, null); - return value; - } - - /** - * Obtain the value of the {@link TopiaTagValues#TAG_NATURAL_ID_MUTABLE} - * tag value on the given classifier. - * - * @param classifier classifier to seek - * @return the none empty value of the found tag value or {@code null} if not found nor empty. - * @see TopiaTagValues#TAG_NATURAL_ID_MUTABLE - * @since 2.5 - */ - public static String getNaturalIdMutableTagValue(ObjectModelClassifier classifier) { - String value = findTagValue(TopiaTagValues.TAG_NATURAL_ID_MUTABLE, classifier, null); - return value; - } - - /** - * Obtain the value of the {@link TopiaTagValues#TAG_INVERSE} - * tag value on the given attribute. - * - * @param attribute attribute to seek - * @return the none empty value of the found tag value or {@code null} if not found nor empty. - * @see TopiaTagValues#TAG_INVERSE - * @since 2.5 - */ - public static String getInverseTagValue(ObjectModelAttribute attribute) { - String value = findTagValue(TopiaTagValues.TAG_INVERSE, attribute, null); - return value; - } - - /** - * Obtain the value of the {@link TopiaTagValues#TAG_LAZY} - * tag value on the given attribute. - * - * @param attribute attribute to seek - * @return the none empty value of the found tag value or {@code null} if not found nor empty. - * @see TopiaTagValues#TAG_LAZY - * @since 2.5 - */ - public static String getLazyTagValue(ObjectModelAttribute attribute) { - String value = findTagValue(TopiaTagValues.TAG_LAZY, attribute, null); - return value; - } - - /** - * Obtain the value of the {@link TopiaTagValues#TAG_FETCH} - * tag value on the given attribute. - * - * @param attribute attribute to seek - * @return the none empty value of the found tag value or {@code null} if not found nor empty. - * @see TopiaTagValues#TAG_FETCH - * @since 2.5 - */ - public static String getFetchTagValue(ObjectModelAttribute attribute) { - String value = findTagValue(TopiaTagValues.TAG_FETCH, attribute, null); - return value; - } - - /** - * Obtain the value of the {@link TopiaTagValues#TAG_ORDER_BY} - * tag value on the given attribute. - * - * @param attribute attribute to seek - * @return the none empty value of the found tag value or {@code null} if not found nor empty. - * @see TopiaTagValues#TAG_ORDER_BY - * @since 2.5 - */ - public static String getOrderByTagValue(ObjectModelAttribute attribute) { - String value = findTagValue(TopiaTagValues.TAG_ORDER_BY, attribute, null); - return value; - } - - /** - * Obtain the value of the {@link TopiaTagValues#TAG_NOT_NULL} - * tag value on the given attribute. - * - * @param attribute attribute to seek - * @return the none empty value of the found tag value or {@code null} if not found nor empty. - * @see TopiaTagValues#TAG_NOT_NULL - * @since 2.5 - */ - public static String getNotNullTagValue(ObjectModelAttribute attribute) { - String value = findTagValue(TopiaTagValues.TAG_NOT_NULL, attribute, null); - return value; - } - - /** - * Obtain the value of the {@link TopiaTagValues#TAG_PROXY_INTERFACE} - * tag value on the given classifier. - * - * @param classifier classifier to seek - * @param model model to seek - * @return the none empty value of the found tag value or {@code null} if not found nor empty. - * @see TopiaTagValues#TAG_PROXY_INTERFACE - * @since 2.5 - */ - public static String getProxyInterfaceTagValue(ObjectModelClassifier classifier, ObjectModel model) { - String value = findTagValue(TopiaTagValues.TAG_PROXY_INTERFACE, classifier, model); - return value; - } - - /** - * Tests if the given classifier own at least one security tag value. - * - * @param classifier the classifier to test - * @return {@code true} if there is at least one security tag value on the given class - * @since 2.5 - */ - public static boolean isClassWithSecurity(ObjectModelClassifier classifier) { - return StringUtils.isNotEmpty(getSecurityCreateTagValue(classifier)) || - StringUtils.isNotEmpty(getSecurityLoadTagValue(classifier)) || - StringUtils.isNotEmpty(getSecurityUpdateTagValue(classifier)) || - StringUtils.isNotEmpty(getSecurityDeleteTagValue(classifier)); - } - - /** - * Obtain the value of the {@link TopiaTagValues#TAG_SECURITY_CREATE} - * tag value on the given classifier. - * - * @param classifier classifier to seek - * @return the none empty value of the found tag value or {@code null} if not found nor empty. - * @see TopiaTagValues#TAG_SECURITY_CREATE - * @since 2.5 - */ - public static String getSecurityCreateTagValue(ObjectModelClassifier classifier) { - String value = findTagValue(TopiaTagValues.TAG_SECURITY_CREATE, classifier, null); - return value; - } - - /** - * Obtain the value of the {@link TopiaTagValues#TAG_SECURITY_DELETE} - * tag value on the given classifier. - * - * @param classifier classifier to seek - * @return the none empty value of the found tag value or {@code null} if not found nor empty. - * @see TopiaTagValues#TAG_SECURITY_DELETE - * @since 2.5 - */ - public static String getSecurityDeleteTagValue(ObjectModelClassifier classifier) { - String value = findTagValue(TopiaTagValues.TAG_SECURITY_DELETE, classifier, null); - return value; - } - - /** - * Obtain the value of the {@link TopiaTagValues#TAG_SECURITY_LOAD} - * tag value on the given classifier. - * - * @param classifier classifier to seek - * @return the none empty value of the found tag value or {@code null} if not found nor empty. - * @see TopiaTagValues#TAG_SECURITY_LOAD - * @since 2.5 - */ - public static String getSecurityLoadTagValue(ObjectModelClassifier classifier) { - String value = findTagValue(TopiaTagValues.TAG_SECURITY_LOAD, classifier, null); - return value; - } - - /** - * Obtain the value of the {@link TopiaTagValues#TAG_SECURITY_UPDATE} - * tag value on the given classifier. - * - * @param classifier classifier to seek - * @return the none empty value of the found tag value or {@code null} if not found nor empty. - * @see TopiaTagValues#TAG_SECURITY_UPDATE - * @since 2.5 - */ - public static String getSecurityUpdateTagValue(ObjectModelClassifier classifier) { - String value = findTagValue(TopiaTagValues.TAG_SECURITY_UPDATE, classifier, null); - return value; - } - - /** - * Obtain the value of the {@link TopiaTagValues#TAG_NOT_GENERATE_TO_STRING} - * tag value on the given class. - * - * @param clazz class to seek - * @param model model to seek - * @return the none empty value of the found tag value or {@code null} if not found nor empty. - * @see TopiaTagValues#TAG_NOT_GENERATE_TO_STRING - * @since 2.5 - */ - public static String getNotGenerateToStringTagValue(ObjectModelClassifier clazz, ObjectModel model) { - String value = findTagValue(TopiaTagValues.TAG_NOT_GENERATE_TO_STRING, clazz, model); - return value; - } - - /** - * Obtain the value of the {@link TopiaTagValues#TAG_SORT_ATTRIBUTE} - * tag value on the given classifier. - * - * @param classifier classifier to seek - * @param model model to seek - * @return the none empty value of the found tag value or {@code null} if not found nor empty. - * @see TopiaTagValues#TAG_SORT_ATTRIBUTE - * @since 2.5 - */ - public static String getSortAttributeTagValue(ObjectModelClassifier classifier, ObjectModel model) { - String value = findTagValue(TopiaTagValues.TAG_SORT_ATTRIBUTE, classifier, model); - return value; - } - - /** - * Obtain the value of the {@link TopiaTagValues#TAG_GENERATE_STANDALONE_ENUM_FOR_DAO_HELPER} - * tag value on the given model. - * - * @param model model to seek - * @return the none empty value of the found tag value or {@code null} if not found nor empty. - * @see TopiaTagValues#TAG_GENERATE_STANDALONE_ENUM_FOR_DAO_HELPER - * @since 2.5 - */ - public static String getGenerateStandaloneEnumForDAOHelperTagValue(ObjectModel model) { - String value = findTagValue(TopiaTagValues.TAG_GENERATE_STANDALONE_ENUM_FOR_DAO_HELPER, null, model); - return value; - } - - /* Obtain the value of the {@link TopiaTagValues#TAG_GENERATE_OPERATOR_FOR_DAO_HELPER} - * tag value on the given model. - * - * @param model model to seek - * @return the none empty value of the found tag value or {@code null} if not found nor empty. - * @see TopiaTagValues#TAG_GENERATE_OPERATOR_FOR_DAO_HELPER - * @since 2.5 - */ - public static String getGenerateOperatorForDAOHelperTagValue(ObjectModel model) { - String value = findTagValue(TopiaTagValues.TAG_GENERATE_OPERATOR_FOR_DAO_HELPER, null, model); - return value; - } - - /** - * Obtain the value of the {@link TopiaTagValues#TAG_TYPE} - * tag value on the given attribute. - * - * @param attribute attribute to seek - * @return the none empty value of the found tag value or {@code null} if not found nor empty. - * @see TopiaTagValues#TAG_TYPE - * @since 2.5 - */ - public static String getTypeTagValue(ObjectModelAttribute attribute) { - String value = findTagValue(TopiaTagValues.TAG_TYPE, attribute, null); - return value; - } - - /** - * Obtain the value of the {@link TopiaTagValues#TAG_SQL_TYPE} - * tag value on the given attribute. - * - * @param attribute attribute to seek - * @return the none empty value of the found tag value or {@code null} if not found nor empty. - * @see TopiaTagValues#TAG_TYPE - * @since 2.5 - */ - public static String getSqlTypeTagValue(ObjectModelAttribute attribute) { - String value = findTagValue(TopiaTagValues.TAG_SQL_TYPE, attribute, null); - return value; - } - - /** - * Obtains the value of the {@link TopiaTagValues#TAG_DAO_IMPLEMENTATION} - * tag value on the given model. - - * - * @param model model to seek - * @return the none empty value of the found tag value or {@code null} if not found nor empty. - * @see TopiaTagValues#TAG_DAO_IMPLEMENTATION - * @since 2.5 - */ - public static String getDaoImplementationTagValue(ObjectModel model) { - String value = findTagValue(TopiaTagValues.TAG_DAO_IMPLEMENTATION, null, model); - return value; - } - - /** - * Obtains the value of the tag value - * {@link TopiaTagValues#TAG_INDEX_FOREIGN_KEYS} on the model or on the - * given attribute. - * - * @param attribute attribute to test - * @param model model to test - * @return none empty value of the found tag value or {@code null} if not found nor empty. - * @see TopiaTagValues#TAG_INDEX_FOREIGN_KEYS - * @since 2.6.5 - */ - public static String getIndexForeignKeys(ObjectModelAttribute attribute, ObjectModel model) { - String value = findTagValue(TopiaTagValues.TAG_INDEX_FOREIGN_KEYS, attribute, model); - return value; - } - - public static boolean hasUseEnumerationNameTagValue(ObjectModelAttribute attr, ObjectModel model) { - String value = findTagValue(TopiaTagValues.TAG_USE_ENUMERATION_NAME, attr, model); - return Boolean.parseBoolean(value); - } - - /** - * Search if the TagValue {@link TopiaTagValues#TAG_GENERATE_TOPIA_ID_IN_DTO} has been - * activated in the model. - * - * @param classifier classifier to seek - * @param model model to seek - * @return the none empty value of the found tag value or {@code null} if not found nor empty. - * @see TopiaTagValues#TAG_GENERATE_TOPIA_ID_IN_DTO - * @since 2.6.7 - */ - public static boolean shouldGenerateDTOTopiaIdTagValue(ObjectModelClassifier classifier, ObjectModel model) { - String tagValue = findTagValue(TopiaTagValues.TAG_GENERATE_TOPIA_ID_IN_DTO, classifier, model); - boolean generate = StringUtils.isNotEmpty(tagValue) && Boolean.valueOf(tagValue); - return generate; - } - -} // TopiaGeneratorUtil - Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaJavaValidator.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaJavaValidator.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaJavaValidator.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,157 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.topia.generator; - -import org.apache.commons.lang3.StringUtils; -import org.nuiton.eugene.models.object.ObjectModel; -import org.nuiton.eugene.models.object.ObjectModelAttribute; -import org.nuiton.eugene.models.object.ObjectModelClass; -import org.nuiton.eugene.models.object.ObjectModelOperation; -import org.nuiton.eugene.models.object.validator.ObjectModelValidator; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * Validateur qui valide : - * - les types des attributs - * - les nom des attributs - * - les duplication d'attibuts - * - * @author chatellier <chatellier@codelutin.com> - * @version $Id$ - */ -public class TopiaJavaValidator extends ObjectModelValidator { - - /** - * Constructor. - * - * @param model model to validate - */ - public TopiaJavaValidator(ObjectModel model) { - super(model); - } - - @Override - protected boolean validateAttribute(ObjectModelAttribute attr) { - - boolean isValid = super.validateAttribute(attr); - - // type null ou vide - if (attr.getType() == null || attr.getType().isEmpty()) { - isValid = false; - - addError(attr, "Invalid type \"" + attr.getType() + "\""); - } - - // name = java reserved keywords - if (!isJavaIdentifier(attr.getName())) { - isValid = false; - - addError(attr, "Attribute name " + attr.getName() - + " is not valid java identifier"); - } - - // test sur les mots réservés ? - - return isValid; - - } - - @Override - protected boolean validateClass(ObjectModelClass clazz) { - - boolean isValid = super.validateClass(clazz); - - // test attribute names duplication - Set<String> attributesName = new HashSet<String>(); - for (ObjectModelAttribute attr : clazz.getAttributes()) { - if (!attr.isNavigable()) { - - // not navigable, so will not use it... - continue; - } - String attrName = attr.getName(); - if (!attributesName.add(attrName)) { - addError(attr, "Attribute name " + attrName - + " already exists"); - - isValid = false; - } - } - - if (TopiaGeneratorUtil.isEntity(clazz)) { - - Set<String> methodsName = new HashSet<String>(); - for (ObjectModelAttribute attr : clazz.getAttributes()) { - - String capitalizeAttrName = StringUtils.capitalize(attr.getName()); - methodsName.add(TopiaGeneratorUtil.OPERATION_GETTER_BOOLEAN_PREFIX + capitalizeAttrName); - methodsName.add(TopiaGeneratorUtil.OPERATION_GETTER_DEFAULT_PREFIX + capitalizeAttrName); - methodsName.add("set" + capitalizeAttrName); - } - - // test if there is a method an already reserved name - for (ObjectModelOperation operation : clazz.getOperations()) { - String operationName = operation.getName(); - if (methodsName.contains(operationName)) { - addError(operation, "Operation name " + operationName - + " is already reserved for a getter/setter of an entity attribute"); - - isValid = false; - } - } - } - - return isValid; - } - - @Override - protected boolean validateModel(ObjectModel model) { - - return super.validateModel(model); - } - - /** - * Returns true if s is a legal Java identifier. - * - * @param s string to test - * @return true if s is a legal Java identifier - */ - public static boolean isJavaIdentifier(String s) { - if (s.length() == 0 || !Character.isJavaIdentifierStart(s.charAt(0))) { - return false; - } - for (int i = 1; i < s.length(); i++) { - if (!Character.isJavaIdentifierPart(s.charAt(i))) { - return false; - } - } - return true; - } -} Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaMetaTransformer.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaMetaTransformer.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaMetaTransformer.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,132 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.topia.generator; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.eugene.AbstractMetaTransformer; -import org.nuiton.eugene.models.object.ObjectModel; -import org.nuiton.eugene.models.object.ObjectModelClass; -import org.nuiton.eugene.models.object.validator.AttributeNamesValidator; -import org.nuiton.eugene.models.object.validator.ClassNamesValidator; -import org.nuiton.eugene.models.object.validator.ObjectModelValidator; - -import java.util.ArrayList; -import java.util.List; - -/** - * Created: 20 déc. 2009 - * - * @author tchemit <chemit@codelutin.com> - * @version $Id$ - * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.generator.TopiaMetaTransformer" - * @since 2.3.0 - */ -public class TopiaMetaTransformer extends AbstractMetaTransformer<ObjectModel> { - - /** Logger */ - private static final Log log = LogFactory.getLog(TopiaMetaTransformer.class); - - public TopiaMetaTransformer() { -// super( -// EntityTransformer.class, -// DAOTransformer.class, -// DAOImplTransformer.class, -// DAOAbstractTransformer.class, -// DAOHelperTransformer.class, -// EntityHibernateMappingGenerator.class -// ); - - setTemplateTypes( - ApplicationContextTransformer.class, - PersistenceContextTransformer.class, - EntityTransformer.class, - EntityDaoTransformer.class, -// DAOTransformer.class, -// DAOImplTransformer.class, -// DAOAbstractTransformer.class, - DAOHelperTransformer.class, - EntityHibernateMappingGenerator.class - ); - } - - protected boolean validateModel(ObjectModel model) { - List<ObjectModelValidator> validators = new ArrayList<ObjectModelValidator>(); - - AttributeNamesValidator attrValidator = new AttributeNamesValidator( - model); - attrValidator.addNameAndReason("analyze", - "Le nom d'attribut \"analyze\" est incompatible avec certains SGBD"); - attrValidator.addNameAndReason("next", - "Le nom d'attribut \"next\" est incompatible avec HSQL"); - attrValidator.addNameAndReason("value", - "Le nom d'attribut \"value\" est incompatible avec certains SGBD"); - attrValidator.addNameAndReason("values", - "Le nom d'attribut \"values\" est incompatible avec certains SGBD"); - attrValidator.addNameAndReason("begin", - "Le nom d'attribut \"begin\" est incompatible avec certains SGBD"); - attrValidator.addNameAndReason("end", - "Le nom d'attribut \"end\" est incompatible avec certains SGBD"); - attrValidator.addNameAndReason("authorization", - "Le nom d'attribut \"authorization\" est incompatible avec certains SGBD"); - attrValidator.addNameAndReason("order", - "Le nom d'attribut \"order\" est incompatible avec certains SGBD"); - validators.add(attrValidator); - - ClassNamesValidator classValidator = new ClassNamesValidator(model); - classValidator.addNameAndReason("constraint", "Nom de classe incompatible avec certains SGBD"); - classValidator.addNameAndReason("user", "Nom de classe incompatible avec certains SGBD"); - validators.add(classValidator); - - validators.add(new TopiaJavaValidator(model)); - validators.add(new TopiaRelationValidator(model)); - - for (ObjectModelValidator validator : validators) { - if (!validator.validate()) { - for (String error : validator.getErrors()) { - if (log.isWarnEnabled()) { - log.warn("[VALIDATION] " + error); - } - } - } - } - - // test before all if there is some entities to generate - List<ObjectModelClass> classes = TopiaGeneratorUtil.getEntityClasses(model, true); - - if (classes.isEmpty()) { - // no entity to generate, can stop safely - if (log.isWarnEnabled()) { - log.warn("No entity to generate, " + getClass().getName() + - " is skipped"); - } - return false; - } - //FIXME-TC20091220 seems we still generate if there is some validation errors ? not very normal - return true; - } - -} Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaRelationValidator.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaRelationValidator.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaRelationValidator.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,121 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - - -/* * -* TopiaRelationValidator.java -* -* Created: 31 mars 2006 -* -* @author Arnaud Thimel <thimel@codelutin.com> -* @version $Revision$ -* -* Mise a jour: $Date$ -* par : $Author$ -*/ - -package org.nuiton.topia.generator; - -import org.nuiton.eugene.models.object.ObjectModel; -import org.nuiton.eugene.models.object.ObjectModelAttribute; -import org.nuiton.eugene.models.object.validator.ObjectModelValidator; - -/** - * Validateur pour les relations du modèle. - * Vérifie que : - * <ul> - * <li>Toutes les relations ont au moins une navigabilité</li> - * <li>Une relation 1-n unidirectionnelle pointant sur une classe ayant des - * sous-classes dans le modèle est incompatibe avec Hibernate</li> - * <li>Toutes les relations ont des reverseAttribute</li> - * </ul> - * - * @version $Id$ - */ -public class TopiaRelationValidator extends ObjectModelValidator { - - /** - * Constructeur de TopiaRelationValidator. - * - * @param model le modèle à valider - */ - public TopiaRelationValidator(ObjectModel model) { - super(model); - } - - /* (non-Javadoc) - * @see org.nuiton.eugene.models.object.validator.ObjectModelValidator#validateAttribute(org.nuiton.eugene.models.object.ObjectModelAttribute) - */ - @Override - protected boolean validateAttribute(ObjectModelAttribute attr) { - boolean isValid = true; - ObjectModelAttribute reverse = attr.getReverseAttribute(); - - /* Relation navigabilité */ - //Pour ne pas avoir de doublons, on ne vérifie que sur le premier - //attribut par ordre alphabétique - if (TopiaGeneratorUtil.isFirstAttribute(attr)) { - if (!attr.isNavigable() && !reverse.isNavigable()) { - addError(attr, "La relation entre " + "\"" + reverse.getType() - + "\"[" + attr.getName() + "] et " + "\"" - + attr.getType() + "\"[" + reverse.getName() + "] " - + "n'est navigable dans aucun sens"); - isValid = false; - } - } - - /* Relation héritage */ - if (TopiaGeneratorUtil.hasUnidirectionalRelationOnAbstractType(attr, model)) { - isValid = false; - addError( - attr, - "La relation entre " - + "\"" - + reverse.getType() - + "\"[" - + attr.getName() - + "] et " - + "\"" - + attr.getType() - + "\"[" - + reverse.getName() - + "] " - + "n'est navigable que dans un sens et " - + "la classe \"" - + attr.getType() - + "\" a des sous-classes. " - + "Des accesseurs doivent donc etre generes pour Hibernate."); - } - - /* Pas d'inverse */ - if (reverse == null && model.hasClass(attr.getType())) { - isValid = false; - addError(attr, "Cet attribut n'a pas d'inverse."); - } - - return isValid; - } - -} //TopiaRelationValidator Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaStereoTypes.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaStereoTypes.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaStereoTypes.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,88 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.topia.generator; - -import org.nuiton.eugene.EugeneStereoTypes; -import org.nuiton.eugene.models.object.ObjectModelAttribute; -import org.nuiton.eugene.models.object.ObjectModelClassifier; -import org.nuiton.eugene.models.object.ObjectModelOperation; - -import static org.nuiton.eugene.ModelPropertiesUtil.StereotypeDefinition; - -/** - * All extra stereotypes usable in topia generators. - * - * @author tchemit <chemit@codelutin.com> - * @since 2.5 - */ -public interface TopiaStereoTypes extends EugeneStereoTypes { - - /** - * Stéréotype pour les objets devant être générées sous forme d'entités - * - * @see TopiaGeneratorUtil#isEntity(ObjectModelClassifier) - * @see TopiaGeneratorUtil#hasEntityStereotype(ObjectModelAttribute) - */ - @StereotypeDefinition(target = {ObjectModelClassifier.class, ObjectModelAttribute.class}, - documentation = "To specify that a class is an Entity") - String STEREOTYPE_ENTITY = "entity"; - - /** - * Stéréotype pour les objets devant être générées sous forme de DTO. - * - * @see TopiaGeneratorUtil#hasDtoStereotype(ObjectModelClassifier) - */ - @StereotypeDefinition(target = ObjectModelClassifier.class, - documentation = "to specify that a class is a DTO") - String STEREOTYPE_DTO = "dto"; - - /** - * Stéréotype pour les interfaces devant être générées sous forme de DAO. - * - * @see TopiaGeneratorUtil#hasDaoStereotype(ObjectModelClassifier) - * @see TopiaGeneratorUtil#hasDaoStereotype(ObjectModelOperation) - */ - @StereotypeDefinition(target = {ObjectModelClassifier.class, ObjectModelOperation.class}, - documentation = "To Specify that a classifier or an operation should be generated as (or in) a DAO") - String STEREOTYPE_DAO = "dao"; - - /** - * Stéréotype pour les collections avec unicité. - * - * @see TopiaGeneratorUtil#hasUniqueStereotype(ObjectModelAttribute) - */ - @StereotypeDefinition(target = ObjectModelAttribute.class, - documentation = "To specify that an attribute is unique (Hibernate mapping)") - String STEREOTYPE_UNIQUE = "unique"; - - /** - * Stéréotype pour les attributs étant des clés primaires. - * - * @see TopiaGeneratorUtil#hasPrimaryKeyStereotype(ObjectModelAttribute) - */ - @StereotypeDefinition(target = ObjectModelAttribute.class, - documentation = "To specify that an attribute is part of a primary key (Hibernate mapping)") - String STEREOTYPE_PRIMARYKAY = "primaryKey"; -} Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaTagValues.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaTagValues.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaTagValues.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,379 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.topia.generator; - -import org.nuiton.eugene.EugeneTagValues; -import org.nuiton.eugene.models.object.ObjectModel; -import org.nuiton.eugene.models.object.ObjectModelAttribute; -import org.nuiton.eugene.models.object.ObjectModelClass; -import org.nuiton.eugene.models.object.ObjectModelClassifier; -import org.nuiton.eugene.models.object.ObjectModelElement; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.persistence.TopiaEntityContextable; -import org.nuiton.topia.persistence.TopiaEntityEnum; - -import static org.nuiton.eugene.ModelPropertiesUtil.TagValueDefinition; - -/** - * All extra tag values usable in topia generators. - * - * @author tchemit <chemit@codelutin.com> - * @since 2.5 - */ -public interface TopiaTagValues extends EugeneTagValues { - - /** - * Tag pour le type de persistence. - * - * @see TopiaGeneratorUtil#getPersistenceType(ObjectModelClassifier) - * @see TopiaGeneratorUtil#getPersistenceTypeTagValue(ObjectModelClassifier) - * @since 2.5 - */ - @TagValueDefinition(target = {ObjectModelClassifier.class}, - documentation = "") - String TAG_PERSISTENCE_TYPE = "persistenceType"; - - /** - * Tag pour que les entités etendent {@link TopiaEntityContextable} et - * se fasse injecter le {@link TopiaContext} par rapport aux autres - * entités qui ne l'ont pas. - * - * @since 2.5.3 - */ - @TagValueDefinition(target = {ObjectModelClassifier.class}, documentation = "") - String TAG_CONTEXTABLE = "contextable"; - - /** - * Tag pour le nom du champ / entité en BD. - * - * @see TopiaGeneratorUtil#getDbNameTagValue(ObjectModelElement) - * @see TopiaGeneratorUtil#getDbName(ObjectModelElement) - * @see TopiaGeneratorUtil#getReverseDbName(ObjectModelAttribute) - */ - @TagValueDefinition(target = {ObjectModelElement.class}, - documentation = "Sets the database name of an element of the model (a table or a column)") - String TAG_DB_NAME = "dbName"; - - /** - * Tag pour le nom du schema en BD. - * - * @see TopiaGeneratorUtil#getDbSchemaNameTagValue(ObjectModelClassifier, ObjectModel) - * @see TopiaGeneratorUtil#getDbSchemaNameTagValue(ObjectModelAttribute, ObjectModel) - * @since 2.5 - */ - @TagValueDefinition(target = {ObjectModel.class, ObjectModelClassifier.class, ObjectModelAttribute.class}, - documentation = "Sets the database schema name") - String TAG_SCHEMA_NAME = "dbSchema"; - - /** - * Tag pour la taille du champ en BD. - * - * @see TopiaGeneratorUtil#getLengthTagValue(ObjectModelAttribute) - * @since 2.5 - */ - @TagValueDefinition(target = {ObjectModelAttribute.class}, - documentation = "Sets the length of an attribute in database") - String TAG_LENGTH = "length"; - - /** - * Tag pour ajouter une annotation à un champ. - * - * @see TopiaGeneratorUtil#getAnnotationTagValue(ObjectModelAttribute) - * @since 2.5 - */ - @TagValueDefinition(target = {ObjectModelAttribute.class}, - documentation = "Sets an annotation of an attribute") - String TAG_ANNOTATION = "annotation"; - - /** - * Tag pour specfier le type d'acces a un champ. - * - * @see TopiaGeneratorUtil#getAccessTagValue(ObjectModelAttribute) - * @since 2.5 - */ - @TagValueDefinition(target = {ObjectModelAttribute.class}, - documentation = "Sets the access type of an attribute (Hibernate mapping)") - String TAG_ACCESS = "access"; - - /** - * Tag pour ajouter un attribut dans une clef métier. - * - * @see TopiaGeneratorUtil#getNaturalIdTagValue(ObjectModelAttribute) - * @see TopiaGeneratorUtil#isNaturalId(ObjectModelAttribute) - * @since 2.5 - */ - @TagValueDefinition(target = {ObjectModelAttribute.class}, - documentation = "Sets an attribute as part of a natural id (Hibernate Mapping)") - String TAG_NATURAL_ID = "naturalId"; - - /** - * Tag pour specifier si une clef metier est mutable. - * - * @see TopiaGeneratorUtil#getNaturalIdMutableTagValue(ObjectModelClassifier) - * @see TopiaGeneratorUtil#isNaturalIdMutable(ObjectModelClass) - * @since 2.5 - */ - @TagValueDefinition(target = {ObjectModelClassifier.class}, - documentation = "Sets if natural id of a entity is mutable (hibernate mapping)") - String TAG_NATURAL_ID_MUTABLE = "naturalIdMutable"; - - /** - * Tag pour permettre de choisir qui contrôle la relation N-N - * bidirectionnelle. A utiliser sur les deux extremités de l'association. - * Mettre inverse=false sur le rôle fils et inverse=true sur le rôle père. - * Par défaut le inverse=true est placé sur le premier rôle trouvé dans - * l'ordre alphabétique. - * - * @see TopiaGeneratorUtil#getInverseTagValue(ObjectModelAttribute) - * @since 2.5 - */ - @TagValueDefinition(target = {ObjectModelAttribute.class}, - documentation = "Sets which part of a N-N relation is master (inverse=true) and slave (inverse=false) (must be put on each side on a such relation) (Hibernate mapping)") - String TAG_INVERSE = "inverse"; - - /** - * Tag pour spécifier la caractère lazy d'une association multiple. - * - * @see TopiaGeneratorUtil#getLazyTagValue(ObjectModelAttribute) - * @since 2.5 - */ - @TagValueDefinition(target = {ObjectModelAttribute.class}, - documentation = "Sets if an association should be lazy (Hibernate mapping)") - String TAG_LAZY = "lazy"; - - /** - * Tag pour spécifier la caractère fetch d'une association multiple. - * - * @see TopiaGeneratorUtil#getFetchTagValue(ObjectModelAttribute) - * @since 2.5 - */ - @TagValueDefinition(target = {ObjectModelAttribute.class}, - documentation = "Sets the fetch caracteristic of an attribute (Hibernate mapping)") - String TAG_FETCH = "fetch"; - - /** - * Tag pour spécifier la caractère order-by d'une association multiple. - * - * @see TopiaGeneratorUtil#getOrderByTagValue(ObjectModelAttribute) - * @since 2.5 - */ - @TagValueDefinition(target = {ObjectModelAttribute.class}, - documentation = "Sets the order by propertie of an multiple association (Hibernate mapping)") - String TAG_ORDER_BY = "orderBy"; - - /** - * Tag pour spécifier la caractère not-null d'un attribut. - * - * @see TopiaGeneratorUtil#getNotNullTagValue(ObjectModelAttribute) - * @since 2.5 - */ - @TagValueDefinition(target = {ObjectModelAttribute.class}, - documentation = "Sets if an attribute must be not null (Hibernate mapping)") - String TAG_NOT_NULL = "notNull"; - - /** - * Tag à placer sur un l'attribut d'une entité. Cet attribut est de type - * énumération : l'ajout de la tagValue indique qu'il faut utiliser le - * {@code name} de l'énumération et non l'ordinal pour stocker la valeur en - * base - */ - @TagValueDefinition(target = {ObjectModelAttribute.class}, - documentation = "'true' if the value of this attribute of type Enumeration should be stored with its name (instead of using ordinal)") - String TAG_USE_ENUMERATION_NAME = "useEnumerationName"; - - /** - * Tag pour configurer l'interface du proxy sur autre chose que l'implementation par defaut. - * <p/> - * Par defaut : - * null > generere le proxy sur l'interface de l'implementation - * Autre valeur : - * "none" > laisse la configuration par defaut d'hibernate - * - * @see TopiaGeneratorUtil#getPersistenceTypeTagValue(ObjectModelClassifier) - * @since 2.5 - */ - @TagValueDefinition(target = {ObjectModel.class, ObjectModelClassifier.class}, - documentation = "Configure the proxy interface on something else than the default implementation (null to use our default implementation, none to let hibernate deal it) (Hibernate mapping)") - String TAG_PROXY_INTERFACE = "hibernateProxyInterface"; - - /** - * Tag pour configurer la stategie d'heritage choisie. - * <p/> - * Par defaut : union-subclass : Table per class strategy - * Autre valeur : - * "subclass" > Single table per class hierarchy strategy - * "joined-subclass" > Joined subclass strategy - * - * @see TopiaGeneratorUtil#getPersistenceTypeTagValue(ObjectModelClassifier) - * @since 3.0 - */ - @TagValueDefinition(target = {ObjectModel.class, ObjectModelClassifier.class}, - documentation = "Configure the proxy interface on something else than the default implementation (null to use our default implementation, none to let hibernate deal it) (Hibernate mapping)") - String TAG_INHERITANCE_STRATEGY = "inheritanceStrategy"; - - /** - * Tag pour spécifier le permissions à la création. - * - * @see TopiaGeneratorUtil#getSecurityCreateTagValue(ObjectModelClassifier) - * @since 2.5 - */ - @TagValueDefinition(target = {ObjectModelClassifier.class}, - documentation = "Sets the create permission on an entity") - String TAG_SECURITY_CREATE = "securityCreate"; - - /** - * Tag pour spécifier le permissions au chargement. - * - * @see TopiaGeneratorUtil#getSecurityLoadTagValue(ObjectModelClassifier) - * @since 2.5 - */ - @TagValueDefinition(target = {ObjectModelClassifier.class}, - documentation = "Sets the load permission on an entity") - String TAG_SECURITY_LOAD = "securityLoad"; - - /** - * Tag pour spécifier le permissions à la mise à jour. - * - * @see TopiaGeneratorUtil#getSecurityUpdateTagValue(ObjectModelClassifier) - * @since 2.5 - */ - @TagValueDefinition(target = {ObjectModelClassifier.class}, - documentation = "Sets the update permission on an entity") - String TAG_SECURITY_UPDATE = "securityUpdate"; - - /** - * Tag pour spécifier le permissions à la suppression. - * - * @see TopiaGeneratorUtil#getSecurityDeleteTagValue(ObjectModelClassifier) - * @since 2.5 - */ - @TagValueDefinition(target = {ObjectModelClassifier.class}, - documentation = "sets the delete permission on an entity") - String TAG_SECURITY_DELETE = "securityDelete"; - - /** - * Tag pour specifier de ne pas generer la methode toString. - * - * @see TopiaGeneratorUtil#getNotGenerateToStringTagValue(ObjectModelClassifier, ObjectModel) - * @see TopiaGeneratorUtil#generateToString(ObjectModelClass, ObjectModel) - * @since 2.5 - */ - @TagValueDefinition(target = {ObjectModel.class, ObjectModelClassifier.class}, - documentation = "To not generate the toString method on entities") - String TAG_NOT_GENERATE_TO_STRING = "notGenerateToString"; - - /** - * Tag pour specifier de trier les attributs par nom lors de la generation. - * - * @see TopiaGeneratorUtil#getSortAttributeTagValue(ObjectModelClassifier, ObjectModel) - * @see TopiaGeneratorUtil#sortAttribute(ObjectModelClass, ObjectModel) - * @since 2.5 - */ - @TagValueDefinition(target = {ObjectModel.class, ObjectModelClassifier.class}, - documentation = "To sort attribute while generation") - String TAG_SORT_ATTRIBUTE = "sortAttribute"; - - /** - * Tag pour specfier si on doit générer la methode getOperator dans les daohelpers. - * - * @see TopiaGeneratorUtil#getGenerateOperatorForDAOHelperTagValue(ObjectModel) - * @see TopiaGeneratorUtil#shouldGenerateOperatorForDAOHelper(ObjectModel) - * @since 2.5 - */ - @TagValueDefinition(target = {ObjectModel.class}, - documentation = "To generate EntityOperation on generated DAOHelper") - String TAG_GENERATE_OPERATOR_FOR_DAO_HELPER = "generateOperatorForDAOHelper"; - - /** - * Tag pour spécifier si on doit générer le {@link TopiaEntityEnum} en tant qu'inner classe - * du dao helper ou pas. - * <p/> - * <b>Note:</b> Par défaut, on génère en tant qu'inner classe. - * - * @see TopiaGeneratorUtil#getGenerateStandaloneEnumForDAOHelperTagValue(ObjectModel) - * @see TopiaGeneratorUtil#shouldGenerateStandaloneEnumForDAOHelper(ObjectModel) - * @since 2.5 - */ - @TagValueDefinition(target = {ObjectModel.class}, - documentation = "To generate a standalon EntityEnum outside the DAOHelper") - String TAG_GENERATE_STANDALONE_ENUM_FOR_DAO_HELPER = "generateStandaloneEnumForDAOHelper"; - - /** - * Tag pour spécifier le type d'une propriété dans le mapping hibernate. - * - * @see TopiaGeneratorUtil#getTypeTagValue(ObjectModelAttribute) - * @since 2.5 - */ - @TagValueDefinition(target = {ObjectModelAttribute.class}, - documentation = "Sets the hibernate type of an attribute (Hibernate mapping)") - String TAG_TYPE = "type"; - - /** - * Tag pour spécifier le type sql d'une propriété dans le mapping hibernate. - * - * @see TopiaGeneratorUtil#getSqlTypeTagValue(ObjectModelAttribute) - * @since 2.5 - */ - @TagValueDefinition(target = {ObjectModelAttribute.class}, - documentation = "Sets the sql type of an attribute (Hibernate mapping)") - String TAG_SQL_TYPE = "sqlType"; - - /** - * To specify the abstract dao to use. - * <p/> - * If none given, will use the {@code org.nuiton.topia.persistence.TopiaDAOImpl}. - * <p/> - * Other value possible is {@code org.nuiton.topia.persistence.TopiaDAOLegacy} - * - * @see TopiaGeneratorUtil#getDaoImplementationTagValue(ObjectModel) - * @since 2.5 - */ - @TagValueDefinition(target = {ObjectModel.class}, - documentation = "Sets the fully qualified name of the DAO implementation to use in generated DAO (default is DAOImpl (base on TopiaQuery))") - String TAG_DAO_IMPLEMENTATION = "daoImplementation"; - - /** - * Stéréotype pour les attributs avec multiplicité nécessitant la création d'un index. - * - * @see TopiaGeneratorUtil#getIndexForeignKeys(ObjectModelAttribute, ObjectModel) - * @since 2.6.5 - */ - @TagValueDefinition(target = {ObjectModel.class, ObjectModelAttribute.class}, - documentation = "Specifies if an nm-multiplicity attribute (or all nm-multiplicity attributes of a given model) needs an index in db (Hibernate mapping)") - String TAG_INDEX_FOREIGN_KEYS = "indexForeignKeys"; - - /** - * Tag to specify if we want to add an "id" property in DTO generated by - * {@link EntityDTOTransformer}. - * <p/> - * - * @see EntityDTOTransformer - * @see TopiaGeneratorUtil#shouldGenerateDTOTopiaIdTagValue(ObjectModelClassifier, ObjectModel) - * @since 2.6.7 - */ - @TagValueDefinition(target = {ObjectModel.class, ObjectModelClassifier.class}, - documentation = "Add a \"id\" property with its getter/setter on a DTO.") - String TAG_GENERATE_TOPIA_ID_IN_DTO = "generateDTOTopiaId"; -} Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/package-info.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/package-info.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/package-info.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,118 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -/** - * TODO-FD20100507 : Need update this javadoc for ToPIA 2.4 - * - * <h1>Les Générateurs</h1> - * - * <h2>TopiaMetaGenerator</h2> - * - * <p>TopiaMetaGenerator permet d'enchainer les différents - * générateurs.</p> - * - * <h2>Les DAO</h2> - * - * <p>Il il y a trois générateurs pour les DAO</p> - * - * <ul> - * <li>DAOHelperGenerator</li> - * - * <li>DAOAbstractGenerator</li> - * - * <li>DAOGenerator</li> - * </ul> - * - * <p><b><i>DAOHelperGenerator</i></b> permet de récupérer les DAOs - * générés spécifiquement pour l'application sans avoir besoin de passer - * le type de l'entité en paramètre. Cette classe contient donc une - * methode get par type d'entity qui permet de récupérer le DAO associé. - * Ces méthodes sont des méthodes statiques et prennent en paramètre un - * TopiaContext.</p> - * - * <p><b><i>DAOAbstractGenerator</i></b> est une classe abstraite même si - * elle peut implanter toutes les méthodes de l'interface TopiaDAO. De - * cette façon on oblige l'existance d'une classe concrète qui en hérite - * soit développé par le développeur soit généré par DAOGenerator. - * DAOAbstractGenerator contient toutes les méthodes findBy, findAllBy, - * ... associées aux attributs existants. La classe généré hérite - * directement ou indirectement de TopiaDAODelegator.</p> - * - * <p><b><i>DAOGenerator</i></b> génère une classe vide qui permet au - * programme de compiler, si le développeur à besoin de méthode find - * supplémentaire sur son DAO, il lui suffit de d'implanter cette classe - * dans ses sources, le processus de génération écrasera alors la classe - * généré par la classe développée spécifiquement.</p> - * - * <h2>Les entités</h2> - * - * <p>Les entités sont de pure POJO et ne contiennent pas de référence en - * interne sur le TopiaContext ou le DAO qui les à créée, elle peuvent - * donc facilement migrer, être utilisé dans différents context, ... le - * but etant qu'elle reste des classes complètement déconnecté à - * l'exécution du framework.</p> - * - * <p>La seul contrainte est qu'elles implante TopiaEntity</p> - * - * <p>Il il y a trois générateurs pour les entités, plus un pour le - * mapping hibernate</p> - * - * <ul> - * <li>EntityInterfaceGenerator</li> - * - * <li>EntityAbstractGenerator</li> - * - * <li>EntityImplGenerator</li> - * - * <li>EntityHibernateMappingGenerator</li> - * </ul> - * - * <p><b><i>EntityInterfaceGenerator</i></b> génère l'interface de - * l'entité avec les méthodes d'accès aux attributs et les opérations - * définis par l'utilisateur dans son diagrammme de classe. Elle implante - * TopiaEntity</p> - * - * <p><b><i>EntityAbstractGenerator</i></b> génère une classe qui - * implante l'interface de l'entité et étend TopiaEntityAbstract qui - * implante les méthodes du framework, méthode d'accès aux attributs - * topiaId, topiaVersion et topiaCreateDate.</p> - * - * <p><b><i>EntityImplGenerator</i></b> génère une classe vide qui permet - * au programme de compiler si l'entité n'a pas d'opération spécifique. - * Si elle a des opérations spécifiques le développeur doit implanter - * cette classe dans ses sources et y mettre le code pour les opérations - * spécifiques, le processus de génération écrasera alors la classe - * généré par la classe développée spécifiquement.</p> - * - * <p><b><i>EntityHibernateMappingGenerator</i></b> génère le fichier de - * mapping pour entité. L'interface est déclaré dans le mapping et est - * mappé sur une table préfixé par I. Ensuite le Impl est déclaré en - * union-subclass de cette interface. On a besoin de l'interface car les - * méthodes l'utilise dans les signatures de méthode lorsqu'il y a un - * lien entre deux entités.</p> - * - * @author poussin <poussin@codelutin.com> - * @version $Id$ - */ -package org.nuiton.topia.generator; \ No newline at end of file Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaEntity.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaEntity.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/persistence/TopiaEntity.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -38,9 +38,6 @@ package org.nuiton.topia.persistence; import org.nuiton.topia.TopiaException; -import org.nuiton.topia.generator.EntityHibernateMappingGenerator; -import org.nuiton.topia.generator.EntityTransformer; -import org.nuiton.topia.generator.TopiaMetaTransformer; import java.beans.PropertyChangeListener; import java.beans.VetoableChangeListener; @@ -49,9 +46,9 @@ import java.util.List; /** - * The TopiaEntity is the main interface for each entity generated with {@link - * TopiaMetaTransformer}. An entity is simply a persistent bean mapped with - * Hibernate. The manipulation on entities (create, update, delete, find) is + * The TopiaEntity is the main interface for each entity generated. + * An entity is simply a persistent bean mapped with Hibernate. + * The manipulation on entities (create, update, delete, find) is * made by the DAO associated. The corresponding DAO interface is {@link * TopiaDAO}. * <p/> @@ -61,8 +58,6 @@ * @author poussin <poussin@codelutin.com> * @author fdesbois <fdesbois@codelutin.com> * @version $Id$ - * @see EntityHibernateMappingGenerator - * @see EntityTransformer */ @SearchFields public interface TopiaEntity extends Serializable { Deleted: trunk/topia-persistence/src/main/resources/META-INF/services/org.nuiton.eugene.ModelPropertiesUtil$ModelPropertiesProvider =================================================================== --- trunk/topia-persistence/src/main/resources/META-INF/services/org.nuiton.eugene.ModelPropertiesUtil$ModelPropertiesProvider 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/main/resources/META-INF/services/org.nuiton.eugene.ModelPropertiesUtil$ModelPropertiesProvider 2013-11-22 18:03:47 UTC (rev 2884) @@ -1 +0,0 @@ -org.nuiton.topia.generator.TopiaGeneratorUtil$TopiaModelPropertiesProvider \ No newline at end of file Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/AbstractEmployeTopiaDao.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/AbstractEmployeTopiaDao.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/AbstractEmployeTopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,33 +0,0 @@ -package org.nuiton.topia; - -/* - * #%L - * ToPIA :: Persistence - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2013 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -import org.nuiton.topiatest.Employe; - -/** - * @author Arnaud Thimel <thimel@codelutin.com> - */ -public abstract class AbstractEmployeTopiaDao<E extends Employe> extends GeneratedEmployeeTopiaDao<E> { -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/AbstractPersonneTopiaDao.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/AbstractPersonneTopiaDao.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/AbstractPersonneTopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,34 +0,0 @@ -package org.nuiton.topia; - -/* - * #%L - * ToPIA :: Persistence - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2013 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -import org.nuiton.topiatest.Personne; - -/** - * @author Arnaud Thimel <thimel@codelutin.com> - */ -public abstract class AbstractPersonneTopiaDao<E extends Personne> extends GeneratedPersonneTopiaDao<E> { - -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/EmployeTopiaDao.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/EmployeTopiaDao.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/EmployeTopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,42 +0,0 @@ -package org.nuiton.topia; - -/* - * #%L - * ToPIA :: Persistence - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2013 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -import java.util.List; - -import org.nuiton.topiatest.Employe; -import org.nuiton.topiatest.Personne; - -/** - * @author Arnaud Thimel <thimel@codelutin.com> - */ -public class EmployeTopiaDao extends AbstractEmployeTopiaDao<Employe> { - - @Override - public List<Personne> findAllPersonnesByXAndY(int x, int y) { - return null; - } - -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/EmployeeDao.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/EmployeeDao.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/EmployeeDao.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,31 +0,0 @@ -package org.nuiton.topia; - -/* - * #%L - * ToPIA :: Persistence - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2013 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -/** - * @author Arnaud Thimel <thimel@codelutin.com> - */ -public interface EmployeeDao { -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/GeneratedEmployeeTopiaDao.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/GeneratedEmployeeTopiaDao.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/GeneratedEmployeeTopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,33 +0,0 @@ -package org.nuiton.topia; - -/* - * #%L - * ToPIA :: Persistence - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2013 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -import org.nuiton.topiatest.Employe; - -/** - * @author Arnaud Thimel <thimel@codelutin.com> - */ -public abstract class GeneratedEmployeeTopiaDao<E extends Employe> extends AbstractPersonneTopiaDao<E> { -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/GeneratedPersonneTopiaDao.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/GeneratedPersonneTopiaDao.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/GeneratedPersonneTopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,60 +0,0 @@ -package org.nuiton.topia; - -/* - * #%L - * ToPIA :: Persistence - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2013 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -import java.util.List; -import java.util.Map; - -import org.nuiton.topia.persistence.AbstractTopiaDao; -import org.nuiton.topia.persistence.TopiaEntity; -import org.nuiton.topia.persistence.TopiaEntityEnum; -import org.nuiton.topiatest.Personne; - -/** - * @author Arnaud Thimel <thimel@codelutin.com> - */ -public abstract class GeneratedPersonneTopiaDao<E extends Personne> extends AbstractTopiaDao<E> implements PersonneDao { - - @Override - public TopiaEntityEnum getTopiaEntityEnum() { - return null; - } - - @Override - public <R extends TopiaEntity> List<R> findUsages(Class<R> type, E entity) throws TopiaException { - return null; - } - - @Override - public Map<Class<? extends TopiaEntity>, List<? extends TopiaEntity>> findAllUsages(E entity) throws TopiaException { - return null; - } - - @Override - public Class<E> getEntityClass() { - return null; - } - -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/PersonneDao.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/PersonneDao.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/PersonneDao.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,38 +0,0 @@ -package org.nuiton.topia; - -/* - * #%L - * ToPIA :: Persistence - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2013 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -import java.util.List; - -import org.nuiton.topiatest.Personne; - -/** - * @author Arnaud Thimel <thimel@codelutin.com> - */ -public interface PersonneDao { - - List<Personne> findAllPersonnesByXAndY(int x, int y); - -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/PersonneTopiaDao.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/PersonneTopiaDao.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/PersonneTopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,41 +0,0 @@ -package org.nuiton.topia; - -/* - * #%L - * ToPIA :: Persistence - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2013 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -import java.util.List; - -import org.nuiton.topiatest.Personne; - -/** - * @author Arnaud Thimel <thimel@codelutin.com> - */ -public class PersonneTopiaDao extends AbstractPersonneTopiaDao<Personne> { - - @Override - public List<Personne> findAllPersonnesByXAndY(int x, int y) { - return null; - } - -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/TestHelper.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/TestHelper.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/TestHelper.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,160 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.topia; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.hibernate.cfg.Environment; -import org.junit.Ignore; -import org.nuiton.util.FileUtil; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -/** - * Helper for all topia tests. - * - * @author tchemit <chemit@codelutin.com> - * @since 2.5 - */ -@Ignore -// this is not a test :) -public class TestHelper { - - private static final Log log = LogFactory.getLog(TestHelper.class); - - protected static File testBasedir; - - protected static File targetdir; - - protected static File dirDatabase; - - public static final String DEFAULT_CONFIGURATION_LOCATION = "/TopiaContextImpl.properties"; - - public static File getTestWorkdir() { - if (testBasedir == null) { - String base = System.getProperty("java.io.tmpdir"); - if (base == null || base.isEmpty()) { - base = new File("").getAbsolutePath(); - } - testBasedir = new File(base); - log.info("basedir for test " + testBasedir); - } - return testBasedir; - } - - public static File getTestBasedir(Class<?> testClass) throws IOException { - File dir = getTestWorkdir(); - File result = new File(dir, testClass.getName()); - if (result.exists()) { - - // when calling this method (always in a BeforeClass method), we wants - // to clean the directory, this is a new build - FileUtils.deleteDirectory(result); - } - - // always create the directory - FileUtil.createDirectoryIfNecessary(result); - return result; - } - - public static TopiaContext initTopiaContext(File testDirectory, - String dbname) - throws IOException, TopiaNotFoundException { - - - TopiaContext topiaContext = initTopiaContext( - testDirectory, - DEFAULT_CONFIGURATION_LOCATION, - dbname - ); - return topiaContext; - } - - public static TopiaContext initTopiaContext(File testDirectory, - String dbPropertiesPath, - String dbname) - throws IOException, TopiaNotFoundException { - - Properties configuration = initTopiaContextConfiguration( - testDirectory, - dbPropertiesPath, - dbname); - return TopiaContextFactory.getContext(configuration); - } - - public static Properties initTopiaContextConfiguration(File testDirectory, - String dbPropertiesPath, - String dbname) - throws IOException { - - Properties configuration = loadHibernateConfiguration(dbPropertiesPath); - - // make sure we always use a different directory - - String dbPath = getDbName(testDirectory, dbname); - - if (log.isInfoEnabled()) { - log.info("dbPath = " + dbPath); - } - configuration.setProperty( - Environment.URL, -// "hibernate.connection.url", - "jdbc:h2:file:" + dbPath); - - return configuration; - } - - public static Properties loadHibernateConfiguration(String dbPropertiesPath) throws IOException { - InputStream stream = TestHelper.class.getResourceAsStream(dbPropertiesPath); - - Properties configuration = new Properties(); - - configuration.load(stream); - configuration.setProperty( - TopiaContextFactory.CONFIG_PERSISTENCE_CLASSES, - TopiaTestDAOHelper.getImplementationClassesAsString()); - return configuration; - } - - public static String getDbName(File testDirectory, String dbname) { - return new File(testDirectory, - dbname + '_' + System.nanoTime()).getAbsolutePath(); - } - - public static Properties initTopiaContextConfiguration(File testDirectory, - String dbname) - throws IOException { - - return initTopiaContextConfiguration( - testDirectory, - DEFAULT_CONFIGURATION_LOCATION, - dbname - ); - } -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/TopiaContextFactoryTest.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/TopiaContextFactoryTest.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/TopiaContextFactoryTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,189 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.topia; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.nuiton.topia.framework.AbstractTopiaContext; - -import java.io.File; -import java.io.IOException; -import java.util.List; -import java.util.Properties; - -/** - * Created: 8 mai 2010 - * - * @author fdesbois <fdesbois@codelutin.com> - * @version $Id$ - */ -public class TopiaContextFactoryTest { - - private static final Log log = - LogFactory.getLog(TopiaContextFactoryTest.class); - - protected static File testBasedir; - - protected Properties properties; - - @BeforeClass - public static void init() throws IOException { - - testBasedir = TopiaDatabase.getTestSpecificDirectory(TopiaContextFactoryTest.class, "dummy"); - - } - - @Before - public void setUp() throws Exception { - properties = new Properties(); - properties.setProperty("prop1", "value1"); - properties.setProperty("prop2", "value2"); - TopiaContextFactory.contextCache.clear(); - } - - @Test - public void testGetContextOpened() throws Exception { - log.debug("## testGetContextOpened"); - - /** PREPARE DATA **/ - String databaseName = "h2data-testGetContextByPropertie"; - File dbDirectory = new File(testBasedir, databaseName); - String url = "jdbc:h2:file:" + dbDirectory; - properties.setProperty("hibernate.connection.url", url); - - AbstractTopiaContext test = new AbstractTopiaContext(properties); - TopiaContextFactory.contextCache.put(properties, test); - - /** EXEC METHOD **/ - List<String> result = TopiaContextFactory.getContextOpened(); - Assert.assertEquals(1, result.size()); - Assert.assertEquals(url, result.get(0)); - } - - @Test - public void testRemoveContext() throws Exception { - log.debug("## testRemoveContext"); - - /** PREPARE DATA **/ - AbstractTopiaContext test = new AbstractTopiaContext(properties); - TopiaContextFactory.contextCache.put(properties, test); - - /** EXEC METHOD **/ - TopiaContextFactory.removeContext(test); - Assert.assertEquals(0, TopiaContextFactory.contextCache.size()); - } - - //@Test - - public void testGetContext() throws Exception { - // TODO-fdesbois-20100508 : only used TopiaUtil.getProperties, need tests for this method - } - - @Test - public void testGetContextByProperties() throws Exception { - log.debug("## testGetContextByProperties"); - - /** PREPARE DATA **/ - Properties propertiesParent = new Properties(properties); - propertiesParent.setProperty("prop3", "value3"); - - Properties propertiesAll = new Properties(); - propertiesAll.setProperty("prop1", "value1"); - propertiesAll.setProperty("prop2", "value2"); - propertiesAll.setProperty("prop3", "value3"); - - /** EXEC METHOD **/ - - log.info("test 0 : add null properties"); - try { - TopiaContextFactory.getContext(null); - } catch (Exception eee) { - Assert.assertEquals(NullPointerException.class, eee.getClass()); - } - - log.info("test 1 : add new properties, will instantiate a new" + - " TopiaContext"); - TopiaContext test1 = TopiaContextFactory.getContext(propertiesParent); - Assert.assertNotNull(test1); - Assert.assertEquals(1, TopiaContextFactory.contextCache.size()); - - log.info("test 2 : with same properties, will retrieve existing" + - " TopiaContext"); - TopiaContext test2 = TopiaContextFactory.getContext(propertiesParent); - Assert.assertEquals(test1, test2); - Assert.assertEquals(1, TopiaContextFactory.contextCache.size()); - - log.info("test 3 : use other properties, will instantiate a different" + - "TopiaContext"); - TopiaContext test3 = TopiaContextFactory.getContext(properties); - log.debug("cache size : " + TopiaContextFactory.contextCache.size()); - log.debug("result : " + test1); - log.debug("result3 : " + test3); - Assert.assertNotSame(test1, test3); - Assert.assertEquals(2, TopiaContextFactory.contextCache.size()); - - log.info("test 4 : use other properties but equivalent to existing " + - "TopiaContext"); - // Test flating of properties - TopiaContext test4 = TopiaContextFactory.getContext(propertiesAll); - Assert.assertEquals(test1, test4); - Assert.assertEquals(2, TopiaContextFactory.contextCache.size()); - - log.info("test5a : reinstantiate new TopiaContext after one is closed."); - // TEST - // Strange behavior the closed flag of context stay true if - // hibernateFactory is not loaded from real properties -// test1.closeContext(); -// Assert.assertTrue(test1.isClosed()); - - // Add properties for Hibernate to have real opened topiaContext - String databaseName = "h2data-testGetContextByPropertie"; - File f = new File(testBasedir, databaseName); - - properties.setProperty("hibernate.connection.username", "sa"); - properties.setProperty("hibernate.connection.password", ""); - properties.setProperty("hibernate.connection.driver_class", "org.h2.Driver"); - properties.setProperty("hibernate.connection.url", - "jdbc:h2:file:" + f.getAbsolutePath()); - - - TopiaContext test5 = TopiaContextFactory.getContext(properties); - Assert.assertNotSame(test1, test5); - Assert.assertEquals(3, TopiaContextFactory.contextCache.size()); - - log.info("test5b : beginTransaction to properly close the context"); - test5.beginTransaction(); - - test5.closeContext(); - - TopiaContext result = TopiaContextFactory.getContext(properties); - Assert.assertNotSame(test5, result); - Assert.assertEquals(3, TopiaContextFactory.contextCache.size()); - } -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/TopiaDatabase.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/TopiaDatabase.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/TopiaDatabase.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,207 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2012 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.topia; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.hibernate.cfg.Configuration; -import org.junit.rules.TestWatcher; -import org.junit.runner.Description; - -import java.io.File; -import java.io.InputStream; -import java.util.Properties; - -/** - * Put this class as a Rule in test to obtain a new isolated db for each test. - * <p/> - * Here is a simple example of usage : - * <pre> - * public class MyTest { - * - * \@Rule - * public final TopiaDatabase db = new TopiaDatabase(); - * - * \@Test - * public void testMethod() throws TopiaException { - * - * TopiaContext tx = db.beginTransaction(); - * ... - * } - * </pre> - * The db created will be unique for each test method (and for each build also). - * <p/> - * You don't need to close any transaction, it will be done for you and the end - * of each method test. - * - * @author tchemit <chemit@codelutin.com> - * @since 2.6.8 - */ -public class TopiaDatabase extends TestWatcher { - - /** Logger. */ - private static final Log log = LogFactory.getLog(TopiaDatabase.class); - - /** A time-stamp, allow to make multiple build and keep the tests data. */ - public static final String TIMESTAMP = String.valueOf(System.nanoTime()); - - private File testBasedir; - - private Properties dbConfiguration; - - private TopiaTestTopiaApplicationContext applicationContext; - - private Configuration hibernateCfg; - - private final String configurationPath; - - public TopiaDatabase() { - this(TestHelper.DEFAULT_CONFIGURATION_LOCATION); - } - - public TopiaDatabase(String configurationPath) { - this.configurationPath = configurationPath; - } - - @Override - protected void starting(Description description) { - - // get test directory - testBasedir = getTestSpecificDirectory( - description.getTestClass(), - description.getMethodName()); - - if (log.isDebugEnabled()) { - log.debug("testBasedir = " + testBasedir); - } - - // create the root context - try { - - dbConfiguration = new Properties(); - InputStream stream = - getClass().getResourceAsStream(configurationPath); - - try { - dbConfiguration.load(stream); - } finally { - stream.close(); - } - dbConfiguration.setProperty( - TopiaContextFactory.CONFIG_PERSISTENCE_CLASSES, - TopiaTestDAOHelper.getImplementationClassesAsString()); - - // make sure we always use a different directory - - String dbPath = new File(testBasedir, "db").getAbsolutePath(); - - if (log.isDebugEnabled()) { - log.debug("dbPath = " + dbPath); - } - dbConfiguration.setProperty( - TopiaContextFactory.CONFIG_URL, "jdbc:h2:file:" + dbPath); - - onDbConfigurationCreate(dbConfiguration, testBasedir, dbPath); - -// rootCtxt = TopiaContextFactory.getContext(dbConfiguration); - applicationContext = new TopiaTestTopiaApplicationContext(dbConfiguration) { - @Override - protected HibernateProvider getHibernateProvider() { - HibernateProvider provider = super.getHibernateProvider(); - hibernateCfg = provider.getHibernateConfiguration(); - return provider; - } - }; - } catch (Exception e) { - throw new IllegalStateException( - "Could not start db at " + testBasedir, e); - } - } - - @Override - public void finished(Description description) { - - if (applicationContext != null && !applicationContext.isClosed()) { - try { - applicationContext.closeContext(); - } catch (TopiaException e) { - if (log.isErrorEnabled()) { - log.error("Could not close topia root context", e); - } - } - } - applicationContext = null; - dbConfiguration = null; - } - - public File getTestBasedir() { - return testBasedir; - } - - public Properties getDbConfiguration() { - return dbConfiguration; - } - - public TopiaTestTopiaApplicationContext getApplicationContext() { - return applicationContext; - } - - public Configuration getHibernateCfg() { - return hibernateCfg; - } - - public TopiaTestTopiaPersistenceContext beginTransaction() throws TopiaException { - return applicationContext.newPersistenceContext(); - } - - protected void onDbConfigurationCreate(Properties configuration, - File testDir, - String dbPath) { - - } - - public static File getTestSpecificDirectory(Class<?> testClassName, String methodName) { - // Trying to look for the temporary folder to store data for the test - String tempDirPath = System.getProperty("java.io.tmpdir"); - if (tempDirPath == null) { - // can this really occur ? - tempDirPath = ""; - if (log.isWarnEnabled()) { - log.warn("'\"java.io.tmpdir\" not defined"); - } - } - File tempDirFile = new File(tempDirPath); - - // create the directory to store database data - String dataBasePath = testClassName.getName() - + File.separator // a directory with the test class name - + methodName// a sub-directory with the method name - + '_' - + TIMESTAMP; // and a timestamp - File databaseFile = new File(tempDirFile, dataBasePath); - return databaseFile; - } -} - Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/TopiaJpaSupportTest.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/TopiaJpaSupportTest.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/TopiaJpaSupportTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,161 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence :: Test Compatibility Kit - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2012 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.topia; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.nuiton.topiatest.Address; -import org.nuiton.topiatest.AddressTopiaDao; -import org.nuiton.topiatest.Gender; -import org.nuiton.topiatest.Personne; -import org.nuiton.topiatest.PersonneTopiaDao; - -import java.util.List; - -/** - * Tests the TopiaContext#find|findAll|findUnique methods - * - * @author Arnaud Thimel <thimel@codelutin.com> - */ -public class TopiaJpaSupportTest { - - @Rule - public final TopiaDatabase db = new TopiaDatabase(); - - protected TopiaTestTopiaPersistenceContext persistenceContext; - protected TopiaJpaSupport jpaSupport; - protected AddressTopiaDao addressDAO; - protected PersonneTopiaDao personneDAO; - protected Address address; - - @Before - public void createCompanies() throws TopiaException { - persistenceContext = db.beginTransaction(); - jpaSupport = persistenceContext.jpaSupport; - - personneDAO = persistenceContext.getPersonneDao(); - addressDAO = persistenceContext.getAddressDao(); - - address = addressDAO.create( - Address.PROPERTY_ADRESS, "17 rue de la Pote Gellée, 44200 NANTES"); - - personneDAO.create( - Personne.PROPERTY_NAME, "Arnaud", - Personne.PROPERTY_GENDER, Gender.MALE); - personneDAO.create( - Personne.PROPERTY_NAME, "Charlotte", - Personne.PROPERTY_GENDER, Gender.FEMALE); - personneDAO.create( - Personne.PROPERTY_NAME, "Hortense", - Personne.PROPERTY_GENDER, Gender.FEMALE); - persistenceContext.commitTransaction(); - } - - @Test - public void testFindDAO() throws TopiaException { - Assert.assertEquals(3, personneDAO.count()); - - Assert.assertEquals(2, personneDAO.findAllByGender(Gender.FEMALE).size()); - Assert.assertNotNull(personneDAO.findByGender(Gender.FEMALE)); - Assert.assertNotNull(personneDAO.findByGender(Gender.MALE)); - Assert.assertNull(personneDAO.findByGender(null)); - - Assert.assertEquals(0, personneDAO.findAllByName("nobody").size()); - } - - @Test - public void testFindAll() throws TopiaException { - Assert.assertEquals(3, personneDAO.count()); - - String query = "from " + Personne.class.getName() + - " where " + Personne.PROPERTY_GENDER + "=:g"; - - List females = jpaSupport.findAll(query, "g", Gender.FEMALE); - Assert.assertEquals(2, females.size()); - - List males = jpaSupport.findAll(query, "g", Gender.MALE); - Assert.assertEquals(1, males.size()); - - List all = jpaSupport.findAll("from " + Personne.class.getName()); - Assert.assertEquals(3, all.size()); - - List none = jpaSupport.findAll("from " + Personne.class.getName() + - " where " + Personne.PROPERTY_NAME + "=:pax", "pax", "nobody"); - Assert.assertEquals(0, none.size()); - } - - @Test - public void testFind() throws TopiaException { - Assert.assertEquals(3, personneDAO.count()); - - String query = "from " + Personne.class.getName() + - " where " + Personne.PROPERTY_GENDER + "=:g"; - - List females = jpaSupport.find(query, 0, 100, "g", Gender.FEMALE); - Assert.assertEquals(2, females.size()); - - females = jpaSupport.find(query, 0, 0, "g", Gender.FEMALE); - Assert.assertEquals(1, females.size()); - Personne charlotte = (Personne)females.get(0); - - females = jpaSupport.find(query, 1, 1, "g", Gender.FEMALE); - Assert.assertEquals(1, females.size()); - Personne hortense = (Personne)females.get(0); - - Assert.assertFalse(hortense.equals(charlotte)); - - // endIndex = -1 not supported in ToPIA 2.6, wait for 3.0 -// females = context.find(query, 0, -1, "g", Gender.FEMALE); -// Assert.assertEquals(2, females.size()); - } - - @Test - public void testFindUnique() throws TopiaException { - Assert.assertEquals(3, personneDAO.count()); - - String query = "from " + Personne.class.getName() + - " where " + Personne.PROPERTY_GENDER + "=:g"; - - Object male = jpaSupport.findUnique(query, "g", Gender.MALE); - Assert.assertNotNull(male); - - Object none = jpaSupport.findUnique("from " + Personne.class.getName() + - " where " + Personne.PROPERTY_NAME + "=:pax", "pax", "nobody"); - Assert.assertNull(none); - } - - @Test(expected = TopiaException.class) - public void testFindUniqueOutOfBounds() throws TopiaException { - Assert.assertEquals(3, personneDAO.count()); - - String query = "from " + Personne.class.getName() + - " where " + Personne.PROPERTY_GENDER + "=:g"; - - Object female = jpaSupport.findUnique(query, "g", Gender.FEMALE); - Assert.assertNotNull(female); - } - -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/EntityStateTest.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/EntityStateTest.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/EntityStateTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,96 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.topia.framework; - -import org.junit.Assert; -import org.junit.Test; - -/** - * EntityStateTest.java - * <p/> - * Created: 22 nov. 06 12:15:11 - * - * @author poussin <poussin@codelutin.com> - * @version $Revision$ - * <p/> - * Last update: $Date$ - * by : $Author$ - */ -public class EntityStateTest { - - /** - * Test les changements d'etat de {@link EntityState}. - * - * @throws Exception - */ - @Test - public void testState() throws Exception { - EntityState state = new EntityState(); - - state.addLoad(); - Assert.assertTrue(state.isLoad()); - Assert.assertFalse(state.isRead()); - Assert.assertFalse(state.isCreate()); - Assert.assertFalse(state.isUpdate()); - Assert.assertFalse(state.isDelete()); - - state.addRead(); - Assert.assertTrue(state.isLoad()); - Assert.assertTrue(state.isRead()); - Assert.assertFalse(state.isCreate()); - Assert.assertFalse(state.isUpdate()); - Assert.assertFalse(state.isDelete()); - - //state.addRead(); - state.addCreate(); - Assert.assertTrue(state.isLoad()); - Assert.assertTrue(state.isRead()); - Assert.assertTrue(state.isCreate()); - Assert.assertFalse(state.isUpdate()); - Assert.assertFalse(state.isDelete()); - - state.addUpdate(); - Assert.assertTrue(state.isLoad()); - Assert.assertTrue(state.isRead()); - Assert.assertTrue(state.isCreate()); - Assert.assertTrue(state.isUpdate()); - Assert.assertFalse(state.isDelete()); - - state.addDelete(); - Assert.assertTrue(state.isLoad()); - Assert.assertTrue(state.isRead()); - Assert.assertTrue(state.isCreate()); - Assert.assertTrue(state.isUpdate()); - Assert.assertTrue(state.isDelete()); - - state = new EntityState(); - state.addDelete(); - Assert.assertFalse(state.isRead()); - Assert.assertFalse(state.isCreate()); - Assert.assertFalse(state.isUpdate()); - Assert.assertTrue(state.isDelete()); - } -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaConnectionProviderHardCoded.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaConnectionProviderHardCoded.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaConnectionProviderHardCoded.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,210 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2011 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.topia.framework; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.Map; -import java.util.Properties; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.hibernate.HibernateException; -import org.hibernate.cfg.Environment; -import org.hibernate.internal.util.ReflectHelper; -import org.hibernate.internal.util.config.ConfigurationHelper; -import org.hibernate.service.jdbc.connections.internal.ConnectionProviderInitiator; -import org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl; - -/** - * Customized connection provider. - * - * @author tchemit <chemit@codelutin.com> - * @since 2.5.3 - */ -public class TopiaConnectionProviderHardCoded extends DriverManagerConnectionProviderImpl { - - private String url; - - private Properties connectionProps; - - private Integer isolation; - - private final ArrayList pool = new ArrayList(); - - private int poolSize; - - private int checkedOut = 0; - - private boolean autocommit; - - /** Logger. */ - private static final Log log = - LogFactory.getLog(TopiaConnectionProviderHardCoded.class); - - @Override - public void configure(Map configurationValues) throws HibernateException { - String driverClass = (String)configurationValues.get(Environment.DRIVER); - - poolSize = ConfigurationHelper.getInt(Environment.POOL_SIZE, configurationValues, 20); //default pool size 20 - log.info("Using Hibernate built-in connection pool (not for production use!)"); - log.info("Hibernate connection pool size: " + poolSize); - - autocommit = ConfigurationHelper.getBoolean(Environment.AUTOCOMMIT, configurationValues); - log.info("autocommit mode: " + autocommit); - - isolation = ConfigurationHelper.getInteger(Environment.ISOLATION, configurationValues); - if (isolation != null) - log.info("JDBC isolation level: " + Environment.isolationLevelToString(isolation)); - - if (driverClass == null) { - log.warn("no JDBC Driver class was specified by property " + Environment.DRIVER); - } else { - try { - // trying via forName() first to be as close to DriverManager's semantics - Class.forName(driverClass); - } catch (ClassNotFoundException cnfe) { - try { - ReflectHelper.classForName(driverClass); - } catch (ClassNotFoundException e) { - String msg = "JDBC Driver class not found: " + driverClass; - log.error(msg, e); - throw new HibernateException(msg, e); - } - } - } - - // use a dummy directory to make sure only the connection provider knows - // the real directory where db is and then make sure hibernate always - // use the connection provider... - String directory = - (String)configurationValues.get(TopiaConnectionProviderTest.TEST_URL); - - url = directory; -// url = props.getProperty(Environment.URL); - -// if (url == null) { -// String msg = "JDBC URL was not specified by property " + Environment.URL; -// log.error(msg); -// throw new HibernateException(msg); -// } - - connectionProps = ConnectionProviderInitiator.getConnectionProperties(configurationValues); - - log.info("using driver: " + driverClass + " at URL: " + url); - // if debug level is enabled, then log the password, otherwise mask it - if (log.isDebugEnabled()) { - log.info("connection properties: " + connectionProps); - } else if (log.isInfoEnabled()) { - log.info("connection properties: " + ConfigurationHelper.maskOut(connectionProps, "password")); - } - } - - @Override - public Connection getConnection() throws SQLException { - if (log.isTraceEnabled()) - log.trace("total checked-out connections: " + checkedOut); - - synchronized (pool) { - if (!pool.isEmpty()) { - int last = pool.size() - 1; - if (log.isTraceEnabled()) { - log.trace("using pooled JDBC connection, pool size: " + last); - } - checkedOut++; - Connection pooled = (Connection) pool.remove(last); - if (isolation != null) - pooled.setTransactionIsolation(isolation.intValue()); - if (pooled.getAutoCommit() != autocommit) - pooled.setAutoCommit(autocommit); - return pooled; - } - } - - log.debug("opening new JDBC connection"); - Connection conn = DriverManager.getConnection(url, connectionProps); - if (isolation != null) conn.setTransactionIsolation(isolation); - if (conn.getAutoCommit() != autocommit) conn.setAutoCommit(autocommit); - - if (log.isDebugEnabled()) { - log.debug("created connection to: " + url + ", Isolation Level: " + conn.getTransactionIsolation()); - } -// if ( log.isTraceEnabled() ) - checkedOut++; - - return conn; - } - - @Override - public void closeConnection(Connection conn) throws SQLException { -// if ( log.isDebugEnabled() ) - checkedOut--; - - synchronized (pool) { - int currentSize = pool.size(); - if (currentSize < poolSize) { - if (log.isTraceEnabled()) { - log.trace("returning connection to pool, pool size: " + (currentSize + 1)); - } - pool.add(conn); - return; - } - } - - log.debug("closing JDBC connection"); - - conn.close(); - } - - @Override - protected void finalize() throws Throwable { - super.finalize(); - close(); - } - - public void close() { - - log.info("cleaning up connection pool: " + url); - - Iterator iter = pool.iterator(); - while (iter.hasNext()) { - try { - ((Connection) iter.next()).close(); - } catch (SQLException sqle) { - log.warn("problem closing pooled connection", sqle); - } - } - pool.clear(); - - } - - @Override - public boolean supportsAggressiveRelease() { - return false; - } -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaConnectionProviderTest.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaConnectionProviderTest.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaConnectionProviderTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,141 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2011 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.topia.framework; - -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.nuiton.topia.TopiaContextFactory; -import org.nuiton.topia.TopiaDatabase; -import org.nuiton.topia.TopiaException; -import org.nuiton.topia.TopiaTestDAOHelper; -import org.nuiton.topia.TopiaTestTopiaPersistenceContext; -import org.nuiton.topia.test.entities.Person; -import org.nuiton.topia.test.entities.PersonDAO; -import org.nuiton.topia.test.entities.PersonTopiaDao; -import org.nuiton.topiatest.Personne; - -import java.io.File; -import java.util.Locale; -import java.util.Properties; - -import static org.junit.Assert.assertNotNull; - -/** - * To test the {@link TopiaConnectionProvider} and make sure all connections - * are done from here... - * - * @author tchemit <chemit@codelutin.com> - * @since 2.5.3 - */ -public class TopiaConnectionProviderTest { - -// private static final Log log = -// LogFactory.getLog(TopiaConnectionProviderTest.class); - - public static final String TEST_URL = "testURL"; - - @Rule - public final TopiaDatabase db = - new TopiaDatabase("/TopiaConnectionProviderHardcoded.properties") { - - @Override - protected void onDbConfigurationCreate(Properties configuration, - File testdir, - String dbPath) { - - Assert.assertFalse(testdir.exists()); - - String dbPathFake = new File(testdir, "fake" + File.separator + "db").getAbsolutePath(); - - Assert.assertFalse(new File(dbPathFake).getParentFile().exists()); - - configuration.setProperty("dbPath", dbPath); - configuration.setProperty("dbPathFake", dbPathFake); - - // give the path where connection provider will create db - configuration.setProperty(TEST_URL, - "jdbc:h2:file:" + dbPath); - - // give a fake db path (we will make sure it is never create after hibernate usage). - configuration.setProperty(TopiaContextFactory.CONFIG_URL, - "jdbc:h2:file:" + dbPathFake); - } - }; - - @Test - public void testWithHardcoded() throws Exception { - -// Properties dbProperties = TestHelper.loadHibernateConfiguration( -// "/TopiaConnectionProviderHardcoded.properties"); -// -// File directory = new File(TestHelper.getDbName(testBasedir, "testWithHardcoded")); - - String dbPath = (String) db.getDbConfiguration().get("dbPath"); - String dbPathFake = (String) db.getDbConfiguration().get("dbPathFake"); - -// new File(directory, "real" + File.separator + "db").getAbsolutePath(); -// Assert.assertFalse(new File(dbPath).getParentFile().exists()); - -// String dbPathFake = new File(directory, "fake" + File.separator + "db").getAbsolutePath(); - -// Assert.assertFalse(new File(dbPathFake).getParentFile().exists()); - -// // give the path where connection provider will create db -// dbProperties.setProperty(TEST_URL, "jdbc:h2:file:" + dbPath); -// -// // give a fake db path (we will make sure it is never create after hibernate usage). -// dbProperties.setProperty(Environment.URL, "jdbc:h2:file:" + dbPathFake); -// -// root = TopiaContextFactory.getContext(dbProperties); - - Locale.setDefault(Locale.FRANCE); - - doStuffOnDb(); - - // the db file must have been created - Assert.assertTrue(new File(dbPath).getParentFile().exists()); - - // make sure the fake db path was never used - Assert.assertFalse(new File(dbPathFake).getParentFile().exists()); - } - - private void doStuffOnDb() throws TopiaException { - TopiaTestTopiaPersistenceContext transaction = db.beginTransaction(); - - try { - PersonDAO dao = TopiaTestDAOHelper.getPersonDAO(transaction); - - Person personne = dao.create(Personne.PROPERTY_NAME, "Jack Bauer"); - transaction.commitTransaction(); - String idPersonne = personne.getTopiaId(); - assertNotNull(idPersonne); - - transaction.commitTransaction(); - } finally { - transaction.closeContext(); - } - } -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaContextImplTest.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaContextImplTest.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaContextImplTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,549 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.topia.framework; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.h2.Driver; -import org.hibernate.cfg.Configuration; -import org.hibernate.mapping.PersistentClass; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.nuiton.topia.TopiaContextFactory; -import org.nuiton.topia.TopiaDatabase; -import org.nuiton.topia.TopiaNotFoundException; -import org.nuiton.topiatest.persistence.Entity1; -import org.nuiton.topiatest.persistence.Entity1Impl; -import org.nuiton.topiatest.service.FakeService; -import org.nuiton.topiatest.service.TestService; - -import java.io.File; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -/** - * Created: 10 mai 2010 - * - * @author fdesbois <fdesbois@codelutin.com> - * @version $Id$ - */ -public class TopiaContextImplTest { - - private static final Log log = - LogFactory.getLog(TopiaContextImplTest.class); - - protected Properties properties = new Properties(); - - static File testBasedir; - - @BeforeClass - public static void setUpClass() throws Exception { - - testBasedir = TopiaDatabase.getTestSpecificDirectory(TopiaContextImplTest.class, "dummy"); - } - - @Before - public void setUp() throws Exception { - properties.clear(); - } - - @After - public void tearDown() throws Exception { - } - - @Test - public void testLoadServices() throws Exception { - if (log.isDebugEnabled()) { - log.debug("## testLoadServices"); - } - - /** PREPARE DATA **/ - properties.setProperty("topia.service.test", - TestService.class.getName()); - - AbstractTopiaContext context = new AbstractTopiaContext(); - - /** EXEC METHOD **/ - if (log.isInfoEnabled()) { - log.info("test 1 : load a simple TestService from properties"); - } - Map<String, TopiaService> results = context.loadServices(properties); - Assert.assertEquals(1, results.size()); - Assert.assertTrue(results.containsKey("test")); - TopiaService service = results.get("test"); - Assert.assertEquals(TestService.class, service.getClass()); - - if (log.isInfoEnabled()) { - log.info("test 2 : load with wrong key : will display a WARN"); - } - properties.clear(); - - properties.setProperty("topia.service.fake", - TestService.class.getName()); - - results = context.loadServices(properties); - Assert.assertEquals(0, results.size()); - Assert.assertFalse(results.containsKey("fake")); - - if (log.isInfoEnabled()) { - log.info("test 3 : load with fake service name : will display an ERROR"); - } - properties.clear(); - - properties.setProperty("topia.service.test", "FAKE"); - - results = context.loadServices(properties); - Assert.assertEquals(0, results.size()); - Assert.assertFalse(results.containsKey("test")); - } - - @Test - public void testGetServices() throws Exception { - if (log.isDebugEnabled()) { - log.debug("## testGetServices"); - } - - /** PREPARE DATA **/ - properties.setProperty("topia.service.test", - TestService.class.getName()); - - // Calling the constructor with properties will load the services - AbstractTopiaContext context = new AbstractTopiaContext(properties); - - // Instantiate a child context and set its parent - AbstractTopiaContext child = new AbstractTopiaContext(context); - - /** EXEC METHOD **/ - if (log.isInfoEnabled()) { - log.info("test 1 : with child context"); - } - Map<String, TopiaService> test1 = child.getServices(); - Assert.assertEquals(1, test1.size()); - Assert.assertTrue(test1.containsKey("test")); - - if (log.isInfoEnabled()) { - log.info("test 2 : test serviceEnabled method"); - } - boolean test2 = child.serviceEnabled("test"); - Assert.assertTrue(test2); - - if (log.isInfoEnabled()) { - log.info("test 3 : test getService method"); - } - TopiaService test3 = child.getService("test"); - Assert.assertEquals(TestService.class, test3.getClass()); - - if (log.isInfoEnabled()) { - log.info("test 4 : test serviceEnabled from class TestService"); - } - boolean test4 = child.serviceEnabled(TestService.class); - Assert.assertTrue(test4); - - if (log.isInfoEnabled()) { - log.info("test 5 : test getService from class TestService"); - } - TestService test5 = child.getService(TestService.class); - Assert.assertNotNull(test5); - - if (log.isInfoEnabled()) { - log.info("test 6 : test serviceEnabled error with class FakeService"); - } - // FakeService doesn't contains property SERVICE_NAME used by - // serviceEnabled method - // Even it's properly loaded the serviceEnabled method will return false - properties.clear(); - properties.setProperty("topia.service.fake", - FakeService.class.getName()); - AbstractTopiaContext otherContext = new AbstractTopiaContext(properties); - - boolean test6 = otherContext.serviceEnabled(FakeService.class); - Assert.assertFalse(test6); - - if (log.isInfoEnabled()) { - log.info("test 7 : test getService with error TopiaNotFoundException" + - " : service not loaded"); - } - // TestService is not loaded in otherContext - try { - TestService test7 = otherContext.getService(TestService.class); - Assert.fail(); - } catch (TopiaNotFoundException eee) { - //log.error(eee.getClass().getSimpleName() + " : " + eee.getMessage()); - //Assert.assertEquals(TopiaNotFoundException.class, eee.getClass()); - } catch (Exception e) { - Assert.fail(); - } - } - - @Test - public void testContextHierarchy() throws Exception { - if (log.isDebugEnabled()) { - log.debug("## testContextHierarchy"); - } - - /** PREPARE DATA **/ - AbstractTopiaContext context = new AbstractTopiaContext(properties); - - /** EXEC METHODS **/ - if (log.isInfoEnabled()) { - log.info("test 1 : constructor with parent context"); - } - AbstractTopiaContext test1 = new AbstractTopiaContext(context); - Assert.assertEquals(context, test1.parentContext); - - if (log.isInfoEnabled()) { - log.info("test 2 : addChildContext"); - } - AbstractTopiaContext test2 = new AbstractTopiaContext(properties); - AbstractTopiaContext child2 = new AbstractTopiaContext(); - test2.addChildContext(child2); - Assert.assertEquals(1, test2.childContext.size()); - - if (log.isInfoEnabled()) { - log.info("test 3 : removeChildContext"); - } - AbstractTopiaContext test3 = new AbstractTopiaContext(properties); - AbstractTopiaContext child3 = new AbstractTopiaContext(test3); - test3.childContext.add(child3); - test3.removeChildContext(child3); - Assert.assertEquals(0, test3.childContext.size()); - - // No remove if context is closed - test3.childContext.add(child3); - test3.closed = true; - test3.removeChildContext(child3); - Assert.assertEquals(1, test3.childContext.size()); - - if (log.isInfoEnabled()) { - log.info("test 4 : getRootContext"); - } - TopiaContextImplementor test4 = child3.getRootContext(); - Assert.assertEquals(test3, test4); - - // Note : existing test is already done for concurrency problem on - // getChildContext(). Go to : http://www.nuiton.org/repositories/browse/sandbox/testTopiaPostgresError/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.commitTransaction(); -// -// daoSource = TopiaTestDAOHelper.getPersonDAO(txSource); -// -// personSource = daoSource.findByTopiaId(personSource.getTopiaId()); -// Assert.assertNotNull(personSource); -// -// petSource = petDAOSource.findByTopiaId(petSource.getTopiaId()); -// Assert.assertNotNull(petSource); -// Assert.assertEquals(1, personSource.sizePet()); -// Assert.assertEquals(petSource, personSource.getPet().iterator().next()); -// -// txTarget = contextTarget.beginTransaction(); -// -// txSource.replicateEntity(txTarget, petSource); -// txSource.replicateEntity(txTarget, personSource); -// -// txTarget.commitTransaction(); -// -// daoTarget = TopiaTestDAOHelper.getPersonDAO(txTarget); -// petDAOTarget = TopiaTestDAOHelper.getPetDAO(txTarget); -// -// personTarget = daoTarget.findByTopiaId(personSource.getTopiaId()); -// Assert.assertNotNull(personTarget); -// Assert.assertEquals(personSource, personTarget); -// Assert.assertEquals(1, personTarget.sizePet()); -// -// petTarget = petDAOTarget.findByTopiaId(petSource.getTopiaId()); -// Assert.assertNotNull(petTarget); -// Assert.assertEquals(petSource, petTarget); -// -// Assert.assertEquals(petTarget, personTarget.getPet().iterator().next()); -// -// -// } finally { -// closeDb(contextSource); -// closeDb(contextTarget); -// } -// -// } -// -// protected static void closeDb(TopiaContext contextSource) { -// if (contextSource != null && !contextSource.isClosed()) -// try { -// contextSource.clear(false); -// } catch (TopiaException e) { -// if (log.isErrorEnabled()) { -// log.error("Could not close db " + contextSource, e); -// } -// } -// } - - -// -// @Test -// public void testGetHibernateConfiguration() throws Exception { -// } -// -// @Test -// public void testGetDAO() throws Exception { -// } -// -// @Test -// public void testBeginTransaction() throws Exception { -// } -// -// @Test -// public void testCommitTransaction() throws Exception { -// } -// -// @Test -// public void testRollbackTransaction() throws Exception { -// } -// -// @Test -// public void testCloseContext() throws Exception { -// } -// -// @Test -// public void testIsClosed() throws Exception { -// } -// -// @Test -// public void testFindByTopiaId() throws Exception { -// } -// -// @Test -// public void testFind() throws Exception { -// } -// -// @Test -// public void testFind2() throws Exception { -// } -// -// @Test -// public void testExecute() throws Exception { -// } -// -// @Test -// public void testAdd() throws Exception { -// } -// -// @Test -// public void testImportXML() throws Exception { -// } -// -// @Test -// public void testExportXML() throws Exception { -// } -// -// -// @Test -// public void testReplicateEntity() throws Exception { -// } -// -// @Test -// public void testReplicateEntities() throws Exception { -// } -// -// @Test -// public void testGetFiresSupport() throws Exception { -// } -// -// @Test -// public void testBackup() throws Exception { -// } -// -// @Test -// public void testRestore() throws Exception { -// } -// -// @Test -// public void testClear() throws Exception { -// } -// -// @Test -// public void testGetPersistenceClasses() throws Exception { -// } -// -// @Test -// public void testIsSchemaExist() throws Exception { -// } -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaContextReplicateTest.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaContextReplicateTest.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaContextReplicateTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,155 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2012 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.topia.framework; - -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.nuiton.topia.TopiaContextFactory; -import org.nuiton.topia.TopiaDatabase; -import org.nuiton.topia.TopiaTestDAOHelper; -import org.nuiton.topia.TopiaTestTopiaPersistenceContext; -import org.nuiton.topia.test.entities.Person; -import org.nuiton.topia.test.entities.PersonDAO; -import org.nuiton.topia.test.entities.Pet; -import org.nuiton.topia.test.entities.PetDAO; - -import java.io.File; -import java.util.Properties; - -/** - * To test replication sugin TopiaContext. - * - * @author tchemit <chemit@codelutin.com> - * @since 2.6.8 - */ -public class TopiaContextReplicateTest { - - @Rule - public final TopiaDatabase dbSource = - new TopiaDatabase() { - - @Override - protected void onDbConfigurationCreate(Properties configuration, File testDir, String dbPath) { - configuration.setProperty( - TopiaContextFactory.CONFIG_URL, "jdbc:h2:file:" + dbPath + "-source"); - - } - }; - - @Rule - public final TopiaDatabase dbTarget = - new TopiaDatabase() { - - @Override - protected void onDbConfigurationCreate(Properties configuration, File testDir, String dbPath) { - configuration.setProperty( - TopiaContextFactory.CONFIG_URL, "jdbc:h2:file:" + dbPath + "-target"); - - } - }; - - @Test - public void replicateEntity() throws Exception { -// -// Properties configSource = TestHelper.initTopiaContextConfiguration( -// testBasedir, -// "/TopiaContextImpl.properties", -// "replicateSource"); -// -// Properties configTarget = TestHelper.initTopiaContextConfiguration( -// testBasedir, -// "/TopiaContextImpl.properties", -// "replicateTarget"); -// - - -// try { -// contextSource = TopiaContextFactory.getContext(configSource); -// contextTarget = TopiaContextFactory.getContext(configTarget); - - TopiaTestTopiaPersistenceContext txSource; - TopiaTestTopiaPersistenceContext txTarget; - PersonDAO daoSource, daoTarget; - PetDAO petDAOSource, petDAOTarget; - Person personSource, personTarget; - Pet petSource, petTarget; - - txSource = dbSource.beginTransaction(); - daoSource = TopiaTestDAOHelper.getPersonDAO(txSource); - petDAOSource = TopiaTestDAOHelper.getPetDAO(txSource); - - personSource = daoSource.create(Person.PROPERTY_FIRSTNAME, " firstName", - Person.PROPERTY_NAME, " name" - ); - - petSource = petDAOSource.create(Pet.PROPERTY_NAME, "name", - Pet.PROPERTY_TYPE, "type", - Pet.PROPERTY_PERSON, personSource - ); - - personSource.addPet(petSource); - - txSource.commitTransaction(); - - daoSource = TopiaTestDAOHelper.getPersonDAO(txSource); - - personSource = daoSource.findByTopiaId(personSource.getTopiaId()); - Assert.assertNotNull(personSource); - - petSource = petDAOSource.findByTopiaId(petSource.getTopiaId()); - Assert.assertNotNull(petSource); - Assert.assertEquals(1, personSource.sizePet()); - Assert.assertEquals(petSource, personSource.getPet().iterator().next()); - - txTarget = dbTarget.beginTransaction(); - - txSource.replicateEntity(txTarget, petSource); - txSource.replicateEntity(txTarget, personSource); - - txTarget.commitTransaction(); - - daoTarget = TopiaTestDAOHelper.getPersonDAO(txTarget); - petDAOTarget = TopiaTestDAOHelper.getPetDAO(txTarget); - - personTarget = daoTarget.findByTopiaId(personSource.getTopiaId()); - Assert.assertNotNull(personTarget); - Assert.assertEquals(personSource, personTarget); - Assert.assertEquals(1, personTarget.sizePet()); - - petTarget = petDAOTarget.findByTopiaId(petSource.getTopiaId()); - Assert.assertNotNull(petTarget); - Assert.assertEquals(petSource, petTarget); - - Assert.assertEquals(petTarget, personTarget.getPet().iterator().next()); - - -// } finally { -// closeDb(contextSource); -// closeDb(contextTarget); -// } - - } -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaUtilTest.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaUtilTest.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaUtilTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,113 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.topia.framework; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.hibernate.cfg.Configuration; -import org.junit.Rule; -import org.junit.Test; -import org.nuiton.topia.TopiaDatabase; -import org.nuiton.topia.test.entities.PersonImpl; -import org.nuiton.topiatest.Personne; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -/** - * Test pour les methodes de {@link TopiaUtil}. - * - * @author tchemit <chemit@codelutin.com> - * @version $Revision$ - * <p/> - * Last update: $Date$ - * by : $Author$ - */ -public class TopiaUtilTest { - - protected static final String PERSON_ID = "org.nuiton.topiatest.Personne#1226701039001#0.6502325993664224"; - - protected static final String PERSON_ID2 = "org.nuiton.topiatest.Personne#1226701039001#0.6502325993664999"; - - @Rule - public final TopiaDatabase db = new TopiaDatabase(); - - @Test - public void testGetTopiaIdPattern() throws Exception { - String expected; - String actual; - - expected = "org\\.nuiton\\.topiatest\\.Personne#(?:\\d+?)#(?:\\d+)\\.(?:\\d+)"; - actual = TopiaUtil.getTopiaIdPattern(Personne.class); - assertEquals(expected, actual); - } - - @Test - public void testGetTopiaPattern() throws Exception { - String expected; - Pattern pattern; - - expected = "(\\d+)-(org\\.nuiton\\.topiatest\\.Personne#(?:\\d+?)#(?:\\d+)\\.(?:\\d+))-(org\\.nuiton\\.topiatest\\.Personne#(?:\\d+?)#(?:\\d+)\\.(?:\\d+))(.*)"; - pattern = TopiaUtil.getTopiaPattern("(\\d+)-%1$s-%1$s(.*)", Personne.class); - assertEquals(expected, pattern.toString()); - - String expression = 123 + "-" + PERSON_ID + "-" + PERSON_ID2 + "-afterall"; - - Matcher matcher = pattern.matcher(expression); - - assertTrue(matcher.matches()); - - assertTrue(matcher.matches()); - assertEquals(4, matcher.groupCount()); - assertEquals("123", matcher.group(1)); - assertEquals(PERSON_ID, matcher.group(2)); - assertEquals(PERSON_ID2, matcher.group(3)); - assertEquals("-afterall", matcher.group(4)); - } - - @Test(expected = IllegalArgumentException.class) - public void testIsSchemaExistFailed() throws Exception { - TopiaUtil.isSchemaExist(db.getHibernateCfg(), "fake"); - } - - @Test - public void testIsSchemaExist() throws Exception { - - String personClassName = PersonImpl.class.getName(); - Configuration hibernateCfg = db.getHibernateCfg(); - - // First, test before DB is created, the table should not exist - assertFalse(TopiaUtil.isSchemaExist(hibernateCfg, personClassName)); - - // Create schema - db.getApplicationContext().createSchema(); - - // Now table should exist - assertTrue(TopiaUtil.isSchemaExist(hibernateCfg, personClassName)); - } -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/TopiaGeneratorUtilTest.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/TopiaGeneratorUtilTest.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/TopiaGeneratorUtilTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,64 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.topia.generator; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -/** @author tchemit <chemit@codelutin.com> */ -public class TopiaGeneratorUtilTest { - - @Deprecated - @Test - public void testConvertVariableNameToConstantName() { - - String variableName = "abc"; - String expResult = "ABC"; - String result = TopiaGeneratorUtil.convertVariableNameToConstantName(variableName); - assertEquals(expResult, result); - - variableName = "ABC"; - expResult = "ABC"; - result = TopiaGeneratorUtil.convertVariableNameToConstantName(variableName); - assertEquals(expResult, result); - - variableName = "abC"; - expResult = "AB_C"; - result = TopiaGeneratorUtil.convertVariableNameToConstantName(variableName); - assertEquals(expResult, result); - - variableName = "AbC"; - expResult = "AB_C"; - result = TopiaGeneratorUtil.convertVariableNameToConstantName(variableName); - assertEquals(expResult, result); - - variableName = "AbC"; - expResult = "AB_C"; - result = TopiaGeneratorUtil.convertVariableNameToConstantName(variableName); - assertEquals(expResult, result); - } -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/TopiaModelPropertiesProviderTest.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/TopiaModelPropertiesProviderTest.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/TopiaModelPropertiesProviderTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,80 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.topia.generator; - -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.nuiton.eugene.ModelPropertiesUtil; -import org.nuiton.eugene.models.object.ObjectModelClassifier; -import org.nuiton.eugene.models.object.ObjectModelOperation; - -/** - * To test {@link TopiaGeneratorUtil.TopiaModelPropertiesProvider}. - * - * @author tchemit <chemit@codelutin.com> - * @since 2.3 - */ -public class TopiaModelPropertiesProviderTest { - - protected ModelPropertiesUtil.ModelPropertiesProvider provider; - - @Before - public void setUp() throws Exception { - provider = new TopiaGeneratorUtil.TopiaModelPropertiesProvider(); - provider.init(); - } - - @Test - public void testGetTagValueTarget() throws Exception { - testTagValue(TopiaTagValues.TAG_PERSISTENCE_TYPE, ObjectModelClassifier.class); - //TODO Finish with other tag values... - } - - @Test - public void testGetStereotypeTarget() throws Exception { - - testStereotype(TopiaStereoTypes.STEREOTYPE_DAO, ObjectModelClassifier.class, ObjectModelOperation.class); - //TODO Finish with other stereotypes... - } - - @Test - public void testGetStore() throws Exception { - } - - protected void testStereotype(String name, Class<?>... expected) { - Class<?>[] classes = provider.getStereotypeTarget(name); - Assert.assertNotNull("Could not find target for " + name, classes); - Assert.assertEquals("Should have " + expected.length + " targets for " + name + " but had " + classes.length, classes.length, expected.length); - Assert.assertArrayEquals(expected, classes); - } - - protected void testTagValue(String name, Class<?>... expected) { - Class<?>[] classes = provider.getTagValueTarget(name); - Assert.assertNotNull("Could not find target for " + name, classes); - Assert.assertEquals("Should have " + expected.length + " targets for " + name + " but had " + classes.length, classes.length, expected.length); - Assert.assertArrayEquals(expected, classes); - } -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/TopiaTestCase.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/TopiaTestCase.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/TopiaTestCase.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,170 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.topia.generator; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.nuiton.topia.TopiaDatabase; -import org.nuiton.topia.TopiaException; -import org.nuiton.topia.TopiaTestDAOHelper; -import org.nuiton.topia.TopiaTestTopiaPersistenceContext; -import org.nuiton.topiatest.Company; -import org.nuiton.topiatest.CompanyDAO; -import org.nuiton.topiatest.Department; -import org.nuiton.topiatest.DepartmentDAO; - -/** - * TopiaTestCase. - * - * @author chatellier - * @version $Revision$ - * <p/> - * Last update : $Date$ - * By : $Author$ - */ -public class TopiaTestCase { - - /** Logger */ - private final static Log log = LogFactory.getLog(TopiaTestCase.class); - - @Rule - public final TopiaDatabase db = new TopiaDatabase(); - -// /** Proprietes */ -// protected static Properties config; -// -// /** TopiaContext */ -// protected static TopiaContext context; - -// /** -// * Init les proprietes de connection a la base -// * -// * @throws IOException for any IO error while getting configuration. -// */ -// @BeforeClass -// public static void init() throws IOException { -// -// File testBasedir = TestHelper.getTestBasedir(TopiaTestCase.class); -// -// config = TestHelper.initTopiaContextConfiguration( -// testBasedir, -// "/TopiaContextImpl.properties", -// "TopiaTestCaseDb"); -//// config = new Properties(); -//// config.setProperty("topia.persistence.classes", TopiaTestDAOHelper.getImplementationClassesAsString()); -//// -//// config.setProperty(Environment.USER, "sa"); -//// config.setProperty(Environment.PASS, ""); -//// config.setProperty(Environment.CURRENT_SESSION_CONTEXT_CLASS, "thread"); -//// config.setProperty(Environment.DIALECT, "org.hibernate.dialect.H2Dialect"); -//// config.setProperty(Environment.DRIVER, "org.h2.Driver"); -//// config.setProperty(Environment.URL, "jdbc:h2:file:" + testBasedir + "/db/data_" + System.currentTimeMillis()); -// } -// -// @AfterClass -// public static void after() throws TopiaException { -// // destroy database -// context.clear(false); -// } - -// /** Create base with schema created. */ -// @Before -// public void setUp() { -// -// if (log.isDebugEnabled()) { -// log.debug("Junit beforeTest"); -// } -// -// try { -// context = TopiaContextFactory.getContext(config); -// -// try { -// context.createSchema(); -// } catch (TopiaException e) { -// log.error("Erreur à la creation du schema", e); -// } -// } catch (TopiaNotFoundException e) { -// log.error("Erreur à la creation du topia context", e); -// } -// } - - @Test - public void testCompositeAssociations() throws TopiaException { - if (log.isDebugEnabled()) { - log.debug("Junit Test testCompositeAssociations"); - } - -// try { - TopiaTestTopiaPersistenceContext newContext = db.beginTransaction(); - - CompanyDAO companyDAO = newContext.getCompanyDao(); - DepartmentDAO departmentDAO = newContext.getDepartmentDao(); - - Company company = companyDAO.create(); - company.setName("Ma société"); - - - Department dep1 = departmentDAO.create(); - dep1.setName("Departement 1"); - Department dep2 = departmentDAO.create(); - dep2.setName("Departement 2"); - Department dep3 = departmentDAO.create(); - dep3.setName("Departement 3"); - Department dep4 = departmentDAO.create(); - dep4.setName("Departement 7"); - - departmentDAO.update(dep1); - departmentDAO.update(dep2); - departmentDAO.update(dep3); - departmentDAO.update(dep4); - - company.addDepartment(dep1); - company.addDepartment(dep2); - company.addDepartment(dep3); - company.addDepartment(dep4); - - companyDAO.update(company); - newContext.commitTransaction(); - - newContext = db.beginTransaction(); - - companyDAO = TopiaTestDAOHelper.getCompanyDAO(newContext); - - company = companyDAO.findByTopiaId(company.getTopiaId()); - - Assert.assertEquals(company.getName(), "Ma société"); - Assert.assertEquals(company.getDepartment().size(), 4); - - newContext.commitTransaction(); -// newContext.closeContext(); -// } catch (TopiaException e) { -// log.error("Erreur pendant le test testCompositeAssociations", e); -// } - } -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/EntityVisitorExportXmlTest.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/EntityVisitorExportXmlTest.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/EntityVisitorExportXmlTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,131 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.topia.persistence; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.nuiton.topia.TopiaDatabase; -import org.nuiton.topia.TopiaException; -import org.nuiton.topia.TopiaTestTopiaPersistenceContext; -import org.nuiton.topiatest.Address; -import org.nuiton.topiatest.AddressTopiaDao; -import org.nuiton.topiatest.Company; -import org.nuiton.topiatest.CompanyTopiaDao; -import org.nuiton.topiatest.Department; -import org.nuiton.topiatest.DepartmentTopiaDao; -import org.nuiton.topiatest.Employe; -import org.nuiton.topiatest.EmployeTopiaDao; - -/** - * Test de visitor. - * - * @author chatellier - * @version $Revision$ - * <p/> - * Last update : $Date$ - * By : $Author$ - */ -public class EntityVisitorExportXmlTest { - - private static final Log log = - LogFactory.getLog(EntityVisitorExportXmlTest.class); - - @Rule - public final TopiaDatabase db = new TopiaDatabase(); - - /** - * Prepare test. - * <p/> - * Add all tests commons data - * - * @throws TopiaException if could not create datas - */ - @Before - public void setUp() throws TopiaException { - - TopiaTestTopiaPersistenceContext newContext = db.beginTransaction(); - try { - // company - CompanyTopiaDao companyDAO = newContext.getCompanyDao(); - Company clCompany = companyDAO.create(Company.PROPERTY_NAME, "CodeLutin"); - - // employe - EmployeTopiaDao employeDAO = newContext.getEmployeDao(); - Employe empl1 = employeDAO.create(Employe.PROPERTY_NAME, "boss", Employe.PROPERTY_SALARY, 30000); - - AddressTopiaDao adressDAO = newContext.getAddressDao(); - Address addr1 = adressDAO.create(Address.PROPERTY_CITY, "Nantes", Address.PROPERTY_ADRESS, "12 Avenue Jules Vernes"); - empl1.setAddress(addr1); - - Employe empl2 = employeDAO.create(Employe.PROPERTY_NAME, "boss2", Employe.PROPERTY_SALARY, 29000); - Address addr2 = adressDAO.create(Address.PROPERTY_CITY, "Nantes", Address.PROPERTY_ADRESS, "12 Avenue Jules Vernes"); - empl2.setAddress(addr2); - - // departement - DepartmentTopiaDao departmentDAO = newContext.getDepartmentDao(); - Department depComm = departmentDAO.create(Department.PROPERTY_NAME, "Commercial"); - depComm.setLeader(empl1); - - Department depDev = departmentDAO.create(Department.PROPERTY_NAME, "Dev"); - depDev.setLeader(empl2); - clCompany.addDepartment(depComm); - clCompany.addDepartment(depDev); - - newContext.commitTransaction(); - } finally { - - newContext.closeContext(); - } - } - - - /** - * Test l'export XML via un visiteur. - * <p/> - * Parcourt en profondeur. - * - * @throws TopiaException - */ - @Test - public void testExportXMLDepth() throws TopiaException { - - TopiaTestTopiaPersistenceContext context = db.beginTransaction(); - - CompanyTopiaDao companyDAO = context.getCompanyDao(); - Company clCompany = companyDAO.findByName("CodeLutin"); - - EntityVisitor delegateVisitor = new ExportXMLVisitor(); - EntityVisitor visitor = new DepthEntityVisitor(delegateVisitor); - clCompany.accept(visitor); - - if (log.isInfoEnabled()) { - log.info("Export XML = \n" + delegateVisitor.toString()); - } - } -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/ExportXMLVisitor.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/ExportXMLVisitor.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/ExportXMLVisitor.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,107 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.topia.persistence; - - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.Ignore; - -/** - * Visitor pour export xml. - * - * @author chatellier - * @version $Revision$ - * <p/> - * Last update : $Date$ - * By : $Author$ - */ -@Ignore -public class ExportXMLVisitor implements EntityVisitor { - - /** log. */ - private static Log log = LogFactory.getLog(ExportXMLVisitor.class); - - protected StringBuffer buffer; - - public ExportXMLVisitor() { - buffer = new StringBuffer(); - } - - @Override - public void start(TopiaEntity e) { - if (log.isDebugEnabled()) { - log.debug("start : " + e); - } - - buffer.append("<").append(e.getClass().getName()); - buffer.append(" topiaId=\"").append(e.getTopiaId()).append("\""); - buffer.append(" topiaCreateDate=\"").append(e.getTopiaCreateDate()).append("\""); - buffer.append(" topiaVersion=\"").append(e.getTopiaVersion()).append("\""); - buffer.append(">\n"); - } - - @Override - public void visit(TopiaEntity e, String name, Class<?> type, Object value) { - if (log.isDebugEnabled()) { - log.debug("visit : " + e); - } - - buffer.append("<").append(type.getName()).append(">").append(value).append("</").append(type.getName()).append(">\n"); - } - - @Override - public void visit(TopiaEntity e, String name, Class<?> collectionType, Class<?> type, - Object value) { - } - - @Override - public void visit(TopiaEntity e, String name, Class<?> collectionType, Class<?> type, int index, Object value) { - visit(e, name, type, value); - } - - @Override - public void end(TopiaEntity e) { - if (log.isDebugEnabled()) { - log.debug("end : " + e); - } - - buffer.append("</").append(e.getClass().getName()).append(">\n"); - } - - @Override - public String toString() { - String content = buffer.toString(); - return content; - } - - @Override - public void clear() { - // do nothing - } - - -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/HqlAndParametersBuilderTest.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/HqlAndParametersBuilderTest.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/HqlAndParametersBuilderTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,116 +0,0 @@ -package org.nuiton.topia.persistence; - -/* - * #%L - * ToPIA :: Persistence - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2013 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.Lists; -import org.junit.Assert; -import org.junit.Test; - -import java.util.Collection; - -public class HqlAndParametersBuilderTest { - - protected HqlAndParametersBuilder hqlAndParametersBuilder = - new HqlAndParametersBuilder(TopiaEntity.class); - - protected static final Collection<String> SOME_VALUES = - Lists.newArrayList("value1", "value2", "value3"); - - protected static final Collection<String> SOME_VALUES_WITH_NULL = - Lists.newArrayList("value1", "value2", null, "value3"); - - @Test - public void testFindAvailableHqlParameterName() { - - String availableHqlParameterName1 = hqlAndParametersBuilder.putHqlParameterWithAvailableName("survey.topiaId", "topiaId1"); - String availableHqlParameterName2 = hqlAndParametersBuilder.putHqlParameterWithAvailableName("survey.topiaId", "topiaId1"); - - Assert.assertNotEquals(availableHqlParameterName1, availableHqlParameterName2); - Assert.assertFalse(availableHqlParameterName1.contains(".")); - Assert.assertFalse(availableHqlParameterName2.contains(".")); - - } - - @Test - public void testEqualsNull() { - - hqlAndParametersBuilder.addEquals("myProp", null); - - String actualHql = hqlAndParametersBuilder.getHql(); - - Assert.assertFalse(actualHql.contains("myProp = null")); - Assert.assertTrue(actualHql.contains("myProp is null")); - - } - - @Test - public void testAddInWithNull() { - - hqlAndParametersBuilder.addIn("myProp", SOME_VALUES_WITH_NULL); - - String actualHql = hqlAndParametersBuilder.getHql(); - - Assert.assertTrue(actualHql.contains("myProp is null or topiaEntity_.myProp in (")); - Assert.assertEquals( - SOME_VALUES_WITH_NULL.size() - 1, // there should be as many argument as in collection minus 1 because null is removed - hqlAndParametersBuilder.getHqlParameters().size()); - - } - - @Test - public void testAddNotEqualsToValue() { - - hqlAndParametersBuilder.addNotEquals("myProp", "value"); - - String actualHql = hqlAndParametersBuilder.getHql(); - - Assert.assertTrue(actualHql.contains("myProp != ")); - Assert.assertFalse(actualHql.contains("myProp = ")); - - } - - @Test - public void testAddNotEqualsToNull() { - - hqlAndParametersBuilder.addNotEquals("myProp", null); - - String actualHql = hqlAndParametersBuilder.getHql(); - - Assert.assertTrue(actualHql.contains("myProp is not null")); - - } - - @Test - public void testAddNotInWithNull() { - - hqlAndParametersBuilder.addNotIn("myProp", SOME_VALUES_WITH_NULL); - - String actualHql = hqlAndParametersBuilder.getHql(); - - Assert.assertTrue(actualHql.contains("myProp is not null and ")); - - } - -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/NaturalIdTest.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/NaturalIdTest.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/NaturalIdTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,185 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.topia.persistence; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.hibernate.PropertyValueException; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.nuiton.topia.TopiaDatabase; -import org.nuiton.topia.TopiaException; -import org.nuiton.topia.TopiaTestDAOHelper; -import org.nuiton.topia.TopiaTestTopiaPersistenceContext; -import org.nuiton.topiatest.NaturalizedEntity; -import org.nuiton.topiatest.NaturalizedEntityDAO; - -/** - * NaturalIdTest - * <p/> - * Created: 18 févr. 2010 - * - * @author fdesbois - * @version $Revision$ - * <p/> - * Mise a jour: $Date$ - * par : $Author$ - */ -public class NaturalIdTest { - - private static final Log log = LogFactory.getLog(NaturalIdTest.class); - - @Rule - public final TopiaDatabase db = new TopiaDatabase(); - - @Test - public void testCreateSucessfull() throws Exception { - log.debug("Test naturalId : create succesfull"); - TopiaTestTopiaPersistenceContext persistenceContext = db.beginTransaction(); - - NaturalizedEntityDAO dao = - persistenceContext.getNaturalizedEntityDao(); - - // No exception will be thrown with the two properties - dao.createByNaturalId(5, "str"); - persistenceContext.commitTransaction(); - - // No exception will only the need property - dao.createByNotNull(3); - persistenceContext.commitTransaction(); - - // No exception will only the need property - dao.create(NaturalizedEntity.PROPERTY_NATURAL_ID_NOT_NULL, 3); - persistenceContext.commitTransaction(); - } - - @Test - public void testCreateFailed() throws Exception { - log.debug("Test naturalId : create failed"); - TopiaTestTopiaPersistenceContext persistenceContext = db.beginTransaction(); - - NaturalizedEntityDAO dao = - persistenceContext.getNaturalizedEntityDao(); - - // Exception will be throw - try { - dao.create(); - persistenceContext.commitTransaction(); - - // Note : this is possible to create an empty entity if the type - // is primitive like 'int' which have a default value of '0' - } catch (TopiaException eee) { - Assert.assertNotNull(eee.getCause()); - Assert.assertTrue(eee.getCause() instanceof PropertyValueException); - Assert.assertEquals("naturalIdNotNull", ((PropertyValueException)eee.getCause()).getPropertyName()); - } -// catch (PropertyValueException eee) { -// Assert.assertEquals("naturalIdNotNull", eee.getPropertyName()); -// } - } - - @Test - public void testUpdateFailed() throws Exception { - log.debug("Test naturalId : update failed"); - - TopiaTestTopiaPersistenceContext persistenceContext = db.beginTransaction(); - - NaturalizedEntityDAO dao = - persistenceContext.getNaturalizedEntityDao(); - - NaturalizedEntity entity = - dao.createByNaturalId(5, "str"); - persistenceContext.commitTransaction(); - - // Exception will be throw : not allowed to modify a naturalId property - try { - entity.setNaturalIdNotNull(8); - persistenceContext.commitTransaction(); - } catch (TopiaException eee) { - Assert.assertEquals("org.hibernate.HibernateException", - eee.getCause().getClass().getName()); - } - } - - @Test - public void testFindByNaturalId() throws Exception { - log.debug("Test naturalId : findByNaturalId"); - TopiaTestTopiaPersistenceContext persistenceContext = db.beginTransaction(); - - - NaturalizedEntityDAO dao = - persistenceContext.getNaturalizedEntityDao(); - - NaturalizedEntity entity = - dao.createByNaturalId(5, "str"); - persistenceContext.commitTransaction(); - - NaturalizedEntity result = dao.findByNaturalId(5, "str"); - - Assert.assertEquals(entity, result); - } - - @Test - public void testExistNaturalId() throws Exception { - log.debug("Test naturalId : existNaturalId"); - TopiaTestTopiaPersistenceContext persistenceContext = db.beginTransaction(); - - - NaturalizedEntityDAO dao = - persistenceContext.getNaturalizedEntityDao(); - - dao.createByNaturalId(5, "str"); - persistenceContext.commitTransaction(); - - boolean result = dao.existByNaturalId(5, "str"); - - Assert.assertTrue(result); - - // not find with only one correct property - result = dao.existByNaturalId(8, "str"); - - Assert.assertFalse(result); - } - - @Test - public void testNaturalIdAreGeneralized() throws Exception { - - // test that natural ids are generalized - String[] generalizedNaturalizedNaturalIds = TopiaTestDAOHelper.TopiaTestEntityEnum.GeneralizedNaturalizedEntity.getNaturalIds(); - String[] naturalizedNaturalIds = TopiaTestDAOHelper.TopiaTestEntityEnum.NaturalizedEntity.getNaturalIds(); - Assert.assertArrayEquals(generalizedNaturalizedNaturalIds, naturalizedNaturalIds); - } - - @Test - public void testNotNullsAreGeneralized() throws Exception { - - // test that not nulls are generalized - String[] generalizedNaturalizedNotNulls = TopiaTestDAOHelper.TopiaTestEntityEnum.GeneralizedNaturalizedEntity.getNotNulls(); - String[] naturalizedNotNulls = TopiaTestDAOHelper.TopiaTestEntityEnum.NaturalizedEntity.getNotNulls(); - Assert.assertArrayEquals(generalizedNaturalizedNotNulls, naturalizedNotNulls); - } -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/TopiaDAOTest.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/TopiaDAOTest.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/TopiaDAOTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,201 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin, Chatellier Eric - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.topia.persistence; - -import java.util.List; - -import org.hamcrest.CoreMatchers; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.nuiton.topia.TopiaDatabase; -import org.nuiton.topia.TopiaException; -import org.nuiton.topia.TopiaTestTopiaPersistenceContext; -import org.nuiton.topia.test.entities.Person; -import org.nuiton.topia.test.entities.PersonDAO; - -import com.google.common.collect.Lists; - -/** - * Test on {@link TopiaDAO}. - * <p/> - * Last update : $Date$ - * By : $Author$ - * - * @author chatellier - * @version $Revision$ - */ -public class TopiaDAOTest { - - @Rule - public final TopiaDatabase db = new TopiaDatabase(); - - protected TopiaTestTopiaPersistenceContext context; - - protected PersonDAO dao; - - @Before - public void setup() throws TopiaException { - - context = db.beginTransaction(); - dao = context.getPersonDao(); - } - - /** - * Test de creer une entité et de verifier qu'elle est - * présente dans la persistence au sein de la transaction. - * - * @throws Exception if any exception while test - */ - @Test - public void testCreateAndFindInTransaction() throws Exception { - - // appel 1 find all - createPerson("toto"); - List<Person> allPerson = dao.findAll(); - Assert.assertEquals(1, allPerson.size()); - context.commitTransaction(); - - // recherce la personne créée dans la même transaction - Person person2 = createPerson("titi"); - allPerson = dao.findAll(); - Assert.assertEquals(2, allPerson.size()); - Assert.assertThat(allPerson, CoreMatchers.hasItem(person2)); - - context.rollbackTransaction(); - - // meme test apres roolback - Person person3 = createPerson("tata"); - allPerson = dao.findAll(); - Assert.assertEquals(2, allPerson.size()); - Assert.assertThat(allPerson, CoreMatchers.hasItem(person3)); - - context.commitTransaction(); - } - - @Test - public void findAllLazyByQuery() throws TopiaException { - - Assert.assertEquals(dao.count(), 0); - - createPersons(101); - - Iterable<Person> allByLazy = dao.findAllLazyByQuery( - 100, - "FROM " + dao.getTopiaEntityEnum().getImplementationFQN() + " ORDER BY id"); - - List<Person> actual = Lists.newArrayList(); - - for (Person person : allByLazy) { - actual.add(person); - } - Assert.assertEquals(dao.count(), actual.size()); - - allByLazy = dao.findAllLazyByQuery( - 54, - "FROM " + dao.getTopiaEntityEnum().getImplementationFQN() + " ORDER BY id"); - - actual = Lists.newArrayList(); - - for (Person person : allByLazy) { - actual.add(person); - } - Assert.assertEquals(dao.count(), actual.size()); - - allByLazy = dao.findAllLazyByQuery( - 49, - "FROM " + dao.getTopiaEntityEnum().getImplementationFQN() + " ORDER BY id"); - - actual = Lists.newArrayList(); - - for (Person person : allByLazy) { - actual.add(person); - } - Assert.assertEquals(dao.count(), actual.size()); - - allByLazy = dao.findAllLazyByQuery( - 101, - "FROM " + dao.getTopiaEntityEnum().getImplementationFQN() + " ORDER BY id"); - - actual = Lists.newArrayList(); - - for (Person person : allByLazy) { - actual.add(person); - } - Assert.assertEquals(dao.count(), actual.size()); - - allByLazy = dao.findAllLazyByQuery( - 102, - "FROM " + dao.getTopiaEntityEnum().getImplementationFQN() + " ORDER BY id"); - - actual = Lists.newArrayList(); - - for (Person person : allByLazy) { - actual.add(person); - } - Assert.assertEquals(dao.count(), actual.size()); - } - - @Test - public void iterateOnTopiaDAO() throws TopiaException { - - createPersons(1999); - - List<Person> excepted = dao.findAll(); - - List<Person> actual = Lists.newArrayList(); - - for (Person person : dao) { - Assert.assertThat(excepted, CoreMatchers.hasItem(person)); - actual.add(person); - } - Assert.assertEquals(excepted.size(), actual.size()); - - dao.setBatchSize(54); - - actual = Lists.newArrayList(); - - for (Person person : dao) { - Assert.assertThat(excepted, CoreMatchers.hasItem(person)); - actual.add(person); - } - Assert.assertEquals(excepted.size(), actual.size()); - - } - - protected void createPersons(int number) throws TopiaException { - for (int i = 0; i < number; i++) { - createPerson("toto" + i); - } - - context.commitTransaction(); - } - - protected Person createPerson(String name) throws TopiaException { - return dao.create(Person.PROPERTY_NAME, name); - } -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/CollectorTest.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/CollectorTest.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/CollectorTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,124 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.topia.persistence.util; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.nuiton.topia.TopiaException; -import org.nuiton.topia.TopiaTestDAOHelper; -import org.nuiton.topia.persistence.TopiaEntity; -import org.nuiton.topia.persistence.TopiaEntityEnum; -import org.nuiton.topiatest.Company; -import org.nuiton.topiatest.CompanyImpl; -import org.nuiton.topiatest.Department; -import org.nuiton.topiatest.DepartmentImpl; -import org.nuiton.topiatest.EmployeImpl; - -/** @author tchemit <chemit@codelutin.com> */ -public class CollectorTest { - - - private static Log log = LogFactory.getLog(CollectorTest.class); - - - static TopiaEntityEnum[] contracts; - - @BeforeClass - public static void setUpClass() throws Exception { - contracts = TopiaTestDAOHelper.getContracts(); - } - - @AfterClass - public static void tearDownClass() throws Exception { - contracts = null; - } - - @Test - public void testCollector() throws Exception { - - Collector<Integer> detector = new Collector<Integer>(contracts) { - - int hits; - - @Override - protected void beforeAll(CollectorVisitor visitor, TopiaEntity... entities) { - super.beforeAll(visitor, entities); - hits = 0; - } - - @Override - protected Integer afterAll(CollectorVisitor visitor, TopiaEntity... entities) { - return hits; - } - - @Override - protected void onStarted(TopiaEntity e, boolean enter) { - super.onStarted(e, enter); - int level = stackSize(); - log.info(String.format("(%1$2d) %2$" + level * 2 + "s %3$s", level, ">>", getStack())); - - hits++; - } - - @Override - protected void onEnded(TopiaEntity e, boolean enter) { - super.onEnded(e, enter); - int level = stackSize() + 1; - log.info(String.format("(%1$2d) %2$" + level * 2 + "s %3$s", level, "<<", getStack())); - } - }; - - Company company = new CompanyImpl(); - EmployeImpl employe = new EmployeImpl(); - Department department = new DepartmentImpl(); - - detect(detector, 1, company); - - company.addEmploye(employe); - detect(detector, 2, company); - - company.addDepartment(department); - detect(detector, 3, company); - - company.removeEmploye(employe); - detect(detector, 2, company); - - company.removeDepartment(department); - detect(detector, 1, company); - } - - protected void detect(Collector<Integer> detector, - int expectedResult, - TopiaEntity... entities) throws TopiaException { - Integer result = detector.detect(entities); - Assert.assertNotNull(result); - Assert.assertEquals(expectedResult, result.intValue()); - } -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/EntityOperatorTest.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/EntityOperatorTest.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/EntityOperatorTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,238 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.topia.persistence.util; - -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.nuiton.topia.TopiaTestDAOHelper; -import org.nuiton.topiatest.Company; -import org.nuiton.topiatest.CompanyImpl; -import org.nuiton.topiatest.Department; -import org.nuiton.topiatest.DepartmentImpl; -import org.nuiton.topiatest.Employe; -import org.nuiton.topiatest.EmployeImpl; -import org.nuiton.topiatest.Personne; -import org.nuiton.topiatest.PersonneImpl; - -import java.util.Collection; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -/** @author tchemit <chemit@codelutin.com> */ -public class EntityOperatorTest { - - public EntityOperatorTest() { - } - - static EntityOperator<Company> operationC; - - static EntityOperator<Employe> operationE; - - static EntityOperator<Personne> operationP; - - static EntityOperator<Department> operationD; - - Company c; - - Department d; - - Employe e; - - Personne p; - - @BeforeClass - public static void setUpClass() throws Exception { - operationC = TopiaTestDAOHelper.getOperator(Company.class); - operationE = TopiaTestDAOHelper.getOperator(Employe.class); - operationP = TopiaTestDAOHelper.getOperator(Personne.class); - operationD = TopiaTestDAOHelper.getOperator(Department.class); - } - - @AfterClass - public static void tearDownClass() throws Throwable { - operationC.finalize(); - operationE.finalize(); - operationP.finalize(); - operationD.finalize(); - } - - @Before - public void setUp() { - c = new CompanyImpl(); - d = new DepartmentImpl(); - e = new EmployeImpl(); - p = new PersonneImpl(); - } - - @After - public void tearDown() { - c = null; - d = null; - e = null; - p = null; - } - - /** Test of newOperator method, of class EntityOperator. */ - @Test - public void testGet() { - - Object actual; - String name; - - e.setName(name = "name"); - actual = operationE.get(Employe.PROPERTY_NAME, e); - assertEquals(name, actual); - - actual = operationP.get(Employe.PROPERTY_NAME, e); - assertEquals(name, actual); - - actual = operationD.get(Department.PROPERTY_COMPANY, d); - assertNull(actual); - - d.setCompany(c); - actual = operationD.get(Department.PROPERTY_COMPANY, d); - assertNotNull(actual); - assertEquals(c, actual); - - actual = operationC.get(Company.PROPERTY_DEPARTMENT, c); - assertNull(actual); - - c.addDepartment(d); - actual = operationC.get(Company.PROPERTY_DEPARTMENT, c); - assertNotNull(actual); - assertFalse(((Collection<?>) actual).isEmpty()); - } - - /** Test of set method, of class EntityOperator. */ - @Test - public void testSet() { - - String name; - - operationE.set(Employe.PROPERTY_NAME, e, name = "name"); - assertEquals(name, e.getName()); - - operationP.set(Employe.PROPERTY_NAME, e, name = "name2"); - assertEquals(name, e.getName()); - } - - /** Test of getChild method, of class EntityOperator. */ - @Test - public void testGetChild() { - Object actual; - String topiaId; - - topiaId = "0"; - - actual = operationC.get(Company.PROPERTY_DEPARTMENT, c); - assertNull(actual); - - actual = operationC.getChild(Company.PROPERTY_DEPARTMENT, c, topiaId); - assertNull(actual); - - c.addDepartment(d); - - actual = operationC.get(Company.PROPERTY_DEPARTMENT, c); - assertNotNull(actual); - assertFalse(((Collection<?>) actual).isEmpty()); - - actual = operationC.getChild(Company.PROPERTY_DEPARTMENT, c, topiaId); - assertNull(actual); - - d.setTopiaId(topiaId); - actual = operationC.getChild(Company.PROPERTY_DEPARTMENT, c, topiaId); - assertNotNull(actual); - assertEquals(d, actual); - - } - - /** Test of addChild method, of class EntityOperator. */ - @Test - public void testAddChild() { - - assertTrue(c.isDepartmentEmpty()); - - operationC.addChild(Company.PROPERTY_DEPARTMENT, c, d); - assertFalse(c.isDepartmentEmpty()); - assertEquals(d, c.getDepartment().iterator().next()); - } - - /** Test of isChildEmpty method, of class EntityOperator. */ - @Test - public void testIsChildEmpty() { - - assertTrue(c.isDepartmentEmpty()); - - boolean actual = operationC.isChildEmpty(Company.PROPERTY_DEPARTMENT, c); - assertTrue(actual); - - c.addDepartment(d); - - actual = operationC.isChildEmpty(Company.PROPERTY_DEPARTMENT, c); - assertFalse(actual); - } - - /** Test of sizeChild method, of class EntityOperator. */ - @Test - public void testChildSize() { - - assertTrue(c.isDepartmentEmpty()); - - int actual = operationC.sizeChild(Company.PROPERTY_DEPARTMENT, c); - assertEquals(0, actual); - - c.addDepartment(d); - - actual = operationC.sizeChild(Company.PROPERTY_DEPARTMENT, c); - assertEquals(1, actual); - c.clearDepartment(); - - actual = operationC.sizeChild(Company.PROPERTY_DEPARTMENT, c); - assertEquals(0, actual); - } - - /** Test of removeChild method, of class EntityOperator. */ - @Test - public void testRemoveChild() { - - assertTrue(c.isDepartmentEmpty()); - - c.addDepartment(d); - - assertFalse(c.isDepartmentEmpty()); - - operationC.removeChild(Company.PROPERTY_DEPARTMENT, c, d); - - assertTrue(c.isDepartmentEmpty()); - } -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityBinderTest.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityBinderTest.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityBinderTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,105 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.topia.persistence.util; - -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import org.nuiton.topia.TopiaTestDAOHelper; -import org.nuiton.topia.persistence.TopiaEntity; -import org.nuiton.topia.persistence.TopiaEntityEnum; -import org.nuiton.topiatest.Company; -import org.nuiton.util.beans.Binder; -import org.nuiton.util.beans.BinderFactory; -import org.nuiton.util.beans.BinderModelBuilder; - -public class TopiaEntityBinderTest { - - static TopiaEntityEnum[] contracts; - - @BeforeClass - public static void setUpClass() throws Exception { - contracts = TopiaTestDAOHelper.getContracts(); - } - - public static class CompanyDTO { - - protected String name; - - protected int siret; - - protected String id; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public int getSiret() { - return siret; - } - - public void setSiret(int siret) { - this.siret = siret; - } - - public String getTopiaId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - } - - @Before - public void setUp() { - BinderFactory.clear(); - } - - @AfterClass - public static void afterClass() { - BinderFactory.clear(); - } - - @Test - public void testBinder() { - - BinderModelBuilder<Company, CompanyDTO> builder = BinderModelBuilder.newEmptyBuilder(Company.class, CompanyDTO.class); - builder.addSimpleProperties(Company.PROPERTY_NAME, Company.PROPERTY_SIRET); - builder.addProperties(TopiaEntity.PROPERTY_TOPIA_ID, "id"); - BinderFactory.registerBinderModel(builder); - - Binder<Company, CompanyDTO> binder = - BinderFactory.newBinder(Company.class, CompanyDTO.class); - Assert.assertNotNull(binder); - } -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityHelperTest.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityHelperTest.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityHelperTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,282 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.topia.persistence.util; - -import org.junit.AfterClass; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Test; -import org.nuiton.topia.TopiaException; -import org.nuiton.topia.TopiaTestDAOHelper; -import org.nuiton.topia.persistence.DefaultTopiaIdFactory; -import org.nuiton.topia.persistence.TopiaEntity; -import org.nuiton.topia.persistence.TopiaEntityEnum; -import org.nuiton.topia.persistence.TopiaIdFactory; -import org.nuiton.topiatest.Company; -import org.nuiton.topiatest.CompanyImpl; -import org.nuiton.topiatest.Department; -import org.nuiton.topiatest.DepartmentImpl; -import org.nuiton.topiatest.Employe; -import org.nuiton.topiatest.EmployeAbstract; -import org.nuiton.topiatest.EmployeImpl; -import org.nuiton.topiatest.Personne; -import org.nuiton.topiatest.PersonneAbstract; -import org.nuiton.topiatest.PersonneImpl; - -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -/** @author tchemit <chemit@codelutin.com> */ -public class TopiaEntityHelperTest { - - protected static TopiaIdFactory topiaIdFactory = new DefaultTopiaIdFactory(); - - protected static TopiaEntityEnum[] contracts; - - protected final Set<Class<? extends TopiaEntity>> contractsClass; - - public TopiaEntityHelperTest() { - contractsClass = new HashSet<Class<? extends TopiaEntity>>(); - contractsClass.add(Company.class); - contractsClass.add(Employe.class); - contractsClass.add(Department.class); - } - - @BeforeClass - public static void setUpClass() throws Exception { - contracts = TopiaTestDAOHelper.getContracts(); - } - - @AfterClass - public static void tearDownClass() throws Exception { - contracts = null; - } - - /** Test of getContractClass method, of class TopiaEntityHelper. */ - @Test - public void testgetContract() { - - Class<?> result = TopiaEntityHelper.getContractClass(null, Company.class); - assertNull(result); - - Class<? extends TopiaEntity> expResult; - - expResult = Employe.class; - - getContractClass(expResult, EmployeImpl.class); - getContractClass(expResult, EmployeAbstract.class); - getContractClass(expResult, Employe.class); - - expResult = Personne.class; - - getContractClass(expResult, PersonneImpl.class); - getContractClass(expResult, PersonneAbstract.class); - getContractClass(expResult, Personne.class); - } - - /** Test of retainContracts method, of class TopiaEntityHelper. */ - @Test - public void testRetainContracts() { - Set<Class<? extends TopiaEntity>> classes = new HashSet<Class<? extends TopiaEntity>>(); - Set<Class<? extends TopiaEntity>> result = TopiaEntityHelper.retainContracts(contracts, classes); - - assertTrue(result.isEmpty()); - - classes.add(PersonneImpl.class); - result = TopiaEntityHelper.retainContracts(contracts, classes); - assertEquals(1, result.size()); - assertTrue(result.contains(Personne.class)); - - classes.add(PersonneAbstract.class); - result = TopiaEntityHelper.retainContracts(contracts, classes); - assertEquals(1, result.size()); - assertTrue(result.contains(Personne.class)); - - classes.add(Personne.class); - result = TopiaEntityHelper.retainContracts(contracts, classes); - assertEquals(1, result.size()); - assertTrue(result.contains(Personne.class)); - - classes.clear(); - classes.add(EmployeImpl.class); - result = TopiaEntityHelper.retainContracts(contracts, classes); - assertEquals(1, result.size()); - assertTrue(result.contains(Employe.class)); - - classes.add(PersonneImpl.class); - result = TopiaEntityHelper.retainContracts(contracts, classes); - assertEquals(2, result.size()); - assertTrue(result.contains(Personne.class)); - assertTrue(result.contains(Employe.class)); - - } - - /** - * Test of detectTypes method, of class TopiaEntityHelper. - * - * @throws TopiaException - */ - @Test - public void testDetectTypes() throws TopiaException { - Company company = new CompanyImpl(); - EmployeImpl employe = new EmployeImpl(); - Department departmnet = new DepartmentImpl(); - - detectTypes(new Class<?>[]{Company.class, Employe.class, Department.class}, company, employe, departmnet); - - company.addEmploye(employe); - detectTypes(new Class<?>[]{Company.class, Employe.class}, company); - - company.addDepartment(departmnet); - departmnet.setCompany(company); - detectTypes(new Class<?>[]{Company.class, Employe.class, Department.class}, company); - - company.removeEmploye(employe); - company.removeDepartment(departmnet); - detectTypes(new Class<?>[]{Company.class}, company); - } - - @Test - public void testDetector() throws Exception { - - Company company = new CompanyImpl(); - company.setTopiaId(topiaIdFactory.newTopiaId(Company.class, company)); - Employe employe = new EmployeImpl(); - employe.setTopiaId(topiaIdFactory.newTopiaId(Employe.class, employe)); - Department department = new DepartmentImpl(); - department.setTopiaId(topiaIdFactory.newTopiaId(Department.class, department)); - - detectEntities(new Class<?>[]{Company.class, Employe.class, Department.class}, new int[]{1, 1, 1}, company, employe, department); - detectEntityIds(new Class<?>[]{Company.class, Employe.class, Department.class}, new int[]{1, 1, 1}, company, employe, department); - - company.addEmploye(employe); - detectEntities(new Class<?>[]{Company.class, Employe.class}, new int[]{1, 1, 1}, company); - detectEntityIds(new Class<?>[]{Company.class, Employe.class}, new int[]{1, 1, 1}, company); - - company.addDepartment(department); - department.setCompany(company); - - detectEntities(new Class<?>[]{Company.class, Employe.class, Department.class}, new int[]{1, 1, 1}, company); - detectEntityIds(new Class<?>[]{Company.class, Employe.class, Department.class}, new int[]{1, 1, 1}, company); - - company.removeEmploye(employe); - company.removeDepartment(department); - - - detectEntities(new Class<?>[]{Company.class}, new int[]{1}, company); - detectEntityIds(new Class<?>[]{Company.class}, new int[]{1}, company); - - detectEntities(new Class<?>[]{Company.class}, new int[]{2}, company, new CompanyImpl()); - detectEntityIds(new Class<?>[]{Company.class}, new int[]{2}, company, new CompanyImpl()); - - department.setCompany(company); - - detectEntities(new Class<?>[]{Company.class, Department.class}, new int[]{1, 1}, department); - detectEntityIds(new Class<?>[]{Company.class, Department.class}, new int[]{1, 1}, department); - - //TODO faire des tests avec des entites avec cycles - } - - protected void detectEntities(Class<?>[] expected, - int[] sizes, - TopiaEntity... data) throws TopiaException { - - Map<Class<? extends TopiaEntity>, List<TopiaEntity>> actual = null; - - try { - actual = TopiaEntityHelper.detectEntities(contracts, contractsClass, data); - - Assert.assertEquals(expected.length, actual.size()); - int index = 0; - for (Class<?> c : expected) { - List<TopiaEntity> value = actual.get(c); - int expectedSize = sizes[index++]; - Assert.assertEquals(expectedSize, value.size()); - } - } finally { - if (actual != null) { - actual.clear(); - } - } - } - - protected void detectEntityIds(Class<?>[] expected, - int[] sizes, - TopiaEntity... data) throws TopiaException { - - TopiaEntityIdsMap actual = null; - - try { - actual = TopiaEntityHelper.detectEntityIds(contracts, - contractsClass, - data - ); - - Assert.assertEquals(expected.length, actual.size()); - int index = 0; - for (Class<?> c : expected) { - List<String> value = actual.get(c); - int expectedSize = sizes[index++]; - Assert.assertEquals(expectedSize, value.size()); - } - } finally { - if (actual != null) { - actual.clear(); - } - } - } - - protected void detectTypes(Class<?>[] expected, TopiaEntity... data) throws TopiaException { - Set<String> fqns = new HashSet<String>(expected.length); - Set<Class<? extends TopiaEntity>> actual = null; - for (Class<?> c : expected) { - fqns.add(c.getName()); - } - try { - actual = TopiaEntityHelper.detectTypes(contracts, data); - Assert.assertEquals(expected.length, actual.size()); - for (Class<? extends TopiaEntity> c : actual) { - Assert.assertTrue(fqns.contains(c.getName())); - } - } finally { - fqns.clear(); - if (actual != null) { - actual.clear(); - } - } - } - - protected void getContractClass(Class<?> expected, Class<? extends TopiaEntity> klass) { - Class<?> result = TopiaEntityHelper.getContractClass(contracts, klass); - assertEquals(expected, result); - } -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTester.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTester.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTester.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,331 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.topia.persistence.util; - -import org.junit.After; -import org.junit.Assert; -import org.nuiton.topia.TopiaException; -import org.nuiton.topia.persistence.TopiaEntity; -import org.nuiton.topia.persistence.TopiaEntityEnum; - -import java.util.Collection; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.SortedMap; - -import static java.util.Map.Entry; - -/** - * A abstract class to help testing {@link TopiaEntityRef} as detectes types, or - * detects or references. - * <p/> - * An example of use if given in the test {@link TopiaEntityRefTesterTest}. - * - * @author tchemit <chemit@codelutin.com> - * @since 2.3.1 - */ -public abstract class TopiaEntityRefTester<T extends TopiaEntityEnum> { - - protected SortedMap<TopiaEntity, List<TopiaEntityRef>> detected; - - protected Iterator<Entry<TopiaEntity, List<TopiaEntityRef>>> itr; - - protected Entry<TopiaEntity, List<TopiaEntityRef>> entry; - - protected List<TopiaEntityRef> refs; - - protected T[] contracts; - - protected int index; - - protected T[] getContracts() { - if (contracts == null) { - contracts = getContracts0(); - } - return contracts; - } - - /** @return all the {@link TopiaEntityEnum} to be used */ - protected abstract T[] getContracts0(); - - @After - public void after() { - itr = null; - entry = null; - refs = null; - detected = null; - index = 0; - } - - /** - * Creates a new entity with the given {@code topiaId} (will use the {@link - * TopiaEntityEnum#getImplementation()} class). - * - * @param constant the constant defining the entity - * @param topiaId the topia to assign - * @param <T> the type of entity - * @return the new entity - * @throws IllegalAccessException if can no access entity constructor - * @throws InstantiationException if can no instanciate the entity - */ - protected <T extends TopiaEntity> T newEntity( - TopiaEntityEnum constant, String topiaId) throws - IllegalAccessException, - InstantiationException { - Class<? extends TopiaEntity> impl = constant.getImplementation(); - TopiaEntity topiaEntity = impl.newInstance(); - topiaEntity.setTopiaId(topiaId); - return (T) topiaEntity; - } - - /** - * Obtain the reference of an association for a given entity. - * <p/> - * Example, to obtain the Pet 'pudding' on a Person : - * <pre>pet[@topiaId='pudding']</pre> - * invoke - * <pre>getAssociationRef('pet',pet);</pre> - * - * @param associationName the name of the association - * @param e the required entity - * @return the reference of the association - */ - protected String getAssociationRef(String associationName, TopiaEntity e) { - return getAssociationRef(associationName, e.getTopiaId()); - } - - /** - * Obtain the reference of an association for a given id. - * <p/> - * Example to obtain the Pet 'pudding' on a Person : - * <pre>pet[@topiaId='pudding']</pre> - * invoke - * <pre>getAssociationRef('pet','pudding');</pre> - * - * @param associationName the name of the association - * @param e the id - * @return the reference of the association - */ - protected String getAssociationRef(String associationName, String e) { - String s = String.format( - TopiaEntityHelper.ASSOCIATION_PATTERN, - associationName, - e - ); - return s; - } - - /** - * Obtain the next entry from the iterator. - * <p/> - * As a side-effect, it will increment the state {@link #index}. - */ - protected void nextEntry() { - if (!itr.hasNext()) { - throw new IllegalStateException("no more entry to get..."); - } - entry = itr.next(); - index = 0; - } - - /** - * Detects the references from the given {@code entity} which have their - * topiaId in the given list of {@code ids}. - * <p/> - * As a side-effect, it will update the states {@code detected} and set the - * iterator {@code itr} to the first position on detected entries. - * - * @param entity the entity to seek - * @param nb the required number of entries - * @param ids the ids to seek - * @throws TopiaException if any pb while visiting entities - */ - protected void detectReferences( - TopiaEntity entity, int nb, String... ids) throws TopiaException { - detected = TopiaEntityHelper.detectReferences( - getContracts(), ids, entity); - assertDetected(nb); - - } - - /** - * Detects the references from the given {@code entity} which have their - * topiaId in the given list of {@code ids}. - * <p/> - * As a side-effect, it will update the states {@code detected} and set the - * iterator {@code itr} to the first position on detected entries. - * - * @param entity the entity to seek - * @param nb the required number of entries - * @param ids the ids to seek - * @throws TopiaException if any pb while visiting entities - */ - protected void detectReferences( - Collection<? extends TopiaEntity> entity, - int nb, String... ids) throws TopiaException { - detected = TopiaEntityHelper.detectReferences( - getContracts(), ids, entity); - assertDetected(nb); - } - - /** - * Detects the type of entities fro the given {@code data}. - * - * @param expected the array of expected types - * @param data the data to seek - * @throws TopiaException if any pb while visiting data - */ - protected void detectTypes(Class<?>[] expected, - TopiaEntity... data) throws TopiaException { - Set<String> fqns = new HashSet<String>(expected.length); - Set<Class<? extends TopiaEntity>> actual = null; - for (Class<?> c : expected) { - fqns.add(c.getName()); - } - try { - actual = TopiaEntityHelper.detectTypes(getContracts(), data); - Assert.assertEquals(expected.length, actual.size()); - for (Class<? extends TopiaEntity> c : actual) { - Assert.assertTrue(fqns.contains(c.getName())); - } - } finally { - fqns.clear(); - if (actual != null) { - actual.clear(); - } - } - } - - /** - * Asserts if the given entry definition is equals to the next entry - * references on internal state state {@code entry}. - * - * @param invoker the invoker of the reference - * @param invokerProperty the access path of the reference - * @param expected the expected topia entities path to access - * reference target - */ - protected void assertNextEntityRef(TopiaEntity invoker, - String invokerProperty, - TopiaEntity... expected) { - assertEntityRef(index, invoker, invokerProperty, expected); - index++; - } - - /** - * Asserts if the given entry definition (of an association) is equals to - * the next entry reference on internal state {@code entry}. - * - * @param invoker the invoker of the reference - * @param association the association name - * @param id the id of the association ( see {@link - * #getAssociationRef(String, TopiaEntity)} - * @param expected the expected topia entities path to access reference - * target - */ - protected void assertNextAssociationEntityRef(TopiaEntity invoker, - String association, - String id, - TopiaEntity... expected) { - String invokerProperty = getAssociationRef(association, id); - assertNextEntityRef(invoker, invokerProperty, expected); - } - - /** - * Asserts if the given entry definition is equals to the reference entry at - * position {@code index} on internal state {@code entry}. - * - * @param index the index of the reference to test in {@code - * entry} - * @param invoker the invoker of the reference - * @param invokerProperty the path of the reference - * @param expected th expected topia entities path to access - * reference target - */ - protected void assertEntityRef(int index, - TopiaEntity invoker, - String invokerProperty, - TopiaEntity... expected) { - Assert.assertNotNull(refs); - Assert.assertTrue("no index [" + index + "] in refs of size " + - refs.size(), index < refs.size()); - TopiaEntityRef actual = refs.get(index); - Assert.assertEquals(actual.getInvoker(), invoker); - Assert.assertEquals(actual.getInvokerProperty(), invokerProperty); - - TopiaEntity[] path = actual.getPath(); - Assert.assertEquals(expected.length, path.length); - for (int i = 0; i < expected.length; i++) { - Assert.assertEquals(expected[i].getTopiaId(), path[i].getTopiaId()); - } - } - - /** - * Asserts if the given {@code expected} entity is equals to the source of - * the internal state {@code entry}. - * - * @param expected the required source of the entry - * @param nbPath the expected number of references of the given entry - */ - protected void assertCurrentEntry(TopiaEntity expected, - int nbPath) { - assertEntry(expected, nbPath, entry); - } - - /** - * Asserts if the given {@code entry} has a good source and a good number of - * references. - * - * @param expected the expected entry source - * @param nbPath the expected number of reference of the entry - * @param entry the entry to test - */ - private void assertEntry(TopiaEntity expected, - int nbPath, - Entry<TopiaEntity, List<TopiaEntityRef>> entry) { - Assert.assertNotNull(entry); - Assert.assertEquals(expected, entry.getKey()); - refs = entry.getValue(); - Assert.assertEquals(nbPath, refs.size()); - } - - /** - * Asserts that the number of detected entries (store in internal state - * {@code detected}) is ok. - * <p/> - * As a side-effect, it will reset the internal state {@code itr} on the - * first entry of the {@code detected} list. - * - * @param size the expected number of detected entries - */ - protected void assertDetected(int size) { - Assert.assertNotNull(detected); - Assert.assertEquals(size, detected.size()); - itr = detected.entrySet().iterator(); - } -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTesterTest.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTesterTest.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/TopiaEntityRefTesterTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,155 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.topia.persistence.util; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.Test; -import org.nuiton.topia.TopiaTestDAOHelper.TopiaTestEntityEnum; -import org.nuiton.topia.test.entities.Person; -import org.nuiton.topia.test.entities.Pet; -import org.nuiton.topia.test.entities.Race; - -/** - * Test the {@link TopiaEntityRefTester} on - * <p/> - * <ul> <li>{@link Pet}</li> <li>{@link Race}</li> <li>{@link Person}</li> - * </ul> - * - * @author tchemit <chemit@codelutin.com> - * @since 2.3.1 - */ -public class TopiaEntityRefTesterTest extends TopiaEntityRefTester<TopiaTestEntityEnum> { - - /** Logger */ - private static final Log log = - LogFactory.getLog(TopiaEntityRefTesterTest.class); - - private static final String PET1 = "pet1"; - - private static final String PET2 = "pet2"; - - private static final String RACE1 = "race1"; - - private static final String PERSON1 = "person1"; - - @Override - protected TopiaTestEntityEnum[] getContracts0() { - return new TopiaTestEntityEnum[]{ - TopiaTestEntityEnum.Pet, - TopiaTestEntityEnum.Person, - TopiaTestEntityEnum.Race, - }; - } - - @Test - public void testNoReferences() throws Exception { - - Pet pet = newEntity(TopiaTestEntityEnum.Pet, PET1); - - detectReferences(pet, 0); - - Race race = newEntity(TopiaTestEntityEnum.Race, RACE1); - - detectReferences(race, 0); - - Person person = newEntity(TopiaTestEntityEnum.Person, PERSON1); - - detectReferences(person, 0); - - } - - @Test - public void testReferences() throws Exception { - - Pet pet = newEntity(TopiaTestEntityEnum.Pet, PET1); - Race race = newEntity(TopiaTestEntityEnum.Race, RACE1); - pet.setRace(race); - Person person = newEntity(TopiaTestEntityEnum.Person, PERSON1); - - detectReferences(pet, 1, RACE1); - - nextEntry(); - assertCurrentEntry(race, 1); - assertNextEntityRef(pet, Pet.PROPERTY_RACE, pet, race); - - pet.setPerson(person); - - detectReferences(pet, 2, RACE1, PERSON1); - - nextEntry(); - assertCurrentEntry(person, 1); - assertNextEntityRef(pet, Pet.PROPERTY_PERSON, pet, person); - - nextEntry(); - assertCurrentEntry(race, 1); - assertNextEntityRef(pet, Pet.PROPERTY_RACE, pet, race); - - person.addPet(pet); - - detectReferences(person, 1, PET1); - - nextEntry(); - assertCurrentEntry(pet, 1); - assertNextAssociationEntityRef(person, Person.PROPERTY_PET, PET1, person, pet); - - Pet pet2 = newEntity(TopiaTestEntityEnum.Pet, PET2); - - person.addPet(pet2); - - detectReferences(person, 3, PET1, PET2, RACE1); - - nextEntry(); - assertCurrentEntry(pet, 1); - assertNextAssociationEntityRef(person, Person.PROPERTY_PET, PET1, person, pet); - - nextEntry(); - assertCurrentEntry(pet2, 1); - assertNextAssociationEntityRef(person, Person.PROPERTY_PET, PET2, person, pet2); - - nextEntry(); - assertCurrentEntry(race, 1); - assertNextEntityRef(pet, Pet.PROPERTY_RACE, person, pet, race); - - pet2.setRace(race); - - detectReferences(person, 3, PET1, PET2, RACE1); - - nextEntry(); - assertCurrentEntry(pet, 1); - assertNextAssociationEntityRef(person, Person.PROPERTY_PET, PET1, person, pet); - - nextEntry(); - assertCurrentEntry(pet2, 1); - assertNextAssociationEntityRef(person, Person.PROPERTY_PET, PET2, person, pet2); - - nextEntry(); - assertCurrentEntry(race, 2); - assertNextEntityRef(pet, Pet.PROPERTY_RACE, person, pet, race); - assertNextEntityRef(pet2, Pet.PROPERTY_RACE, person, pet2, race); - - } -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/test/ano1882/DAOAbstractTransformerTest.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/test/ano1882/DAOAbstractTransformerTest.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/test/ano1882/DAOAbstractTransformerTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,57 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2012 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.topia.test.ano1882; - -import org.junit.Rule; -import org.junit.Test; -import org.nuiton.topia.TopiaDatabase; -import org.nuiton.topia.TopiaTestDAOHelper; -import org.nuiton.topia.TopiaTestTopiaPersistenceContext; - -import java.util.Arrays; - -public class DAOAbstractTransformerTest { - - @Rule - public final TopiaDatabase db = new TopiaDatabase(); - - @Test - public void testAno1882() throws Exception { - TopiaTestTopiaPersistenceContext transaction = db.beginTransaction(); - - FrenchCompanyDAO dao = TopiaTestDAOHelper.getFrenchCompanyDAO(transaction); - SIRETDAO siretDAO = TopiaTestDAOHelper.getSIRETDAO(transaction); - SIRET siret = siretDAO.create(); - FrenchCompany entity = - dao.create( - FrenchCompany.PROPERTY_S_IREN, null, - FrenchCompany.PROPERTY_SIREN2, null, - FrenchCompany.PROPERTY_S_IRET, Arrays.asList(siret), - FrenchCompany.PROPERTY_SIRET2, null); - transaction.commitTransaction(); - dao.delete(entity); - transaction.commitTransaction(); - } -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topia/test/evo1912/EntityDTOTransformerTest.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/test/evo1912/EntityDTOTransformerTest.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/test/evo1912/EntityDTOTransformerTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,46 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2012 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.topia.test.evo1912; - -import org.junit.Assert; -import org.junit.Test; -import org.nuiton.topiatest.CompanyDTO; - -/** @author ymartel <martel@codelutin.com> */ -public class EntityDTOTransformerTest { - - @Test - public void testEvo1912() throws Exception { - // simply test the getter/setter on id property : with the tagValue, they should be generated - CompanyDTO companyDTO = new CompanyDTO(); - String originalId = companyDTO.getTopiaId(); - Assert.assertNull(originalId); - String wantedId = "mycompany"; - companyDTO.setTopiaId(wantedId); - String updatedId = companyDTO.getTopiaId(); - Assert.assertEquals(wantedId, updatedId); - } - -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topiatest/AbstractExtraDAOEntityTopiaDao.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topiatest/AbstractExtraDAOEntityTopiaDao.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topiatest/AbstractExtraDAOEntityTopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,40 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.topiatest; - -import org.nuiton.topia.TopiaException; - -/** - * Created: 26 mai 2010 - * - * @author fdesbois <fdesbois@codelutin.com> - * @version $Id$ - */ -public class AbstractExtraDAOEntityTopiaDao<E extends ExtraDAOEntity> extends GeneratedExtraDAOEntityTopiaDao<E> { - - @Override - public void extra() throws TopiaException { - } -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topiatest/EnumTest.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topiatest/EnumTest.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topiatest/EnumTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,75 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2011 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.topiatest; - -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.nuiton.topia.TopiaDatabase; -import org.nuiton.topia.TopiaException; -import org.nuiton.topia.TopiaTestDAOHelper; -import org.nuiton.topia.TopiaTestTopiaPersistenceContext; - -/** - * Test the support of possibility to have an attribute of type enumeration - * in a entity - */ -public class EnumTest { - - @Rule - public final TopiaDatabase db = new TopiaDatabase(); - - /** - * Create an entity having two field of type enumeration. One is stored - * using ordinal, the other using the name. - * <p/> - * The test check that values are stored, and that find methods works - * - * @throws TopiaException if any exception with db - */ - @Test - public void storeEntityWithEnumValue() throws TopiaException { - TopiaTestTopiaPersistenceContext transaction = db.beginTransaction(); - - PersonneDAO dao = TopiaTestDAOHelper.getPersonneDAO(transaction); - Personne personne = new PersonneImpl(); - personne.setGender(Gender.FEMALE); - personne.setOtherGender(Gender.MALE); - dao.create(personne); - String topiaId = personne.getTopiaId(); - transaction.commitTransaction(); - transaction.closeContext(); - - transaction = db.beginTransaction(); - dao = TopiaTestDAOHelper.getPersonneDAO(transaction); - dao.findByTopiaId(topiaId); - Assert.assertEquals(Gender.FEMALE, personne.getGender()); - Assert.assertEquals(Gender.MALE, personne.getOtherGender()); - - Assert.assertNotNull(dao.findByGender(Gender.FEMALE)); - Assert.assertNotNull(dao.findByOtherGender(Gender.MALE)); - transaction.closeContext(); - } -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topiatest/Gender.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topiatest/Gender.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topiatest/Gender.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,29 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2011 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.topiatest; - -public enum Gender { - MALE, FEMALE -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topiatest/Title.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topiatest/Title.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topiatest/Title.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,37 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2011 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.topiatest; - -/** - * To test http://nuiton.org/issues/1732. - * - * @author tchemit <chemit@codelutin.com> - * @since 2.6.2 - */ -public enum Title { - Mr, - Madam, - Other -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topiatest/beangen/RoueImpl.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topiatest/beangen/RoueImpl.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topiatest/beangen/RoueImpl.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,53 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.topiatest.beangen; - -import org.nuiton.topiatest.Product; - -/** - * RoueImpl - * - * Created: 14 janv. 2010 - * - * @author fdesbois - * @version $Revision$ - * - * Mise a jour: $Date$ - * par : $Author$ - */ -public class RoueImpl extends Roue { - - @Override - public void mount() { - throw new UnsupportedOperationException("Not supported yet."); - } - - @Override - public Product getModel(String id) { - throw new UnsupportedOperationException("Not supported yet."); - } - -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topiatest/deletetest/AbstractContact2TopiaDao.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topiatest/deletetest/AbstractContact2TopiaDao.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topiatest/deletetest/AbstractContact2TopiaDao.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,51 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - -package org.nuiton.topiatest.deletetest; - - -import org.nuiton.topia.TopiaException; -import org.nuiton.topiatest.Company; -import org.nuiton.topiatest.Employe; - -import java.util.Set; -import java.util.TreeSet; - -/** - * - * @author desbois - */ -public class AbstractContact2TopiaDao<E extends Contact2> extends GeneratedContact2TopiaDao<E> { - - @Override - public Set<Contact2> findAllByCompany(Company company) throws TopiaException { - Set<Contact2> contacts = new TreeSet<Contact2>(); - for (Employe e : company.getEmploye()) { - contacts.addAll(e.getContacts()); - } - return contacts; - } - -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topiatest/deletetest/DeleteEntityTest.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topiatest/deletetest/DeleteEntityTest.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topiatest/deletetest/DeleteEntityTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,206 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ - - -/** - * DeleteEntityTest.java - * - * Created: 4 juin 2009 - * - * @author Florian Desbois <fdesbois@codelutin.com> - * @version $Revision$ - * - * Mise a jour: $Date$ - * par : $Author$ - */ - -package org.nuiton.topiatest.deletetest; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.Assert; -import org.junit.Rule; -import org.junit.Test; -import org.nuiton.topia.TopiaDatabase; -import org.nuiton.topia.TopiaException; -import org.nuiton.topia.TopiaTestDAOHelper; -import org.nuiton.topia.TopiaTestTopiaPersistenceContext; -import org.nuiton.topiatest.Gender; -import org.nuiton.topiatest.Personne; -import org.nuiton.topiatest.PersonneDAO; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; - -/** - * Deleting tests with DAO and Entities generated with ToPIA (diagram - * delete-test in topiatest.zargo). Different case of deleting, with inheritance - * or NMultiplicity relationship between two entities, or both. Initiate from an - * issue with DAOAbstractGenerator delete method generation. Tests with H2 - * Database. Configuration in src/test/resources/TopiaContextImpl.properties - */ -public class DeleteEntityTest { - - private static final Log log = LogFactory.getLog(DeleteEntityTest.class); - - @Rule - public final TopiaDatabase db = new TopiaDatabase(); - - /** - * Test for deleting entities with inheritance. Delete from the DAO linked - * with the subclass entity and from the DAO linked with the superclass - * entity. In the test model, the two entities have NMultiplicity - * relationship without association class entity. - * - * @throws TopiaException if any exception while manipulating db - */ - @Test - public void testDeleteEntityWithInheritance() throws TopiaException { - log.debug("START TEST : testDeleteEntityWithInheritance"); - - TopiaTestTopiaPersistenceContext transaction = db.beginTransaction(); - - log.debug("DAO : PersonneDAO"); - PersonneDAO dao = TopiaTestDAOHelper.getPersonneDAO(transaction); - - log.debug("CREATE PERSONNE : Bob Marley"); - Personne personne = dao.create(Personne.PROPERTY_NAME, "Bob Marley"); - transaction.commitTransaction(); - String idPersonne = personne.getTopiaId(); - assertNotNull(idPersonne); - log.debug("ENTITY PERSONNE SAVED !"); - - log.debug("DELETE PERSONNE"); - dao.delete(personne); - transaction.commitTransaction(); - Personne res = dao.forTopiaIdEquals(idPersonne).findAnyOrNull(); - assertNull(res); - log.debug("ENTITY PERSONNE DELETED !"); - - log.debug("CREATE PERSONNE : Ziggy Marley"); - Personne personne2 = dao.create(Personne.PROPERTY_NAME, "Ziggy Marley"); - transaction.commitTransaction(); - String idPersonne2 = personne2.getTopiaId(); - assertNotNull(idPersonne2); - log.debug("ENTITY PERSONNE SAVED !"); - - log.debug("DAO parent (abstract) : PartyDAO"); - Party2DAO dao2 = TopiaTestDAOHelper.getParty2DAO(transaction); - - log.debug("DELETE PERSONNE with PartyDAO"); - dao2.delete(personne2); - transaction.commitTransaction(); - Party2 res2 = dao2.forTopiaIdEquals(idPersonne2).findAnyOrNull(); - assertNull(res2); - log.debug("ENTITY PERSONNE DELETED !"); - - - } - - /** - * Test for deleting entities with NMultiplicity relation without - * association class entity. Test DAO generation for deleting references - * between two entities with NMultiplicity relation. In the test model, the - * two entities have both inheritance. - * - * @throws TopiaException if any exception while manipulating db - */ - @Test - public void testDeleteEntityWithManyToManyRelation() throws TopiaException { - log.debug("START TEST : testDeleteEntityWithManyToManyRelation"); - - TopiaTestTopiaPersistenceContext transaction = db.beginTransaction(); - - PersonneDAO dao = TopiaTestDAOHelper.getPersonneDAO(transaction); - - log.debug("CREATE PERSONNE : Bob Marley"); - Personne personne = dao.create(Personne.PROPERTY_NAME, "Bob Marley"); - transaction.commitTransaction(); - String idPersonne = personne.getTopiaId(); - assertNotNull(idPersonne); - log.debug("ENTITY PERSONNE SAVED !"); - - Contact2DAO contactDAO = TopiaTestDAOHelper.getContact2DAO(transaction); - - log.debug("CREATE CONTACT : jaja@codelutin.com"); - Contact2 contact = contactDAO.create(Contact2.PROPERTY_CONTACT_VALUE, "jaja@codelutin.com"); - transaction.commitTransaction(); - String idContact = contact.getTopiaId(); - assertNotNull(idContact); - log.debug("ENTITY CONTACT SAVED !"); - - log.debug("ADD CONTACT TO PERSONNE"); - personne.addContacts(contact); - transaction.commitTransaction(); - assertEquals(1, personne.getContacts().size()); - log.debug("CONTACT ADDED !"); - - log.debug("DELETE PERSONNE"); - dao.delete(personne); - transaction.commitTransaction(); - Personne res = dao.forTopiaIdEquals(idPersonne).findAnyOrNull(); - assertNull(res); - log.debug("ENTITY PERSONNE DELETED !"); - - assertEquals(0, contact.getParty2().size()); - - log.debug("DELETE CONTACT"); - contactDAO.delete(contact); - transaction.commitTransaction(); - Contact2 res2 = contactDAO.forTopiaIdEquals(idContact).findAnyOrNull(); - assertNull(res2); - log.debug("ENTITY PERSONNE DELETED !"); - - } - - /** - * Test than deleting entities will modify isPersisted() result - */ - @Test - public void testIsPersisted() { - log.debug("START TEST : testIsPersisted"); - - TopiaTestTopiaPersistenceContext transaction = db.beginTransaction(); - - PersonneDAO dao = TopiaTestDAOHelper.getPersonneDAO(transaction); - - Personne person = dao.newInstance(); - Assert.assertNull(person.getTopiaId()); - - person.setName("Arno"); - person.setGender(Gender.MALE); - Assert.assertFalse(person.isPersisted()); - - Personne person2 = dao.create(person); - Assert.assertTrue(person.isPersisted()); - Assert.assertTrue(person2.isPersisted()); - - dao.delete(person2); - Assert.assertFalse(person.isPersisted()); - Assert.assertFalse(person2.isPersisted()); - } - -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,49 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.topiatest.persistence; - -import org.nuiton.topia.persistence.TopiaEntity; - -/** - * Created: 11 mai 2010 - * - * @author fdesbois <fdesbois@codelutin.com> - * @version $Id$ - */ -public interface Entity1 extends TopiaEntity { - - String ATTR_1 = "attr1"; - - String ATTR_2 = "attr2"; - - String getAttr1(); - - void setAttr1(String attr1); - - String getAttr2(); - - void setAttr2(String attr2); - -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1Abstract.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1Abstract.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1Abstract.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,83 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.topiatest.persistence; - -import org.nuiton.topia.TopiaException; -import org.nuiton.topia.persistence.EntityVisitor; -import org.nuiton.topia.persistence.TopiaEntityAbstract; - -/** - * Created: 11 mai 2010 - * - * @author fdesbois <fdesbois@codelutin.com> - * @version $Id$ - */ -public abstract class Entity1Abstract extends TopiaEntityAbstract - implements Entity1 { - - protected String attr1; - - protected String attr2; - - @Override - public String getAttr1() { - fireOnPreRead(ATTR_1, attr1); - String result = attr1; - fireOnPostRead(ATTR_1, attr1); - return result; - } - - @Override - public void setAttr1(String attr1) { - String _oldValue = this.attr1; - fireOnPreWrite(ATTR_1, _oldValue, attr1); - this.attr1 = attr1; - fireOnPostWrite(ATTR_1, _oldValue, attr1); - } - - @Override - public String getAttr2() { - fireOnPreRead(ATTR_2, attr2); - String result = attr2; - fireOnPostRead(ATTR_2, attr2); - return result; - } - - @Override - public void setAttr2(String attr2) { - String _oldValue = this.attr2; - fireOnPreWrite(ATTR_2, _oldValue, attr2); - this.attr2 = attr2; - fireOnPostWrite(ATTR_2, _oldValue, attr2); - } - - @Override - public void accept(EntityVisitor visitor) throws TopiaException { - visitor.start(this); - visitor.visit(this, ATTR_1, String.class, attr1); - visitor.visit(this, ATTR_2, String.class, attr2); - visitor.end(this); - } -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1Impl.hbm.xml =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1Impl.hbm.xml 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1Impl.hbm.xml 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,37 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- - #%L - ToPIA :: Persistence - - $Id$ - $HeadURL$ - %% - Copyright (C) 2004 - 2010 CodeLutin - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Lesser General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Lesser Public License for more details. - - You should have received a copy of the GNU General Lesser Public - License along with this program. If not, see - <http://www.gnu.org/licenses/lgpl-3.0.html>. - #L% - --> - -<!--<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">--> -<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> -<hibernate-mapping default-access="field" auto-import="true" package="org.nuiton.topiatest"> - <class name="org.nuiton.topiatest.persistence.Entity1Impl" table="entity1" node="org.nuiton.topiatest.persistence.Entity1Impl" abstract="false" proxy="org.nuiton.topiatest.persistence.Entity1" > - <id name="topiaId" type="string" length="255" node="@topiaId"/> - <version name="topiaVersion" type="long" node="@topiaVersion"/> - <property name="topiaCreateDate" type="timestamp" node="@topiaCreateDate"/> - <property name="attr1" type="java.lang.String" access="field" column="attr1" node="attr1"/> - <property name="attr2" type="java.lang.String" access="field" column="attr2" node="attr2"/> - </class> -</hibernate-mapping> Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1Impl.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1Impl.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/Entity1Impl.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,37 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.topiatest.persistence; - -import org.nuiton.topia.TopiaException; -import org.nuiton.topia.persistence.EntityVisitor; - -/** - * Created: 11 mai 2010 - * - * @author fdesbois <fdesbois@codelutin.com> - * @version $Id$ - */ -public class Entity1Impl extends Entity1Abstract { -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/package-info.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/package-info.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topiatest/persistence/package-info.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,28 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -/** - * Contains persistent entities for Tests. - */ -package org.nuiton.topiatest.persistence; \ No newline at end of file Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topiatest/service/FakeService.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topiatest/service/FakeService.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topiatest/service/FakeService.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,63 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.topiatest.service; - -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.framework.TopiaContextImplTest; -import org.nuiton.topia.framework.TopiaService; - -/** - * FakeService which implements {@link TopiaService} to test existing service - * from {@link TopiaContextImplTest#testGetServices()}. This fake service - * doesn't contains property SERVICE_NAME used by {@link - * org.nuiton.topia.framework.AbstractTopiaContext#serviceEnabled(Class)}. - * <p/> - * Created: 10 mai 2010 - * - * @author fdesbois <fdesbois@codelutin.com> - * @version $Id$ - */ -public class FakeService implements TopiaService { - - @Override - public String getServiceName() { - return "fake"; - } - - @Override - public Class<?>[] getPersistenceClasses() { - return new Class<?>[0]; - } - - @Override - public boolean preInit(TopiaContext context) { - return true; - } - - @Override - public boolean postInit(TopiaContext context) { - return true; - } -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topiatest/service/TestService.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topiatest/service/TestService.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topiatest/service/TestService.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,67 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -package org.nuiton.topiatest.service; - -import org.junit.Ignore; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.framework.TopiaContextImplTest; -import org.nuiton.topia.framework.TopiaContextImplementor; -import org.nuiton.topia.framework.TopiaService; - -/** - * TestService which implements {@link TopiaService} to test loading from {@link - * TopiaContextImplTest#testLoadServices()}. - * <p/> - * Created: 10 mai 2010 - * - * @author fdesbois <fdesbois@codelutin.com> - * @version $Id$ - */ -@Ignore -public class TestService implements TopiaService { - - /** Needed field to use {@link TopiaContext#serviceEnabled(Class)} * */ - public static final String SERVICE_NAME = "test"; - - @Override - public String getServiceName() { - return SERVICE_NAME; - } - - @Override - public Class<?>[] getPersistenceClasses() { - return new Class<?>[0]; - } - - @Override - public boolean preInit(TopiaContext context) { - return true; - } - - @Override - public boolean postInit(TopiaContext context) { - return true; - } -} Deleted: trunk/topia-persistence/src/test/java/org/nuiton/topiatest/service/package-info.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topiatest/service/package-info.java 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/java/org/nuiton/topiatest/service/package-info.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,29 +0,0 @@ -/* - * #%L - * ToPIA :: Persistence - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2004 - 2010 CodeLutin - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Lesser Public License for more details. - * - * You should have received a copy of the GNU General Lesser Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/lgpl-3.0.html>. - * #L% - */ -/** - * This package contains classes which implements {@link - * org.nuiton.topia.framework.TopiaService} to test services API. - */ -package org.nuiton.topiatest.service; \ No newline at end of file Deleted: trunk/topia-persistence/src/test/resources/TopiaConnectionProviderHardcoded.properties =================================================================== --- trunk/topia-persistence/src/test/resources/TopiaConnectionProviderHardcoded.properties 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/resources/TopiaConnectionProviderHardcoded.properties 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,35 +0,0 @@ -### -# #%L -# ToPIA :: Persistence -# -# $Id$ -# $HeadURL$ -# %% -# Copyright (C) 2004 - 2010 CodeLutin -# %% -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Lesser Public License for more details. -# -# You should have received a copy of the GNU General Lesser Public -# License along with this program. If not, see -# <http://www.gnu.org/licenses/lgpl-3.0.html>. -# #L% -### -# Proprietes par defaut pour une base de donnees de type H2 -hibernate.hbm2ddl.auto=update -hibernate.show_sql=false - -hibernate.dialect=org.hibernate.dialect.H2Dialect -hibernate.connection.username=sa -hibernate.connection.password= -hibernate.connection.driver_class=org.h2.Driver -hibernate.connection.provider_class=org.nuiton.topia.framework.TopiaConnectionProviderHardCoded -# tchemit 2010-11-28 : comment this line, each test must define his own db path -#hibernate.connection.url=jdbc:h2:file:target/surefire-workdir/h2data \ No newline at end of file Deleted: trunk/topia-persistence/src/test/resources/TopiaContextImpl.properties =================================================================== --- trunk/topia-persistence/src/test/resources/TopiaContextImpl.properties 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/resources/TopiaContextImpl.properties 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,34 +0,0 @@ -### -# #%L -# ToPIA :: Persistence -# -# $Id$ -# $HeadURL$ -# %% -# Copyright (C) 2004 - 2010 CodeLutin -# %% -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Lesser Public License for more details. -# -# You should have received a copy of the GNU General Lesser Public -# License along with this program. If not, see -# <http://www.gnu.org/licenses/lgpl-3.0.html>. -# #L% -### -# Proprietes par defaut pour une base de donnees de type H2 -hibernate.hbm2ddl.auto=update -hibernate.show_sql=false - -hibernate.dialect=org.hibernate.dialect.H2Dialect -hibernate.connection.username=sa -hibernate.connection.password= -hibernate.connection.driver_class=org.h2.Driver -# tchemit 2010-11-28 : comment this line, each test must define his own db path -#hibernate.connection.url=jdbc:h2:file:target/surefire-workdir/h2data \ No newline at end of file Deleted: trunk/topia-persistence/src/test/resources/log4j.properties =================================================================== --- trunk/topia-persistence/src/test/resources/log4j.properties 2013-11-22 17:48:55 UTC (rev 2883) +++ trunk/topia-persistence/src/test/resources/log4j.properties 2013-11-22 18:03:47 UTC (rev 2884) @@ -1,36 +0,0 @@ -### -# #%L -# ToPIA :: Persistence -# -# $Id$ -# $HeadURL$ -# %% -# Copyright (C) 2004 - 2010 CodeLutin -# %% -# This program is free software: you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License as -# published by the Free Software Foundation, either version 3 of the -# License, or (at your option) any later version. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Lesser Public License for more details. -# -# You should have received a copy of the GNU General Lesser Public -# License along with this program. If not, see -# <http://www.gnu.org/licenses/lgpl-3.0.html>. -# #L% -### -#\u00a0This log is used to display trace in generation - -# Global logging configuration -log4j.rootLogger=WARN, stdout -# Console output... -log4j.appender.stdout=org.apache.log4j.ConsoleAppender -log4j.appender.stdout.layout=org.apache.log4j.PatternLayout -log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) %M - %m%n -# package level -log4j.logger.org.nuiton.topia=INFO -#log4j.logger.org.nuiton.topiatest=DEBUG -log4j.logger.org.nuiton.topia.persistence.util=INFO Property changes on: trunk/topia-templates ___________________________________________________________________ Added: svn:ignore + target *.ipr *.iws *.iml .idea Property changes on: trunk/topia-templates/LICENSE.txt ___________________________________________________________________ Added: svn:keywords + Author Date Id Revision Added: svn:eol-style + native Property changes on: trunk/topia-templates/README.txt ___________________________________________________________________ Added: svn:keywords + Author Date Id Revision Added: svn:eol-style + native Added: trunk/topia-templates/pom.xml =================================================================== --- trunk/topia-templates/pom.xml (rev 0) +++ trunk/topia-templates/pom.xml 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,187 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- + #%L + ToPIA :: Persistence + + $Id$ + $HeadURL: http://svn.nuiton.org/svn/topia/trunk/topia-persistence/pom.xml $ + %% + Copyright (C) 2004 - 2010 CodeLutin + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Lesser Public License for more details. + + You should have received a copy of the GNU General Lesser Public + License along with this program. If not, see + <http://www.gnu.org/licenses/lgpl-3.0.html>. + #L% + --> + +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>org.nuiton</groupId> + <artifactId>topia</artifactId> + <version>3.0-SNAPSHOT</version> + </parent> + + <groupId>org.nuiton.topia</groupId> + <artifactId>topia-templates</artifactId> + <packaging>jar</packaging> + + <name>ToPIA :: Templates</name> + <description>Persistence templates</description> + + <dependencies> + + <dependency> + <groupId>${project.groupId}</groupId> + <artifactId>topia-persistence</artifactId> + <version>${project.version}</version> + </dependency> + + <dependency> + <groupId>org.nuiton.eugene</groupId> + <artifactId>eugene</artifactId> + </dependency> + + <dependency> + <groupId>org.nuiton.eugene</groupId> + <artifactId>eugene-java-templates</artifactId> + </dependency> + + <dependency> + <groupId>com.google.guava</groupId> + <artifactId>guava</artifactId> + </dependency> + + <dependency> + <groupId>commons-collections</groupId> + <artifactId>commons-collections</artifactId> + </dependency> + + <dependency> + <groupId>commons-beanutils</groupId> + <artifactId>commons-beanutils</artifactId> + </dependency> + + <dependency> + <groupId>commons-logging</groupId> + <artifactId>commons-logging</artifactId> + </dependency> + + <dependency> + <groupId>commons-io</groupId> + <artifactId>commons-io</artifactId> + </dependency> + + <dependency> + <groupId>org.apache.commons</groupId> + <artifactId>commons-lang3</artifactId> + </dependency> + + <dependency> + <groupId>org.hibernate</groupId> + <artifactId>hibernate-core</artifactId> + </dependency> + <dependency> + <groupId>org.hibernate</groupId> + <artifactId>hibernate-ehcache</artifactId> + </dependency> + + <dependency> + <groupId>javassist</groupId> + <artifactId>javassist</artifactId> + </dependency> + + <dependency> + <groupId>org.slf4j</groupId> + <artifactId>slf4j-log4j12</artifactId> + </dependency> + + <!-- BD H2 for testing --> + <dependency> + <groupId>com.h2database</groupId> + <artifactId>h2</artifactId> + </dependency> + + <dependency> + <groupId>junit</groupId> + <artifactId>junit</artifactId> + </dependency> + + <dependency> + <groupId>org.hamcrest</groupId> + <artifactId>hamcrest-core</artifactId> + </dependency> + + <dependency> + <groupId>log4j</groupId> + <artifactId>log4j</artifactId> + <scope>test</scope> + </dependency> + + </dependencies> + + <build> + + <plugins> + + <!-- process templates --> + <plugin> + <groupId>org.nuiton.processor</groupId> + <artifactId>processor-maven-plugin</artifactId> + </plugin> + + <!-- expose new plexus components --> + <plugin> + <groupId>org.codehaus.plexus</groupId> + <artifactId>plexus-component-metadata</artifactId> + <executions> + <execution> + <goals> + <goal>generate-metadata</goal> + </goals> + </execution> + </executions> + </plugin> + + </plugins> + </build> + + <profiles> + + <!-- reporting at release time --> + <profile> + <id>reporting</id> + <activation> + <property> + <name>performRelease</name> + <value>true</value> + </property> + </activation> + + <reporting> + <plugins> + + <plugin> + <groupId>org.codehaus.plexus</groupId> + <artifactId>plexus-maven-plugin</artifactId> + <version>${plexusPluginVersion}</version> + </plugin> + + </plugins> + </reporting> + + </profile> + + </profiles> +</project> Property changes on: trunk/topia-templates/pom.xml ___________________________________________________________________ Added: svn:mime-type + text/xml Added: svn:keywords + Author Date Id Revision Added: svn:eol-style + native Property changes on: trunk/topia-templates/src ___________________________________________________________________ Added: svn:ignore + target *.ipr *.iws *.iml .idea Property changes on: trunk/topia-templates/src/main ___________________________________________________________________ Added: svn:ignore + target *.ipr *.iws *.iml .idea Property changes on: trunk/topia-templates/src/main/java ___________________________________________________________________ Added: svn:ignore + target *.ipr *.iws *.iml .idea Property changes on: trunk/topia-templates/src/main/java/org ___________________________________________________________________ Added: svn:ignore + target *.ipr *.iws *.iml .idea Property changes on: trunk/topia-templates/src/main/java/org/nuiton ___________________________________________________________________ Added: svn:ignore + target *.ipr *.iws *.iml .idea Property changes on: trunk/topia-templates/src/main/java/org/nuiton/topia ___________________________________________________________________ Added: svn:ignore + target *.ipr *.iws *.iml .idea Property changes on: trunk/topia-templates/src/main/java/org/nuiton/topia/templates ___________________________________________________________________ Added: svn:ignore + target *.ipr *.iws *.iml .idea Copied: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/ApplicationContextTransformer.java (from rev 2882, trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/ApplicationContextTransformer.java) =================================================================== --- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/ApplicationContextTransformer.java (rev 0) +++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/ApplicationContextTransformer.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,269 @@ +package org.nuiton.topia.templates; + +/*{generator option: parentheses = false}*/ + +/*{generator option: writeString = +}*/ + +import org.nuiton.eugene.java.ObjectModelTransformerToJava; +import org.nuiton.eugene.models.object.ObjectModel; +import org.nuiton.eugene.models.object.ObjectModelClass; +import org.nuiton.eugene.models.object.ObjectModelJavaModifier; +import org.nuiton.eugene.models.object.ObjectModelOperation; +import org.nuiton.topia.AbstractTopiaApplicationContext; +import org.nuiton.topia.persistence.TopiaEntity; +import org.nuiton.topia.persistence.util.EntityOperator; +import org.nuiton.topia.persistence.util.EntityOperatorStore; + +import java.lang.reflect.Array; +import java.util.List; +import java.util.Properties; + +/** + * To generate PersistenceHelper + * + * @author tchemit <chemit@codelutin.com> + * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.templates.ApplicationContextTransformer" + * @since 3.0 + */ +public class ApplicationContextTransformer extends ObjectModelTransformerToJava { + + @Override + public void transformFromModel(ObjectModel input) { + + String packageName = TopiaGeneratorUtil.getApplicationContextPackage(this, model); + + String applicationContextAbstractName = TopiaGeneratorUtil.getApplicationContextAbstractName(model); + + String applicationContextConcreteName = TopiaGeneratorUtil.getApplicationContextConcreteName(model); + + boolean generateAbstract = !isInClassPath(packageName, applicationContextAbstractName); + + boolean generateConcrete = !isInClassPath(packageName, applicationContextConcreteName); + + + if (generateAbstract) { + + generateAbstract(packageName, + applicationContextAbstractName); + } + + if (generateConcrete) { + + generateImpl(packageName, + applicationContextAbstractName, + applicationContextConcreteName); + } + + } + + protected void generateAbstract(String packageName, + String className) { + + // try to find a super class by tag-value +// String superClass = TopiaGeneratorUtil.getPersistenceContextSuperClassTagValue(model); + String superClass = null; + + if (superClass == null) { + + // no super-class, use default one + superClass = AbstractTopiaApplicationContext.class.getName(); + } + + ObjectModelClass output = createAbstractClass(className, packageName); + + String persistenceContextConcreteName = TopiaGeneratorUtil.getPersistenceContextConcreteName(model); + setSuperClass(output, superClass + "<" + persistenceContextConcreteName + ">"); + + // detect if there is a contract to set on abstract + String contractName = TopiaGeneratorUtil.getPersistenceContextInterfaceName(model); + +// addInterface(output, TopiaPersistenceContext.class); + + boolean addPersistenceContextContract = isInClassPath(packageName, contractName); + + if (addPersistenceContextContract) { + addInterface(output, packageName + "." + contractName); + } + + String modelName = model.getName(); + String daoHelperClazzName = modelName + "DAOHelper"; + + String entityEnumName = modelName + "EntityEnum"; + + List<ObjectModelClass> entityClasses = + TopiaGeneratorUtil.getEntityClasses(model, true); + + boolean generateOperator = + TopiaGeneratorUtil.shouldGenerateOperatorForDAOHelper(model); + + boolean generateStandaloneEnum = + TopiaGeneratorUtil.shouldGenerateStandaloneEnumForDAOHelper(model); + + if (!generateStandaloneEnum) { + + addImport(output, packageName + "." + daoHelperClazzName + "." + entityEnumName); + + } + + addImport(output, TopiaEntity.class); + addImport(output, Array.class); + addImport(output, Array.class); + + if (generateOperator) { + addImport(output, EntityOperator.class); + addImport(output, EntityOperatorStore.class); + } + + // add public constructor + ObjectModelOperation constructor = addConstructor( + output, + ObjectModelJavaModifier.PUBLIC); + addParameter(constructor, Properties.class, "properties"); + setOperationBody(constructor, "" +/*{ + super(properties); + }*/ + ); + + constructor = addConstructor( + output, + ObjectModelJavaModifier.PUBLIC); + addParameter(constructor, "java.util.Map<String, String>", "configuration"); + setOperationBody(constructor, "" +/*{ + super(configuration); + }*/ + ); + + ObjectModelOperation op; + + // getModelVersion method + op = addOperation(output, "newPersistenceContext", persistenceContextConcreteName, ObjectModelJavaModifier.PUBLIC); + addAnnotation(output, op, Override.class); + setOperationBody(op, "" +/*{ + <%=persistenceContextConcreteName%> newContext = new <%=persistenceContextConcreteName%>( + getHibernateProvider(), getTopiaListenableSupport(), getTopiaIdFactory()); + registerPersistenceContext(newContext); + return newContext; + }*/ + ); + + // getModelVersion method + String modelVersion = model.getVersion(); + op = addOperation(output, "getModelVersion", "String", ObjectModelJavaModifier.PUBLIC); + setOperationBody(op, "" +/*{ + return "<%=modelVersion%>"; + }*/ + ); + + // getModelName method + op = addOperation(output, "getModelName", "String", ObjectModelJavaModifier.PUBLIC); + setOperationBody(op, "" +/*{ + return "<%=modelName%>"; + }*/ + ); + + // getContractClass method + op = addOperation(output, "getContractClass", "<T extends TopiaEntity> Class<T>", ObjectModelJavaModifier.PUBLIC); + addParameter(op, "Class<T>", "klass"); + setOperationBody(op, "" +/*{ + <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass); + return (Class<T>) constant.getContract(); + }*/ + ); + + // getImplementationClass method + op = addOperation(output, "getImplementationClass", "<T extends TopiaEntity> Class<T>", ObjectModelJavaModifier.PUBLIC); + addParameter(op, "Class<T>", "klass"); + setOperationBody(op, "" +/*{ + <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass); + return (Class<T>) constant.getImplementation(); + }*/ + ); + + // getContractClasses method + op = addOperation(output, "getContractClasses", "Class<? extends TopiaEntity>[]", ObjectModelJavaModifier.PUBLIC); + setOperationBody(op, "" +/*{ + <%=entityEnumName%>[] values = <%=entityEnumName%>.values(); + Class<? extends TopiaEntity>[] result = (Class<? extends TopiaEntity>[]) Array.newInstance(Class.class, values.length); + for (int i = 0; i < values.length; i++) { + result[i] = values[i].getContract(); + } + return result; + }*/ + ); + + // getImplementationClasses method + op = addOperation(output, "getImplementationClasses", "Class<? extends TopiaEntity>[]", ObjectModelJavaModifier.PUBLIC); + setOperationBody(op, "" +/*{ + <%=entityEnumName%>[] values = <%=entityEnumName%>.values(); + Class<? extends TopiaEntity>[] result = (Class<? extends TopiaEntity>[]) Array.newInstance(Class.class, values.length); + for (int i = 0; i < values.length; i++) { + result[i] = values[i].getImplementation(); + } + return result; + }*/ + ); + + // getContracts method + op = addOperation(output, "getContracts", entityEnumName + "[]", ObjectModelJavaModifier.PUBLIC); + setOperationBody(op, "" +/*{ + return <%=entityEnumName%>.values(); + }*/ + ); + + if (generateOperator) { + // getOperator method + op = addOperation(output, "getOperator", "<T extends TopiaEntity> EntityOperator<T>", ObjectModelJavaModifier.PUBLIC); + addParameter(op, "Class<T>", "klass"); + setOperationBody(op, "" +/*{ + <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass); + return EntityOperatorStore.getOperator(constant); + }*/ + ); + } + + } + + protected ObjectModelClass generateImpl(String packageName, + String applicationContextAbstractName, + String applicationContextConcreteName) { + + ObjectModelClass output = createClass(applicationContextConcreteName, packageName); + + setSuperClass(output, applicationContextAbstractName); + + // add public constructor + ObjectModelOperation constructor = addConstructor( + output, + ObjectModelJavaModifier.PUBLIC); + addParameter(constructor, Properties.class, "properties"); + setOperationBody(constructor, "" +/*{ + super(properties); + }*/ + ); + + constructor = addConstructor( + output, + ObjectModelJavaModifier.PUBLIC); + addParameter(constructor, "java.util.Map<String, String>", "configuration"); + setOperationBody(constructor, "" +/*{ + super(configuration); + }*/ + ); + + return output; + } + +} Copied: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/BinderHelperTransformer.java (from rev 2882, trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/BinderHelperTransformer.java) =================================================================== --- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/BinderHelperTransformer.java (rev 0) +++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/BinderHelperTransformer.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,249 @@ +package org.nuiton.topia.templates; + +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.eugene.GeneratorUtil; +import org.nuiton.eugene.java.ObjectModelTransformerToJava; +import org.nuiton.eugene.models.object.*; +import org.nuiton.topia.persistence.TopiaEntity; +import org.nuiton.topia.persistence.util.TopiaEntityBinder; +import org.nuiton.topia.persistence.util.TopiaEntityHelper; +import org.nuiton.util.beans.BinderModelBuilder; +import org.nuiton.util.beans.BinderFactory; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + + +/*{generator option: parentheses = false}*/ +/*{generator option: writeString = +}*/ + +/** + * A template to generate a helper for {@link TopiaEntityBinder}. + * + * @author tchemit <chemit@codelutin.com> + * @version $Id$ + * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.templates.BinderHelperTransformer" + * @since 2.3.1 + */ +public class BinderHelperTransformer extends ObjectModelTransformerToJava { + + private static final Log log = + LogFactory.getLog(BinderHelperTransformer.class); + + + @Override + public void transformFromModel(ObjectModel model) { + ObjectModelClass resultClass; + + List<ObjectModelClass> classes = TopiaGeneratorUtil.getEntityClasses(model, true); + + if (CollectionUtils.isEmpty(classes)) { + + // no entity classes, so no generation + log.warn("No entity to generate, " + getClass().getName() + " is skipped"); + return; + } + + String packageName = getOutputProperties().getProperty(PROP_DEFAULT_PACKAGE); + String modelName = model.getName(); + String binderHelperClazzName = modelName + "BinderHelper"; + String daoHelperClazzName = modelName + "DAOHelper"; + + resultClass = createClass(binderHelperClazzName, packageName); + + setSuperClass(resultClass, BinderFactory.class); + + + addImport(resultClass, TopiaEntityBinder.class); + addImport(resultClass, TopiaEntityHelper.class); + addImport(resultClass, TopiaEntity.class); + addImport(resultClass, BinderModelBuilder.class); + + ObjectModelOperation op; + + op = addOperation(resultClass, + "getTopiaBinder", + "<E extends TopiaEntity> TopiaEntityBinder<E>", + ObjectModelJavaModifier.PUBLIC, + ObjectModelJavaModifier.STATIC); + addParameter(op, "Class<E>", "entityClass"); + addParameter(op, "String", "contextName"); + setOperationBody(op, "" +/*{ + return (TopiaEntityBinder<E>) newBinder(entityClass, entityClass, contextName, TopiaEntityBinder.class); + }*/ + ); + + op = addOperation(resultClass, + "getSimpleTopiaBinder", + "<E extends TopiaEntity> TopiaEntityBinder<E>", + ObjectModelJavaModifier.PUBLIC, + ObjectModelJavaModifier.STATIC); + addParameter(op, "Class<E>", "entityClass"); + setOperationBody(op, "" +/*{ + return getTopiaBinder(entityClass, "<%=modelName%>"); + }*/ + ); + + op = addOperation(resultClass, + "registerTopiaBinder", + "void", + ObjectModelJavaModifier.PUBLIC, + ObjectModelJavaModifier.STATIC); + addParameter(op, "BinderModelBuilder", "builder"); + addParameter(op, "String", "contextName"); + setOperationBody(op, "" +/*{ + registerBinderModel(builder, contextName); + }*/ + ); + + op = addOperation(resultClass, + "registerTopiaBinder", + "<E extends TopiaEntity> TopiaEntityBinder<E>", + ObjectModelJavaModifier.PUBLIC, + ObjectModelJavaModifier.STATIC); + addParameter(op, "Class<E>", "entityClass"); + addParameter(op, "BinderModelBuilder", "builder"); + addParameter(op, "String", "contextName"); + setOperationBody(op, "" +/*{ + registerBinderModel(builder, contextName); + return getTopiaBinder(entityClass, contextName); + }*/ + ); + + op = addOperation(resultClass, + "copy", + "<E extends TopiaEntity> void", + ObjectModelJavaModifier.PUBLIC, + ObjectModelJavaModifier.STATIC); + addParameter(op, "String", "contextName"); + addParameter(op, "E", "source"); + addParameter(op, "E", "target"); + addParameter(op, "boolean", "tech"); + setOperationBody(op, "" +/*{ + Class<E> entityClass = (Class<E>) TopiaEntityHelper.getContractClass(<%=daoHelperClazzName%>.getContracts(), target.getClass()); + TopiaEntityBinder<E> binder = getTopiaBinder(entityClass, contextName); + if (binder == null) { + throw new NullPointerException("could not find a simple topia binder of type : " + target.getClass()); + } + binder.load(source, target, tech); + }*/ + ); + + op = addOperation(resultClass, + "simpleCopy", + "<E extends TopiaEntity> void", + ObjectModelJavaModifier.PUBLIC, + ObjectModelJavaModifier.STATIC); + addParameter(op, "E", "source"); + addParameter(op, "E", "target"); + addParameter(op, "boolean", "tech"); + setOperationBody(op, "" +/*{ + Class<E> entityClass = (Class<E>) TopiaEntityHelper.getContractClass(<%=daoHelperClazzName%>.getContracts(), target.getClass()); + TopiaEntityBinder<E> binder = getSimpleTopiaBinder(entityClass); + if (binder == null) { + throw new NullPointerException("could not find a simple topia binder of type : " + target.getClass()); + } + binder.load(source, target, tech); + }*/ + ); + + StringBuilder initCode = new StringBuilder(); + + for (ObjectModelClass clazz : classes) { + + String prefix = getConstantPrefix(clazz, ""); + + if (StringUtils.isEmpty(prefix)) { + + // no specific prefix, so no prefix + if (log.isWarnEnabled()) { + log.warn("[" + clazz.getName() + "] Will generate constants with NO prefix, not a good idea..."); + } + } + + setConstantPrefix(prefix); + + generateBinder(modelName, clazz, resultClass, initCode); + + } + + op = addOperation(resultClass, "initBinders", "void", ObjectModelJavaModifier.PROTECTED, ObjectModelJavaModifier.STATIC); + setOperationBody(op, initCode.toString()); + + op = addOperation(resultClass, null, (String) null, ObjectModelJavaModifier.STATIC); + setOperationBody(op, "" + /*{ + initBinders(); +}*/ + ); + } + + protected void generateBinder(String modelName, + ObjectModelClass clazz, + ObjectModelClass resultClass, + StringBuilder initCode) { + + List<ObjectModelAttribute> list = new ArrayList<ObjectModelAttribute>(); + for (ObjectModelAttribute attr : clazz.getAttributes()) { + if (!attr.isNavigable()) { + continue; + } + + if (GeneratorUtil.isNMultiplicity(attr)) { + // not dealing with association + continue; + } + + list.add(attr); + } + + String clazzName = clazz.getName(); + + if (list.isEmpty()) { + // no attribute, do nothing + if (log.isDebugEnabled()) { + log.debug("no attribute to add in a binder for " + clazzName + + ", will not generate it."); + } + return; + } + + if (log.isDebugEnabled()) { + log.debug("generate simple binder for " + clazzName); + } + addImport(resultClass, clazz); + initCode.append("" +/*{ + BinderModelBuilder<<%=clazzName%>, <%=clazzName%>> builder<%=clazzName%> = + BinderModelBuilder.newEmptyBuilder(<%=clazzName%>.class); + builder<%=clazzName%>.addSimpleProperties( +}*/ + ); + Iterator<ObjectModelAttribute> itr = list.iterator(); + while (itr.hasNext()) { + ObjectModelAttribute attr = itr.next(); + String attrName = attr.getName(); + boolean hasNext = itr.hasNext(); + initCode.append("" +/*{ <%=clazzName%>.<%=getConstantName(attrName)%><%=(hasNext?",\n":"")%>}*/ + ); + } + initCode.append("" +/*{ + ); + registerTopiaBinder(builder<%=clazzName%>, "<%=modelName%>"); + }*/ + ); + } +} + Copied: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/DAOHelperTransformer.java (from rev 2882, trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DAOHelperTransformer.java) =================================================================== --- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/DAOHelperTransformer.java (rev 0) +++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/DAOHelperTransformer.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,501 @@ +package org.nuiton.topia.templates; + +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.eugene.java.ObjectModelTransformerToJava; +import org.nuiton.eugene.models.object.ObjectModel; +import org.nuiton.eugene.models.object.ObjectModelAttribute; +import org.nuiton.eugene.models.object.ObjectModelClass; +import org.nuiton.eugene.models.object.ObjectModelEnumeration; +import org.nuiton.eugene.models.object.ObjectModelJavaModifier; +import org.nuiton.eugene.models.object.ObjectModelOperation; +import org.nuiton.eugene.models.object.ObjectModelType; +import org.nuiton.eugene.models.object.xml.ObjectModelAttributeImpl; +import org.nuiton.eugene.models.object.xml.ObjectModelEnumerationImpl; +import org.nuiton.topia.TopiaContext; +import org.nuiton.topia.TopiaDaoSupplier; +import org.nuiton.topia.TopiaException; +import org.nuiton.topia.persistence.TopiaDAO; +import org.nuiton.topia.persistence.TopiaEntity; +import org.nuiton.topia.persistence.TopiaEntityEnum; +import org.nuiton.topia.persistence.util.EntityOperator; +import org.nuiton.topia.persistence.util.EntityOperatorStore; + +import java.lang.reflect.Array; +import java.util.Arrays; +import java.util.List; +import java.util.Set; + + +/*{generator option: parentheses = false}*/ + +/*{generator option: writeString = +}*/ + +/** + * Created: 13 nov. 2009 09:05:17 + * + * @author tchemit <chemit@codelutin.com> + * @version $Id$ + * @since 2.3.0 + * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.templates.DAOHelperTransformer" + */ +public class DAOHelperTransformer extends ObjectModelTransformerToJava { + + private static final Log log = + LogFactory.getLog(DAOHelperTransformer.class); + + @Override + public void transformFromModel(ObjectModel model) { + String packageName = + getOutputProperties().getProperty(PROP_DEFAULT_PACKAGE); + String modelName = model.getName(); + String daoHelperClazzName = modelName + "DAOHelper"; + String entityEnumName = modelName + "EntityEnum"; + + List<ObjectModelClass> classes = + TopiaGeneratorUtil.getEntityClasses(model, true); + + boolean generateOperator = + TopiaGeneratorUtil.shouldGenerateOperatorForDAOHelper(model); + + boolean generateStandaloneEnum = + TopiaGeneratorUtil.shouldGenerateStandaloneEnumForDAOHelper(model); + + ObjectModelClass daoHelper = createClass(daoHelperClazzName, + packageName); + + ObjectModelEnumeration entityEnum; + + if (generateStandaloneEnum) { + if (log.isDebugEnabled()) { + log.debug("Will generate standalone " + entityEnumName + + " in package " + packageName); + } + entityEnum = createEnumeration(entityEnumName, packageName); + addImport(entityEnum, TopiaEntity.class); + addImport(entityEnum, EntityOperatorStore.class); + addImport(entityEnum, Arrays.class); + addImport(entityEnum, ArrayUtils.class); + + } else { + entityEnum = (ObjectModelEnumerationImpl) + addInnerClassifier(daoHelper, + ObjectModelType.OBJECT_MODEL_ENUMERATION, + entityEnumName + ); + addImport(daoHelper, TopiaEntityEnum.class); + addImport(daoHelper, EntityOperatorStore.class); + addImport(daoHelper, Arrays.class); + addImport(daoHelper, ArrayUtils.class); + } + + // generate DAOHelper + createDAOHelper(model, + daoHelper, + daoHelperClazzName, + entityEnumName, + generateOperator, + classes + ); + + // generate TopiaEntityEnum + createEntityEnum(entityEnum, + daoHelperClazzName, + entityEnumName, + generateOperator, + generateStandaloneEnum, + classes + ); + } + + protected void createDAOHelper(ObjectModel model, + ObjectModelClass daoHelper, + String daoHelperClazzName, + String entityEnumName, + boolean generateOperator, + List<ObjectModelClass> classes) { + + String modelName = model.getName(); + String modelVersion = model.getVersion(); + + addImport(daoHelper, TopiaDAO.class); + addImport(daoHelper, TopiaEntity.class); + addImport(daoHelper, TopiaContext.class); + addImport(daoHelper, Array.class); + + if (generateOperator) { + addImport(daoHelper,EntityOperator.class); + addImport(daoHelper, EntityOperatorStore.class); + } + + addAnnotation(daoHelper, daoHelper, Deprecated.class); + + // add non public constructor + ObjectModelOperation constructor = + addConstructor(daoHelper, ObjectModelJavaModifier.PROTECTED); + setOperationBody(constructor," "); + + ObjectModelOperation op; + + // getModelVersion method + op = addOperation(daoHelper, "getModelVersion", "String", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); + setOperationBody(op, "" +/*{ + return "<%=modelVersion%>"; + }*/ + ); + + // getModelName method + op = addOperation(daoHelper, "getModelName", "String", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); + setOperationBody(op, "" +/*{ + return "<%=modelName%>"; + }*/ + ); + + + for (ObjectModelClass clazz : classes) { + String clazzName = clazz.getName(); + String daoClazzName = clazzName + "DAO"; + + // specialized getXXXDao method + op = addOperation(daoHelper, "get" + daoClazzName, clazz.getPackageName() + '.' + daoClazzName, ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); + addParameter(op, TopiaDaoSupplier.class, "supplier"); + addImport(daoHelper, clazz); + addException(op, TopiaException.class); + setOperationBody(op, "" +/*{ + <%=daoClazzName%> result = supplier.getDao(<%=clazzName%>.class, <%=daoClazzName%>.class); + return result; + }*/ + ); + + } + + // obsolete generic getDAO method + op = addOperation(daoHelper, "getDAO", "<T extends TopiaEntity, D extends TopiaDAO<? super T>> D", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); + addParameter(op, TopiaContext.class, "context"); + addParameter(op, "Class<T>", "klass"); + addException(op, TopiaException.class); + addAnnotation(daoHelper, op, Deprecated.class); + setOperationBody(op, "" +/*{ + D dao = getDao(context, klass); + return dao; + }*/ + ); + + // generic getDao method + op = addOperation(daoHelper, "getDao", "<T extends TopiaEntity, D extends TopiaDAO<? super T>> D", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); + addParameter(op, TopiaContext.class, "context"); + addParameter(op, "Class<T>", "klass"); + addException(op, TopiaException.class); + setOperationBody(op, "" +/*{ + <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass); + D dao = (D) context.getDao(constant.getContract()); + return dao; + }*/ + ); + + op = addOperation(daoHelper, "getDao", "<T extends TopiaEntity, D extends TopiaDAO<? super T>> D", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); + addParameter(op, TopiaContext.class, "context"); + addParameter(op, "T", "entity"); + addException(op, TopiaException.class); + setOperationBody(op, "" +/*{ + <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(entity); + D dao = (D) context.getDao(constant.getContract()); + return dao; + }*/ + ); + + // getContractClass method + op = addOperation(daoHelper, "getContractClass", "<T extends TopiaEntity> Class<T>", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); + addParameter(op, "Class<T>", "klass"); + setOperationBody(op, "" +/*{ + <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass); + return (Class<T>) constant.getContract(); + }*/ + ); + + // getImplementationClass method + op = addOperation(daoHelper, "getImplementationClass", "<T extends TopiaEntity> Class<T>", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); + addParameter(op, "Class<T>", "klass"); + setOperationBody(op, "" +/*{ + <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass); + return (Class<T>) constant.getImplementation(); + }*/ + ); + + // getContractClasses method + op = addOperation(daoHelper, "getContractClasses", "Class<? extends TopiaEntity>[]", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); + setOperationBody(op, "" +/*{ + <%=entityEnumName%>[] values = <%=entityEnumName%>.values(); + Class<? extends TopiaEntity>[] result = (Class<? extends TopiaEntity>[]) Array.newInstance(Class.class, values.length); + for (int i = 0; i < values.length; i++) { + result[i] = values[i].getContract(); + } + return result; + }*/ + ); + + // getImplementationClasses method + op = addOperation(daoHelper, "getImplementationClasses", "Class<? extends TopiaEntity>[]", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); + setOperationBody(op, "" +/*{ + <%=entityEnumName%>[] values = <%=entityEnumName%>.values(); + Class<? extends TopiaEntity>[] result = (Class<? extends TopiaEntity>[]) Array.newInstance(Class.class, values.length); + for (int i = 0; i < values.length; i++) { + result[i] = values[i].getImplementation(); + } + return result; + }*/ + ); + + // getImplementationClassesAsString method + op = addOperation(daoHelper, "getImplementationClassesAsString", "String", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); + setOperationBody(op, "" +/*{ + StringBuilder buffer = new StringBuilder(); + for (Class<? extends TopiaEntity> aClass : getImplementationClasses()) { + buffer.append(',').append(aClass.getName()); + } + return buffer.substring(1); + }*/ + ); + + // getContracts method + op = addOperation(daoHelper, "getContracts", entityEnumName+"[]", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); + setOperationBody(op, "" +/*{ + return <%=entityEnumName%>.values(); + }*/ + ); + + if (generateOperator) { + // getOperator method + op = addOperation(daoHelper, "getOperator", "<T extends TopiaEntity> EntityOperator<T>", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); + addParameter(op,"Class<T>","klass"); + setOperationBody(op, "" +/*{ + <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass); + return EntityOperatorStore.getOperator(constant); + }*/ + ); + } + } + + protected void createEntityEnum(ObjectModelEnumeration entityEnum, + String daoHelperClazzName, + String entityEnumName, + boolean generateOperator, + boolean generateStandaloneEnum, + List<ObjectModelClass> classes) { + + ObjectModelAttributeImpl attr; + ObjectModelOperation op; + + addInterface(entityEnum, TopiaEntityEnum.class); + + for (ObjectModelClass clazz : classes) { + String clazzName = clazz.getName(); + + boolean withNatural = false; + boolean withNotNull = false; + StringBuilder naturalIdsParams = new StringBuilder(); + StringBuilder notNullParams = new StringBuilder(); + + Set<ObjectModelAttribute> naturalIdsAttributes = TopiaGeneratorUtil.getNaturalIdAttributes(clazz); + for (ObjectModelAttribute attribute: naturalIdsAttributes) { + withNatural = true; + // attribut metier + naturalIdsParams.append(", \"").append(attribute.getName()).append("\""); + } + Set<ObjectModelAttribute> notNullIdsAttributes = TopiaGeneratorUtil.getNotNullAttributes(clazz); + for (ObjectModelAttribute attribute : notNullIdsAttributes) { + withNotNull = true; + // attribut not-null + notNullParams.append(", \"").append(attribute.getName()).append("\""); + } + + StringBuilder params = new StringBuilder(clazzName + ".class"); + if (withNotNull) { + params.append(", new String[]{ " + notNullParams.substring(2) + " }"); + } else { + params.append(", ArrayUtils.EMPTY_STRING_ARRAY"); + } + if (withNatural) { + params.append(", ").append(naturalIdsParams.substring(2)); + } + addLiteral(entityEnum, clazzName + '(' + params.toString() + ')'); + + if (generateStandaloneEnum) { + addImport(entityEnum, clazz); + } + } + + attr = (ObjectModelAttributeImpl) addAttribute(entityEnum, "contract", "Class<? extends TopiaEntity>"); + attr.setDocumentation("The contract of the entity."); + + attr = (ObjectModelAttributeImpl) addAttribute(entityEnum, "implementationFQN", "String"); + attr.setDocumentation("The fully qualified name of the implementation of the entity."); + + attr = (ObjectModelAttributeImpl) addAttribute(entityEnum, "implementation", "Class<? extends TopiaEntity>"); + attr.setDocumentation("The implementation class of the entity (will be lazy computed at runtime)."); + + attr = (ObjectModelAttributeImpl) addAttribute(entityEnum, "naturalIds", "String[]"); + attr.setDocumentation("The array of property involved in the natural key of the entity."); + + attr = (ObjectModelAttributeImpl) addAttribute(entityEnum, "notNulls", "String[]"); + attr.setDocumentation("The array of not null properties of the entity."); + + // constructor + op = addConstructor(entityEnum, ObjectModelJavaModifier.PACKAGE); + addParameter(op,"Class<? extends TopiaEntity >","contract"); + addParameter(op,"String[]","notNulls"); + addParameter(op,"String...","naturalIds"); + setOperationBody(op, "" +/*{ + this.contract = contract; + this.notNulls = Arrays.copyOf(notNulls, notNulls.length); + this.naturalIds = naturalIds; + implementationFQN = contract.getName() + "Impl"; + }*/ + ); + + // getContract method + op = addOperation(entityEnum, "getContract", "Class<? extends TopiaEntity>", ObjectModelJavaModifier.PUBLIC); + addAnnotation(entityEnum,op,Override.class); + setOperationBody(op, "" +/*{ + return contract; + }*/ + ); + + // getNaturalIds method + op = addOperation(entityEnum, "getNaturalIds", "String[]", ObjectModelJavaModifier.PUBLIC); + addAnnotation(entityEnum,op,Override.class); + setOperationBody(op, "" +/*{ + return naturalIds; + }*/ + ); + + // isUseNaturalIds method + op = addOperation(entityEnum, "isUseNaturalIds", "boolean", ObjectModelJavaModifier.PUBLIC); + addAnnotation(entityEnum,op,Override.class); + setOperationBody(op, "" +/*{ + return naturalIds.length > 0; + }*/ + ); + + // getNotNulls method + op = addOperation(entityEnum, "getNotNulls", "String[]", ObjectModelJavaModifier.PUBLIC); + addAnnotation(entityEnum,op,Override.class); + setOperationBody(op, "" +/*{ + return notNulls; + }*/ + ); + + // isUseNotNulls method + op = addOperation(entityEnum, "isUseNotNulls", "boolean", ObjectModelJavaModifier.PUBLIC); + addAnnotation(entityEnum,op,Override.class); + setOperationBody(op, "" +/*{ + return notNulls.length > 0; + }*/ + ); + + // getImplementationFQN method + op = addOperation(entityEnum, "getImplementationFQN","String",ObjectModelJavaModifier.PUBLIC); + addAnnotation(entityEnum, op, Override.class); + setOperationBody(op, "" +/*{ + return implementationFQN; + }*/ + ); + + // setImplementationFQN method + op = addOperation(entityEnum, "setImplementationFQN","void",ObjectModelJavaModifier.PUBLIC); + addAnnotation(entityEnum,op,Override.class); + addParameter(op,"String","implementationFQN"); + if (generateOperator) { + setOperationBody(op, "" +/*{ + this.implementationFQN = implementationFQN; + implementation = null; + // reinit the operators store + EntityOperatorStore.clear(); + }*/ + ); + } else { + setOperationBody(op, "" +/*{ + this.implementationFQN = implementationFQN; + this.implementation = null; + }*/ + ); + } + + // accept method + op = addOperation(entityEnum, "accept","boolean",ObjectModelJavaModifier.PUBLIC); + addAnnotation(entityEnum,op,Override.class); + addParameter(op,"Class<? extends TopiaEntity>","klass"); + setOperationBody(op, "" +/*{ + return <%=daoHelperClazzName%>.getContractClass(klass) == contract; + }*/ + ); + + // getImplementation method + op = addOperation(entityEnum, "getImplementation","Class<? extends TopiaEntity>",ObjectModelJavaModifier.PUBLIC); + addAnnotation(entityEnum,op,Override.class); + addImport(entityEnum, TopiaException.class); + setOperationBody(op, "" +/*{ + if (implementation == null) { + try { + implementation = (Class<? extends TopiaEntity>) Class.forName(implementationFQN); + } catch (ClassNotFoundException e) { + throw new TopiaException("could not find class " + implementationFQN, e); + } + } + return implementation; + }*/ + ); + + // valueOf method + op = addOperation(entityEnum, "valueOf", entityEnumName, ObjectModelJavaModifier.PUBLIC,ObjectModelJavaModifier.STATIC); + addParameter(op,"TopiaEntity", "entity"); + setOperationBody(op, "" +/*{ + return valueOf(entity.getClass()); + }*/ + ); + + // valueOf method + op = addOperation(entityEnum, "valueOf", entityEnumName, ObjectModelJavaModifier.PUBLIC,ObjectModelJavaModifier.STATIC); + addParameter(op,"Class<?>", "klass"); + setOperationBody(op, "" +/*{ + if (klass.isInterface()) { + return valueOf(klass.getSimpleName()); + } + for (<%=entityEnumName%> entityEnum : <%=entityEnumName%>.values()) { + if (entityEnum.getContract().isAssignableFrom(klass)) { + //todo check it works for inheritance + return entityEnum; + } + } + throw new IllegalArgumentException("no entity defined for the class " + klass + " in : " + Arrays.toString(<%=entityEnumName%>.values())); + }*/ + ); + } +} Copied: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/DTOTransformer.java (from rev 2882, trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DTOTransformer.java) =================================================================== --- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/DTOTransformer.java (rev 0) +++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/DTOTransformer.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,437 @@ +package org.nuiton.topia.templates; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.eugene.GeneratorUtil; +import org.nuiton.eugene.java.ObjectModelTransformerToJava; +import org.nuiton.eugene.models.object.*; + +import java.beans.PropertyChangeListener; +import java.beans.PropertyChangeSupport; +import java.io.Serializable; +import java.util.Collection; +import java.util.List; + + +/*{generator option: parentheses = false}*/ + +/*{generator option: writeString = +}*/ + +/** + * Created: 20 déc. 2009 + * + * @author tchemit <chemit@codelutin.com> + * @version $Id$ + * @since 2.3.0 + * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.templates.DTOTransformer" + */ +public class DTOTransformer extends ObjectModelTransformerToJava { + + /** + * Logger + */ + private static final Log log = LogFactory.getLog(DTOTransformer.class); + + @Override + public void transformFromClass(ObjectModelClass clazz) { + if (!TopiaGeneratorUtil.hasDtoStereotype(clazz)) { + return; + } + String clazzName = clazz.getName(); + ObjectModelClass result; + result = createClass(clazzName + "DTO", clazz.getPackageName()); + addImport(result, ToStringBuilder.class); + addImport(result, PropertyChangeListener.class); + + setDocumentation(result, "Implantation DTO pour l'entité " + StringUtils.capitalize(clazzName) + "."); + String extendClass = ""; + for (ObjectModelClass parent : clazz.getSuperclasses()) { + extendClass = parent.getQualifiedName() + "DTO"; + // no multi-inheritance in java + break; + } + if (extendClass.length() > 0) { + setSuperClass(result, extendClass); + } + + addInterface(result, Serializable.class); + for (ObjectModelInterface parentInterface : clazz.getInterfaces()) { + if (TopiaGeneratorUtil.hasDtoStereotype(parentInterface)) { + addInterface(result, parentInterface.getName() + "DTO"); + } else { + addInterface(result, parentInterface.getName()); + } + } + + addAttributes(result, clazz); + + addOperations(result, clazz); + } + + protected void addAttributes(ObjectModelClass result, ObjectModelClass clazz) { + + String svUID = TopiaGeneratorUtil.findTagValue("dto-serialVersionUID", clazz, model); + if (StringUtils.isNotEmpty(svUID)) { + addAttribute(result, "serialVersionUID", long.class, svUID, ObjectModelJavaModifier.FINAL, ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); + } + + addAttribute(result, "p", PropertyChangeSupport.class, null, ObjectModelJavaModifier.PROTECTED); + +/* +* Définition des attributs +*/ + ObjectModelAttribute attr2; + for (ObjectModelAttribute attr : clazz.getAttributes()) { + ObjectModelAttribute reverse = attr.getReverseAttribute(); + + String attributeName; + String attributeType; + if (!(attr.isNavigable() + || attr.hasAssociationClass())) { + continue; + } + + String attrName = attr.getName(); + String attrVisibility = attr.getVisibility(); + String attrType = attr.getType(); + if (!GeneratorUtil.isNMultiplicity(attr)) { + if (!attr.hasAssociationClass()) { + if (isDTO(attrType)) { + attrType += "DTO"; + } + attributeType = attrType; + attributeName = attrName; + } else { + String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(attr); + attributeType = attr.getAssociationClass().getQualifiedName(); + attributeName = GeneratorUtil.toLowerCaseFirstLetter(assocAttrName); + } + } else { + if (!attr.hasAssociationClass()) { + String nMultType; + if (attr.isOrdered()) { + nMultType = List.class.getName() + "<"; + } else { + nMultType = Collection.class.getName() + "<"; + } + nMultType += attrType; + if (isDTO(attrType)) { + nMultType += "DTO"; + } + nMultType += ">"; + + attributeType = nMultType; + attributeName = attrName; + } else { + String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(attr); + String assocClassFQN = attr.getAssociationClass().getQualifiedName(); + String nMultType; + if (attr.isOrdered()) { + nMultType = List.class.getName() + "<"; + } else { + nMultType = Collection.class.getName() + "<"; + } + nMultType += assocClassFQN; + if (isDTO(attrType)) { + nMultType += "DTO"; + } + nMultType += ">"; + attributeType = nMultType; + attributeName = GeneratorUtil.toLowerCaseFirstLetter(assocAttrName); + } + } + + attr2 = addAttribute(result, attributeName, attributeType, null, ObjectModelJavaModifier.PROTECTED); + + if (attr2 != null) { + if (TopiaGeneratorUtil.hasDocumentation(attr)) { + setDocumentation(attr2, attr.getDocumentation()); + } + String annotation = TopiaGeneratorUtil.getAnnotationTagValue(attr); + if (StringUtils.isNotEmpty(annotation)) { + addAnnotation(result, attr2, annotation); + } + } + } /* end for*/ + + //Déclaration des attributs d'une classe d'associations + if (clazz instanceof ObjectModelAssociationClass) { + ObjectModelAssociationClass assoc = (ObjectModelAssociationClass) clazz; + for (ObjectModelAttribute attr : assoc.getParticipantsAttributes()) { + if (attr != null) { + String attrName = attr.getName(); + String attrVisibility = attr.getVisibility(); + String attrType = attr.getType(); + if (isDTO(attrType)) { + attrType += "DTO"; + } + addAttribute(result, GeneratorUtil.toLowerCaseFirstLetter(attrName), attrType); + } + } + } + + } + + protected void addOperations(ObjectModelClass result, ObjectModelClass clazz) { + ObjectModelOperation op; + op = addOperation(result, "addPropertyChangeListener", "void", ObjectModelJavaModifier.PUBLIC); + addParameter(op, PropertyChangeListener.class, "listener"); + setOperationBody(op, "" +/*{ + p.addPropertyChangeListener(listener); + }*/ + ); + + op = addOperation(result, "addPropertyChangeListener", "void", ObjectModelJavaModifier.PUBLIC); + addParameter(op, String.class, "propertyName"); + addParameter(op, PropertyChangeListener.class, "listener"); + setOperationBody(op, "" +/*{ + p.addPropertyChangeListener(propertyName, listener); + }*/ + ); + + op = addOperation(result, "removePropertyChangeListener", "void", ObjectModelJavaModifier.PUBLIC); + addParameter(op, PropertyChangeListener.class, "listener"); + setOperationBody(op, "" +/*{ + p.removePropertyChangeListener(listener); + }*/ + ); + + op = addOperation(result, "removePropertyChangeListener", "void", ObjectModelJavaModifier.PUBLIC); + addParameter(op, String.class, "propertyName"); + addParameter(op, PropertyChangeListener.class, "listener"); + setOperationBody(op, "" +/*{ + p.removePropertyChangeListener(propertyName, listener); + }*/ + ); + /* + * Définition des getteurs et setteurs + */ + for (ObjectModelAttribute attr : clazz.getAttributes()) { + + ObjectModelAttribute reverse = attr.getReverseAttribute(); + +// if (!(attr.isNavigable() || hasUnidirectionalRelationOnAbstractType(reverse, model))) { + if (!attr.isNavigable()) { + continue; + } + + String attrName = attr.getName(); + String attrType = attr.getType(); + String attrTypeDTO = attr.getType(); + if (isDTO(attrType)) { + attrTypeDTO += "DTO"; + } + + if (!GeneratorUtil.isNMultiplicity(attr)) { + if (!attr.hasAssociationClass()) { + op = addOperation(result, "set" + StringUtils.capitalize(attrName), "void", ObjectModelJavaModifier.PUBLIC); + addParameter(op, attrTypeDTO, "value"); + setOperationBody(op, "" +/*{ + <%=attrTypeDTO%> oldValue = this.<%=attrName%>; + this.<%=attrName%> = value; + p.firePropertyChange("<%=attrName%>", oldValue, value); + }*/ + ); + + op = addOperation(result, "get" + StringUtils.capitalize(attrName), attrTypeDTO, ObjectModelJavaModifier.PUBLIC); + setOperationBody(op, "" +/*{ + return <%=attrName%>; + }*/ + ); + + } else { + String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(attr); + String assocClassFQN = attr.getAssociationClass().getQualifiedName(); + if (log.isTraceEnabled()) { + log.trace("assocAttrName: " + assocAttrName); + } + op = addOperation(result, "set" + StringUtils.capitalize(assocAttrName), "void", ObjectModelJavaModifier.PUBLIC); + addParameter(op, assocClassFQN + "DTO", "association"); + setOperationBody(op, "" +/*{ + <%=assocClassFQN%>DTO oldAssocation = this.<%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%>; + this.<%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%> = association; + p.firePropertyChange("<%=attrName%>", oldAssocation, assocation); + }*/ + ); + + op = addOperation(result, "get" + StringUtils.capitalize(assocAttrName), assocClassFQN + "DTO", ObjectModelJavaModifier.PUBLIC); + setOperationBody(op, "" +/*{ + return <%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%>; + }*/ + ); + } + } else { //NMultiplicity + if (!attr.hasAssociationClass()) { //Méthodes remplacées par des accesseurs sur les classes d'assoc + + String nMultType; + if (attr.isOrdered()) { + nMultType = List.class.getName() + "<" + attrTypeDTO + ">"; + } else { + nMultType = Collection.class.getName() + "<" + attrTypeDTO + ">"; + } + op = addOperation(result, "set" + StringUtils.capitalize(attrName), "void", ObjectModelJavaModifier.PUBLIC); + addParameter(op, nMultType, "values"); + setOperationBody(op, "" +/*{ + <%=nMultType%> oldValues = this.<%=attrName%>; + this.<%=attrName%> = values; + p.firePropertyChange("<%=attrName%>", oldValues, values); + }*/ + ); + + op = addOperation(result, "addChild" + StringUtils.capitalize(attrName), attrTypeDTO, ObjectModelJavaModifier.PUBLIC); + addParameter(op, attrTypeDTO, attrName); + StringBuilder buffercode = new StringBuilder(); + + buffercode.append("" +/*{ + this.<%=attrName%>.add(<%=attrName%>); + }*/ + ); + + if (reverse != null && reverse.isNavigable()) { + String reverseAttrName = reverse.getName(); + buffercode.append("" +/*{ <%=attrName%>.set<%=StringUtils.capitalize(reverseAttrName)%>(this); + }*/ + ); + } + buffercode.append("" +/*{ return <%=attrName%>; + }*/ + ); + setOperationBody(op, buffercode.toString()); + + op = addOperation(result, "removeChild", "void"); + addParameter(op, attrTypeDTO, attrName); + + buffercode = new StringBuilder(); + buffercode.append("" +/*{ + this.<%=attrName%>.remove(<%=attrName%>); + }*/ + ); + + if (reverse != null && reverse.isNavigable()) { + String reverseAttrName = reverse.getName(); + buffercode.append("" +/*{ <%=attrName%>.set<%=StringUtils.capitalize(reverseAttrName)%>(null); + }*/ + ); + } + setOperationBody(op, buffercode.toString()); + + } else { + String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(attr); + String assocClassFQN = attr.getAssociationClass().getQualifiedName(); + String nMultType; + if (attr.isOrdered()) { + nMultType = List.class.getName() + "<" + assocClassFQN + "DTO>"; + } else { + nMultType = Collection.class.getName() + "<" + assocClassFQN + "DTO>"; + } + if (log.isTraceEnabled()) { + log.trace("assocAttrName: " + assocAttrName); + } + op = addOperation(result, "set" + StringUtils.capitalize(assocAttrName), "void"); + addParameter(op, nMultType, "values"); + setOperationBody(op, "" +/*{ + <%=nMultType%> oldValues = this.<%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%>; + this.<%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%> = values; + p.firePropertyChange("<%=attrName%>", oldValues, values); + }*/ + ); + } + if (!attr.hasAssociationClass()) { + String nMultType; + if (attr.isOrdered()) { + nMultType = List.class.getName() + "<" + attrTypeDTO + ">"; + } else { + nMultType = Collection.class.getName() + "<" + attrTypeDTO + ">"; + } + op = addOperation(result, "get" + StringUtils.capitalize(attrName), nMultType); + setOperationBody(op, "" +/*{ + return this.<%=attrName%>; + }*/ + ); + } else { + String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(attr); + String assocClassFQN = attr.getAssociationClass().getQualifiedName(); + String nMultType; + if (attr.isOrdered()) { + nMultType = List.class.getName() + "<" + assocClassFQN + "DTO>"; + } else { + nMultType = Collection.class.getName() + "<" + assocClassFQN + "DTO>"; + } + if (log.isTraceEnabled()) { + log.trace("assocAttrName: " + assocAttrName); + } + op = addOperation(result, "get" + StringUtils.capitalize(assocAttrName), nMultType); + setOperationBody(op, "" +/*{ + return this.<%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%>; + }*/ + ); + } + } + } + + op = addOperation(result, "toString", String.class, ObjectModelJavaModifier.PUBLIC); + StringBuilder buffer = new StringBuilder(); + + buffer.append("" +/*{ + String result = new ToStringBuilder(this). +}*/ + ); + + for (Object o : clazz.getAttributes()) { + ObjectModelAttribute attr = (ObjectModelAttribute) o; + if (!(attr.isNavigable() + || attr.hasAssociationClass())) { + continue; + } + //FIXME possibilité de boucles (non directes) + ObjectModelClass attrEntity = null; + if (model.hasClass(attr.getType())) { + attrEntity = model.getClass(attr.getType()); + } + boolean isDTO = attrEntity != null && + TopiaGeneratorUtil.isEntity(attrEntity); //THIMEL : STEREOTYPE ENTITY ??? + ObjectModelAttribute reverse = attr.getReverseAttribute(); + if (isDTO && (reverse == null || !reverse.isNavigable()) && !attr.hasAssociationClass() || !isDTO) { + String attrName = attr.getName(); + buffer.append("" +/*{ append("<%=attrName%>", this.<%=attrName%>). +}*/ + ); + } + } + buffer.append("" +/*{ toString(); + return result; + }*/ + ); + setOperationBody(op, buffer.toString()); + } + + public boolean isDTO(String type) { + ObjectModelClassifier clazz = model.getClassifier(type); + return clazz != null && TopiaGeneratorUtil.hasDtoStereotype(clazz); + } + + +} + Copied: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityDTOTransformer.java (from rev 2882, trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityDTOTransformer.java) =================================================================== --- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityDTOTransformer.java (rev 0) +++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityDTOTransformer.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,343 @@ + +package org.nuiton.topia.templates; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.nuiton.eugene.GeneratorUtil; +import org.nuiton.eugene.java.ObjectModelTransformerToJava; +import org.nuiton.eugene.models.object.ObjectModelAssociationClass; +import org.nuiton.eugene.models.object.ObjectModelAttribute; +import org.nuiton.eugene.models.object.ObjectModelClass; +import org.nuiton.eugene.models.object.ObjectModelClassifier; +import org.nuiton.eugene.models.object.ObjectModelJavaModifier; +import org.nuiton.eugene.models.object.ObjectModelModifier; +import org.nuiton.eugene.models.object.ObjectModelOperation; +import org.nuiton.topia.templates.TopiaGeneratorUtil; + +import java.beans.PropertyChangeListener; +import java.beans.PropertyChangeSupport; +import java.io.Serializable; + +import static org.nuiton.topia.templates.TopiaGeneratorUtil.hasUnidirectionalRelationOnAbstractType; +import static org.nuiton.topia.templates.TopiaGeneratorUtil.shouldGenerateDTOTopiaIdTagValue; + + +/*{generator option: parentheses = false}*/ + +/*{generator option: writeString = +}*/ + +/** + * Created: 14 déc. 2009 + * + * @author tchemit <chemit@codelutin.com> + * @version $Id$ + * @since 2.3.0 + * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.templates.EntityDTOTransformer" + * @deprecated since 3.0, will not be replaced + */ +@Deprecated +public class EntityDTOTransformer extends ObjectModelTransformerToJava { + + public boolean isEntity(String type) { + ObjectModelClassifier clazz = model.getClassifier(type); + return clazz != null && ! clazz.isEnum() + && TopiaGeneratorUtil.isEntity(clazz); + } + + @Override + public void transformFromClass(ObjectModelClass clazz) { + if (!TopiaGeneratorUtil.isEntity(clazz)) { + return; + } + String clazzName = clazz.getName(); + ObjectModelClass result; + result = createClass(clazzName + "DTO", clazz.getPackageName()); + addImport(result, ToStringBuilder.class); + addImport(result, PropertyChangeListener.class); + + setDocumentation(result, "Implantation DTO pour l'entité " + StringUtils.capitalize(clazzName) + "."); + String extendClass = ""; + for (ObjectModelClass parent : clazz.getSuperclasses()) { + extendClass = parent.getQualifiedName() + "DTO"; + // no multi-inheritance in java + break; + } + if (extendClass.length() > 0) { + setSuperClass(result, extendClass); + } + addInterface(result, Serializable.class); + + + addAttributes(result,clazz); + + addOperations(result,clazz); + + } + + protected void addAttributes(ObjectModelClass result, ObjectModelClass clazz) { + + String svUID = TopiaGeneratorUtil.findTagValue("dto-serialVersionUID", clazz, model); + if (svUID != null) { + addAttribute(result, "serialVersionUID", "long", svUID, ObjectModelJavaModifier.FINAL, ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); + } + + boolean generateDTOId = shouldGenerateDTOTopiaIdTagValue(clazz, model); + if (generateDTOId) { + addAttribute(result, "topiaId", "String"); + } + + ObjectModelAttribute attr2; + for (ObjectModelAttribute attr : clazz.getAttributes()) { + ObjectModelAttribute reverse = attr.getReverseAttribute(); + + // pour les asso quoi qu'il arrive il faut les lier des 2 cotes + // pour pouvoir supprimer en cascade l'asso lors de la suppression + // d'un des cotes + if (!(attr.isNavigable() + || hasUnidirectionalRelationOnAbstractType(reverse, model) + || attr.hasAssociationClass())) { + continue; + } + + String attrVisibility = attr.getVisibility(); + ObjectModelModifier modifier = ObjectModelJavaModifier.fromVisibility(attrVisibility); + if (!attr.hasAssociationClass()) { + String attrType = attr.getType(); + String attrName = attr.getName(); + if (isEntity(attrType)) { + attrType += "DTO"; + } + if (!GeneratorUtil.isNMultiplicity(attr)) { + attr2 = addAttribute(result, attrName, attrType, null, modifier); + } else { + attr2 = addAttribute(result, attrName, attrType + "[]", null, modifier); + } + } else { + String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(attr); + String assocClassFQN = attr.getAssociationClass().getQualifiedName(); + if (!GeneratorUtil.isNMultiplicity(attr)) { + attr2 = addAttribute(result, GeneratorUtil.toLowerCaseFirstLetter(assocAttrName), assocClassFQN + "DTO", null, modifier); + } else { + attr2 = addAttribute(result, GeneratorUtil.toLowerCaseFirstLetter(assocAttrName), assocClassFQN + "DTO[]", null, modifier); + } + } + if (attr2 != null) { + if (TopiaGeneratorUtil.hasDocumentation(attr)) { + setDocumentation(attr2, attr.getDocumentation()); + } + + String annotation = TopiaGeneratorUtil.getAnnotationTagValue(attr); + if (!StringUtils.isEmpty(annotation)) { + addAnnotation(result, attr2, annotation); + } + } + } + + //Déclaration des attributs d'une classe d'associations + if (clazz instanceof ObjectModelAssociationClass) { + ObjectModelAssociationClass assoc = (ObjectModelAssociationClass) clazz; + for (ObjectModelAttribute attr : assoc.getParticipantsAttributes()) { + if (attr != null) { + String attrVisibility = attr.getVisibility(); + ObjectModelModifier modifier = ObjectModelJavaModifier.fromVisibility(attrVisibility); + String attrType = attr.getType(); + String attrName = attr.getName(); + if (isEntity(attrType)) { + attrType += "DTO"; + } + addAttribute(result, GeneratorUtil.toLowerCaseFirstLetter(attrName), attrType, null, modifier); + } + } + } + + addAttribute(result,"p", PropertyChangeSupport.class,"new PropertyChangeSupport(this)",ObjectModelJavaModifier.PROTECTED,ObjectModelJavaModifier.FINAL); + } + + protected void addOperations(ObjectModelClass result,ObjectModelClass clazz) { + + boolean generateDTOId = shouldGenerateDTOTopiaIdTagValue(clazz, model); + ObjectModelOperation op; + if (generateDTOId) { + op = addOperation(result, "setTopiaId", "void", ObjectModelJavaModifier.PUBLIC); + addParameter(op, "String", "topiaId"); + setOperationBody(op, "" +/*{ + this.topiaId = topiaId; + }*/ + ); + + op = addOperation(result, "getTopiaId", "String", ObjectModelJavaModifier.PUBLIC); + setOperationBody(op, "" +/*{ + return topiaId; + }*/ + ); + } + + op = addOperation(result, "addPropertyChangeListener", "void"); + addParameter(op,PropertyChangeListener.class,"listener"); + setOperationBody(op,"" +/*{ + p.addPropertyChangeListener(listener); + }*/ + ); + + op = addOperation(result, "addPropertyChangeListener", "void"); + addParameter(op, String.class, "propertyName"); + addParameter(op, PropertyChangeListener.class, "listener"); + setOperationBody(op, "" +/*{ + p.addPropertyChangeListener(propertyName, listener); + }*/ + ); + + op = addOperation(result, "removePropertyChangeListener", "void"); + addParameter(op, PropertyChangeListener.class, "listener"); + setOperationBody(op, "" +/*{ + p.removePropertyChangeListener(listener); + }*/ + ); + + op = addOperation(result, "removePropertyChangeListener", "void"); + addParameter(op, String.class, "propertyName"); + addParameter(op, PropertyChangeListener.class, "listener"); + setOperationBody(op, "" +/*{ + p.removePropertyChangeListener(propertyName, listener); + }*/ + ); + + for (ObjectModelAttribute attr : clazz.getAttributes()) { + + ObjectModelAttribute reverse = attr.getReverseAttribute(); + + if (!(attr.isNavigable() || hasUnidirectionalRelationOnAbstractType(reverse, model))) { + continue; + } + + String attrName = attr.getName(); + + if (!attr.hasAssociationClass()) { + String attrType = attr.getType(); + if (isEntity(attrType)) { + attrType += "DTO"; + } + String setterName = getJavaBeanMethodName("set", attrName); + String getterName = getJavaBeanMethodName("get", attrName); + if (!GeneratorUtil.isNMultiplicity(attr)) { + op = addOperation(result, setterName, "void", ObjectModelJavaModifier.PUBLIC); + addParameter(op, attrType, "value"); + setOperationBody(op, "" +/*{ + <%=attrType%> oldValue = this.<%=attrName%>; + this.<%=attrName%> = value; + p.firePropertyChange("<%=attrName%>", oldValue, value); + }*/ + ); + + op = addOperation(result, getterName, attrType, ObjectModelJavaModifier.PUBLIC); + setOperationBody(op, "" +/*{ + return <%=attrName%>; + }*/ + ); + + } else { + + op = addOperation(result, setterName, "void", ObjectModelJavaModifier.PUBLIC); + addParameter(op, attrType+"[]", "values"); + setOperationBody(op, "" +/*{ + <%=attrType%>[] oldValues = this.<%=attrName%>; + this.<%=attrName%> = values; + p.firePropertyChange("<%=attrName%>", oldValues, values); + }*/ + ); + + op = addOperation(result, getterName, attrType+"[]", ObjectModelJavaModifier.PUBLIC); + setOperationBody(op, "" +/*{ + return <%=attrName%>; + }*/ + ); + } + } else { + String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(attr); + String propertyName = GeneratorUtil.toLowerCaseFirstLetter(assocAttrName); + String assocClassFQN = attr.getAssociationClass().getQualifiedName(); + String setterName = getJavaBeanMethodName("set", assocAttrName); + String getterName = getJavaBeanMethodName("get", assocAttrName); + if (!GeneratorUtil.isNMultiplicity(attr)) { + op = addOperation(result, setterName, "void", ObjectModelJavaModifier.PUBLIC); + addParameter(op, assocClassFQN + "DTO", "association"); + setOperationBody(op, "" +/*{ + <%=assocClassFQN%>DTO oldAssocation= this.<%=propertyName%>; + this.<%=propertyName%> = association; + p.firePropertyChange("<%=attrName%>", oldAssocation, assocation); + }*/ + ); + + op = addOperation(result, getterName, assocClassFQN + "DTO", ObjectModelJavaModifier.PUBLIC); + setOperationBody(op, "" +/*{ + return <%=propertyName%>; + }*/ + ); + + } else { + op = addOperation(result, setterName, "void", ObjectModelJavaModifier.PUBLIC); + addParameter(op, assocClassFQN + "DTO[]", "values"); + setOperationBody(op, "" +/*{ + <%=assocClassFQN%>DTO[] oldValues = this.<%=propertyName%>; + this.<%=propertyName%> = values; + p.firePropertyChange("<%=attrName%>", oldValues, values); + }*/ + ); + + op = addOperation(result, getterName, assocClassFQN + "DTO[]", ObjectModelJavaModifier.PUBLIC); + setOperationBody(op, "" +/*{ + return this.<%=propertyName%>; + }*/ + ); + } + } + } + + op = addOperation(result,"toString",String.class, ObjectModelJavaModifier.PUBLIC); + StringBuilder buffer = new StringBuilder(); + + buffer.append("" +/*{ + String result = new ToStringBuilder(this). +}*/ + ); + + for (Object o : clazz.getAttributes()) { + ObjectModelAttribute attr = (ObjectModelAttribute) o; + //FIXME possibilité de boucles (non directes) + ObjectModelClass attrEntity = null; + if (model.hasClass(attr.getType())) { + attrEntity = model.getClass(attr.getType()); + } + boolean isEntity = attrEntity != null && TopiaGeneratorUtil.isEntity(attrEntity); + ObjectModelAttribute reverse = attr.getReverseAttribute(); + if (isEntity && (reverse == null || !reverse.isNavigable()) && !attr.hasAssociationClass() || !isEntity) { + String attrName = attr.getName(); + buffer.append("" +/*{ append("<%=attrName%>", this.<%=attrName%>). +}*/ + ); + } + } + buffer.append("" +/*{ toString(); + return result; +}*/ + ); + setOperationBody(op, buffer.toString()); + } +} Copied: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityDaoTransformer.java (from rev 2882, trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityDaoTransformer.java) =================================================================== --- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityDaoTransformer.java (rev 0) +++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityDaoTransformer.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,1138 @@ +package org.nuiton.topia.templates; + +/*{generator option: parentheses = false}*/ +/*{generator option: writeString = +}*/ + +import com.google.common.base.Strings; +import com.google.common.collect.Sets; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.eugene.GeneratorUtil; +import org.nuiton.eugene.java.JavaGeneratorUtil; +import org.nuiton.eugene.java.ObjectModelTransformerToJava; +import org.nuiton.eugene.models.object.ObjectModel; +import org.nuiton.eugene.models.object.ObjectModelAssociationClass; +import org.nuiton.eugene.models.object.ObjectModelAttribute; +import org.nuiton.eugene.models.object.ObjectModelClass; +import org.nuiton.eugene.models.object.ObjectModelClassifier; +import org.nuiton.eugene.models.object.ObjectModelDependency; +import org.nuiton.eugene.models.object.ObjectModelInterface; +import org.nuiton.eugene.models.object.ObjectModelJavaModifier; +import org.nuiton.eugene.models.object.ObjectModelOperation; +import org.nuiton.topia.TopiaException; +import org.nuiton.topia.persistence.TopiaEntity; +import org.nuiton.topia.persistence.TopiaQueryBuilderAddCriteriaOrRunQueryStep; + +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; + +/** + * To generate all <code>DAO</code> related classes for a given entity. + * + * @author tchemit <chemit@codelutin.com> + * @since 2.5.4 + * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.templates.EntityDaoTransformer" + */ +public class EntityDaoTransformer extends ObjectModelTransformerToJava { + + /** Logger. */ + private static final Log log = + LogFactory.getLog(EntityDaoTransformer.class); + + /** + * map of direct usages (values) for each entity (key). + * <p/> + * This map is used to generate the findUsages methods for DAOAbstract. + */ + protected Map<ObjectModelClass, Set<ObjectModelClass>> usages; + + /** + * All entities fqn of the model (used to detect if an attribute is not + * an entity). + */ + protected Set<String> allEntitiesFqn; + + /** + * The class of abstract dao to use. + * @since 2.5 + */ + protected Class<?> daoImplementation; + + protected String entityEnumName; + + protected String entityEnumPackage; + + /** + * Map of extra operations for DAO. The key of the map is the qualified + * name of the entity relative to the DAO. + */ + protected Map<String, Collection<ObjectModelOperation>> extraOperations = + new HashMap<String, Collection<ObjectModelOperation>>(); + + @Override + public void transformFromModel(ObjectModel model) { + + boolean generateStandaloneEnum = + TopiaGeneratorUtil.shouldGenerateStandaloneEnumForDAOHelper(model); + String modelName = model.getName(); + + entityEnumName = modelName + "EntityEnum"; + + String packageName = + getOutputProperties().getProperty(PROP_DEFAULT_PACKAGE); + + if (generateStandaloneEnum) { + entityEnumPackage = packageName + "." + entityEnumName; + } else { + String daoHelperClazzName = modelName + "DAOHelper"; + entityEnumPackage = packageName + "." + daoHelperClazzName + "." + entityEnumName; + } + + usages = TopiaGeneratorUtil.searchDirectUsages(model); + + daoImplementation = TopiaGeneratorUtil.getDAOImplementation(model); + + + // keep all classifiers on the model which are entities + List<ObjectModelClass> allEntities = + TopiaGeneratorUtil.getEntityClasses(model, true); + allEntitiesFqn = new HashSet<String>(allEntities.size()); + for (ObjectModelClass entity : allEntities) { + String fqn = entity.getQualifiedName(); + allEntitiesFqn.add(fqn); + Collection<ObjectModelOperation> daoOperations = + new HashSet<ObjectModelOperation>(); + for (ObjectModelOperation op : entity.getOperations()) { + if (TopiaGeneratorUtil.hasDaoStereotype(op)) { + daoOperations.add(op); + } + } + + if (daoOperations.isEmpty()) { + + // found some dao operations + extraOperations.put(fqn, daoOperations); + } + } + } + + @Override + public void transformFromInterface(ObjectModelInterface interfacez) { + if (!TopiaGeneratorUtil.hasDaoStereotype(interfacez)) { + return; + } + + /** + * EVO #636 : Manage extra operations for DAO from "dao" dependency + * between an interface with stereotype <<dao>> (dependency client) and + * a class with stereotype <<entity>> (dependency supplier). + */ + + ObjectModelDependency dependency = + interfacez.getDependency(TopiaGeneratorUtil.DEPENDENCIES_DAO); + + if (dependency == null) { + if (log.isWarnEnabled()) { + log.warn("Could not find dependency " + + TopiaGeneratorUtil.DEPENDENCIES_DAO + + " but DAO stereotype was placed on the interface " + + interfacez.getName()); + } + return; + } + + ObjectModelClassifier classifier = dependency.getSupplier(); + + if (!TopiaGeneratorUtil.isEntity(classifier)) { + + // dependency supplier is not an entity... + if (log.isWarnEnabled()) { + log.warn("Dependency supplier " + + classifier.getQualifiedName() + + " is not an entity."); + } + return; + } + + // keep only direct operations + Collection<ObjectModelOperation> operations = + interfacez.getOperations(); + + if (CollectionUtils.isEmpty(operations)) { + + // no operations on interface, this is not normal + if (log.isWarnEnabled()) { + log.warn("No operation found on interface with DAO " + + "stereotype "+classifier.getQualifiedName()); + } + return; + } + if (log.isDebugEnabled()) { + log.debug("add "+operations.size()+" extra operation(s) for DAO"); + } + + extraOperations.put(classifier.getQualifiedName(), operations); + } + + @Override + public void transformFromClass(ObjectModelClass clazz) { + if (!TopiaGeneratorUtil.isEntity(clazz)) { + // not an entity + return; + } + String clazzName = clazz.getName(); + String clazzFQN = clazz.getQualifiedName(); + + if (isGenerateGeneratedDao(clazz)) { + generateGeneratedDao(clazz, clazzName, clazzFQN); + } + + if (isGenerateAbstractDao(clazz)) { + generateAbstractDao(clazz, clazzName, clazzFQN); + } + + if (isGenerateLegacyDao(clazz)) { + generateLegacyDao(clazz, clazzName, clazzFQN); + } + + if (isGenerateConcreteDao(clazz)) { + generateConcreteDao(clazz, clazzName, clazzFQN); + } + + } + + protected boolean isGenerateLegacyDao(ObjectModelClass input) { + + String daoLegacyFqn = TopiaGeneratorUtil.getLegacyDaoFqn(input); + + if (isInClassPath(daoLegacyFqn)) { + + // already in class-path + return false; + } + + // can safely generate the dao impl + return true; + } + + protected boolean isGenerateConcreteDao(ObjectModelClass input) { + + String daoConcreteFqn = TopiaGeneratorUtil.getConcreteDaoFqn(input); + + if (isInClassPath(daoConcreteFqn)) { + + // already in class-path + return false; + } + + // can safely generate the dao impl + return true; + } + + protected boolean isGenerateGeneratedDao(ObjectModelClass input) { + + String daoGeneratedFqn = TopiaGeneratorUtil.getGeneratedDaoFqn(input); + + if (isInClassPath(daoGeneratedFqn)) { + + // already in class-path + return false; + } + + // can safely generate the dao impl + return true; + + } + + protected boolean isGenerateAbstractDao(ObjectModelClass input) { + + String fqn = TopiaGeneratorUtil.getAbstractDaoFqn(input); + + if (isInClassPath(fqn)) { + + // already in class-path + return false; + } + + Collection<ObjectModelOperation> moreOperations = + extraOperations.get(input.getQualifiedName()); + + if (CollectionUtils.isNotEmpty(moreOperations)) { + + // no user operations, can not generate it + return false; + } + + // can safely generate the dao impl + return true; + + } + + protected void generateLegacyDao(ObjectModelClass clazz, String clazzName, String clazzFQN) { + ObjectModelClass daoClass = createClass(TopiaGeneratorUtil.getLegacyDaoName(clazz), clazz.getPackageName()); + addAnnotation(daoClass, daoClass, Deprecated.class); + setDocumentation(daoClass, "/**\n" + + " * Cette classe etend le DAOImpl pour parametrer la classe avec le bon type\n" + + " * Cette classe est marque finale car l'heritage entre les DAO se fait\n" + + " * sur les DOAImpl, c-a-d que DAOAbstract peut etendre le DAOImpl\n" + + " */"); + setSuperClass(daoClass, TopiaGeneratorUtil.getAbstractDaoFqn(clazz) + "<" + clazzName + ">"); + } + + protected void generateConcreteDao(ObjectModelClass clazz, String clazzName, String clazzFQN) { + String concreteDaoName = TopiaGeneratorUtil.getConcreteDaoName(clazz); + ObjectModelClass daoClass = createClass(concreteDaoName, clazz.getPackageName()); + setDocumentation(daoClass, "/**\n" + + " * Cette classe etend le DAOImpl pour parametrer la classe avec le bon type\n" + + " * Cette classe est marque finale car l'heritage entre les DAO se fait\n" + + " * sur les DOAImpl, c-a-d que DAOAbstract peut etendre le DAOImpl\n" + + " */"); + // to support legacy dao + String superclassQualifiedName = TopiaGeneratorUtil.getLegacyDaoFqn(clazz); + // TODO brendan 04/10/13 above line should be replaced by +// String superclassQualifiedName = TopiaGeneratorUtil.getAbstractDaoFqn(clazz) + "<" + clazzName + ">"; + setSuperClass(daoClass, superclassQualifiedName); + + // TODO AThimel 25/10/13 Remove the next lines in ToPIA 3.1 + // Look for legacy Dao class, then warn user if found in classpath + String legacyConcreteDaoName = TopiaGeneratorUtil.getLegacyDaoName(clazz); + warnOnLegacyClassDetected(clazz.getPackageName(), legacyConcreteDaoName, concreteDaoName, null, + TopiaGeneratorUtil.getAbstractDaoFqn(clazz) + "<" + clazzName + ">"); + } + + protected void generateAbstractDao(ObjectModelClass clazz, + String clazzName, + String clazzFQN) { + + Collection<ObjectModelOperation> moreOperations = + extraOperations.get(clazz.getQualifiedName()); + + if (CollectionUtils.isEmpty(moreOperations)) { + + // no business Dao found, can safely generate the abstract Dao class + + String abstractDaoName = TopiaGeneratorUtil.getAbstractDaoName(clazz); + String daoGenerics = "<E extends " + clazzName + ">"; + ObjectModelClass abstractDaoClass = createClass(abstractDaoName + daoGenerics, clazz.getPackageName()); + String documentation = String.format("/**%n" + + " * Implantation du Dao pour l'entité '%s'.%n" + + " * L'utilisateur peut remplacer cette classe par la sienne en la mettant%n" + + " * simplement dans ses sources. Cette classe générée sera alors simplement%n" + + " * ignorée à la génération suivante.%n" + + " */", clazzName); + setDocumentation(abstractDaoClass, documentation); + String superclassQualifiedName = TopiaGeneratorUtil.getGeneratedDaoFqn(clazz) + "<E>"; + setSuperClass(abstractDaoClass, superclassQualifiedName); + + // TODO AThimel 25/10/13 Remove the next lines in ToPIA 3.1 + // Look for legacy Dao class, then warn user if found in classpath + String legacyDaoImplName = TopiaGeneratorUtil.getLegacyDaoName(clazz) + "Impl"; + warnOnLegacyClassDetected(clazz.getPackageName(), legacyDaoImplName, abstractDaoName, daoGenerics, + superclassQualifiedName); + + } + } + + // TODO AThimel 25/10/13 Remove this method in ToPIA 3.1 + protected void warnOnLegacyClassDetected(String packageName, + String legacyDaoName, + String daoName, + String daoGenerics, + String superclassQualifiedName) { + + String legacyDaoFqn = String.format("%s.%s", packageName, legacyDaoName); + + // AThimel 25/10/13 Not using isInClassPath(fqn) because this method logs that file won't be generated + if (log.isWarnEnabled() && getFileInClassPath(legacyDaoFqn) != null) { + String format = "public class %s%s extends %s {"; + String superclassName = superclassQualifiedName.substring(superclassQualifiedName.lastIndexOf('.') + 1); + String daoDeclaration = String.format(format, daoName, Strings.nullToEmpty(daoGenerics), superclassName); + String warnMessage = "Legacy DAO detected : %s !%n" + + " - You should consider renaming '%s' to '%s'%n" + + " - Expected class declaration is : %s%n" + + "%n"; // AThimel 29/10/13 Add a new line for log clearness + log.warn(String.format(warnMessage, legacyDaoFqn, legacyDaoName, daoName, daoDeclaration)); + } + + } + + protected void generateGeneratedDao(ObjectModelClass clazz, + String clazzName, + String clazzFQN) { + ObjectModelClass daoAbstractClass = createAbstractClass(TopiaGeneratorUtil.getGeneratedDaoName(clazz) + "<E extends " + clazzName + '>', + clazz.getPackageName()); + + // super class + + String superClassName = null; + for (ObjectModelClass parent : clazz.getSuperclasses()) { + if (TopiaGeneratorUtil.isEntity(parent)) { + superClassName = TopiaGeneratorUtil.getAbstractDaoFqn(parent) + "<E>"; + // in java no multi-inheritance + break; + } + } + if (superClassName == null) { + superClassName = daoImplementation.getName() + "<E>"; + } + if (log.isDebugEnabled()) { + log.debug("super class = " + superClassName); + } + setSuperClass(daoAbstractClass, superClassName); + + String prefix = getConstantPrefix(clazz, ""); + setConstantPrefix(prefix); + + // imports + + Collection<ObjectModelOperation> daoOperations = getDaoOperations(clazz); + + if (TopiaGeneratorUtil.isCollectionNeeded(daoOperations)) { + addImport(daoAbstractClass, Collection.class); + } + if (TopiaGeneratorUtil.isSetNeeded(daoOperations)) { + addImport(daoAbstractClass, Set.class); + } + addImport(daoAbstractClass, List.class); + addImport(daoAbstractClass, TopiaException.class); + addImport(daoAbstractClass, TopiaQueryBuilderAddCriteriaOrRunQueryStep.class); + + ObjectModelOperation op; + + // getEntityClass + + op = addOperation(daoAbstractClass, + "getEntityClass", + "Class<E>", + ObjectModelJavaModifier.PUBLIC); + addAnnotation(daoAbstractClass, op,Override.class); + setOperationBody(op, "" +/*{ + return (Class<E>) <%=clazzName%>.class; + }*/ + ); + + // getTopiaEntityEnum + addImport(daoAbstractClass, entityEnumPackage); + op = addOperation(daoAbstractClass, + "getTopiaEntityEnum", + entityEnumName, + ObjectModelJavaModifier.PUBLIC); + addAnnotation(daoAbstractClass, op,Override.class); + setOperationBody(op, "" +/*{ + return <%=entityEnumName%>.<%=clazzName%>; + }*/ + ); + + generateDAOOperations(daoAbstractClass, daoOperations); + + generateDelete(clazz, daoAbstractClass); + + generateNaturalId(daoAbstractClass, clazz); + + generateNotNull(daoAbstractClass, clazz); + + for (ObjectModelAttribute attr : clazz.getAttributes()) { + if (!attr.isNavigable()) { + continue; + } + + if (!GeneratorUtil.isNMultiplicity(attr)) { + generateNoNMultiplicity(clazzName, daoAbstractClass, attr, false); + } else { + generateNMultiplicity(clazzName, daoAbstractClass, attr); + } + } + + if (clazz instanceof ObjectModelAssociationClass) { + ObjectModelAssociationClass assocClass = + (ObjectModelAssociationClass) clazz; + for (ObjectModelAttribute attr : assocClass.getParticipantsAttributes()) { + if (attr != null) { + if (!GeneratorUtil.isNMultiplicity(attr)) { + generateNoNMultiplicity(clazzName, daoAbstractClass, attr, true); + } else { + generateNMultiplicity(clazzName, daoAbstractClass, attr); + } + } + } + } + + Set<ObjectModelClass> usagesForclass = usages.get(clazz); + generateFindUsages(clazz, daoAbstractClass, usagesForclass); + } + + protected void generateDelete(ObjectModelClass clazz, + ObjectModelClass result) { + + StringBuilder body = new StringBuilder(); + String modelName = StringUtils.capitalize(model.getName()); + String providerFQN = getOutputProperties().getProperty( + PROP_DEFAULT_PACKAGE) + '.' + modelName + + "DAOHelper.getImplementationClass"; + + for (ObjectModelAttribute attr : clazz.getAttributes()) { + + String attrType = GeneratorUtil.getSimpleName(attr.getType()); + + String reverseAttrName = attr.getReverseAttributeName(); + ObjectModelAttribute reverse = attr.getReverseAttribute(); + if (attr.hasAssociationClass() || + reverse == null || !reverse.isNavigable()) { + + // never treate a non reverse and navigable attribute + // never treate an association class attribute + continue; + } + + // at this point we are sure to have a attribute which is + // - reverse + // - navigable + // - not from an association class + if (!allEntitiesFqn.contains(attr.getType())) { + + // this attribute is not from an entity, don't treate it + if (log.isDebugEnabled()) { + log.debug("[" + result.getName() + "] Skip attribute [" + + attr.getName() + "] with type " + attr.getType()); + } + continue; + } + + // At this point, the attribute type is a entity + if (GeneratorUtil.isNMultiplicity(attr) && + GeneratorUtil.isNMultiplicity(reverse)) { + // On doit absolument supprimer pour les relations many-to-many + // le this de la collection de l'autre cote + + String attrDBName = TopiaGeneratorUtil.getDbName(attr); + String attrClassifierDBName = TopiaGeneratorUtil.getDbName(attr.getClassifier()); + String attrJoinTableName = TopiaGeneratorUtil.getManyToManyTableName(attr); + String attrReverseDBName = TopiaGeneratorUtil.getReverseDbName(attr); + + //FIXME_-FC-20100413 Use a TopiaQuery (use HQLin elements) +// // Add DAOHelper +// String daoHelper = modelName + "DAOHelper"; +// String daoHelperFQN = getOutputProperties(). +// getProperty(PROP_DEFAULT_PACKAGE) + '.' + daoHelper; +// addImport(result, daoHelperFQN); +// +// // Add import for TopiaQuery +// addImport(result, TopiaQuery.class); +// +// // Entity DAO and reversePropertyName +// String entityDAO = attrType + "DAO"; +// String reverseAttrNameProperty = +// attrType + "." + getConstantName(reverseAttrName); +// +// +// <%=entityDAO%> dao = <%=daoHelper%>.get<%=entityDAO%>(getTopiaContext()); +// TopiaQuery query = dao.createQuery("B"). +// addFrom(entity.getClass(), "A"). +// add("A", entity). +// addInElements("A", "B." + <%=reverseAttrNameProperty%>); +// +// System.out.println("Query : " + query); +// List<<%=attrType%>> list = dao.findAllByQuery(query); + + String removeName = getJavaBeanMethodName("remove", reverseAttrName); + body.append("" +/*{ + { + List<<%=attrType%>> list = topiaHibernateSupport.getHibernateSession().createSQLQuery( + "SELECT main.topiaid " + + "from <%=attrClassifierDBName%> main, <%=attrJoinTableName%> secondary " + + "where main.topiaid=secondary.<%=attrDBName%>" + + " and secondary.<%=attrReverseDBName%>='" + entity.getTopiaId() + "'") + .addEntity("main", <%=providerFQN%>(<%=attrType%>.class)).list(); + + for (<%=attrType%> item : list) { + item.<%=removeName%>(entity); + } + } +}*/ + ); + } else if (!GeneratorUtil.isNMultiplicity(reverse)) { + // On doit mettre a null les attributs qui ont cet objet sur les + // autres entites en one-to-* + // TODO peut-etre qu'hibernate est capable de faire ca tout seul ? + // THIMEL: J'ai remplacé reverse.getName() par reverseAttrName sans certitude + addImport(result, attrType); + addImport(result, attr.getType() + "TopiaDao"); // AThimel 30/10/13 Not using attrType because we need FQN // Can use TopiaGeneratorUtil.getConcreteDaoFqn(...) ? + String attrSimpleType = TopiaGeneratorUtil.getClassNameFromQualifiedName(attrType); + // XXX brendan 04/10/13 do not hard code concrete dao name + String attrConcreteDaoClassName = attrSimpleType + "TopiaDao"; + String getName = getJavaBeanMethodName("get", reverseAttrName); + String setName = getJavaBeanMethodName("set", reverseAttrName); + + body.append("" + /*{ + { + <%=attrConcreteDaoClassName%> dao = topiaDaoSupplier + .getDao(<%=attrSimpleType%>.class, <%=attrConcreteDaoClassName%>.class); + List<<%=attrSimpleType%>> list = dao + .forProperties(<%=attrSimpleType%>.<%=getConstantName(reverseAttrName)%>, entity) + .findAll(); + for (<%=attrSimpleType%> item : list) { + + // sletellier : Set null only if target is concerned by deletion + if (entity.equals(item.<%=getName%>())) { + item.<%=setName%>(null); + } + }*/ + ); + if (attr.isAggregate()) { + body.append("" +/*{ + topiaDaoSupplier.getDao(<%=attrSimpleType%>.class).delete(item); +}*/ + ); + } + body.append("" +/*{ + } + } +}*/ + ); + + } + } + + if (body.length()>0) { + // something specific was done, need to generate the method + ObjectModelOperation op; + op = addOperation(result, "delete", "void", ObjectModelJavaModifier.PUBLIC); + addAnnotation(result, op,Override.class); + addParameter(op, "E", "entity"); + body.append("" +/*{ + super.delete(entity); + }*/ + ); + setOperationBody(op, body.toString()); + } + + + + } + + protected void generateFindUsages(ObjectModelClass clazz, + ObjectModelClass result, + Set<ObjectModelClass> usagesForclass) { + + builder.addImport(result, LinkedList.class.getName()); + builder.addImport(result, Map.class.getName()); + builder.addImport(result, HashMap.class.getName()); + builder.addImport(result, TopiaEntity.class.getName()); + + if (clazz instanceof ObjectModelAssociationClass || + usagesForclass.isEmpty()) { + // not for an association class + // just let a null method + ObjectModelOperation operation; + operation = addOperation(result, + "findUsages", + "<U extends TopiaEntity> List<U>", + ObjectModelJavaModifier.PUBLIC); + + addParameter(operation, "Class<U>", "type"); + addParameter(operation, "E", "entity"); + addAnnotation(result, operation, Override.class); + setOperationBody(operation, "" +/*{ + return new LinkedList<U>(); + }*/ + ); + + operation = addOperation(result, + "findAllUsages", + "Map<Class<? extends TopiaEntity>, List<? extends TopiaEntity>>", + ObjectModelJavaModifier.PUBLIC); + + addParameter(operation, "E", "entity"); + addAnnotation(result, operation, Override.class); + setOperationBody(operation, "" +/*{ + return new HashMap<Class<? extends TopiaEntity>, List<? extends TopiaEntity>>(); + }*/ + ); + + return; + } + List<ObjectModelClass> allEntities; + Map<String, ObjectModelClass> allEntitiesByFQN; + + allEntities = TopiaGeneratorUtil.getEntityClasses(model, true); + allEntitiesByFQN = new TreeMap<String, ObjectModelClass>(); + + // prepare usages map and fill allEntitiesByFQN map + for (ObjectModelClass klass : allEntities) { + allEntitiesByFQN.put(klass.getQualifiedName(), klass); + } + + ObjectModelOperation operation; + operation = addOperation(result, + "findUsages", + "<U extends TopiaEntity> List<U>", + ObjectModelJavaModifier.PUBLIC); + + addParameter(operation, "Class<U>", "type"); + addParameter(operation, "E", "entity"); + addAnnotation(result, operation, Override.class); + StringBuilder buffer = new StringBuilder(300); + buffer.append("" +/*{ + List<?> result = new LinkedList(); + List tmp; +}*/ + ); + + for (ObjectModelClass usageClass : usagesForclass) { + String usageType = usageClass.getQualifiedName(); + builder.addImport(result, usageType); + String usageSimpleType = + TopiaGeneratorUtil.getClassNameFromQualifiedName(usageType); + String usageSimplePropertyMethod = "findAllBy" + usageSimpleType; + String usageCollectionPropertyMethod = "findAllContaining" + usageSimpleType; + for (ObjectModelAttribute attr : usageClass.getAttributes()) { + if (!attr.isNavigable()) { + // skip this case + continue; + } + String type; + String attrName = attr.getName(); + if (attr.hasAssociationClass()) { + //FIXME-TC20100224 dont known how to do this ? + continue; +// type = attr.getAssociationClass().getQualifiedName(); +// //FIXME-TC20100224 : this is crazy ??? must find the good name +// // Perhaps need to make different cases? +// attrName = attrName + "_" + TopiaGeneratorUtil.toLowerCaseFirstLetter(attr.getAssociationClass().getName()); + } else { + type = attr.getType(); + } + if (!allEntitiesByFQN.containsKey(type)) { + // not a entity, can skip for this attribute + continue; + } + ObjectModelClass targetEntity = allEntitiesByFQN.get(type); +// if (!type.equals(clazz.getQualifiedName())) { + if (!targetEntity.equals(clazz)) { + // not a good attribute reference + continue; + } + // found something to seek + + String methodName; + if (TopiaGeneratorUtil.isNMultiplicity(attr)) { + methodName = getJavaBeanMethodName("findAllContains", attrName); + } else { + methodName = getJavaBeanMethodName("findAllBy", attrName); + } + String daoName = StringUtils.capitalize(usageSimpleType) + "DAO"; + + builder.addImport(result, usageClass.getPackageName() + '.' + daoName); + + buffer.append("" +/*{ + if (type == <%=usageSimpleType%>.class) { + <%=daoName%> dao = (<%=daoName%>) + topiaDaoSupplier.getDao(<%=usageSimpleType%>.class); + tmp = dao.<%=methodName%>(entity); + result.addAll(tmp); + } +}*/ + ); + } + } + + buffer.append("" +/*{ + return (List<U>) result; + }*/ + ); + setOperationBody(operation, buffer.toString()); + + operation = addOperation(result, + "findAllUsages", + "Map<Class<? extends TopiaEntity>, List<? extends TopiaEntity>>", + ObjectModelJavaModifier.PUBLIC); + + addParameter(operation, "E", "entity"); + addAnnotation(result, operation, Override.class); + + buffer = new StringBuilder(300); + buffer.append("" +/*{ + Map<Class<? extends TopiaEntity>,List<? extends TopiaEntity>> result; + result = new HashMap<Class<? extends TopiaEntity>, List<? extends TopiaEntity>>(<%=usagesForclass.size()%>); + + List<? extends TopiaEntity> list; +}*/ + ); + for (ObjectModelClass usageClass : usagesForclass) { + + String fqn = usageClass.getName(); + buffer.append("" +/*{ + list = findUsages(<%=fqn%>.class, entity); + if (!list.isEmpty()) { + result.put(<%=fqn%>.class, list); + } +}*/ + ); + + } + buffer.append("" +/*{ + return result; + }*/ + ); + + setOperationBody(operation, buffer.toString()); + } + + /** + * Generation of DAO operations signatures from class. These operations are + * abstract and identified by <<dao>> stereotype in the model. The + * developper must defined these methods in the DAOImpl associated to this + * DAOAbstract. + * + * @param result clazz where to add operations + * @param operations operations to generate + * @deprecated will be removed ASAP in topia 3.0 + */ + @Deprecated + protected void generateDAOOperations(ObjectModelClass result, + Collection<ObjectModelOperation> + operations) { + if (CollectionUtils.isEmpty(operations)) { + + // no extra operations to generate + return; + } + + for (ObjectModelOperation op : operations) { + + Set<String> exceptions = op.getExceptions(); + cloneOperation(op, + result, + true, + ObjectModelJavaModifier.ABSTRACT, + ObjectModelJavaModifier.fromVisibility(op.getVisibility()) + ); + } + } + + + protected void generateNoNMultiplicity(String clazzName, + ObjectModelClass result, + ObjectModelAttribute attr, + boolean isAssoc) { + String attrName = attr.getName(); + String attrType = attr.getType(); + String propertyName = clazzName + "." + getConstantName(attrName); + + String attrTypeForGeneric; + if (JavaGeneratorUtil.isPrimitiveType(attrType)) { + attrTypeForGeneric = TopiaGeneratorUtil.getClassForPrimitiveType(attr); + } else { + attrTypeForGeneric = attrType; + } + + if (!isAssoc && attr.hasAssociationClass()) { + String assocClassName = attr.getAssociationClass().getName(); + String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(attr); + // It is about transitivity : use the property to access the + // associationClass + '.' + the property to access the expected + // attribute + // <class>.<attrAssoc> + '.' + <assocClass>.<attr> + propertyName = + clazzName + '.' + getConstantName(assocAttrName) + + " + '.' + " + + assocClassName + '.' + getConstantName(attrName); + } + + ObjectModelOperation op; + op = addOperation(result, + getJavaBeanMethodName("for", attrName, "In"), + "TopiaQueryBuilderAddCriteriaOrRunQueryStep<E>", + ObjectModelJavaModifier.PUBLIC); + addParameter(op, "Iterable<" + attrTypeForGeneric + ">", "v"); + setOperationBody(op, "" +/*{ + TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> result = forIn(<%=propertyName%>, (Iterable) v); + return result; + }*/ + ); + + op = addOperation(result, + getJavaBeanMethodName("for", attrName, "Equals"), + "TopiaQueryBuilderAddCriteriaOrRunQueryStep<E>", + ObjectModelJavaModifier.PUBLIC); + addParameter(op, attrType, "v"); + setOperationBody(op, "" +/*{ + TopiaQueryBuilderAddCriteriaOrRunQueryStep<E> result = forEquals(<%=propertyName%>, v); + return result; + }*/ + ); + + String methodToDelegateName = op.getName(); + + op = addOperation(result, + getJavaBeanMethodName("findBy", attrName), + "E", + ObjectModelJavaModifier.PUBLIC); + addParameter(op, attrType, "v"); + setOperationBody(op, "" +/*{ + return <%=methodToDelegateName%>(v).findAnyOrNull(); + }*/ + ); + + addAnnotation(result, op, Deprecated.class); + + op = addOperation(result, + getJavaBeanMethodName("findAllBy", attrName), + "List<E>", + ObjectModelJavaModifier.PUBLIC); + addParameter(op, attrType, "v"); + setOperationBody(op, "" +/*{ + return <%=methodToDelegateName%>(v).findAll(); + }*/ + ); + + addAnnotation(result, op, Deprecated.class); + + if (!isAssoc && attr.hasAssociationClass()) { + String assocClassName = attr.getAssociationClass().getName(); + String assocClassFQN = attr.getAssociationClass().getQualifiedName(); + String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(attr); + String assocPropertyConstantName = getConstantName(assocAttrName); + op = addOperation(result, + getJavaBeanMethodName("findBy", assocClassName), + "E", + ObjectModelJavaModifier.PUBLIC); + addParameter(op, assocClassFQN, "value"); + setOperationBody(op, "" +/*{ + E result = findByProperty(<%=clazzName + "." + assocPropertyConstantName%>, value); + return result; + }*/ + ); + + op = addOperation(result, + getJavaBeanMethodName("findAllBy", assocClassName), + "List<E>", + ObjectModelJavaModifier.PUBLIC); + addParameter(op, assocClassFQN, "value"); + setOperationBody(op, "" +/*{ + List<E> result = findAllByProperty(<%=clazzName + "." + assocPropertyConstantName%>, value); + return result; + }*/ + ); + } + } + + protected void generateNMultiplicity(String clazzName, + ObjectModelClass result, + ObjectModelAttribute attr) { + String attrName = attr.getName(); + String attrType = attr.getType(); + if (attr.hasAssociationClass()) { + // do nothing for association class, too complex... + return; + } + ObjectModelOperation op; + + op = addOperation(result, + getJavaBeanMethodName("for", attrName, "Contains"), + "TopiaQueryBuilderAddCriteriaOrRunQueryStep<E>", + ObjectModelJavaModifier.PUBLIC); + addParameter(op, attrType, "v"); + setOperationBody(op, "" +/*{ + return forContains(<%=clazzName + "." + getConstantName(attrName)%>, v); + }*/ + ); + + String methodToDelegateName = op.getName(); + + op = addOperation(result, + getJavaBeanMethodName("findContains", attrName), + "E", + ObjectModelJavaModifier.PUBLIC); + addParameter(op, attrType, "v"); + setOperationBody(op, "" +/*{ + return <%=methodToDelegateName%>(v).findAnyOrNull(); + }*/ + ); + + addAnnotation(result, op, Deprecated.class); + + op = addOperation(result, + getJavaBeanMethodName("findAllContains", attrName), + "List<E>", + ObjectModelJavaModifier.PUBLIC); + addParameter(op, attrType, "v"); + setOperationBody(op, "" +/*{ + return <%=methodToDelegateName%>(v).findAll(); + }*/ + ); + + addAnnotation(result, op, Deprecated.class); + + } + + + /** + * Obtain business operations of the DAO. + * + * This operations can not be generated, but must be written by developper. + * + * @param clazz the clazz to test. + * @return collections of extra operations, or empty collection if none found. + * @deprecated Dao operation will not be generated anymore in a very close future + */ + @Deprecated + public Collection<ObjectModelOperation> getDaoOperations( + ObjectModelClass clazz) { + +// // Note : this collection will contains extra operations for DAO. +// // Overriding existing generated methods is not managed yet +// Collection<ObjectModelOperation> results = +// new ArrayList<ObjectModelOperation>(); + +// // This code will be deprecated +// for (ObjectModelOperation op : clazz.getOperations()) { +// if (TopiaGeneratorUtil.hasDaoStereotype(op)) { +// results.add(op); +// } +// } + + Collection<ObjectModelOperation> extra = + extraOperations.get(clazz.getQualifiedName()); + if (extra != null && !extra.isEmpty() && log.isWarnEnabled()) { + log.warn("Dao contract in model will not be supported in topia 3.0"); + } + return extra; +// if (extra != null) { +// for (ObjectModelOperation op : extra) { +// results.add(op); +// } +// } + +// return results; + } + + private void generateNaturalId(ObjectModelClass result, + ObjectModelClass clazz) { + Set<ObjectModelAttribute> props = + TopiaGeneratorUtil.getNaturalIdAttributes(clazz); + + if (!props.isEmpty()) { + + if (log.isDebugEnabled()) { + log.debug("generateNaturalId for " + props); + } + ObjectModelOperation findByNaturalId = addOperation(result, + "findByNaturalId", "E", ObjectModelJavaModifier.PUBLIC); + + ObjectModelOperation existByNaturalId = addOperation(result, + "existByNaturalId", "boolean", ObjectModelJavaModifier.PUBLIC); + + ObjectModelOperation createByNaturalId = addOperation(result, + "createByNaturalId", "E", ObjectModelJavaModifier.PUBLIC); + + Set<String> properties = Sets.newLinkedHashSet(); + String clazzName = clazz.getName(); + + for (ObjectModelAttribute attr : props) { + + String propName = attr.getName(); + String type = attr.getType(); + + addParameter(findByNaturalId, type, propName); + addParameter(existByNaturalId, type, propName); + addParameter(createByNaturalId, type, propName); + + String property = clazzName + '.' + getConstantName(propName) + ", " + propName; + properties.add(property); + + } + + String arguments = StringUtils.join(properties, ", "); + + setOperationBody(findByNaturalId, "" +/*{ + return forProperties(<%=arguments%>).findUnique(); + }*/ + ); + + setOperationBody(existByNaturalId, "" +/*{ + return forProperties(<%=arguments%>).exists(); + }*/ + ); + + setOperationBody(createByNaturalId, "" +/*{ + return create(<%=arguments%>); + }*/ + ); + } + } + + protected void generateNotNull(ObjectModelClass result, + ObjectModelClass clazz) { + + Set<ObjectModelAttribute> props = + TopiaGeneratorUtil.getNotNullAttributes(clazz); + + if (!props.isEmpty()) { + + if (log.isDebugEnabled()) { + log.debug("generateNotNull for " + props); + } + + ObjectModelOperation createByNotNull = addOperation(result, + "createByNotNull", "E", ObjectModelJavaModifier.PUBLIC); + + String createProperties = ""; +// String params = ""; + String clazzName = clazz.getName(); + for (ObjectModelAttribute attr : props) { + String propName = attr.getName(); + // add property as param in both methods + addParameter(createByNotNull, attr.getType(), propName); + + createProperties += + ", " + clazzName + '.' + getConstantName(propName) + + ", " + propName; + //params += ", " + propName; + } + createProperties = createProperties.substring(2); + //params = params.substring(2); + + setOperationBody(createByNotNull, "" +/*{ + return create(<%=createProperties%>); + }*/ + ); + } + } +} Copied: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityHibernateMappingGenerator.java (from rev 2882, trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityHibernateMappingGenerator.java) =================================================================== --- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityHibernateMappingGenerator.java (rev 0) +++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityHibernateMappingGenerator.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,743 @@ +/*{generator option: parentheses = true}*/ +/*{generator option: writeString = output.write}*/ + +/* * +* EntityHibernateMappingGenerator.java +* +* Created: 12 déc. 2005 +* +* @author Arnaud Thimel <thimel@codelutin.com> +* @version $Revision$ +* +*/ + +package org.nuiton.topia.templates; + +import org.apache.commons.lang3.BooleanUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.eugene.models.object.ObjectModelAssociationClass; +import org.nuiton.eugene.models.object.ObjectModelAttribute; +import org.nuiton.eugene.models.object.ObjectModelClass; +import org.nuiton.eugene.models.object.ObjectModelGenerator; + +import java.beans.Introspector; +import java.io.File; +import java.io.IOException; +import java.io.Writer; +import java.sql.Types; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +import static org.nuiton.topia.templates.TopiaGeneratorUtil.hasUnidirectionalRelationOnAbstractType; + +/** + * + * @author poussin <poussin@codelutin.com> + * @version $Id$ + * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.templates.EntityHibernateMappingGenerator" + */ +public class EntityHibernateMappingGenerator extends ObjectModelGenerator { + + /** + * Logger. + */ + private static final Log log = LogFactory + .getLog(EntityHibernateMappingGenerator.class); + + private static final String HIBERNATE_ATTRIBUTE_DEFAULT = "default"; + + private static final String HIBERNATE_ATTRIBUTE_SQL_TYPE = "sql-type"; + + private static final String HIBERNATE_ATTRIBUTE_NAME = "name"; + + private Map<String, String[]> columnNamesMap = new HashMap<String, String[]>(); + + public static final String HIBERNATE_ATTRIBUTE_LAZY = "lazy"; + + public static final String HIBERNATE_ATTRIBUTE_FETCH = "fetch"; + + public static final String HIBERNATE_ATTRIBUTE_NOT_NULL = "not-null"; + + public static final String HIBERNATE_ATTRIBUTE_SCHEMA = "schema"; + + public static final String HIBERNATE_ATTRIBUTE_INDEX = "index"; + + public static final String HIBERNATE_ATTRIBUTE_UNIQUE = "unique"; + + public static final String HIBERNATE_ATTRIBUTE_LENGTH = "length"; + + public static final String HIBERNATE_ATTRIBUTE_ORDER_BY = "order-by"; + + @Override + public String getFilenameForClass(ObjectModelClass clazz) { + String DOName = TopiaGeneratorUtil.getDOType(clazz, model); + return DOName.replace('.', File.separatorChar) + ".hbm.xml"; + } + + @Override + public void generateFromClass(Writer output, + ObjectModelClass input) throws IOException { + String persistenceType = TopiaGeneratorUtil.getPersistenceType(input); + if (!TopiaGeneratorUtil.isEntity(input) && + TopiaGeneratorUtil.PERSISTENCE_TYPE_HIBERNATE.equals(persistenceType)) { + return; + } +/*{<?xml version="1.0" encoding="UTF-8"?> +<hibernate-mapping xmlns="http://www.hibernate.org/xsd/hibernate-mapping" + xsi:schemaLocation="http://www.hibernate.org/xsd/hibernate-mapping classpath://org/hibernate/hibernate-mapping-4.0.xsd" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + default-access="field" auto-import="true" package="<%=input.getPackageName()%>"> +}*/ + boolean haveSuper = input.getSuperclasses().size() > 0; + // la liste des attributs faisant parti de la clef metier + List<ObjectModelAttribute> naturalAttributes = new ArrayList<ObjectModelAttribute>(); + // la liste des autres attributs + List<ObjectModelAttribute> noneNaturalAttributes = new ArrayList<ObjectModelAttribute>(); + + String clazzDOType = TopiaGeneratorUtil.getDOType(input, model); + String tableName = TopiaGeneratorUtil.getDbName(input); + String isAbstract = BooleanUtils.toStringTrueFalse(input.isAbstract()); + String clazzFQN = input.getQualifiedName(); + + String optionalAttributes = ""; + String schema = TopiaGeneratorUtil.getDbSchemaNameTagValue(input, model); + if (schema != null) { + optionalAttributes += "schema=\"" + schema + "\" "; + } + + //On précise au proxy de quelle interface hérite l'objet + String proxyTagValue = TopiaGeneratorUtil.getProxyInterfaceTagValue(input, model); + if (StringUtils.isEmpty(proxyTagValue) || !proxyTagValue.equals("none")) { + optionalAttributes += "proxy=\"" + clazzFQN + "\" "; + } + + String inheritanceStrategy = null; + if (haveSuper) { + ObjectModelClass superClass = input.getSuperclasses().iterator().next(); + String superClassname = superClass.getQualifiedName(); + if (log.isDebugEnabled()) { + log.debug("superClass for " + input.getQualifiedName() + " is " + superClassname); + } + String superClassDOType = TopiaGeneratorUtil.getDOType(superClassname, model); + inheritanceStrategy = TopiaGeneratorUtil.getInheritanceStrategyTagValue(superClass); + if ("joined-subclass".equals(inheritanceStrategy) || "union-subclass".equals(inheritanceStrategy)) { + optionalAttributes += "table=\"" + tableName + "\""; + } + if ("subclass".equals(inheritanceStrategy)) { + optionalAttributes += "discriminator-value=\"" + clazzDOType + "\""; + } +/*{ <<%=inheritanceStrategy%> name="<%=clazzDOType%>" extends="<%=superClassDOType%>" node="<%=clazzDOType%>" abstract="<%=isAbstract%>" <%=optionalAttributes%>> +}*/ + if ("joined-subclass".equals(inheritanceStrategy)) { +/*{ <key column="topiaId" /> +}*/ + } + // FIXME mieux gerer le cas haveSuper + noneNaturalAttributes.addAll(input.getAttributes()); + } else { +/*{ <class name="<%=clazzDOType%>" table="<%=tableName%>" node="<%=clazzDOType%>" abstract="<%=isAbstract%>" <%=optionalAttributes%>> + <id name="topiaId" type="string" length="255" node="@topiaId"/> +}*/ + // cas où on defini la super class, il faut un discriminator seulement dans le cas de + // la strategy subclass + String currentInheritanceStrategy = TopiaGeneratorUtil.getInheritanceStrategyTagValue(input); + if ("subclass".equals(currentInheritanceStrategy)) { +/*{ <discriminator column="topiaDiscriminator" type="string" /> +}*/ + } + + // on detecte les attributs des clef metiers + for (ObjectModelAttribute attr : input.getAttributes()) { + if (TopiaGeneratorUtil.isNaturalId(attr)) { + // attribut metier + naturalAttributes.add(attr); + } else { + // attribut normal + noneNaturalAttributes.add(attr); + } + } + if (!naturalAttributes.isEmpty()) { + // generation de la clef metier + boolean mutable = TopiaGeneratorUtil.isNaturalIdMutable(input); + String mutableStr = mutable ? " mutable=\"true\"" : ""; + if (log.isDebugEnabled()) { + log.debug("natural-id detected for class " + input.getName() + " (" + mutableStr + ") attributes : " + naturalAttributes); + } +/*{ <natural-id<%=mutableStr%>> +}*/ + generateAttributes(output, input, naturalAttributes, " "); +/*{ </natural-id> +}*/ + } +/*{ <version name="topiaVersion" type="long" node="@topiaVersion"/> + <property name="topiaCreateDate" type="timestamp" node="@topiaCreateDate"/> +}*/ + } + + generateAttributes(output, input, noneNaturalAttributes, ""); + + if (haveSuper) { +/*{ </<%=inheritanceStrategy%>> +}*/ + } else { +/*{ </class> +}*/ + } + + generateDatabaseObjects(output, input, naturalAttributes); + generateDatabaseObjects(output, input, noneNaturalAttributes); + +/*{</hibernate-mapping> +}*/ + } + + protected void generateDatabaseObjects(Writer output, + ObjectModelClass clazz, + List<ObjectModelAttribute> attributes) throws IOException { + + for (ObjectModelAttribute attribute : attributes) { + if (!attribute.isNavigable() || + attribute.hasAssociationClass() || + !TopiaGeneratorUtil.isNMultiplicity(attribute) || + attribute.getClassifier() == null || + !TopiaGeneratorUtil.isEntity(attribute.getClassifier()) + ) { + + // skip for this case (not a nm-multiplicity attribute) + continue; + } + + String indexForeignKeys = + TopiaGeneratorUtil.getIndexForeignKeys(attribute, model); + + if (StringUtils.isEmpty(indexForeignKeys) || !Boolean.valueOf(indexForeignKeys)) { + + // no index to put of the attribute. + continue; + } + + // add database-object to create and drop index + + String tableName; + String indexName = "idx_" + clazz.getName() + "_" + attribute.getName(); + String propertyName; + + + if (TopiaGeneratorUtil.isNMultiplicity(attribute.getReverseMaxMultiplicity())) { + + // many to many + tableName = TopiaGeneratorUtil.getManyToManyTableName(attribute); + propertyName = TopiaGeneratorUtil.getDbName(attribute.getReverseAttribute()); + } else { + + // one to many + tableName =TopiaGeneratorUtil.getDbName(attribute.getClassifier()); + propertyName = TopiaGeneratorUtil.getDbName(attribute.getReverseAttribute()); + } + + // add schema if exist (http://nuiton.org/issues/2052) + String schema = TopiaGeneratorUtil.getDbSchemaNameTagValue(clazz, model); + if (StringUtils.isNotEmpty(schema)) { + tableName = schema + "." + tableName; + } +/*{ <database-object> + <create>CREATE INDEX <%=indexName%> ON <%=tableName%>(<%=propertyName%>)</create> + <drop>DROP INDEX <%=indexName%></drop> + </database-object> +}*/ + + } + } + protected void generateAttributes(Writer output, + ObjectModelClass clazz, + List<ObjectModelAttribute> attributes, + String prefix) throws IOException { + for (ObjectModelAttribute attr : attributes) { + ObjectModelAttribute reverse = attr.getReverseAttribute(); + + // pour les asso quoi qu'il arrive il faut les lier des 2 cotes + // pour pouvoir supprimer en cascade l'asso lors de la suppression + // d'un des cotes + if (attr.isNavigable() + || hasUnidirectionalRelationOnAbstractType(reverse, model) + || attr.hasAssociationClass()) { + if (!TopiaGeneratorUtil.isNMultiplicity(attr)) { + if (attr.getClassifier() != null && TopiaGeneratorUtil.isEntity(attr.getClassifier())) { + if (TopiaGeneratorUtil.isNMultiplicity(attr.getReverseMaxMultiplicity()) && !attr.hasAssociationClass()) { + generateHibernateManyToOne(output, attr, prefix); + } else { + generateHibernateOneToOne(output, attr, prefix); + } + } else { + generateHibernateProperty(output, attr, prefix); + } + } else { + if (attr.getClassifier() != null && TopiaGeneratorUtil.isEntity(attr.getClassifier())) { + if (TopiaGeneratorUtil.isNMultiplicity(attr.getReverseMaxMultiplicity()) && !attr.hasAssociationClass()) { + generateHibernateManyToMany(output, attr, prefix); + } else { + generateHibernateOneToMany(output, attr, prefix); + } + } else { + generateHibernateMany(output, attr, prefix); + } + } + } + } + + //Attributs pour les classes d'association + if (clazz instanceof ObjectModelAssociationClass) { + ObjectModelAssociationClass assoc = (ObjectModelAssociationClass)clazz; + for (ObjectModelAttribute attr : assoc.getParticipantsAttributes()) { + if (attr != null) { + +// Note(poussin) pour moi quoi qu'il arrive sur la classe d'association il faut +// un many-to-one, sinon on a des problemes. +// if ((!attr.getReverseAttribute().isNavigable()) || !Util.isNMultiplicity(attr.getReverseAttribute())) { +// / *{ <one-to-one name="<%=getName(attr, true)%>" class="<%=getType(attr, true)%>"<%=(TopiaGeneratorUtil.notEmpty(attr.getTagValue(TopiaGeneratorUtil.TAG_LENGTH))?(" length=\"" + attr.getTagValue(TopiaGeneratorUtil.TAG_LENGTH) + "\""):"")%><%=(attr.isComposite()?" cascade=\"delete\"":"")%>/> +// } */ +// } else { + String notNull = " " + generateFromTagValue(HIBERNATE_ATTRIBUTE_NOT_NULL, TopiaGeneratorUtil.getNotNullTagValue(attr)); + String attrName = getName(attr, true); + String attrType = getType(attr, true); + String lazy = generateFromTagValue(HIBERNATE_ATTRIBUTE_LAZY, TopiaGeneratorUtil.getLazyTagValue(attr)); + String attrColumn = TopiaGeneratorUtil.getDbName(attr); +/*{<%=prefix%> <many-to-one name="<%=attrName%>" class="<%=attrType%>" <%=lazy%>column="<%=attrColumn%>" node="<%=attrName%>/@topiaId" <%=notNull%>/> +}*/ +// } + //Ne sert plus grâce à l'utilisation de la navigabilité +// if (!attr.getReverseAttribute().isNavigable()) { +// String type = TopiaGeneratorUtil.getDOType(((ObjectModelClassifier)attr.getDeclaringElement()).getQualifiedName(), model); +// String name = Util.toLowerCaseFirstLetter(attr.getDeclaringElement().getName()); +// if (log.isTraceEnabled()) {log.trace("reverse: " + type + " " + name);} +// if (!Util.isNMultiplicity(attr)) { +//{<!-- <one-to-one name="<%=name%>" class="<%=type%>"/> +//} +// } else { +//{ <many-to-one name="<%=name%>" class="<%=type%>" column="<%=name.toLowerCase()%>"/> --> +//} +// } +// } + } + } + } + } + + protected String getName(ObjectModelAttribute attr) { + return getName(attr, false); + } + + protected String getName(ObjectModelAttribute attr, boolean isAssoc) { + String result = Introspector.decapitalize(attr.getName()); + if (attr.hasAssociationClass() && !isAssoc) { + result = TopiaGeneratorUtil.getAssocAttrName(attr); + } + return result; + } + + protected String getType(ObjectModelAttribute attr) { + return getType(attr, false); + } + + protected String getType(ObjectModelAttribute attr, boolean isAssoc) { + String type = attr.getType(); + String attrType = TopiaGeneratorUtil.getTypeTagValue(attr); + if (StringUtils.isNotEmpty(attrType)) { + + // tag value detected of the attribute + type = attrType; + } else { + + String modelType = model.getTagValue(type); + if (StringUtils.isNotEmpty(modelType)) { + + // tag value detected of the model + + //TODO tchemit 20100507 Explain What todes it do ? Dont understand the story of columnNamesMap + int bracketIndex = modelType.indexOf('('); + if (bracketIndex != -1) { + type = modelType.substring(0, bracketIndex); + int bracketEndIndex = modelType.indexOf(')', bracketIndex + 1); + String colmunList; + if (bracketEndIndex != -1) { + colmunList = modelType.substring(bracketIndex + 1, bracketEndIndex); + } else { + colmunList = modelType.substring(bracketIndex); + } + columnNamesMap.put(type, colmunList.split(",")); + } else { + type = modelType; + } + } + } + if (attr.hasAssociationClass() && !isAssoc) { + type = attr.getAssociationClass().getQualifiedName(); + } + return TopiaGeneratorUtil.getDOType(type, model); + } + + protected void generateHibernateProperty(Writer output, + ObjectModelAttribute attr, + String prefix) throws IOException { + String attrType = getType(attr); + + String accessField = "field"; + String tagValue = TopiaGeneratorUtil.getAccessTagValue(attr); + if (StringUtils.isNotEmpty(tagValue)) { + accessField = tagValue; + } + String attrName = attr.getName(); + String declaringElementDBName = TopiaGeneratorUtil.getDbName(attr.getDeclaringElement()); + String tableName = declaringElementDBName + "_" + attrName; + + boolean attrIsEnumeration = attr.getClassifier() != null + && attr.getClassifier().isEnum(); + + if (attrType.trim().endsWith("[]")) { + attrType = attrType.trim().substring(0, attrType.trim().length()-2); + + String optionalAttributes = ""; + String schema = TopiaGeneratorUtil.getDbSchemaNameTagValue(attr, model); + if (schema != null) { + optionalAttributes += generateFromTagValue(HIBERNATE_ATTRIBUTE_SCHEMA, schema); +// optionalAttributes += "schema=\"" + schema + "\" "; + } + + if (TopiaGeneratorUtil.hasIndexedStereotype(attr)) { + String indexName = tableName + "_idx"; + optionalAttributes += generateFromTagValue(HIBERNATE_ATTRIBUTE_INDEX, indexName); +// optionalAttributes += "index=\"" + indexName + "\" "; + } + +/*{<%=prefix%> <primitive-array name="<%=attrName%>" table="<%=tableName%>" access="<%=accessField%>" <%=optionalAttributes%>> +<%=prefix%> <key column="<%=declaringElementDBName%>"/> +<%=prefix%> <list-index column="<%=attrName%>_idx"/> +<%=prefix%> <element type="<%=attrType%>"/> +<%=prefix%> </primitive-array> +}*/ + } else { + String optionalAttributes = ""; + if (TopiaGeneratorUtil.hasIndexedStereotype(attr)) { + String indexName = tableName + "_idx"; + optionalAttributes += generateFromTagValue(HIBERNATE_ATTRIBUTE_INDEX, indexName); +// optionalAttributes += "index=\"" + indexName + "\""; + } + + if (TopiaGeneratorUtil.hasUniqueStereotype(attr)) { + // the trim method is called on optionalAttributes after this set to suppress unusual space if no index is set on this attribute + optionalAttributes += generateFromTagValue(HIBERNATE_ATTRIBUTE_UNIQUE, "true"); +// optionalAttributes += " unique=\"true\""; + } + optionalAttributes += generateFromTagValue(HIBERNATE_ATTRIBUTE_NOT_NULL, TopiaGeneratorUtil.getNotNullTagValue(attr)); +/*{<%=prefix%> <property name="<%=attrName%>" access="<%=accessField%>"}*/ + if ( ! attrIsEnumeration) { +/*{ type="<%=attrType%>"}*/ + } + optionalAttributes = optionalAttributes.trim(); + String[] columnNames = columnNamesMap.get(attrType); + + // contains all required attributes for a column node + Map<String,String> columnAttributes = new TreeMap<String, String>(); + if (StringUtils.isNotEmpty(attr.getDefaultValue())) { + //TC-20100129 with a default value we must use the column child tag + + String defaultValue = attr.getDefaultValue().trim(); + columnAttributes.put(HIBERNATE_ATTRIBUTE_DEFAULT, defaultValue); + } + String sqlType = TopiaGeneratorUtil.getSqlTypeTagValue(attr); + if (!StringUtils.isEmpty(sqlType)) { + + // an specific sql type was specified for the attribute, use it + columnAttributes.put(HIBERNATE_ATTRIBUTE_SQL_TYPE, sqlType); + } + + // add length attribute if required + String lengthTagValue = TopiaGeneratorUtil.getLengthTagValue(attr); + if (!StringUtils.isEmpty(lengthTagValue)) { + + optionalAttributes += generateFromTagValue(HIBERNATE_ATTRIBUTE_LENGTH, lengthTagValue); + } + + optionalAttributes = optionalAttributes.trim(); + if (StringUtils.isNotEmpty(optionalAttributes)) { + optionalAttributes = " " + optionalAttributes; + } + + // to know if specific column name mapping is given + boolean noSpecifiedColumn = columnNames == null || columnNames.length == 0; + + if (noSpecifiedColumn) { + + String attrColumn = TopiaGeneratorUtil.getDbName(attr); + + if (columnAttributes.isEmpty()) { + + // simple case with no column node to generate + +/*{ column="<%=attrColumn%>" node="<%=attrName%>"<%=optionalAttributes%>}*/ + if (attrIsEnumeration) { +/*{> +<%=prefix%> <type name="org.hibernate.type.EnumType"> +<%=prefix%> <param name="<%=org.hibernate.type.EnumType.ENUM%>"><%=attrType%></param>}*/ + + // if the user tuned the model to use name instead of + // ordinal to store the values, we must add a clause + boolean useEnumerationName = TopiaGeneratorUtil.hasUseEnumerationNameTagValue(attr, model); + if (useEnumerationName) { + String enumSQLType = String.valueOf(Types.VARCHAR); +/*{ +<%=prefix%> <!-- using name instead of ordinal to store enumeration value --> +<%=prefix%> <param name="<%=org.hibernate.type.EnumType.TYPE%>"><%=enumSQLType%></param>}*/ + } + +/*{ +<%=prefix%> </type> +<%=prefix%> </property> +}*/ + } else { +/*{/> +}*/ + } + } else { + + // there is some attributes to write for the column node + + columnAttributes.put(HIBERNATE_ATTRIBUTE_NAME, attrColumn); + + String columnAttributesAsString =""; + for (Map.Entry<String, String> entry : + columnAttributes.entrySet()) { + String name = entry.getKey(); + String value = entry.getValue(); + columnAttributesAsString += generateFromTagValue(name, value, null); + } + columnAttributesAsString = " " + columnAttributesAsString.trim(); +/*{<%=optionalAttributes%>> +<%=prefix%> <column<%=columnAttributesAsString%>/> +<%=prefix%> </property> +}*/ + } + } else { + + // there is a colum name mapping specified, must use it + //FIXME tchemit 2010-12-29 Really don't know how to apply columnAttributes for multi-columns... +/*{<%=optionalAttributes%>> +}*/ + for (String columnName : columnNames) { + columnName = attrName + "_" + columnName.trim(); +/*{<%=prefix%> <column name="<%=columnName%>"/> +}*/ + } +/*{<%=prefix%> </property> +}*/ + } + } + } + + protected void generateHibernateOneToOne(Writer output, + ObjectModelAttribute attr, + String prefix) throws IOException { +// boolean accessField = hasUnidirectionalRelationOnAbstractType(attr.getReverseAttribute(), model); +/// *{ <one-to-one name="<%=getName(attr)%>" class="<%=getType(attr)%>"<%=(TopiaGeneratorUtil.notEmpty(attr.getTagValue(TopiaGeneratorUtil.TAG_LENGTH))?(" length=\"" + attr.getTagValue(TopiaGeneratorUtil.TAG_LENGTH) + "\""):"")%><%=((attr.isComposite() || attr.hasAssociationClass())?" cascade=\"delete\"":"")%><%=((accessField)?" access=\"field\"":"")%> node="<%=getName(attr)%>/@topiaId" /> +//} */ + + // for hibernate many-to-one with unique="true" => one-to-one + // but if it is one-to-zero-or-one unique contraints is violated + // with null values + boolean unique = TopiaGeneratorUtil.isOneMultiplicity(attr); + generateHibernateManyToOne(output, attr, unique, prefix); + + } + + protected void generateHibernateOneToMany(Writer output, + ObjectModelAttribute attr, + String prefix) throws IOException { + boolean needsIndex = TopiaGeneratorUtil.hasIndexedStereotype(attr); + boolean isInverse = attr.getReverseAttribute().isNavigable(); + isInverse |= hasUnidirectionalRelationOnAbstractType(attr, model); + + String attrName = getName(attr); // ??? + String attrType = getType(attr); + String reverseAttrDBName = TopiaGeneratorUtil.getReverseDbName(attr); + String orderBy = generateFromTagValue(HIBERNATE_ATTRIBUTE_ORDER_BY, TopiaGeneratorUtil.getOrderByTagValue(attr)); + + String cascade = ""; + if (attr.isComposite() || attr.hasAssociationClass()) { + cascade += "cascade=\"all,delete-orphan\" "; + } + + String lazy = generateFromTagValue(HIBERNATE_ATTRIBUTE_LAZY, TopiaGeneratorUtil.getLazyTagValue(attr), "true"); + + String fetch = generateFromTagValue(HIBERNATE_ATTRIBUTE_FETCH, TopiaGeneratorUtil.getFetchTagValue(attr)); + + String collType = TopiaGeneratorUtil.getNMultiplicityHibernateType(attr); + String inverse = ""; + if (isInverse) { + inverse = "inverse=\"true\" "; + } + if (needsIndex) { +/*{<%=prefix%> <<%=collType%> name="<%=attrName%>" <%=inverse%><%=lazy%><%=cascade%>node="<%=attrName%>"> +<%=prefix%> <key column="<%=reverseAttrDBName%>"/> +<%=prefix%> <list-index column="<%=reverseAttrDBName%>_idx"/> +<%=prefix%> <one-to-many class="<%=attrType%>" node="topiaId"/> +<%=prefix%> </<%=collType%>> +}*/ + }else { +/*{<%=prefix%> <<%=collType%> name="<%=attrName%>" <%=inverse%><%=orderBy%><%=fetch%><%=lazy%><%=cascade%>node="<%=attrName%>"> +<%=prefix%> <key column="<%=reverseAttrDBName%>"/> +<%=prefix%> <one-to-many class="<%=attrType%>" node="topiaId"/> +<%=prefix%> </<%=collType%>> +}*/ + } + } + + private String generateFromTagValue(String attributeName, String tagValue) { + return generateFromTagValue(attributeName, tagValue, null); + } + + /** + * Generate hibernate xml attribute with a final space. + * @param attributeName + * @param tagValue + * @param defaultValue + * @return + */ + private String generateFromTagValue(String attributeName, String tagValue, String defaultValue) { + String result = ""; + if (StringUtils.isNotEmpty(tagValue)) { + result+= attributeName + "=\"" + tagValue+"\" "; + } else if (defaultValue != null) { + result+= attributeName + "=\"" + defaultValue +"\" "; + } +// if (attr.hasTagValue(tagName) || defaultValue != null) { +// result+= attributeName + "=\""; +// if (attr.hasTagValue(tagName)) { +// result += attr.getTagValue(tagName); +// } else { +// result += defaultValue; +// } +// result += "\" "; +// } + return result; + } + + protected void generateHibernateMany(Writer output, + ObjectModelAttribute attr, + String prefix) throws IOException { + boolean needsIndex = TopiaGeneratorUtil.hasIndexedStereotype(attr); + String attrName = getName(attr); + String attrType = getType(attr); + String collType = TopiaGeneratorUtil.getNMultiplicityHibernateType(attr); + String lazy = generateFromTagValue(HIBERNATE_ATTRIBUTE_LAZY, TopiaGeneratorUtil.getLazyTagValue(attr)); + String attrColumn = TopiaGeneratorUtil.getDbName(attr); + +/*{<%=prefix%> <<%=collType%> name="<%=attrName%>" <%=lazy%>node="<%=attrName%>"> +<%=prefix%> <key column="OWNER"/> +}*/ + if (needsIndex) { +/*{<%=prefix%> <list-index/> +}*/ + } +/*{<%=prefix%> <element type="<%=attrType%>" column="<%=attrColumn%>" node="id"/> +<%=prefix%> </<%=collType%>> +}*/ + } + + protected void generateHibernateManyToOne(Writer output, + ObjectModelAttribute attr, + String prefix) throws IOException { + generateHibernateManyToOne(output, attr, false, prefix); + } + + protected void generateHibernateManyToOne(Writer output, + ObjectModelAttribute attr, + boolean isUnique, + String prefix) throws IOException { + String attrName = getName(attr); + String attrType = getType(attr); + String attrColumn = TopiaGeneratorUtil.getDbName(attr); +/*{<%=prefix%> <many-to-one name="<%=attrName%>" class="<%=attrType%>" column="<%=attrColumn%>" }*/ + if (attr.isComposite() || attr.hasAssociationClass()) { +/*{cascade="delete" }*/ + } + // Pour le test suivant, on verifie d'abord que l'attribut a un reverse. + // S'il n'en a pas, cela signifie qu'il ne s'agit pas d'un entite + // (au sens stereotype entity), donc a donc pas besoin de faire un access=field. + if (attr.getReverseAttribute() != null && hasUnidirectionalRelationOnAbstractType(attr.getReverseAttribute(), model)) { +/*{access="field" }*/ + } + // vérifier si le tag lazy est defini par defaut dans le fichier de proprietes + String lazy = generateFromTagValue(HIBERNATE_ATTRIBUTE_LAZY, TopiaGeneratorUtil.getLazyTagValue(attr)); +/*{<%=lazy%>}*/ + String notNull = generateFromTagValue(HIBERNATE_ATTRIBUTE_NOT_NULL, TopiaGeneratorUtil.getNotNullTagValue(attr)); +/*{<%=notNull%>}*/ + if (isUnique) { +/*{unique="true" }*/ + } +/*{node="<%=attrName%>/@topiaId"}*/ + +/*{/> +}*/ + } + + protected void generateHibernateManyToMany(Writer output, + ObjectModelAttribute attr, + String prefix) throws IOException { + // On ne met le inverse="true" uniquement pour un seul coté de la relation. + // Dans le cas contraire, les modifications dans la relation ne seront + // pas sauvegardées. Ceci n'est vrai que si les deux coté sont navigable + boolean isInverse = attr.isNavigable() && attr.getReverseAttribute().isNavigable(); + //isInverse |= !Util.isFirstAttribute(attr); + //isInverse = false; // 20070117 poussin: pour du many, jamais de inverse + + // Modification FD-2010-04-01 : + // Le tagvalue "inverse" permet de spécifier qui possède le + // inverse="true". Il est impératif de l'utiliser sur les deux + // extrémités pour ne pas avoir de surprise. + String inverseValue = TopiaGeneratorUtil.getInverseTagValue(attr); + if (StringUtils.isNotEmpty(inverseValue)) { + isInverse &= Boolean.parseBoolean(inverseValue); + // Si aucun tagvalue n'est défini, le choix est arbitraire : le + // premier attribut dans l'ordre alphabétique sera choisi pour porter le + // inverse="true" + } else { + isInverse &= TopiaGeneratorUtil.isFirstAttribute(attr); + } + + boolean needsIndex = TopiaGeneratorUtil.hasIndexedStereotype(attr); + String cascade = ""; + if (attr.isComposite() || attr.hasAssociationClass()) { + cascade = " cascade=\"delete,delete-orphan\""; + } + + String attrType = getType(attr); + String attrName = getName(attr); + String attrColumn = TopiaGeneratorUtil.getDbName(attr); + String lazy = generateFromTagValue(HIBERNATE_ATTRIBUTE_LAZY, TopiaGeneratorUtil.getLazyTagValue(attr), "true"); + String orderBy = generateFromTagValue(HIBERNATE_ATTRIBUTE_ORDER_BY, TopiaGeneratorUtil.getOrderByTagValue(attr)); + String collType = TopiaGeneratorUtil.getNMultiplicityHibernateType(attr); + String tableName = TopiaGeneratorUtil.getManyToManyTableName(attr); + String inverse = ""; + if (isInverse) { + inverse = "inverse=\"true\" "; + } + String reverseAttrDBName = TopiaGeneratorUtil.getReverseDbName(attr); + +/*{<%=prefix%> <<%=collType%> name="<%=attrName%>" table="<%=tableName%>" <%=inverse%><%=lazy%><%=cascade%> node="<%=attrName%>"> +<%=prefix%> <key column="<%=reverseAttrDBName%>"/> +}*/ + if (needsIndex) { +/*{<%=prefix%> <list-index column="<%=reverseAttrDBName%>_idx"/> +}*/ + } +/*{<%=prefix%> <many-to-many class="<%=attrType%>" column="<%=attrColumn%>" <%=orderBy%>node="topiaId"/> +<%=prefix%> </<%=collType%>> +}*/ + } + +} //EntityHibernateMappingGenerator Copied: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityTransformer.java (from rev 2882, trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityTransformer.java) =================================================================== --- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityTransformer.java (rev 0) +++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/EntityTransformer.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,1630 @@ +package org.nuiton.topia.templates; + +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.eugene.EugeneTagValues; +import org.nuiton.eugene.java.ObjectModelTransformerToJava; +import org.nuiton.eugene.models.object.ObjectModelAssociationClass; +import org.nuiton.eugene.models.object.ObjectModelAttribute; +import org.nuiton.eugene.models.object.ObjectModelClass; +import org.nuiton.eugene.models.object.ObjectModelClassifier; +import org.nuiton.eugene.models.object.ObjectModelInterface; +import org.nuiton.eugene.models.object.ObjectModelJavaModifier; +import org.nuiton.eugene.models.object.ObjectModelModifier; +import org.nuiton.eugene.models.object.ObjectModelOperation; +import org.nuiton.eugene.models.object.ObjectModelParameter; +import org.nuiton.topia.TopiaDaoSupplier; +import org.nuiton.topia.TopiaException; +import org.nuiton.topia.persistence.EntityVisitor; +import org.nuiton.topia.persistence.TopiaEntity; +import org.nuiton.topia.persistence.TopiaEntityAbstract; +import org.nuiton.topia.persistence.TopiaEntityContextable; +import org.nuiton.topia.persistence.util.TopiaEntityHelper; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +import static org.nuiton.topia.templates.TopiaGeneratorUtil.hasUnidirectionalRelationOnAbstractType; + + + +/*{generator option: parentheses = false}*/ +/*{generator option: writeString = +}*/ + +/** + * A template to generate all the {@link TopiaEntity} api for all classifier + * with a {@code entity} stereotype. + * + * For example, given a {@code House} entity, it will generates : + * <ul> + * <li>{@code House} : contract of entity</li> + * <li>{@code AbstractHouse} : default abstract implementation of entity</li> + * <li>{@code HouseImpl} : default impl of abstract entity</li> + * </ul> + * + * <b>Note: </b> The impl will ony be generated in these cases : + * <ul> + * <li>There is no abstract method</li> + * <li>There is no already defined such class in class-path</li> + * </ul> + * + * @author tchemit <chemit@codelutin.com> + * @since 2.3.4 + * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.templates.EntityTransformer" + */ +public class EntityTransformer extends ObjectModelTransformerToJava { + + /** Logger */ + private static final Log log = LogFactory.getLog(EntityTransformer.class); + + protected ObjectModelInterface outputInterface; + + protected ObjectModelClass outputAbstract; + + protected ObjectModelClass outputImpl; + + private boolean associationClass; + + protected boolean generateInterface; + + protected boolean generateAbstract; + + protected boolean generateImpl; + + protected boolean generateBooleanGetMethods; + + protected void clean() { + outputInterface = null; + outputAbstract = null; + outputImpl = null; + } + + @Override + public void transformFromClass(ObjectModelClass input) { + + if (!TopiaGeneratorUtil.isEntity(input)) { + + // not an entity, skip class. + return; + } + + if (log.isDebugEnabled()) { + log.debug("for entity : " + input.getQualifiedName()); + log.debug("Will use classLoader " + getClassLoader()); + } + + // fix once for all the constant prefix to use + String prefix = getConstantPrefix(input, ""); + if (StringUtils.isEmpty(prefix)) { + + // no specific prefix, so no prefix + if (log.isWarnEnabled()) { + log.warn("[" + input.getName() + "] Will generate constants with NO prefix, not a good idea... \n" + + "Use '" + EugeneTagValues.TAG_CONSTANT_PREFIX + + "' tagvalue in your xmi properties. For example " + + "for all the model : model.tagvalue." + EugeneTagValues.TAG_CONSTANT_PREFIX + "=PROPERTY_"); + } + } + setConstantPrefix(prefix); + + generateInterface = isGenerateInterface(input); + generateAbstract = isGenerateAbstract(input); + generateImpl = isGenerateImpl(input); + + generateBooleanGetMethods = TopiaGeneratorUtil.isDoNotGenerateBooleanGetMethods(model, input); + + if (generateInterface) { + + // Create Entity Interface and its header + createEntityInterface(input); + } + + if (generateAbstract) { + + // Create Entity Abstract class and its header + createEntityAbstractClass(input); + } + + // Generate i18n block + String i18nPrefix = TopiaGeneratorUtil.getI18nPrefixTagValue(input, model); + if (!StringUtils.isEmpty(i18nPrefix)) { + generateI18nBlock(input, outputAbstract, i18nPrefix); + } + + // Create accept operation, will be updated during property generation + createAcceptOperation(); + + // Add constant, attribute and operations for each property + generateProperties(input.getAttributes()); + + // Case of association class : properties from participants/extremities + // of the association class. + if (input instanceof ObjectModelAssociationClass) { + ObjectModelAssociationClass association = + (ObjectModelAssociationClass)input; + associationClass = true; + generateProperties(association.getParticipantsAttributes()); + associationClass = false; + } + + closeAcceptOperation(); + + // Add extra constants (from uml dependency) + generateExtraConstants(input); + + // Add extra operations (defined on the entity) + generateExtraOperations(input); + + // Implement aggregate and composite operations + generateAggregateOperation(input); + generateCompositeOperation(input); + + // Implement toString operation + if (TopiaGeneratorUtil.generateToString(input, model)) { + generateToStringOperation(input); + } + + // Generate serialVersionUID on abstract class + generateSerialVersionUID(input, outputAbstract); + + // Generate Entity Implementation class + if (generateImpl) { + generateImpl(input); + generateSerialVersionUID(input, outputImpl); + } + + + + // Clean data output after transformation + clean(); + } + + protected void generateSerialVersionUID(ObjectModelClass input, + ObjectModelClass ouput) { + + // serialVersionUID + String svUID = TopiaGeneratorUtil.findTagValue(TopiaGeneratorUtil.SERIAL_VERSION_UID, + input, + model + ); + if (svUID == null) { + + // use a default one + svUID = TopiaGeneratorUtil.generateSerialVersionUID(ouput) + "L"; + } + addConstant(ouput, TopiaGeneratorUtil.SERIAL_VERSION_UID, long.class, svUID, + ObjectModelJavaModifier.PRIVATE); + } + + protected void createEntityInterface(ObjectModelClass input) { + + outputInterface = createInterface(input.getName(), + input.getPackageName()); + + // Documentation + if (TopiaGeneratorUtil.hasDocumentation(input)) { + setDocumentation(outputInterface, input.getDocumentation()); + } + + if (log.isTraceEnabled()) { + log.trace("Will add interfaces on " + + outputInterface.getQualifiedName()); + } + + List<String> interfaceAlreadyDone = new LinkedList<String> (); + // Extends + for (ObjectModelClassifier parent : input.getInterfaces()) { + addInterface(interfaceAlreadyDone, outputInterface, parent); + } + + // Extends from inheritance + boolean needTopiaEntity = true; + for (ObjectModelClassifier parent : input.getSuperclasses()) { + if (TopiaGeneratorUtil.isEntity(parent)) { + addInterface(interfaceAlreadyDone, outputInterface, parent); + needTopiaEntity = false; + break; + } + } + + // Extends TopiaEntity (only if hasn't parent entity) + if (needTopiaEntity) { + + Class<?> interfaze = TopiaEntity.class; + + if (TopiaGeneratorUtil.isContextable(input)) { + interfaze = TopiaEntityContextable.class; + } + + addInterface(interfaceAlreadyDone, + outputInterface, + interfaze); + + } else if (TopiaGeneratorUtil.isContextable(input)) { + // Even if there is no need to implement TopiaEntity, it might be + // necessary to implement TopiaEntityContextable + addInterface(interfaceAlreadyDone, + outputInterface, + TopiaEntityContextable.class); + } + } + + protected void createEntityAbstractClass(ObjectModelClass input) { + + outputAbstract = createAbstractClass(input.getName() + "Abstract", + input.getPackageName()); + + // Documentation + StringBuilder doc = new StringBuilder(); + doc.append("Implantation POJO pour l'entité {@link "); + doc.append(StringUtils.capitalize(outputInterface.getName())); + doc.append("}\n"); + + String dbName = TopiaGeneratorUtil.getDbName(input); + if (dbName != null) { + doc.append("<p>Nom de l'entité en BD : "); + doc.append(dbName); + doc.append(".</p>"); + } + + setDocumentation(outputAbstract, doc.toString()); + + // Implements + addInterface(outputAbstract, outputInterface.getName()); + + // Extends + for (ObjectModelClass parent : input.getSuperclasses()) { + //tchemit-2011-09-12 What ever abstract or not, we alwyas use an Impl, moreover use the util method instead + String extendClass = TopiaGeneratorUtil.getDOType(parent, model); +// String extendClass = parent.getQualifiedName(); +// //Si une des classes parentes définies des méthodes abstraites, son +// // impl ne sera pas créé +// boolean abstractParent = TopiaGeneratorUtil.shouldBeAbstract(parent); +// if (TopiaGeneratorUtil.isEntity(parent)) { +// if (abstractParent) { +// extendClass += "Abstract"; +// } else { +// extendClass += "Impl"; +// } +// } + setSuperClass(outputAbstract, extendClass); + } + + // Extends TopiaEntityAbstract (only if hasn't parent entity) + if (outputAbstract.getSuperclasses().isEmpty()) { + setSuperClass(outputAbstract, TopiaEntityAbstract.class); + } + + addContextableMethods(input, outputAbstract); + } + + /** + * Ajout les methodes necessaire à l'interface {@link TopiaEntityContextable} + * si le tagValue {@link TopiaTagValues#TAG_CONTEXTABLE} est renseigné. + * @param input + * @param outputAbstract + */ + protected void addContextableMethods(ObjectModelClass input, + ObjectModelClass outputAbstract) { + + if (TopiaGeneratorUtil.isContextable(input)) { + + addImport(outputAbstract, TopiaDaoSupplier.class); + + // topiaContext attribute + ObjectModelAttribute topiaContextAttribute = addAttribute( + outputAbstract, "topiaDaoSupplier", TopiaDaoSupplier.class, null, + ObjectModelJavaModifier.PROTECTED, ObjectModelJavaModifier.TRANSIENT); + setDocumentation(topiaContextAttribute, + "TopiaDAO instance associated with the current \n" + + "instance. For internal usage only"); + + ObjectModelOperation op = addOperation(outputAbstract, + "getTopiaDAOSupplier", TopiaDaoSupplier.class, + ObjectModelJavaModifier.PUBLIC); + setDocumentation(op,"@since 3.0"); + addAnnotation(outputAbstract, op, Override.class); + setOperationBody(op, "" +/*{ + return topiaDaoSupplier; + }*/ + ); + + op = addOperation(outputAbstract, + "setTopiaDAOSupplier", "void", + ObjectModelJavaModifier.PUBLIC); + addException(op, TopiaException.class); + addParameter(op, TopiaDaoSupplier.class, "topiaDaoSupplier"); + setDocumentation(op, +// "@param context The context to set.\n" + +// "@throws TopiaException if trying to replace a context\n" + + "@since 3.0"); + addAnnotation(outputAbstract, op, Override.class); + setOperationBody(op, "" +/*{ + if (this.topiaDaoSupplier == null) { + this.topiaDaoSupplier = topiaDaoSupplier; +// } else { +// throw new TopiaException("TopiaContext replacement is forbidden"); + } + }*/ + ); + + op = addOperation(outputAbstract, "update", "void", + ObjectModelJavaModifier.PUBLIC); + addException(op, TopiaException.class); +// setDocumentation(op,"@since 2.5.3"); + addAnnotation(outputAbstract, op, Override.class); + setOperationBody(op, "" +/*{ + getTopiaDAOSupplier().getDao(<%=input.getName()%>.class).update(this); + }*/ + ); + + op = addOperation(outputAbstract, "delete", "void", ObjectModelJavaModifier.PUBLIC); + addException(op, TopiaException.class); +// setDocumentation(op,"@since 2.5.3"); + addAnnotation(outputAbstract, op, Override.class); + setOperationBody(op, "" +/*{ + getTopiaDAOSupplier().getDao(<%=input.getName()%>.class).delete(this); + }*/ + ); + } + } + + protected boolean isGenerateInterface(ObjectModelClass input) { + + boolean alreadyInClassPath = !isInClassPath(input); + return alreadyInClassPath; + } + + protected boolean isGenerateAbstract(ObjectModelClass input) { + + String fqn = input.getQualifiedName() + " Abstract"; + boolean alreadyInClassPath = !isInClassPath(fqn); + return alreadyInClassPath; + } + + protected boolean isGenerateImpl(ObjectModelClass input) { + + Collection<ObjectModelOperation> operations = input.getOperations(); + String fqn = input.getQualifiedName() + "Impl"; + + boolean alreadyInClassPath = isInClassPath(fqn); + if (alreadyInClassPath) { + + return false; + } + + // On ne génère pas le impl si l'entité a des opérations + if (!operations.isEmpty()) { + + log.info("Will not generate [" + fqn + "], there is some operations to manually implement"); + return false; + } + + //De même, on ne génère pas le impl si il y a des opérations venant des + // superclasses non implémentées + for (ObjectModelOperation otherOp : input.getAllOtherOperations(false)) { + if (otherOp.isAbstract()) { + log.info("Will not generate [" + fqn + "], there is an abstract operation [" + otherOp.getName() + "] in allOtherOperations."); + return false; + } + } + + return true; + } + + protected void generateImpl(ObjectModelClass input) { + + String implName = input.getName() + "Impl"; + String packageName = input.getPackageName(); + if (isVerbose()) { + log.info("Will generate [" + implName + "]"); + } + + if (isAbstract(input)) { + outputImpl = createAbstractClass(implName, packageName); + } else { + outputImpl = createClass(implName, packageName); + } + + setDocumentation(outputImpl, "Implantation des operations pour l'entité " + + input.getName() + "."); + setSuperClass(outputImpl, input.getQualifiedName() + "Abstract"); + } + + /** + * Generate extra constants if {@code input} has dependencies on + * enum used as constant injector. + * + * @param input Entity class to treate + */ + protected void generateExtraConstants(ObjectModelClass input) { + Set<String> constants = addConstantsFromDependency(input, outputInterface); + + if (log.isDebugEnabled()) { + log.debug("Add constants from dependency : " + constants); + } + } + + protected void generateExtraOperations(ObjectModelClass input) { + for (ObjectModelOperation operation : input.getOperations()) { + + String opName = operation.getName(); + String opType = operation.getReturnType(); + ObjectModelModifier visibility = + ObjectModelJavaModifier.fromVisibility(operation.getVisibility()); + + if (log.isDebugEnabled()) { + log.debug("Extra operation for : " + input.getQualifiedName() + + " - method : " + opName + + " - returnType : " + opType + + " - visibility : " + visibility); + } + + // Deprecated from 2.3.4 + // Pas de génération des signatures de méthodes pour celles à intégrer au DAO de l'entité + if (TopiaGeneratorUtil.hasDaoStereotype(operation)) { + return; + + // Generate entity methods which have not a public visibility. + // Only in abstract entity class as abstract operation. + } else if (!visibility.equals(ObjectModelJavaModifier.PUBLIC)) { + addOperation(outputAbstract, opName, opType, visibility, + ObjectModelJavaModifier.ABSTRACT); + + // Other operations, only in entity interface, implementations + // need to be done in implementation class created by developper + } else { + cloneOperationSignature(operation, outputInterface, true); + } + } + } + + /** + * Generate properties from {@code attributes}. Generate + * constant, attribute and operations for each property. + * + * @param attributes Input attributes + */ + protected void generateProperties(Collection<ObjectModelAttribute> attributes) { + for (ObjectModelAttribute attribute : attributes) { + + if (!associationClass) { + + // FIXME-fdesbois-2010-06-25 : Strange behavior to keep those links, will break hibernate, may be a problem in mapping + if (!attribute.isNavigable() && attribute.hasAssociationClass()) { + generatePropertyConstant(attribute); + + generatePropertyAttribute(attribute); + + updateAcceptOperation(attribute); + } + + if (!attribute.isNavigable() && + !TopiaGeneratorUtil.hasUnidirectionalRelationOnAbstractType( + attribute.getReverseAttribute(), model)) { + continue; + } + } + + // constant + generatePropertyConstant(attribute); + + // attribute + generatePropertyAttribute(attribute); + + // operations + generatePropertyOperations(attribute); + + // update accept body + updateAcceptOperation(attribute); + } + } + + // ------------------------------------------------------------------------- + // Generate for property + // ------------------------------------------------------------------------- + + /** + * Generate constant in interface for {@code attribute}. + * + * @param attribute Input attribute to treate + * @see #getPropertyName(ObjectModelAttribute) + */ + protected void generatePropertyConstant(ObjectModelAttribute attribute) { + String attrName = getPropertyName(attribute); + + if (log.isDebugEnabled()) { + log.debug("Generate constant for property : " + attrName); + } + + addAttribute(outputInterface, getConstantName(attrName), String.class, + "\"" + attrName + "\""); + } + + protected void generatePropertyAttribute(ObjectModelAttribute attribute) { + + String attrName = getPropertyName(attribute); + String attrType = getPropertyType(attribute); + String collectionType = getCollectionType(attribute); + + if (collectionType != null) { + attrType = collectionType + "<" + attrType + ">"; + } + + //String attrVisibility = attr.getVisibility(); + + // Declaration + ObjectModelAttribute property = + addAttribute(outputAbstract, attrName, attrType, null, + //ObjectModelJavaModifier.toValue(attrVisibility), + ObjectModelJavaModifier.PROTECTED + ); + + // Documentation + StringBuilder buffer = new StringBuilder(); + if (TopiaGeneratorUtil.hasDocumentation(attribute)) { + String attrDocumentation = attribute.getDocumentation(); + buffer.append(attrDocumentation).append('\n'); + } + + String dbName = TopiaGeneratorUtil.getDbName(attribute); + if (!StringUtils.isEmpty(dbName)) { + buffer.append("Nom de l'attribut en BD : ").append(dbName).append('\n'); + } + setDocumentation(property, buffer.toString()); + + // Annotation + String annotation = TopiaGeneratorUtil.getAnnotationTagValue(attribute); + if (!StringUtils.isEmpty(annotation)) { + //FIXME Make annotation works... + //TODO tchemit 20100513 Test it still works + addAnnotation(outputAbstract, property, annotation); + } + } + + /** + * Generation operations for {@code attributes}. + * One method exists for each operation to generate. Methods starting + * with 'addSingle' is for maxMultiplicity attribute = 1 and for collection + * case, methods start with 'addMultiple'. Other case are take care in each + * method (association class, reverse, entity reference, ...). + * + * @param attribute Input attribute to treate + * @see #addSingleGetOperation(ObjectModelAttribute, String, String) + * @see #addSingleSetOperation(ObjectModelAttribute) + * @see #addMultipleAddOperation(ObjectModelAttribute, String) + * @see #addMultipleAddAllOperation(ObjectModelAttribute, String) + * @see #addMultipleSetOperation(ObjectModelAttribute, String, String) + * @see #addMultipleRemoveOperation(ObjectModelAttribute) + * @see #addMultipleClearOperation(ObjectModelAttribute, String, String) + * @see #addMultipleGetOperation(ObjectModelAttribute, String) + * @see #addMultipleGetTopiaIdOperation(ObjectModelAttribute) + * @see #addMultipleGetOperationFromEntity(ObjectModelAttribute) + * @see #addMultipleSizeOperation(ObjectModelAttribute) + * @see #addMultipleIsEmptyOperation(ObjectModelAttribute) + */ + protected void generatePropertyOperations(ObjectModelAttribute attribute) { + + if (attribute.getMaxMultiplicity() == 1 || associationClass) { + + // setXXX + addSingleSetOperation(attribute); + + boolean booleanProperty = + TopiaGeneratorUtil.isBooleanPrimitive(attribute); + + String attrType = getPropertyType(attribute); + + if (booleanProperty) { + + // isXXX + addSingleGetOperation( + attribute, + attrType, + TopiaGeneratorUtil.OPERATION_GETTER_BOOLEAN_PREFIX); + } + + if (!booleanProperty || generateBooleanGetMethods) { + + // getXXX + addSingleGetOperation( + attribute, + attrType, + TopiaGeneratorUtil.OPERATION_GETTER_DEFAULT_PREFIX); + } + + } else { + + // List, Set or Collection ? + String collectionInterface = + TopiaGeneratorUtil.getNMultiplicityInterfaceType(attribute); + String collectionImpl = + TopiaGeneratorUtil.getNMultiplicityObjectType(attribute); + + addImport(outputInterface, collectionInterface); + addImport(outputAbstract, collectionInterface); + addImport(outputAbstract, collectionImpl); + + collectionInterface = + TopiaGeneratorUtil.getSimpleName(collectionInterface); + collectionImpl = + TopiaGeneratorUtil.getSimpleName(collectionImpl); + + // addXXX + addMultipleAddOperation(attribute, collectionImpl); + + // addAllXXX + addMultipleAddAllOperation(attribute, collectionInterface); + + // setXXX + addMultipleSetOperation(attribute, collectionInterface, collectionImpl); + + // removeXXX + addMultipleRemoveOperation(attribute); + + // clearXXX + addMultipleClearOperation(attribute, collectionInterface, collectionImpl); + + // getXXX + addMultipleGetOperation(attribute, collectionInterface); + + if (TopiaGeneratorUtil.isEntity(attribute, model)) { + + // getXXXByTopiaId + addMultipleGetTopiaIdOperation(attribute); + } + + if (attribute.hasAssociationClass()) { + // getXXX with entity parameter + addMultipleGetOperationFromEntity(attribute); + } + + // sizeXXX + addMultipleSizeOperation(attribute); + + // isXXXEmpty + addMultipleIsEmptyOperation(attribute); + } + } + + protected void addSingleSetOperation(ObjectModelAttribute attribute) { + + String attrName = getPropertyName(attribute); + String attrType = getPropertyType(attribute); + + if (log.isDebugEnabled()) { + log.debug("Generate single 'set' operation for property : " + attrName + + " [" + attrType + "]"); + } + + // Interface operation + ObjectModelOperation interfaceOperation = + createPropertySetterSignature(outputInterface, attrType, attrName, + ""); + + // Implementation + ObjectModelOperation implOperation = createImplOperation(interfaceOperation); + + attrType = TopiaGeneratorUtil.getSimpleName(attrType); + + String constantName = getConstantName(attrName); + + setOperationBody(implOperation, "" +/*{ + <%=attrType%> oldValue = this.<%=attrName%>; + fireOnPreWrite(<%=constantName%>, oldValue, <%=attrName%>); + this.<%=attrName%> = <%=attrName%>; + fireOnPostWrite(<%=constantName%>, oldValue, <%=attrName%>); + }*/ + ); + } + + /** + * Add getter for simple property (neither association nor multiple). + * Will add two different operations for boolean case ('is' method and + * 'get' method). This method add the operation in both {@code + * outputAbstract} and {@code outputInterface}. + * + * @param attribute ObjectModelAttribute for getter operation + * @param attrType type of the attribute + * @param operationPrefix Operation prefix : 'get' by default, if prefix + * is null + */ + protected void addSingleGetOperation(ObjectModelAttribute attribute, + String attrType, + String operationPrefix) { + + String attrName = getPropertyName(attribute); + + if (log.isDebugEnabled()) { + log.debug("Generate single '" + operationPrefix + "' operation for property : " + + attrName + " [" + attrType + "]"); + } + + String constantName = getConstantName(attrName); + + // Interface operation + ObjectModelOperation interfaceOperation = + addOperation(outputInterface, getJavaBeanMethodName(operationPrefix, attrName), + attrType, ObjectModelJavaModifier.PACKAGE); + + // Implementation + ObjectModelOperation implOperation = + createImplOperation(interfaceOperation); + + attrType = TopiaGeneratorUtil.getSimpleName(attrType); + + setOperationBody(implOperation, "" +/*{ + fireOnPreRead(<%=constantName%>, <%=attrName%>); + <%=attrType%> result = this.<%=attrName%>; + fireOnPostRead(<%=constantName%>, <%=attrName%>); + return result; + }*/ + ); + } + + protected void addMultipleAddOperation(ObjectModelAttribute attribute, + String collectionImpl) { + + String attrName = getPropertyName(attribute); + String attrType = getPropertyType(attribute); + ObjectModelAttribute reverse = attribute.getReverseAttribute(); + + if (log.isDebugEnabled()) { + log.debug("Generate multiple 'add' operation for property : " + attrName + + " [" + attrType + "]"); + } + + String constantName = getConstantName(attrName); + + // Interface operation + ObjectModelOperation interfaceOperation = + addOperation(outputInterface, getJavaBeanMethodName("add", attrName), + void.class, ObjectModelJavaModifier.PACKAGE); + ObjectModelParameter param = + addParameter(interfaceOperation, attrType, attrName); + + // Implementation + ObjectModelOperation implOperation = createImplOperation(interfaceOperation); + + attrType = TopiaGeneratorUtil.getSimpleName(attrType); + + StringBuilder body = new StringBuilder(); + + body.append("" +/*{ + fireOnPreWrite(<%=constantName%>, null, <%=attrName%>); + if (this.<%=attrName%> == null) { + this.<%=attrName%> = new <%=collectionImpl%><<%=attrType%>>(); + } +}*/ + ); + + if (reverse != null && (reverse.isNavigable() || + hasUnidirectionalRelationOnAbstractType(attribute, model))) { + String getterName = getJavaBeanMethodName("get", reverse.getName()); + String setterName = getJavaBeanMethodName("set", reverse.getName()); + + String reverseAttrType = TopiaGeneratorUtil.getSimpleName(reverse.getType()); + + if (!TopiaGeneratorUtil.isNMultiplicity(reverse)) { + body.append("" +/*{ + <%=attrName%>.<%=setterName%>(this); +}*/ + ); + // Don't manage reverse attribute add if attribute has associationClass + } else if (!attribute.hasAssociationClass()) { + body.append("" +/*{ + if (<%=attrName%>.<%=getterName%>() == null) { + <%=attrName%>.<%=setterName%>(new <%=collectionImpl%><<%=reverseAttrType%>>()); + } + <%=attrName%>.<%=getterName%>().add(this); +}*/ + ); + } + } + body.append("" +/*{ + this.<%=attrName%>.add(<%=attrName%>); + fireOnPostWrite(<%=constantName%>, this.<%=attrName%>.size(), null, <%=attrName%>); + }*/ + ); + setOperationBody(implOperation, body.toString()); + } + + protected void addMultipleAddAllOperation(ObjectModelAttribute attribute, + String collectionInterface) { + + String attrName = getPropertyName(attribute); + String attrType = getPropertyType(attribute); + + if (log.isDebugEnabled()) { + log.debug("Generate multiple 'addAll' operation for property : " + attrName + + " [" + attrType + "]"); + } + + // Interface operation + ObjectModelOperation interfaceOperation = + addOperation(outputInterface, getJavaBeanMethodName("addAll", attrName), + void.class, ObjectModelJavaModifier.PACKAGE); + ObjectModelParameter param = + addParameter(interfaceOperation, collectionInterface + "<" + attrType + ">", attrName); + + // Implementation + ObjectModelOperation implOperation = + createImplOperation(interfaceOperation); + + attrType = TopiaGeneratorUtil.getSimpleName(attrType); + String addMethodName = getJavaBeanMethodName("add", attrName); + setOperationBody(implOperation, "" +/*{ + if (<%=attrName%> == null) { + return; + } + for (<%=attrType%> item : <%=attrName%>) { + <%=addMethodName%>(item); + } + }*/ + ); + } + + protected void addMultipleSetOperation(ObjectModelAttribute attribute, + String collectionInterface, + String collectionImpl) { + + String attrName = getPropertyName(attribute); + String referenceType = getPropertyType(attribute); + String attrType = collectionInterface + "<" + referenceType + ">"; + String constantName = getConstantName(attrName); + + if (log.isDebugEnabled()) { + log.debug("Generate multiple 'set' operation for property : " + attrName + + " [" + attrType + "]"); + } + + // Interface operation + ObjectModelOperation interfaceOperation = + createPropertySetterSignature(outputInterface, attrType, attrName, + ""); + + ObjectModelOperation implOperation = createImplOperation(interfaceOperation); + + attrType = TopiaGeneratorUtil.getSimpleName(attrType); + referenceType = TopiaGeneratorUtil.getSimpleName(referenceType); + + // Force fire for collection + setOperationBody(implOperation, "" +/*{ + // Copy elements to keep data for fire with new reference + <%=attrType%> oldValue = this.<%=attrName%> != null ? new <%=collectionImpl%><<%=referenceType%>>(this.<%=attrName%>) : null; + fireOnPreWrite(<%=constantName%>, oldValue, <%=attrName%>); + this.<%=attrName%> = <%=attrName%>; + fireOnPostWrite(<%=constantName%>, oldValue, <%=attrName%>); + }*/ + ); + } + + protected void addMultipleRemoveOperation(ObjectModelAttribute attribute) { + + String attrName = getPropertyName(attribute); + String attrType = getPropertyType(attribute); + ObjectModelAttribute reverse = attribute.getReverseAttribute(); + String constantName = getConstantName(attrName); + + if (log.isDebugEnabled()) { + log.debug("Generate 'remove' operation for property : " + attrName + + " [" + attrType + "]"); + } + + // Interface operation + ObjectModelOperation interfaceOperation = + addOperation(outputInterface, getJavaBeanMethodName("remove" , attrName), + void.class, ObjectModelJavaModifier.PACKAGE); + ObjectModelParameter param = + addParameter(interfaceOperation, attrType, attrName); + + // Implementation + ObjectModelOperation implOperation = createImplOperation(interfaceOperation); + + attrType = TopiaGeneratorUtil.getSimpleName(attrType); + + StringBuilder body = new StringBuilder(); + + body.append("" +/*{ + fireOnPreWrite(<%=constantName%>, <%=attrName%>, null); + if (this.<%=attrName%> == null || !this.<%=attrName%>.remove(<%=attrName%>)) { + throw new IllegalArgumentException("List does not contain given element"); + } +}*/ + ); + + if (reverse != null && (reverse.isNavigable() || + hasUnidirectionalRelationOnAbstractType(attribute, model))) { + String getterName = getJavaBeanMethodName("get", reverse.getName()); + String setterName = getJavaBeanMethodName("set", reverse.getName()); + if (!TopiaGeneratorUtil.isNMultiplicity(reverse)) { + body.append("" +/*{ + <%=attrName%>.<%=setterName%>(null); +}*/ + ); + // Don't manage reverse attribute remove if attribute has associationClass + } else if (!attribute.hasAssociationClass()) { + body.append("" +/*{ + <%=attrName%>.<%=getterName%>().remove(this); +}*/ + ); + } + } + body.append("" +/*{ + fireOnPostWrite(<%=constantName%>, this.<%=attrName%>.size() + 1, <%=attrName%>, null); + }*/ + ); + setOperationBody(implOperation, body.toString()); + } + + protected void addMultipleClearOperation(ObjectModelAttribute attribute, + String collectionInterface, + String collectionImpl) { + + String attrName = getPropertyName(attribute); + String attrType = getPropertyType(attribute); + ObjectModelAttribute reverse = attribute.getReverseAttribute(); + String constantName = getConstantName(attrName); + + if (log.isDebugEnabled()) { + log.debug("Generate multiple 'clear' operation for property : " + attrName + + " [" + attrType + "]"); + } + + // Interface operation + ObjectModelOperation interfaceOperation = + addOperation(outputInterface, getJavaBeanMethodName("clear" , attrName), + void.class, ObjectModelJavaModifier.PACKAGE); + + // Implementation + ObjectModelOperation implOperation = createImplOperation(interfaceOperation); + + attrType = TopiaGeneratorUtil.getSimpleName(attrType); + + StringBuilder body = new StringBuilder("" +/*{ + if (this.<%=attrName%> == null) { + return; + } +}*/ + ); + + if (reverse != null && (reverse.isNavigable() || + hasUnidirectionalRelationOnAbstractType(attribute, model))) { + String getterName = getJavaBeanMethodName("get", reverse.getName()); + String setterName = getJavaBeanMethodName("set", reverse.getName()); + body.append("" +/*{ for (<%=attrType%> item : this.<%=attrName%>) { +}*/ + ); + if (!TopiaGeneratorUtil.isNMultiplicity(reverse)) { + body.append("" +/*{ item.<%=setterName%>(null); +}*/ + ); + // Don't manage reverse attribute remove if attribute has associationClass + } else if (!attribute.hasAssociationClass()) { + body.append("" +/*{ item.<%=getterName%>().remove(this); +}*/ + ); + } + body.append("" +/*{ } +}*/ + ); + } + body.append("" +/*{ <%=collectionInterface%><<%=attrType%>> oldValue = new <%=collectionImpl%><<%=attrType%>>(this.<%=attrName%>); + fireOnPreWrite(<%=constantName%>, oldValue, this.<%=attrName%>); + this.<%=attrName%>.clear(); + fireOnPostWrite(<%=constantName%>, oldValue, this.<%=attrName%>); + }*/ + ); + setOperationBody(implOperation, body.toString()); + } + + protected void addMultipleGetOperation(ObjectModelAttribute attribute, + String collectionInterface) { + + String attrName = getPropertyName(attribute); + String attrType = collectionInterface + "<" + getPropertyType(attribute) + ">"; + + if (log.isDebugEnabled()) { + log.debug("Generate multiple 'get' operation for property : " + attrName + + " [" + attrType + "]"); + } + + // Interface operation + ObjectModelOperation interfaceOperation = + addOperation(outputInterface, getJavaBeanMethodName("get" , attrName), + attrType, ObjectModelJavaModifier.PACKAGE); + + // Implementation + ObjectModelOperation implOperation = createImplOperation(interfaceOperation); + + setOperationBody(implOperation, "" +/*{ + return <%=attrName%>; + }*/ + ); + } + + protected void addMultipleGetTopiaIdOperation(ObjectModelAttribute attribute) { + + String attrName = getPropertyName(attribute); + String attrType = getPropertyType(attribute); + + if (log.isDebugEnabled()) { + log.debug("Generate multiple 'getByTopiaId' operation for property : " + attrName + + " [" + attrType + "]"); + } + + // Interface operation + ObjectModelOperation interfaceOperation = + addOperation(outputInterface, getJavaBeanMethodName("get", attrName) + "ByTopiaId", + attrType, ObjectModelJavaModifier.PACKAGE); + ObjectModelParameter param = + addParameter(interfaceOperation, String.class, "topiaId"); + + // Implementation + ObjectModelOperation implOperation = + createImplOperation(interfaceOperation); + + addImport(outputAbstract, TopiaEntityHelper.class); + + setOperationBody(implOperation, "" +/*{ + return TopiaEntityHelper.getEntityByTopiaId(<%=attrName%>, topiaId); + }*/ + ); + } + + protected void addMultipleGetOperationFromEntity(ObjectModelAttribute attribute) { + + // reference to the real attribute name + String referenceName = attribute.getName(); + String referenceType = attribute.getType(); + + String referenceGetterName = getJavaBeanMethodName("get", referenceName); + // association attribute name + String attrName = getPropertyName(attribute); + String attrType = getPropertyType(attribute); + + if (log.isDebugEnabled()) { + log.debug("Generate multiple 'getFromEntity' operation for property : " + attrName + + " [" + attrType + "]"); + } + + // Interface operation + ObjectModelOperation interfaceOperation = + addOperation(outputInterface, + getJavaBeanMethodName("get", attrName), attrType); + + addParameter(interfaceOperation, referenceType, referenceName); + + // Implementation + ObjectModelOperation implOperation = createImplOperation(interfaceOperation); + + attrType = TopiaGeneratorUtil.getSimpleName(attrType); + + setOperationBody(implOperation, "" +/*{ + if (<%=referenceName%> == null || this.<%=attrName%> == null) { + return null; + } + for (<%=attrType%> item : this.<%=attrName%>) { + if (<%=referenceName%>.equals(item.<%=referenceGetterName%>())) { + return item; + } + } + return null; + }*/ + ); + } + + protected void addMultipleSizeOperation(ObjectModelAttribute attribute) { + + String attrName = getPropertyName(attribute); + + if (log.isDebugEnabled()) { + log.debug("Generate multiple 'size' operation for property : " + attrName); + } + + // Interface operation + ObjectModelOperation interfaceOperation = + addOperation(outputInterface, getJavaBeanMethodName("size", attrName), + int.class, ObjectModelJavaModifier.PACKAGE); + + // Implementation + ObjectModelOperation implOperation = createImplOperation(interfaceOperation); + + setOperationBody(implOperation, "" +/*{ + if (<%=attrName%> == null) { + return 0; + } + return <%=attrName%>.size(); + }*/ + ); + } + + protected void addMultipleIsEmptyOperation(ObjectModelAttribute attribute) { + + String attrName = getPropertyName(attribute); + + if (log.isDebugEnabled()) { + log.debug("Generate multiple 'isEmpty' operation for property : " + attrName); + } + + String sizeMethodName = getJavaBeanMethodName("size", attrName); + // Interface operation + ObjectModelOperation interfaceOperation = + addOperation(outputInterface, getJavaBeanMethodName("is", attrName)+ "Empty", + boolean.class, ObjectModelJavaModifier.PACKAGE); + + // Implementation + ObjectModelOperation implOperation = createImplOperation(interfaceOperation); + + setOperationBody(implOperation, "" +/*{ + int size = <%=sizeMethodName%>(); + return size == 0; + }*/ + ); + } + + // ------------------------------------------------------------------------- + // Generate util operations + // ------------------------------------------------------------------------- + + private ObjectModelOperation acceptOperation; + + private StringBuilder acceptOperationBody; + + protected void createAcceptOperation() { + + // Declaration + acceptOperation = addOperation(outputAbstract, "accept", void.class); + addAnnotation(outputAbstract, acceptOperation , Override.class); + ObjectModelParameter param = + addParameter(acceptOperation, EntityVisitor.class, "visitor"); + + addException(acceptOperation, TopiaException.class); + + // Body init + acceptOperationBody = new StringBuilder("" +/*{ + visitor.start(this); +}*/ + ); + } + + protected void updateAcceptOperation(ObjectModelAttribute attribute) { + String attrName = + TopiaGeneratorUtil.getSimpleName(getPropertyName(attribute)); + String attrType = + TopiaGeneratorUtil.getSimpleName(getPropertyType(attribute)); + String collectionType = getCollectionType(attribute); + String constantName = getConstantName(attrName); + if (collectionType != null) { + collectionType = TopiaGeneratorUtil.getSimpleName(collectionType); + acceptOperationBody.append("" +/*{ visitor.visit(this, <%=constantName%>, <%=collectionType%>.class, <%=attrType%>.class, <%=attrName%>); +}*/ + ); + } else { + acceptOperationBody.append("" +/*{ visitor.visit(this, <%=constantName%>, <%=attrType%>.class, <%=attrName%>); +}*/ + ); + } + } + + protected void closeAcceptOperation() { + acceptOperationBody.append("" +/*{ visitor.end(this); + }*/ + ); + setOperationBody(acceptOperation, acceptOperationBody.length() == 0 ? + " " : acceptOperationBody.toString()); + } + + protected void generateToStringOperation(ObjectModelClass input) { + + if (log.isDebugEnabled()) { + log.debug("generate toString method for entity " + + outputInterface.getQualifiedName()); + } + ObjectModelOperation operation = + addOperation(outputAbstract, "toString", String.class); + + addAnnotation(outputAbstract, operation, Override.class); + + addImport(outputAbstract, ToStringBuilder.class); + + StringBuilder body = new StringBuilder("" +/*{ + String result = new ToStringBuilder(this). +}*/ + ); + for (ObjectModelAttribute attr : input.getAttributes()) { + + //FIXME possibilité de boucles (non directes) + + ObjectModelClass attrEntity = null; + + if (model.hasClass(attr.getType())) { + attrEntity = model.getClass(attr.getType()); + } + + boolean isEntity = attrEntity != null && + TopiaGeneratorUtil.isEntity(attrEntity); + + ObjectModelAttribute reverse = attr.getReverseAttribute(); + if (isEntity && (reverse == null || !reverse.isNavigable()) + && !attr.hasAssociationClass() || !isEntity) { + String attrName = attr.getName(); + String constantName = getConstantName(attrName); + body.append("" +/*{ append(<%=constantName%>, this.<%=attrName%>). +}*/ + ); + } + } + body.append("" +/*{ toString(); + return result; + }*/ + ); + setOperationBody(operation, body.length() == 0 ? " " : body.toString()); + + } + + protected void generateCompositeOperation(ObjectModelClass input) { + + ObjectModelOperation operation = + addOperation(outputAbstract, "getComposite", + List.class.getName() + '<' + TopiaEntity.class.getName() + '>'); + + addException(operation, TopiaException.class); + addAnnotation(outputAbstract, operation, Override.class); + + StringBuilder body; + if (!TopiaGeneratorUtil.isContextable(input)) { + body = new StringBuilder("" +/*{ + throw new UnsupportedOperationException("Since ToPIA 3.0, 'getComposite' is only available for contextable entities"); + }*/ + ); + } else { + addImport(outputAbstract, ArrayList.class); + addImport(outputAbstract, List.class); + + body = new StringBuilder("" +/*{ + List<TopiaEntity> tmp = new ArrayList<TopiaEntity>(); + + // pour tous les attributs rechecher les composites et les class d'asso + // on les ajoute dans tmp +}*/ + ); + for (ObjectModelAttribute attr : input.getAttributes()) { + + if (attr.referenceClassifier() && + TopiaGeneratorUtil.isEntity(attr.getClassifier())) { + + if (attr.isComposite()) { + String attrName = attr.getName(); + String getterName = getJavaBeanMethodName("get", attrName); + if (TopiaGeneratorUtil.isNMultiplicity(attr)) { + body.append("" +/*{ if (<%=getterName%>() != null) { + tmp.addAll(<%=getterName%>()); + } +}*/ + ); + } else { + body.append("" +/*{ tmp.add(<%=getterName%>()); +}*/ + ); + } + } else if (attr.hasAssociationClass()) { + String assocAttrName = TopiaGeneratorUtil.getAssocAttrName( + attr); + String assocClassFQN = TopiaGeneratorUtil.getSimpleName( + attr.getAssociationClass().getQualifiedName()); + String ref = "this." + TopiaGeneratorUtil.toLowerCaseFirstLetter( + assocAttrName); + if (!TopiaGeneratorUtil.isNMultiplicity(attr)) { + body.append("" +/*{ + if (<%=ref%> != null) { + tmp.add(<%=ref%>); + } +}*/ + ); + } else { + ObjectModelAttribute reverse = attr.getReverseAttribute(); + String reverseAttrName = reverse.getName(); + // On utilise pas l'attribut car il est potentiellement + // pas a jour, car pour les asso avec cardinalité + // personne ne fait de add. Ce qui est normal, mais + // pour pouvoir faire tout de meme des delete en cascade + // sur les asso, le champs est dans le mapping + // hibernate et donc il le faut aussi dans la classe + // sinon hibernate rale lorsqu'il charge l'objet + // if (<%=ref%> != null) { + // tmp.addAll(<%=ref%>); + // } + + body.append("" +/*{ + { + org.nuiton.topia.persistence.TopiaDAO<<%=assocClassFQN%>> dao = getTopiaContext().getDao(<%=assocClassFQN%>.class); + List<<%=assocClassFQN%>> findAllByProperties = dao.findAllByProperties("<%=reverseAttrName%>", this); + if (findAllByProperties != null) { + tmp.addAll(findAllByProperties); + } + } +}*/ + ); + } + } + } + } + body.append("" +/*{ + // on refait un tour sur chaque entity de tmp pour recuperer leur + // composite + List<TopiaEntity> result = new ArrayList<TopiaEntity>(); + for (TopiaEntity entity : tmp) { + if (entity != null) { + result.add(entity); + result.addAll(entity.getComposite()); + } + } + return result; + }*/ + ); + } + + setOperationBody(operation, body.length() == 0 ? " " : body.toString()); + } + + protected void generateAggregateOperation(ObjectModelClass input) { + + ObjectModelOperation operation = + addOperation(outputAbstract, "getAggregate", + List.class.getName() + '<' + TopiaEntity.class.getName() + '>'); + + addException(operation, TopiaException.class); + addAnnotation(outputAbstract, operation, Override.class); + + + StringBuilder body = new StringBuilder(); + if (!TopiaGeneratorUtil.isContextable(input)) { + body = new StringBuilder("" +/*{ + throw new UnsupportedOperationException("Since ToPIA 3.0, 'getComposite' is only available for contextable entities"); + }*/ + ); + } else { + + addImport(outputAbstract, ArrayList.class); + addImport(outputAbstract, List.class); + body .append("" +/*{ + List<TopiaEntity> tmp = new ArrayList<TopiaEntity>(); + + // pour tous les attributs rechecher les composites et les class d'asso + // on les ajoute dans tmp +}*/ + ); + for (ObjectModelAttribute attr : input.getAttributes()) { + + if (attr.referenceClassifier() && + TopiaGeneratorUtil.isEntity(attr.getClassifier()) && + attr.isAggregate()) { + + String attrName = attr.getName(); + String getterName = getJavaBeanMethodName("get", attrName); + if (TopiaGeneratorUtil.isNMultiplicity(attr)) { + body.append("" +/*{ tmp.addAll(<%=getterName%>()); +}*/ + ); + } else { + body.append("" +/*{ tmp.add(<%=getterName%>()); +}*/ + ); + } + } + } + body.append("" +/*{ + // on refait un tour sur chaque entity de tmp pour recuperer leur + // composite + List<TopiaEntity> result = new ArrayList<TopiaEntity>(); + for (TopiaEntity entity : tmp) { + result.add(entity); + result.addAll(entity.getAggregate()); + } + return result; + }*/ + ); + } + setOperationBody(operation, body.length() == 0 ? " " : body.toString()); + } + + // ------------------------------------------------------------------------- + // Helpers + // ------------------------------------------------------------------------- + + protected boolean isAbstract(ObjectModelClass clazz) { + if (clazz.isAbstract()) { + return true; + } + + //Une classe peut être abstraite si elle a des méthodes définies dans + // ses superinterface et non implantées dans ses superclasses + Collection<ObjectModelOperation> allInterfaceOperations = + clazz.getAllInterfaceOperations(true); + allInterfaceOperations.removeAll(clazz.getAllOtherOperations(true)); + for (ObjectModelOperation op : allInterfaceOperations) { + boolean implementationFound = false; + for (ObjectModelClass superClazz : clazz.getSuperclasses()) { + for (ObjectModelOperation matchingOp : + superClazz.getOperations(op.getName())) { + implementationFound = op.equals(matchingOp) && + !matchingOp.isAbstract(); + if (implementationFound) { + break; + } + } + if (implementationFound) { + break; + } + } + if (!implementationFound) { + if (log.isDebugEnabled()) { + log.debug(clazz.getName() + " : abstract operation " + op); + } + return true; + } + } + return false; + } + + protected String getCollectionType(ObjectModelAttribute attribute) { + String result = null; + if (!associationClass && TopiaGeneratorUtil.isNMultiplicity(attribute)) { + result = TopiaGeneratorUtil.getNMultiplicityInterfaceType(attribute); + } + return result; + } + + protected String getPropertyName(ObjectModelAttribute attribute) { + String propertyName = attribute.getName(); + if (!associationClass && attribute.hasAssociationClass()) { + propertyName = TopiaGeneratorUtil.getAssocAttrName(attribute); + } + return propertyName; + } + + protected String getPropertyType(ObjectModelAttribute attribute) { + String propertyType = attribute.getType(); + if (!associationClass && attribute.hasAssociationClass()) { + propertyType = attribute.getAssociationClass().getQualifiedName(); + } + return propertyType; + } + + protected ObjectModelOperation createImplOperation(ObjectModelOperation interfaceOperation) { + ObjectModelOperation implOperation = + cloneOperationSignature(interfaceOperation, outputAbstract, false); + addAnnotation(outputAbstract, implOperation, Override.class); + return implOperation; + } + + /** + * TODO-fdesbois-2010-06-25 : This method can be put in JavaBuilder or ObjectModelTransformerToJava + * + * This method create an set operation in {@code classifier} with + * {@code propertyType} as return type and {@code propertyName} used for + * operation name ('set[propertyName]'). {@code operationDocument} can + * also be added to the operation created. Only signature with default + * visibility will be added. + * + * @param classifier Classifier where the operation will be added + * @param propertyType Type of the property (better if qualified name) + * @param propertyName Name of the property to set + * @param operationDocumentation Documentation for the operation + * @return the created operation + */ + protected ObjectModelOperation createPropertySetterSignature(ObjectModelClassifier classifier, + String propertyType, + String propertyName, + String operationDocumentation) { + // Operation + ObjectModelOperation operation = + addOperation(classifier, + getJavaBeanMethodName("set", propertyName), void.class); + + ObjectModelParameter param = + addParameter(operation, propertyType, propertyName); + + // Documentation + if (StringUtils.isNotEmpty(operationDocumentation)) { + setDocumentation(operation, operationDocumentation); + setDocumentation(param, "La valeur de l'attribut à positionner."); + } + + return operation; + } + + protected void addInterface(List<String> interfaceAlreadyDone, + ObjectModelClassifier output, + ObjectModelClassifier interfaze) { + String qualifiedName = interfaze.getQualifiedName(); + if (!interfaceAlreadyDone.contains(qualifiedName)) { + + interfaceAlreadyDone.add(qualifiedName); + + if (output != null) { + + // add it to output + addInterface(output, qualifiedName); + + if (log.isTraceEnabled()) { + log.trace("Add interface " + qualifiedName + " on " + + output.getQualifiedName()); + } + } else { + if (log.isTraceEnabled()) { + log.trace("Skip included interface " + qualifiedName); + } + } + + // scan also all interfaces or super-classes of it + for (ObjectModelClassifier parent : interfaze.getInterfaces()) { + addInterface(interfaceAlreadyDone, null, parent); + } + } + } + + protected void addInterface(List<String> interfaceAlreadyDone, + ObjectModelClassifier output, + Class<?> clazz) { + String qualifiedName = clazz.getName(); + if (!interfaceAlreadyDone.contains(qualifiedName)) { + + // add it to output + addInterface(output, qualifiedName); + + } + } +} Copied: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/PersistenceContextTransformer.java (from rev 2882, trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/PersistenceContextTransformer.java) =================================================================== --- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/PersistenceContextTransformer.java (rev 0) +++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/PersistenceContextTransformer.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,262 @@ +package org.nuiton.topia.templates; + +/*{generator option: parentheses = false}*/ + +/*{generator option: writeString = +}*/ + +import org.nuiton.eugene.java.ObjectModelTransformerToJava; +import org.nuiton.eugene.models.object.ObjectModel; +import org.nuiton.eugene.models.object.ObjectModelClass; +import org.nuiton.eugene.models.object.ObjectModelJavaModifier; +import org.nuiton.eugene.models.object.ObjectModelOperation; +import org.nuiton.topia.AbstractTopiaPersistenceContext; +import org.nuiton.topia.HibernateProvider; +import org.nuiton.topia.TopiaListenableSupport; +import org.nuiton.topia.persistence.TopiaEntity; +import org.nuiton.topia.persistence.TopiaIdFactory; +import org.nuiton.topia.persistence.util.EntityOperator; +import org.nuiton.topia.persistence.util.EntityOperatorStore; + +import java.lang.reflect.Array; +import java.util.List; + +/** + * To generate PersistenceHelper + * + * @author tchemit <chemit@codelutin.com> + * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.templates.PersistenceContextTransformer" + * @since 3.0 + */ +public class PersistenceContextTransformer extends ObjectModelTransformerToJava { + + @Override + public void transformFromModel(ObjectModel input) { + + String packageName = TopiaGeneratorUtil.getPersistenceContextPackage(this, model); + + String entityAbstractName = TopiaGeneratorUtil.getPersistenceContextAbstractName(model); + + String entityConcreteName = TopiaGeneratorUtil.getPersistenceContextConcreteName(model); + + boolean generateAbstract = !isInClassPath(packageName, entityAbstractName); + + boolean generateConcrete = !isInClassPath(packageName, entityConcreteName); + + + if (generateAbstract) { + + generateAbstract(packageName, + entityAbstractName); + } + + if (generateConcrete) { + + generateImpl(packageName, + entityAbstractName, + entityConcreteName); + } + + } + + protected void generateAbstract(String packageName, + String className) { + + // try to find a super class by tag-value +// String superClass = TopiaGeneratorUtil.getPersistenceContextSuperClassTagValue(model); + String superClass = null; + + if (superClass == null) { + + // no super-class, use default one + superClass = AbstractTopiaPersistenceContext.class.getName(); + } + + ObjectModelClass output = createAbstractClass(className, packageName); + + setSuperClass(output, superClass); + + // detect if there is a contract to set on abstract + String contractName = TopiaGeneratorUtil.getPersistenceContextInterfaceName(model); + +// addInterface(output, TopiaPersistenceContext.class); + + boolean addPersistenceContextContract = isInClassPath(packageName, contractName); + + if (addPersistenceContextContract) { + addInterface(output, packageName + "." + contractName); + } + + String modelName = model.getName(); + String daoHelperClazzName = modelName + "DAOHelper"; + + String entityEnumName = modelName + "EntityEnum"; + + List<ObjectModelClass> entityClasses = + TopiaGeneratorUtil.getEntityClasses(model, true); + + boolean generateOperator = + TopiaGeneratorUtil.shouldGenerateOperatorForDAOHelper(model); + + boolean generateStandaloneEnum = + TopiaGeneratorUtil.shouldGenerateStandaloneEnumForDAOHelper(model); + + if (!generateStandaloneEnum) { + + addImport(output, packageName + "." + daoHelperClazzName + "." + entityEnumName); + + } + +// addImport(output, TopiaDAO.class); + addImport(output, TopiaEntity.class); +// addImport(output, TopiaContext.class); + addImport(output, Array.class); + addImport(output, Array.class); + + if (generateOperator) { + addImport(output, EntityOperator.class); + addImport(output, EntityOperatorStore.class); + } + + // add public constructor + ObjectModelOperation constructor = addConstructor( + output, + ObjectModelJavaModifier.PUBLIC); + addParameter(constructor, HibernateProvider.class, "hibernateProvider"); + addParameter(constructor, TopiaListenableSupport.class, "listenableSupport"); + addParameter(constructor, TopiaIdFactory.class, "topiaIdFactory"); + setOperationBody(constructor, "" +/*{ + super(hibernateProvider, listenableSupport, topiaIdFactory); + }*/ + ); + + ObjectModelOperation op; + + // getModelVersion method + String modelVersion = model.getVersion(); + op = addOperation(output, "getModelVersion", "String", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); + setOperationBody(op, "" +/*{ + return "<%=modelVersion%>"; + }*/ + ); + + // getModelName method + op = addOperation(output, "getModelName", "String", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); + setOperationBody(op, "" +/*{ + return "<%=modelName%>"; + }*/ + ); + + for (ObjectModelClass clazz : entityClasses) { + String clazzName = clazz.getName(); + + // TODO brendan 14/10/13 use method + String daoContractName = clazzName + "Dao"; + String daoClazzName = TopiaGeneratorUtil.getConcreteDaoName(clazz); + + // specialized getXXXDao method + op = addOperation(output, "get" + daoContractName, clazz.getPackageName() + '.' + daoClazzName); + addImport(output, clazz); + setOperationBody(op, "" +/*{ + <%=daoClazzName%> result = getDao(<%=clazzName%>.class, <%=daoClazzName%>.class); + return result; + }*/ + ); + + } + + // getContractClass method + op = addOperation(output, "getContractClass", "<T extends TopiaEntity> Class<T>", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); + addParameter(op, "Class<T>", "klass"); + setOperationBody(op, "" +/*{ + <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass); + return (Class<T>) constant.getContract(); + }*/ + ); + + // getImplementationClass method + op = addOperation(output, "getImplementationClass", "<T extends TopiaEntity> Class<T>", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); + addParameter(op, "Class<T>", "klass"); + setOperationBody(op, "" +/*{ + <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass); + return (Class<T>) constant.getImplementation(); + }*/ + ); + + // getContractClasses method + op = addOperation(output, "getContractClasses", "Class<? extends TopiaEntity>[]", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); + setOperationBody(op, "" +/*{ + <%=entityEnumName%>[] values = <%=entityEnumName%>.values(); + Class<? extends TopiaEntity>[] result = (Class<? extends TopiaEntity>[]) Array.newInstance(Class.class, values.length); + for (int i = 0; i < values.length; i++) { + result[i] = values[i].getContract(); + } + return result; + }*/ + ); + + // getImplementationClasses method + op = addOperation(output, "getImplementationClasses", "Class<? extends TopiaEntity>[]", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); + setOperationBody(op, "" +/*{ + <%=entityEnumName%>[] values = <%=entityEnumName%>.values(); + Class<? extends TopiaEntity>[] result = (Class<? extends TopiaEntity>[]) Array.newInstance(Class.class, values.length); + for (int i = 0; i < values.length; i++) { + result[i] = values[i].getImplementation(); + } + return result; + }*/ + ); + + // getContracts method + op = addOperation(output, "getContracts", entityEnumName + "[]", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); + setOperationBody(op, "" +/*{ + return <%=entityEnumName%>.values(); + }*/ + ); + + if (generateOperator) { + // getOperator method + op = addOperation(output, "getOperator", "<T extends TopiaEntity> EntityOperator<T>", ObjectModelJavaModifier.PUBLIC, ObjectModelJavaModifier.STATIC); + addParameter(op, "Class<T>", "klass"); + setOperationBody(op, "" +/*{ + <%=entityEnumName%> constant = <%=entityEnumName%>.valueOf(klass); + return EntityOperatorStore.getOperator(constant); + }*/ + ); + } + + } + + protected ObjectModelClass generateImpl(String packageName, + String entityAbstractName, + String entityConcreteName) { + + ObjectModelClass output = createClass(entityConcreteName, packageName); + + setSuperClass(output, entityAbstractName); + + ObjectModelOperation constructor = addConstructor( + output, + ObjectModelJavaModifier.PUBLIC); + addParameter(constructor, HibernateProvider.class, "hibernateProvider"); + addParameter(constructor, TopiaListenableSupport.class, "listenableSupport"); + addParameter(constructor, TopiaIdFactory.class, "topiaIdFactory"); + setOperationBody(constructor, "" +/*{ + super(hibernateProvider, listenableSupport, topiaIdFactory); + }*/ + ); + + return output; + } + +} Copied: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaGeneratorUtil.java (from rev 2882, trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaGeneratorUtil.java) =================================================================== --- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaGeneratorUtil.java (rev 0) +++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaGeneratorUtil.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,1687 @@ +package org.nuiton.topia.templates; + +import com.google.common.base.Preconditions; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.eugene.AbstractGenerator; +import org.nuiton.eugene.GeneratorUtil; +import org.nuiton.eugene.ModelPropertiesUtil; +import org.nuiton.eugene.java.JavaGeneratorUtil; +import org.nuiton.eugene.java.ObjectModelTransformerToJava; +import org.nuiton.eugene.models.object.ObjectModel; +import org.nuiton.eugene.models.object.ObjectModelAssociationClass; +import org.nuiton.eugene.models.object.ObjectModelAttribute; +import org.nuiton.eugene.models.object.ObjectModelClass; +import org.nuiton.eugene.models.object.ObjectModelClassifier; +import org.nuiton.eugene.models.object.ObjectModelElement; +import org.nuiton.eugene.models.object.ObjectModelInterface; +import org.nuiton.eugene.models.object.ObjectModelOperation; +import org.nuiton.eugene.models.object.ObjectModelParameter; +import org.nuiton.topia.persistence.AbstractTopiaDao; +import org.nuiton.topia.persistence.TopiaDAOImpl; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; + +/** + * Classe regroupant divers méthodes utiles pour la génération des entités + * <p/> + * Created: 13 déc. 2005 + * + * @author Arnaud Thimel <thimel@codelutin.com> + * @author tchemit <tchemit@codelutin.com> + * @author fdesbois <fdesbois@codelutin.com> + * @author chatellier <chatellier@codelutin.com> + * @version $Id$ + */ +public class TopiaGeneratorUtil extends JavaGeneratorUtil { + + /** Logger */ + private static final Log log = LogFactory.getLog(TopiaGeneratorUtil.class); + + /** + * dependency to add extra operations for entity dao. + * + * @since 2.3.4 + */ + public static final String DEPENDENCIES_DAO = "dao"; + + /** Type de persistence Hibernate */ + public static final String PERSISTENCE_TYPE_HIBERNATE = "hibernate"; + + /** Type de persistence LDAP */ + public static final String PERSISTENCE_TYPE_LDAP = "ldap"; + + /** Type de persistence par défaut (si aucun précisé) */ + public static final String PERSISTENCE_TYPE_DEFAULT = PERSISTENCE_TYPE_HIBERNATE; + + /** Propriété des générateurs indiquant le package par défaut */ + public static final String PROPERTY_DEFAULT_PACKAGE = "defaultPackage"; + + /** Le package par défaut si aucun n'est spécifié */ + public static final String DEFAULT_PACKAGE = "org.codelutin.malo"; + + /** Stratégie d'heritage par defaut. */ + public static final String DEFAULT_INHERITANCE_STRATEGY = "union-subclass"; + + /** + * The Eugene provider of tag values and stereotypes. + * + * @author tchemit <chemit@codelutin.com> + * @plexus.component role="org.nuiton.eugene.ModelPropertiesUtil$ModelPropertiesProvider" role-hint="topia" + * @since 2.3 + */ + public static class TopiaModelPropertiesProvider extends ModelPropertiesUtil.ModelPropertiesProvider { + + @Override + public void init() throws IllegalAccessException { + scanStereotypeClass(TopiaStereoTypes.class); + scanTagValueClass(TopiaTagValues.class); + } + } + + /** + * Renvoie le package par défaut pour le générateur donné + * + * @param generator le générateur donné + * @return le package par défaut du générator donné + */ + public static String getDefaultPackage(AbstractGenerator<?> generator) { + String packageName = generator.getProperty(PROPERTY_DEFAULT_PACKAGE); + if (StringUtils.isBlank(packageName)) { + packageName = DEFAULT_PACKAGE; + } + return packageName; + } + + public static String getApplicationContextPackage(ObjectModelTransformerToJava transformer, + ObjectModel model) { + + String result = transformer.getDefaultPackageName(); + + return result; + } + + public static String getPersistenceContextPackage(ObjectModelTransformerToJava transformer, + ObjectModel model) { + + String result = transformer.getDefaultPackageName(); + + return result; + } + + public static String getDaoPackage(ObjectModelTransformerToJava transformer, + ObjectModel model, + ObjectModelClassifier input) { + + Preconditions.checkState(isEntity(input), "Cant' find dao package name for a none entity " + input); + String result = input.getPackageName(); + return result; + } + + public static String getApplicationContextInterfaceName(ObjectModel model) { + return model.getName() + "ApplicationContext"; + } + + public static String getApplicationContextAbstractName(ObjectModel model) { + return "Abstract" + model.getName() + "TopiaApplicationContext"; + } + + public static String getApplicationContextConcreteName(ObjectModel model) { + return model.getName() + "TopiaApplicationContext"; + } + + public static String getPersistenceContextAbstractName(ObjectModel model) { + return "Abstract" + model.getName() + "TopiaPersistenceContext"; + } + + public static String getPersistenceContextConcreteName(ObjectModel model) { + return model.getName() + "TopiaPersistenceContext"; + } + + public static String getPersistenceContextInterfaceName(ObjectModel model) { + return model.getName() + "PersistenceContext"; + } + + public static String getEntityAbstractName(ObjectModelClass input) { + return "AbstractTopia" + input.getName(); + } + + public static String getEntityConcreteName(ObjectModelClass input) { + return input.getName(); + } + + public static String getAbstractDaoName(ObjectModelClass input) { + return "Abstract" + input.getName() + "TopiaDao"; + } + + public static String getGeneratedDaoName(ObjectModelClass input) { + return "Generated" + input.getName() + "TopiaDao"; + } + + public static String getConcreteDaoName(ObjectModelClass input) { + return input.getName() + "TopiaDao"; + } + + @Deprecated + public static String getLegacyDaoName(ObjectModelClass input) { + return input.getName() + "DAO"; + } + + public static String getAbstractDaoFqn(ObjectModelClass input) { + return input.getPackageName() + "." + getAbstractDaoName(input); + } + + public static String getGeneratedDaoFqn(ObjectModelClass input) { + return input.getPackageName() + "." + getGeneratedDaoName(input); + } + + public static String getConcreteDaoFqn(ObjectModelClass input) { + return input.getPackageName() + "." + getConcreteDaoName(input); + } + + @Deprecated + public static String getLegacyDaoFqn(ObjectModelClass input) { + return input.getPackageName() + "." + getLegacyDaoName(input); + } + + public static String getEntityPackage(ObjectModelTransformerToJava transformer, + ObjectModel model, + ObjectModelClassifier input) { + + String result = input.getPackageName(); + return result; + } + + /** + * Renvoie l'interface DAO associée à la classe passée en paramètre + * + * @param clazz la classe à tester + * @param model le modele utilisé + * @return l'interface trouvée ou null sinon + */ + public static ObjectModelInterface getDAOInterface(ObjectModelClass clazz, + ObjectModel model) { + for (Object o : model.getInterfaces()) { + ObjectModelInterface daoInterface = (ObjectModelInterface) o; + if (daoInterface.getName().equals(clazz.getName() + "DAO")) { + if (hasDaoStereotype(daoInterface)) { + return daoInterface; + } + } + } + return null; + } + + /** + * Renvoie le type de persistence pour le classifier donné. Si aucun n'est + * trouvé, le type par défaut est utilisé + * + * @param classifier l'élément à tester + * @return le type de persitence pour l'élément donné. + * @since 2.5 + */ + public static String getPersistenceType(ObjectModelClassifier classifier) { + String tag = getPersistenceTypeTagValue(classifier); + if (StringUtils.isEmpty(tag)) { + tag = PERSISTENCE_TYPE_DEFAULT; + } + return tag; + } + + /** + * Obtain the reverse db name of an attribute. + * <p/> + * If attribute has a specific reverse attribute, use his db name, otherwise + * suffix the db name of the attribute by {@code _id}. + * + * @param attr the attribute to seek + * @return the value of the reverse name + * @since 2.5 + */ + public static String getReverseDbName(ObjectModelAttribute attr) { + if (attr.getReverseAttribute() != null) { + return getDbName(attr.getReverseAttribute()); + } else { + return getDbName(attr) + "_id"; + } + } + + /** + * Renvoie le nom BD de l'élement passé en paramètre. Elle se base sur le + * tag associé si il existe, sinon sur le nom de l'élément + * + * @param element l'élément à tester + * @return le nom de table + */ + public static String getDbName(ObjectModelElement element) { + if (element == null) { + return null; + } + String value = getDbNameTagValue(element); + if (!StringUtils.isEmpty(value)) { + return value; + } + return toLowerCaseFirstLetter(element.getName()); + } + + /** + * Cherche si le tagvalue {@link TopiaTagValues#TAG_GENERATE_OPERATOR_FOR_DAO_HELPER} a été + * activé dans le model. + * + * @param model le modele utilisé + * @return {@code true} si le tag value trouvé dans le modèle, {@code false} + * sinon. + * @since 2.5 + */ + public static boolean shouldGenerateOperatorForDAOHelper(ObjectModel model) { + String tagValue = getGenerateOperatorForDAOHelperTagValue(model); + boolean generate = StringUtils.isNotEmpty(tagValue) && + Boolean.valueOf(tagValue); + return generate; + } + + /** + * Cherche si le tagvalue {@link TopiaTagValues#TAG_GENERATE_OPERATOR_FOR_DAO_HELPER} a été + * activé dans le model. + * + * @param model le modele utilisé + * @return {@code true} si le tag value trouvé dans le modèle, {@code false} + * sinon. + * @since 2.5 + */ + public static boolean shouldGenerateStandaloneEnumForDAOHelper(ObjectModel model) { + String tagValue = getGenerateStandaloneEnumForDAOHelperTagValue(model); + boolean generate = StringUtils.isNotEmpty(tagValue) && + Boolean.valueOf(tagValue); + return generate; + } + + /** + * Cherche et renvoie la liste des attributs constituant la clef metier + * d'une classe. + * + * @param clazz la classe à tester + * @return la liste des attributs de la clef métier + */ + public static Set<ObjectModelAttribute> getNaturalIdAttributes( + ObjectModelClass clazz) { + + // use {@link LinkedHashSet} to keep order and prevent duplicate natural ids found + Set<ObjectModelAttribute> results = + new LinkedHashSet<ObjectModelAttribute>(); + for (ObjectModelAttribute attr : clazz.getAttributes()) { + if (isNaturalId(attr)) { + results.add(attr); + } + } + + // sletellier : #2050 Natural id and not null attributes are not propagated on generalized entities (http://nuiton.org/issues/2050) + Collection<ObjectModelClass> superclasses = clazz.getSuperclasses(); + for (ObjectModelClass superClass : superclasses) { + Set<ObjectModelAttribute> naturalIdsOfSuperClass = getNaturalIdAttributes(superClass); + results.addAll(naturalIdsOfSuperClass); + } + return results; + } + + /** + * Cherche et renvoie la liste des attributs qui ne doivent pas etre null dans + * une classe. + * + * @param clazz la classe à tester + * @return la liste des attributs qui ne doivent pas etre null + */ + public static Set<ObjectModelAttribute> getNotNullAttributes( + ObjectModelClass clazz) { + + // use {@link LinkedHashSet} to keep order and prevent duplicate not null found + Set<ObjectModelAttribute> results = + new LinkedHashSet<ObjectModelAttribute>(); + for (ObjectModelAttribute attr : clazz.getAttributes()) { + if (isNotNull(attr)) { + results.add(attr); + } + } + + Collection<ObjectModelClass> superclasses = clazz.getSuperclasses(); + for (ObjectModelClass superClass : superclasses) { + Set<ObjectModelAttribute> notNullOfSuperClass = getNotNullAttributes(superClass); + results.addAll(notNullOfSuperClass); + } + + // Association class participants are obviously not null + if (clazz instanceof ObjectModelAssociationClass) { + List<ObjectModelAttribute> participantsAttributes = ((ObjectModelAssociationClass) clazz).getParticipantsAttributes(); + results.addAll(participantsAttributes); + } + + return results; + } + + /** + * Test if we need to generate {@code toString} method for the given class. + * + * @param clazz class to test + * @param model model + * @return {@code true} if {@code toString} should be generated. + * clef métier. + */ + public static boolean generateToString(ObjectModelClass clazz, + ObjectModel model) { + String value = getNotGenerateToStringTagValue(clazz, model); + return StringUtils.isEmpty(value); + } + + + /** + * Cherche et renvoie la liste des attributs constituant la clef metier + * d'une classe. + * + * @param clazz la classe à tester + * @param model le modele + * @return la liste des attributs de la clef métier ou null si pas de + * clef métier. + */ + public static boolean sortAttribute(ObjectModelClass clazz, + ObjectModel model) { + String value = getSortAttributeTagValue(clazz, model); + return "true".equals(value); + } + + /** + * Detecte si un attribut fait partie d'une clef metier. + * + * @param attribute l'attribut à tester + * @return {@code true} si l'attribut fait partie d'une clef metier, + * <code>false</cdoe> sinon. + */ + public static boolean isNaturalId(ObjectModelAttribute attribute) { + String value = getNaturalIdTagValue(attribute); + if (StringUtils.isEmpty(value)) { + // valeur null, donc pas positionnee + return false; + } + try { + return Boolean.valueOf(value.trim()); + } catch (Exception e) { + // on a pas reussi a convertir en boolean. + //todo peut-être declancher une exception ? + return false; + } + } + + /** + * Detecte si un attribut est marqué comme non null. + * Les naturalId {@link #isNaturalId} sont not null par défaut + * + * @param attribute l'attribut à tester + * @return {@code true} si l'attribut doit être non null, + * par défaut pour les naturalId, {@code false} sinon.. + * @since 2.6.9 + */ + public static boolean isNotNull(ObjectModelAttribute attribute) { + String value = getNotNullTagValue(attribute); + if (StringUtils.isEmpty(value)) { + // valeur null, donc pas positionnee + return isNaturalId(attribute); + } + try { + return Boolean.valueOf(value.trim()); + } catch (Exception e) { + // on a pas reussi a convertir en boolean. + //todo peut-être declancher une exception ? + return false; + } + } + + public static <Type extends ObjectModelElement> Collection<Type> getElementsWithStereotype( + Collection<Type> elements, String... stereotypes) { + Collection<Type> result = new ArrayList<Type>(); + for (Type element : elements) { + if (hasStereotypes(element, stereotypes)) { + result.add(element); + } + } + return result; + } + + public static boolean hasStereotypes(ObjectModelElement element, + String... stereotypes) { + for (String stereotype : stereotypes) { + if (!element.hasStereotype(stereotype)) { + return false; + } + } + return true; + } + + public static String getPrimaryKeyAttributesListDeclaration( + ObjectModelClass clazz, boolean includeName) { + String attributes = ""; + Collection<ObjectModelAttribute> attributeCollection; + attributeCollection = getElementsWithStereotype(clazz.getAttributes(), + TopiaStereoTypes.STEREOTYPE_PRIMARYKAY); + for (ObjectModelAttribute attr : attributeCollection) { + attributes += attr.getType(); + if (includeName) { + attributes += ' ' + attr.getName(); + } + attributes += ", "; + } + if (attributes.length() > 0) { + attributes = attributes.substring(0, attributes.length() - 2); + } + return attributes; + } + + public static boolean isAssociationClassDoublon(ObjectModelAttribute attr) { + return attr.getReverseAttribute() != null && + attr.getDeclaringElement().equals( + attr.getReverseAttribute().getDeclaringElement()) && + !GeneratorUtil.isFirstAttribute(attr); + } + + public static String getDOType(ObjectModelElement elem, ObjectModel model) { + String type = elem.getName(); + if (elem instanceof ObjectModelAttribute) { + type = ((ObjectModelAttribute) elem).getType(); + } + if (elem instanceof ObjectModelClass) { + type = ((ObjectModelClass) elem).getQualifiedName(); + } + return getDOType(type, model); + } + + public static String getDOType(String type, ObjectModel model) { + if (!model.hasClass(type)) { + return type; + } + ObjectModelClass clazz = model.getClass(type); + if (isEntity(clazz)) { + //tchemit-2011-09-12 What ever abstract or not, we always use an Impl + type += "Impl"; +// if (shouldBeAbstract(clazz)) { +// type += "Abstract"; +// } else { +// type += "Impl"; +// } + } + return type; + } + + private static final Set<String> numberTypes = new HashSet<String>(); + + private static final Set<String> textTypes = new HashSet<String>(); + + private static final Set<String> booleanTypes = new HashSet<String>(); + + private static final Set<String> primitiveTypes = new HashSet<String>(); + + private static final Map<String, String> primitiveTypeToClass = new HashMap<String, String>(); + + private static final String VOID_TYPE = "void"; + + static { + + primitiveTypeToClass.put("byte", "java.lang.Byte"); + primitiveTypeToClass.put("short", "java.lang.Short"); + primitiveTypeToClass.put("int", "java.lang.Integer"); + primitiveTypeToClass.put("long", "java.lang.Long"); + primitiveTypeToClass.put("float", "java.lang.Float"); + primitiveTypeToClass.put("double", "java.lang.Double"); + primitiveTypeToClass.put("char", "java.lang.Char"); + primitiveTypeToClass.put("boolean", "java.lang.Boolean"); + + numberTypes.add("byte"); + numberTypes.add("java.lang.Byte"); + numberTypes.add("Byte"); + numberTypes.add("short"); + numberTypes.add("java.lang.Short"); + numberTypes.add("Short"); + numberTypes.add("int"); + numberTypes.add("java.lang.Integer"); + numberTypes.add("Integer"); + numberTypes.add("long"); + numberTypes.add("java.lang.Long"); + numberTypes.add("Long"); + numberTypes.add("float"); + numberTypes.add("java.lang.Float"); + numberTypes.add("Float"); + numberTypes.add("double"); + numberTypes.add("java.lang.Double"); + numberTypes.add("Double"); + + textTypes.add("char"); + textTypes.add("java.lang.Char"); + textTypes.add("Char"); + textTypes.add("java.lang.String"); + textTypes.add("String"); + + booleanTypes.add("boolean"); + booleanTypes.add("java.lang.Boolean"); + booleanTypes.add("Boolean"); + + primitiveTypes.addAll(numberTypes); + primitiveTypes.addAll(textTypes); + primitiveTypes.addAll(booleanTypes); + } + + public static boolean isNumericType(ObjectModelAttribute attr) { + return numberTypes.contains(attr.getType()); + } + + public static boolean isTextType(ObjectModelAttribute attr) { + return textTypes.contains(attr.getType()); + } + + public static boolean isDateType(ObjectModelAttribute attr) { + return "java.util.Date".equals(attr.getType()); + } + + public static boolean isBooleanType(ObjectModelAttribute attr) { + return booleanTypes.contains(attr.getType()); + } + + public static boolean isPrimitiveType(ObjectModelAttribute attr) { + return primitiveTypes.contains(attr.getType()); + } + + public static String getClassForPrimitiveType(ObjectModelAttribute attr) { + Preconditions.checkState(isPrimitiveType(attr)); + String className = primitiveTypeToClass.get(attr.getType()); + Preconditions.checkNotNull(className); + return className; + } + + /** + * Indique si la classe specifiee n'a aucune ou que des methodes abstraites + * + * @param clazz l'instance de ObjectModelClass + * @return true si la classe n'a que des operations abstraite ou aucune + * operation + */ + public static boolean hasNothingOrAbstractMethods(ObjectModelClass clazz) { + boolean result = true; + Iterator<?> operations = clazz.getOperations().iterator(); + while (result && operations.hasNext()) { + ObjectModelOperation op = (ObjectModelOperation) operations.next(); + result = op.isAbstract(); + } + return result; + } + + /** + * Indique si la classe specifiee devrait etre abstraite + * + * @param clazz l'instance de ObjectModelClass + * @return true dans ce cas, false sinon + */ + public static boolean shouldBeAbstract(ObjectModelClass clazz) { + return clazz != null && clazz.isAbstract() && + hasNothingOrAbstractMethods(clazz); + } + + /** + * <p> + * Cette méthode permet de détecter si + * - l'attribut représente une relation 1-n + * - cette relation est unidirectionnelle + * - le type de l'attribut représente un entité + * - cette entité a des sous-classes dans le modèle + * <p/> + * Ce cas correspond à une incompatibilité d'Hibernate qui nous oblige a + * adopter un comportement particulier. + * </p> + * + * @param attr l'attribut a tester + * @param model le model + * @return true si et seulement si il s'agit bien de ce type de relation + */ + public static boolean hasUnidirectionalRelationOnAbstractType( + ObjectModelAttribute attr, ObjectModel model) { + ObjectModelAttribute reverse = attr.getReverseAttribute(); + //relation 1-n + if (reverse != null && isNMultiplicity(attr) && + !isNMultiplicity(reverse)) { + //Pas de navigabilité + if (!reverse.isNavigable()) { + //Il s'agit d'une entity + ObjectModelClass clazz = model.getClass(attr.getType()); + if (clazz != null && isEntity(clazz)) { + //Cette classe a des sous-classes dans le modèle + for (ObjectModelClass subClass : model.getClasses()) { + if (subClass.getSuperclasses().contains(clazz)) { + return true; + } + } + } + } + } + return false; + } + + /** + * Renvoie le nom unique de table pour une relation ManyToMany en fonction + * de l'attribut <code>attr</code> + * <p/> + * Plusieurs cas de figure: + * <li> + * + * @param attr l'attribut servant de base au calcul du nom + * @return le nom de la table + */ + public static String getManyToManyTableName(ObjectModelAttribute attr) { + String result; + + if (attr.hasAssociationClass()) { + result = getDbName(attr.getAssociationClass()); + } else { + String name = attr.getName(); + String revers = attr.getReverseAttributeName(); + + if (name.compareToIgnoreCase(revers) < 0) { + result = name + '_' + revers; + } else { + result = revers + '_' + name; + } + } + return result.toLowerCase(); + } + + /** + * Renvoie le type d'interface à utiliser en fonction de l'attribut + * + * @param attr l'attribut a traiter + * @return String + */ + public static String getNMultiplicityInterfaceType( + ObjectModelAttribute attr) { + if (hasUniqueStereotype(attr)) { + return Set.class.getName(); + } else if (JavaGeneratorUtil.hasIndexedStereotype(attr) || attr.isOrdered()) { + return List.class.getName(); + } + return Collection.class.getName(); + } + + /** + * Renvoie le type d'objet (instance) à utiliser en fonction de l'attribut + * + * @param attr l'attribut a traiter + * @return String + */ + public static String getNMultiplicityObjectType(ObjectModelAttribute attr) { + if (hasUniqueStereotype(attr)) { + return HashSet.class.getName(); + } else if (JavaGeneratorUtil.hasIndexedStereotype(attr) || attr.isOrdered()) { + //On considère qu'on ne sait pas traiter vraiment l'attribut "ordered" + // puisqu'on va conserver l'ordre d'insertion, et non un ordre en + // fonction d'un élément donné. Donc on renvoi une ArrayList + return ArrayList.class.getName(); + } + LinkedList.class.getName(); + return ArrayList.class.getName(); + } + + /** + * Renvoie le type d'interface à utiliser en fonction de l'attribut + * + * @param attr l'attribut a traiter + * @return String + */ + public static String getNMultiplicityHibernateType( + ObjectModelAttribute attr) { + if (hasUniqueStereotype(attr)) { + return "set"; + } else if (JavaGeneratorUtil.hasIndexedStereotype(attr)) { + return "list"; + } + //attr.isOrdered() - On génère le ordered en bag + return "bag"; + } + + /** + * Obtain the list of entities classes with the possibility to sort the + * result. + * + * @param model the current model to scan + * @param sort flag to allow sort the result + * @return the list of filtred classes by their stereotype + */ + public static List<ObjectModelClass> getEntityClasses(ObjectModel model, + boolean sort) { + return getClassesByStereotype(TopiaStereoTypes.STEREOTYPE_ENTITY, model, sort); + } + + /** + * Obtain the list of classes for a given stereotype with the possibility + * to sort the result. + * + * @param stereotype filter stereotype + * @param model the current model to scan + * @param sort flag to allow sort the result + * @return the list of filtred classes by their stereotype + */ + public static List<ObjectModelClass> getClassesByStereotype( + String stereotype, ObjectModel model, boolean sort) { + List<ObjectModelClass> classes = new ArrayList<ObjectModelClass>(); + for (ObjectModelClass clazz : model.getClasses()) { + if (clazz.hasStereotype(stereotype)) { + classes.add(clazz); + } + } + if (sort && !classes.isEmpty()) { + + Collections.sort(classes, OBJECT_MODEL_CLASS_COMPARATOR); + } + return classes; + } + + static public final Comparator<ObjectModelClass> + OBJECT_MODEL_CLASS_COMPARATOR = + new Comparator<ObjectModelClass>() { + + @Override + public int compare(ObjectModelClass o1, + ObjectModelClass o2) { + return o1.getQualifiedName().compareTo( + o2.getQualifiedName()); + } + }; + + /** + * Detecte si la clef metier d'une classe est mutable ou pas. + * <p/> + * On respecte la valeur par defaut d'hibernate, à savoir que par default + * une clef metier est non mutable. + * + * @param clazz la classe a tester + * @return {@code true} si le tag value a ete positionne sur la classe + * via le tag {@link TopiaTagValues#TAG_NATURAL_ID_MUTABLE}, {@code false} + * sinon. + */ + public static boolean isNaturalIdMutable(ObjectModelClass clazz) { + String value = getNaturalIdMutableTagValue(clazz); + if (StringUtils.isEmpty(value)) { + // valeur null, donc par default positionnee + return false; + } + try { + return Boolean.valueOf(value.trim()); + } catch (Exception e) { + // on a pas reussi a convertir en boolean. + //todo peut-être declancher une exception ? + return false; + } + } + + /** + * Retourne true si le tagValue {@link TopiaTagValues#TAG_CONTEXTABLE} + * à la valeur {@code true}. + * + * @param classifier classifier to test + * @return {@code true} si {@link TopiaTagValues#TAG_CONTEXTABLE} == {@code true} + */ + public static boolean isContextable(ObjectModelClassifier classifier) { + boolean result = false; + String value = classifier.getTagValue(TopiaTagValues.TAG_CONTEXTABLE); + if (StringUtils.equalsIgnoreCase(value, "true")) { + result = true; + } + return result; + } + + /** + * Obtain the list of fqn of object involed in the given class. + * + * @param aClass the clazz to inspect + * @param incomingFqns incoming fqns + * @return the list of fqn of attributes + */ + public static List<String> getImports(ObjectModelClass aClass, + String... incomingFqns) { + Set<String> tmp = new HashSet<String>(); + tmp.addAll(Arrays.asList(incomingFqns)); + getImports(aClass, tmp); + List<String> result = cleanImports(aClass.getPackageName(), tmp); + return result; + } + + /** + * Obtain the list of fqn of object involed in the given interface. + * + * @param anInterface the interface to inspect + * @param incomingFqns incoming fqns + * @return the list of fqn of attributes + */ + public static List<String> getImports(ObjectModelInterface anInterface, + String... incomingFqns) { + Set<String> tmp = new HashSet<String>(); + tmp.addAll(Arrays.asList(incomingFqns)); + getImports(anInterface, tmp); + List<String> result = cleanImports(anInterface.getPackageName(), tmp); + return result; + } + + /** + * Obtain the list of fqn of object involed in the given class. + * + * @param aClass the class to inspect + * @param fqns where to store found fqns + */ + protected static void getImports(ObjectModelClass aClass, + Set<String> fqns) { + // scan attributes + for (ObjectModelAttribute attr : aClass.getAttributes()) { + fqns.add(attr.getType()); + if (isNMultiplicity(attr)) { + String collectionType = getNMultiplicityInterfaceType(attr); + fqns.add(collectionType); + String collectionObject = getNMultiplicityObjectType(attr); + fqns.add(collectionObject); + } + } + for (ObjectModelAttribute attribute : aClass.getAllOtherAttributes()) { + fqns.add(attribute.getType()); + } + // scan associations + if (aClass instanceof ObjectModelAssociationClass) { + ObjectModelAssociationClass assoc = + (ObjectModelAssociationClass) aClass; + for (ObjectModelAttribute attr : + assoc.getParticipantsAttributes()) { + if (attr == null) { + continue; + } + fqns.add(attr.getType()); + if (isNMultiplicity(attr)) { + String collectionType = getNMultiplicityInterfaceType(attr); + fqns.add(collectionType); + String collectionObject = getNMultiplicityObjectType(attr); + fqns.add(collectionObject); + } + } + } + // scan operations + for (ObjectModelOperation operation : aClass.getOperations()) { + getImports(operation, fqns); + } + // scan super interfaces + for (ObjectModelInterface modelInterface : aClass.getInterfaces()) { + fqns.add(modelInterface.getQualifiedName()); + getImports(modelInterface, fqns); + } + // scan super classes + for (ObjectModelClass modelClass : aClass.getSuperclasses()) { + fqns.add(modelClass.getQualifiedName()); + getImports(modelClass); + } + } + + /** + * Obtain the list of fqn of object involed in the given interface. + * + * @param anInterface the interface to inspect + * @param fqns where to store found fqns + */ + protected static void getImports(ObjectModelInterface anInterface, + Set<String> fqns) { + // scan operations + for (ObjectModelOperation operation : anInterface.getOperations()) { + getImports(operation, fqns); + } + // scan super interfaces + for (ObjectModelInterface modelInterface : anInterface.getInterfaces()) { + fqns.add(modelInterface.getQualifiedName()); + getImports(modelInterface, fqns); + } + } + + /** + * Obtain the fqn's list of all involed type in a givne operation. + * + * @param operation operation to inspect + * @param fqns where to store found fqns + */ + protected static void getImports(ObjectModelOperation operation, + Set<String> fqns) { + String fqn = operation.getReturnType(); + fqns.add(fqn); + for (ObjectModelParameter parameter : operation.getParameters()) { + fqns.add(parameter.getType()); + } + } + + /** + * Clean a set of fqns, transform it into a {@link List} and sort it. + * + * @param packageName the current package name + * @param fqns the dirty set of fqns + * @return the sorted cleaned list of fqns. + */ + protected static List<String> cleanImports(String packageName, + Set<String> fqns) { + fqns.removeAll(primitiveTypes); + fqns.remove(VOID_TYPE); + int packageLength = packageName.length(); + List<String> genericType = new ArrayList<String>(); + for (Iterator<String> it = fqns.iterator(); it.hasNext(); ) { + String fqn = it.next(); + int lastIndex = fqn.lastIndexOf("."); + if (lastIndex == packageLength && fqn.startsWith(packageName)) { + // same package + it.remove(); + continue; + } + int genericIndex = fqn.indexOf('<'); + if (genericIndex != -1) { + genericType.add(fqn.substring(0, genericIndex)); + it.remove(); + } + } + fqns.addAll(genericType); + + ArrayList<String> result = new ArrayList<String>(fqns); + Collections.sort(result); + return result; + } + + /** + * Obtain the class to use as abstract dao. + * <p/> + * It will look after a tag value {@link TopiaTagValues#TAG_DAO_IMPLEMENTATION} in model + * and if not found will use the default value which is {@link TopiaDAOImpl}. + * + * @param model the model which could contains + * @return the type of the abstract dao to use + * @since 2.5 + */ + public static Class<?> getDAOImplementation(ObjectModel model) { + String daoImpl = getDaoImplementationTagValue(model); + Class<?> result; + if (StringUtils.isEmpty(daoImpl)) { + + // use the default dao implementation of topia + result = AbstractTopiaDao.class; + } else { + try { + result = Class.forName(daoImpl); + } catch (ClassNotFoundException e) { + String message = "Could not find dao implementation named " + daoImpl; + log.error(message); + throw new IllegalStateException(message, e); + } + } + return result; + } + + public static Map<ObjectModelClass, Set<ObjectModelClass>> + searchDirectUsages(ObjectModel model) { + List<ObjectModelClass> allEntities; + Map<String, ObjectModelClass> allEntitiesByFQN; + Map<ObjectModelClass, Set<ObjectModelClass>> usages; + + allEntities = getEntityClasses(model, true); + + allEntitiesByFQN = new TreeMap<String, ObjectModelClass>(); + usages = new LinkedHashMap<ObjectModelClass, Set<ObjectModelClass>>(); + + // prepare usages map and fill allEntitiesByFQN map + for (ObjectModelClass klass : allEntities) { + usages.put(klass, new HashSet<ObjectModelClass>()); + allEntitiesByFQN.put(klass.getQualifiedName(), klass); + } + + // first pass to detect direct usages + for (ObjectModelClass klass : allEntities) { + searchDirectUsages(klass, allEntitiesByFQN, usages); + } + allEntities.clear(); + allEntitiesByFQN.clear(); + return usages; + + } + + public static void searchDirectUsages( + ObjectModelClass klass, + Map<String, ObjectModelClass> allEntitiesByFQN, + Map<ObjectModelClass, Set<ObjectModelClass>> usages) { + + if (log.isDebugEnabled()) { + log.debug("for entity " + klass.getQualifiedName()); + } + for (ObjectModelAttribute attr : klass.getAttributes()) { + if (!attr.isNavigable()) { + // skip this case + continue; + } + String type; + if (attr.hasAssociationClass()) { + type = attr.getAssociationClass().getQualifiedName(); + } else { + type = attr.getType(); + } + if (!allEntitiesByFQN.containsKey(type)) { + // not a entity, can skip for this attribute + continue; + } + if (log.isDebugEnabled()) { + log.debug(" uses " + type); + } + // register the klass as using the targetEntity + ObjectModelClass targetEntity = allEntitiesByFQN.get(type); + Set<ObjectModelClass> classes = usages.get(targetEntity); + classes.add(klass); + } + } + + public static boolean isImportNeeded(Collection<ObjectModelOperation> operations, + String importName) { + if (CollectionUtils.isNotEmpty(operations)) { + for (ObjectModelOperation op : operations) { + if (op.getReturnType().contains(importName)) { + return true; + } + for (ObjectModelParameter param : op.getParameters()) { + if (param.getType().contains(importName)) { + return true; + } + } + } + } + return false; + } + + public static boolean isCollectionNeeded( + Collection<ObjectModelOperation> operations) { + return isImportNeeded(operations, + Collection.class.getSimpleName()); + } + + public static boolean isSetNeeded(Collection<ObjectModelOperation> operations) { + return isImportNeeded(operations, + Set.class.getSimpleName()); + } + + /** + * Check if the given classifier has the + * {@link TopiaStereoTypes#STEREOTYPE_ENTITY} stereotype. + * + * @param classifier classifier to test + * @return {@code true} if stereotype was found, {@code false} otherwise + * @see TopiaStereoTypes#STEREOTYPE_ENTITY + * @since 2.5 + */ + public static boolean hasEntityStereotype(ObjectModelClassifier classifier) { + return classifier.hasStereotype(TopiaStereoTypes.STEREOTYPE_ENTITY); + } + + /** + * Check if the given attribute type is an entity. + * + * @param attribute attribute to test + * @param model model containing the attribute + * @return {@code true} if type of attribute is an entity, + * {@code false} otherwise + * @see TopiaStereoTypes#STEREOTYPE_ENTITY + * @since 2.7 + */ + public static boolean isEntity(ObjectModelAttribute attribute, + ObjectModel model) { + if (isPrimitiveType(attribute)) { + return false; + } + String attributeType = attribute.getType(); + ObjectModelClassifier typeclassifier = + model.getClassifier(attributeType); + return typeclassifier != null && isEntity(typeclassifier); + } + + /** + * Check if the given classifier has the + * {@link TopiaStereoTypes#STEREOTYPE_ENTITY} and is not an enumeration + * + * @param classifier classifier to test + * @return {@code true} if stereotype was found and classifier is not + * enumeration, {@code false} otherwise + * @see TopiaStereoTypes#STEREOTYPE_ENTITY + * @since 2.5 + */ + public static boolean isEntity(ObjectModelClassifier classifier) { + return hasEntityStereotype(classifier) && !classifier.isEnum(); + } + + + /** + * Check if the given attribute has the + * {@link TopiaStereoTypes#STEREOTYPE_ENTITY} stereotype. + * + * @param attribute attribute to test + * @return {@code true} if stereotype was found, {@code false otherwise} + * @see TopiaStereoTypes#STEREOTYPE_ENTITY + * @since 2.5 + */ + public static boolean hasEntityStereotype(ObjectModelAttribute attribute) { + return attribute.hasStereotype(TopiaStereoTypes.STEREOTYPE_ENTITY); + } + + /** + * Check if the given classifier has the + * {@link TopiaStereoTypes#STEREOTYPE_DTO} stereotype. + * + * @param classifier classifier to test + * @return {@code true} if stereotype was found, {@code false otherwise} + * @see TopiaStereoTypes#STEREOTYPE_DTO + * @since 2.5 + */ + public static boolean hasDtoStereotype(ObjectModelClassifier classifier) { + return classifier.hasStereotype(TopiaStereoTypes.STEREOTYPE_DTO); + } + + /** + * Check if the given classifier has the + * {@link TopiaStereoTypes#STEREOTYPE_DAO} stereotype. + * + * @param classifier classifier to test + * @return {@code true} if stereotype was found, {@code false otherwise} + * @see TopiaStereoTypes#STEREOTYPE_DAO + * @since 2.5 + */ + public static boolean hasDaoStereotype(ObjectModelClassifier classifier) { + return classifier.hasStereotype(TopiaStereoTypes.STEREOTYPE_DAO); + } + + /** + * Check if the given operation has the + * {@link TopiaStereoTypes#STEREOTYPE_DAO} stereotype. + * + * @param operation operation to test + * @return {@code true} if stereotype was found, {@code false otherwise} + * @see TopiaStereoTypes#STEREOTYPE_DAO + * @since 2.5 + */ + public static boolean hasDaoStereotype(ObjectModelOperation operation) { + return operation.hasStereotype(TopiaStereoTypes.STEREOTYPE_DAO); + } + + /** + * Check if the given attribute has the + * {@link TopiaStereoTypes#STEREOTYPE_UNIQUE} stereotype. + * + * @param attribute attribute to test + * @return {@code true} if stereotype was found, {@code false otherwise} + * @see TopiaStereoTypes#STEREOTYPE_UNIQUE + * @since 2.5 + */ + public static boolean hasUniqueStereotype(ObjectModelAttribute attribute) { + return attribute.hasStereotype(TopiaStereoTypes.STEREOTYPE_UNIQUE); + } + + /** + * Check if the given attribute has the + * {@link TopiaStereoTypes#STEREOTYPE_PRIMARYKAY} stereotype. + * + * @param attribute attribute to test + * @return {@code true} if stereotype was found, {@code false otherwise} + * @see TopiaStereoTypes#STEREOTYPE_PRIMARYKAY + * @since 2.5 + */ + public static boolean hasPrimaryKeyStereotype(ObjectModelAttribute attribute) { + return attribute.hasStereotype(TopiaStereoTypes.STEREOTYPE_PRIMARYKAY); + } + + /** + * Obtain the value of the {@link TopiaTagValues#TAG_PERSISTENCE_TYPE} + * tag value on the given classifier. + * + * @param classifier classifier to seek + * @return the none empty value of the found tag value or {@code null} if not found nor empty. + * @see TopiaTagValues#TAG_PERSISTENCE_TYPE + * @since 2.5 + */ + public static String getPersistenceTypeTagValue(ObjectModelClassifier classifier) { + String value = findTagValue(TopiaTagValues.TAG_PERSISTENCE_TYPE, classifier, null); + return value; + } + + /** + * Obtain the value of the {@link TopiaTagValues#TAG_INHERITANCE_STRATEGY} + * tag value on the given classifier. + * + * @param classifier classifier to seek + * @return the none empty value of the found tag value or {@code null} if not found nor empty. + * @see TopiaTagValues#TAG_INHERITANCE_STRATEGY + * @since 3.0 + */ + public static String getInheritanceStrategyTagValue(ObjectModelClassifier classifier) { + String value = findTagValue(TopiaTagValues.TAG_INHERITANCE_STRATEGY, classifier, null); + if (value == null) { + value = DEFAULT_INHERITANCE_STRATEGY; + } + return value; + } + + /** + * Obtain the value of the {@link TopiaTagValues#TAG_DB_NAME} + * tag value on the given classifier. + * + * @param element classifier to seek + * @return the none empty value of the found tag value or {@code null} if not found nor empty. + * @see TopiaTagValues#TAG_DB_NAME + * @since 2.5 + */ + public static String getDbNameTagValue(ObjectModelElement element) { + String value = findTagValue(TopiaTagValues.TAG_DB_NAME, element, null); + return value; + } + + /** + * Obtain the value of the {@link TopiaTagValues#TAG_SCHEMA_NAME} + * tag value on the given classifier. + * + * @param classifier classifier to seek + * @param model model to seek + * @return the none empty value of the found tag value or {@code null} if not found nor empty. + * @see TopiaTagValues#TAG_SCHEMA_NAME + * @since 2.5 + */ + public static String getDbSchemaNameTagValue(ObjectModelClassifier classifier, ObjectModel model) { + String value = findTagValue(TopiaTagValues.TAG_SCHEMA_NAME, classifier, model); + return value; + } + + /** + * Obtain the value of the {@link TopiaTagValues#TAG_SCHEMA_NAME} + * tag value on the given attribute. + * + * @param attribute attribute to seek + * @param model model to seek + * @return the none empty value of the found tag value or {@code null} if not found nor empty. + * @see TopiaTagValues#TAG_SCHEMA_NAME + * @since 2.5 + */ + public static String getDbSchemaNameTagValue(ObjectModelAttribute attribute, ObjectModel model) { + String value = findTagValue(TopiaTagValues.TAG_SCHEMA_NAME, attribute, model); + return value; + } + + /** + * Obtain the value of the {@link TopiaTagValues#TAG_LENGTH} + * tag value on the given attribute. + * + * @param attribute attribute to seek + * @return the none empty value of the found tag value or {@code null} if not found nor empty. + * @see TopiaTagValues#TAG_LENGTH + * @since 2.5 + */ + public static String getLengthTagValue(ObjectModelAttribute attribute) { + String value = findTagValue(TopiaTagValues.TAG_LENGTH, attribute, null); + return value; + } + + /** + * Obtain the value of the {@link TopiaTagValues#TAG_ANNOTATION} + * tag value on the given attribute. + * + * @param attribute attribute to seek + * @return the none empty value of the found tag value or {@code null} if not found nor empty. + * @see TopiaTagValues#TAG_ANNOTATION + * @since 2.5 + */ + public static String getAnnotationTagValue(ObjectModelAttribute attribute) { + String value = findTagValue(TopiaTagValues.TAG_ANNOTATION, attribute, null); + return value; + } + + /** + * Obtain the value of the {@link TopiaTagValues#TAG_ACCESS} + * tag value on the given attribute. + * + * @param attribute attribute to seek + * @return the none empty value of the found tag value or {@code null} if not found nor empty. + * @see TopiaTagValues#TAG_ACCESS + * @since 2.5 + */ + public static String getAccessTagValue(ObjectModelAttribute attribute) { + String value = findTagValue(TopiaTagValues.TAG_ACCESS, attribute, null); + return value; + } + + /** + * Obtain the value of the {@link TopiaTagValues#TAG_NATURAL_ID} + * tag value on the given attribute. + * + * @param attribute attribute to seek + * @return the none empty value of the found tag value or {@code null} if not found nor empty. + * @see TopiaTagValues#TAG_NATURAL_ID + * @since 2.5 + */ + public static String getNaturalIdTagValue(ObjectModelAttribute attribute) { + String value = findTagValue(TopiaTagValues.TAG_NATURAL_ID, attribute, null); + return value; + } + + /** + * Obtain the value of the {@link TopiaTagValues#TAG_NATURAL_ID_MUTABLE} + * tag value on the given classifier. + * + * @param classifier classifier to seek + * @return the none empty value of the found tag value or {@code null} if not found nor empty. + * @see TopiaTagValues#TAG_NATURAL_ID_MUTABLE + * @since 2.5 + */ + public static String getNaturalIdMutableTagValue(ObjectModelClassifier classifier) { + String value = findTagValue(TopiaTagValues.TAG_NATURAL_ID_MUTABLE, classifier, null); + return value; + } + + /** + * Obtain the value of the {@link TopiaTagValues#TAG_INVERSE} + * tag value on the given attribute. + * + * @param attribute attribute to seek + * @return the none empty value of the found tag value or {@code null} if not found nor empty. + * @see TopiaTagValues#TAG_INVERSE + * @since 2.5 + */ + public static String getInverseTagValue(ObjectModelAttribute attribute) { + String value = findTagValue(TopiaTagValues.TAG_INVERSE, attribute, null); + return value; + } + + /** + * Obtain the value of the {@link TopiaTagValues#TAG_LAZY} + * tag value on the given attribute. + * + * @param attribute attribute to seek + * @return the none empty value of the found tag value or {@code null} if not found nor empty. + * @see TopiaTagValues#TAG_LAZY + * @since 2.5 + */ + public static String getLazyTagValue(ObjectModelAttribute attribute) { + String value = findTagValue(TopiaTagValues.TAG_LAZY, attribute, null); + return value; + } + + /** + * Obtain the value of the {@link TopiaTagValues#TAG_FETCH} + * tag value on the given attribute. + * + * @param attribute attribute to seek + * @return the none empty value of the found tag value or {@code null} if not found nor empty. + * @see TopiaTagValues#TAG_FETCH + * @since 2.5 + */ + public static String getFetchTagValue(ObjectModelAttribute attribute) { + String value = findTagValue(TopiaTagValues.TAG_FETCH, attribute, null); + return value; + } + + /** + * Obtain the value of the {@link TopiaTagValues#TAG_ORDER_BY} + * tag value on the given attribute. + * + * @param attribute attribute to seek + * @return the none empty value of the found tag value or {@code null} if not found nor empty. + * @see TopiaTagValues#TAG_ORDER_BY + * @since 2.5 + */ + public static String getOrderByTagValue(ObjectModelAttribute attribute) { + String value = findTagValue(TopiaTagValues.TAG_ORDER_BY, attribute, null); + return value; + } + + /** + * Obtain the value of the {@link TopiaTagValues#TAG_NOT_NULL} + * tag value on the given attribute. + * + * @param attribute attribute to seek + * @return the none empty value of the found tag value or {@code null} if not found nor empty. + * @see TopiaTagValues#TAG_NOT_NULL + * @since 2.5 + */ + public static String getNotNullTagValue(ObjectModelAttribute attribute) { + String value = findTagValue(TopiaTagValues.TAG_NOT_NULL, attribute, null); + return value; + } + + /** + * Obtain the value of the {@link TopiaTagValues#TAG_PROXY_INTERFACE} + * tag value on the given classifier. + * + * @param classifier classifier to seek + * @param model model to seek + * @return the none empty value of the found tag value or {@code null} if not found nor empty. + * @see TopiaTagValues#TAG_PROXY_INTERFACE + * @since 2.5 + */ + public static String getProxyInterfaceTagValue(ObjectModelClassifier classifier, ObjectModel model) { + String value = findTagValue(TopiaTagValues.TAG_PROXY_INTERFACE, classifier, model); + return value; + } + + /** + * Tests if the given classifier own at least one security tag value. + * + * @param classifier the classifier to test + * @return {@code true} if there is at least one security tag value on the given class + * @since 2.5 + */ + public static boolean isClassWithSecurity(ObjectModelClassifier classifier) { + return StringUtils.isNotEmpty(getSecurityCreateTagValue(classifier)) || + StringUtils.isNotEmpty(getSecurityLoadTagValue(classifier)) || + StringUtils.isNotEmpty(getSecurityUpdateTagValue(classifier)) || + StringUtils.isNotEmpty(getSecurityDeleteTagValue(classifier)); + } + + /** + * Obtain the value of the {@link TopiaTagValues#TAG_SECURITY_CREATE} + * tag value on the given classifier. + * + * @param classifier classifier to seek + * @return the none empty value of the found tag value or {@code null} if not found nor empty. + * @see TopiaTagValues#TAG_SECURITY_CREATE + * @since 2.5 + */ + public static String getSecurityCreateTagValue(ObjectModelClassifier classifier) { + String value = findTagValue(TopiaTagValues.TAG_SECURITY_CREATE, classifier, null); + return value; + } + + /** + * Obtain the value of the {@link TopiaTagValues#TAG_SECURITY_DELETE} + * tag value on the given classifier. + * + * @param classifier classifier to seek + * @return the none empty value of the found tag value or {@code null} if not found nor empty. + * @see TopiaTagValues#TAG_SECURITY_DELETE + * @since 2.5 + */ + public static String getSecurityDeleteTagValue(ObjectModelClassifier classifier) { + String value = findTagValue(TopiaTagValues.TAG_SECURITY_DELETE, classifier, null); + return value; + } + + /** + * Obtain the value of the {@link TopiaTagValues#TAG_SECURITY_LOAD} + * tag value on the given classifier. + * + * @param classifier classifier to seek + * @return the none empty value of the found tag value or {@code null} if not found nor empty. + * @see TopiaTagValues#TAG_SECURITY_LOAD + * @since 2.5 + */ + public static String getSecurityLoadTagValue(ObjectModelClassifier classifier) { + String value = findTagValue(TopiaTagValues.TAG_SECURITY_LOAD, classifier, null); + return value; + } + + /** + * Obtain the value of the {@link TopiaTagValues#TAG_SECURITY_UPDATE} + * tag value on the given classifier. + * + * @param classifier classifier to seek + * @return the none empty value of the found tag value or {@code null} if not found nor empty. + * @see TopiaTagValues#TAG_SECURITY_UPDATE + * @since 2.5 + */ + public static String getSecurityUpdateTagValue(ObjectModelClassifier classifier) { + String value = findTagValue(TopiaTagValues.TAG_SECURITY_UPDATE, classifier, null); + return value; + } + + /** + * Obtain the value of the {@link TopiaTagValues#TAG_NOT_GENERATE_TO_STRING} + * tag value on the given class. + * + * @param clazz class to seek + * @param model model to seek + * @return the none empty value of the found tag value or {@code null} if not found nor empty. + * @see TopiaTagValues#TAG_NOT_GENERATE_TO_STRING + * @since 2.5 + */ + public static String getNotGenerateToStringTagValue(ObjectModelClassifier clazz, ObjectModel model) { + String value = findTagValue(TopiaTagValues.TAG_NOT_GENERATE_TO_STRING, clazz, model); + return value; + } + + /** + * Obtain the value of the {@link TopiaTagValues#TAG_SORT_ATTRIBUTE} + * tag value on the given classifier. + * + * @param classifier classifier to seek + * @param model model to seek + * @return the none empty value of the found tag value or {@code null} if not found nor empty. + * @see TopiaTagValues#TAG_SORT_ATTRIBUTE + * @since 2.5 + */ + public static String getSortAttributeTagValue(ObjectModelClassifier classifier, ObjectModel model) { + String value = findTagValue(TopiaTagValues.TAG_SORT_ATTRIBUTE, classifier, model); + return value; + } + + /** + * Obtain the value of the {@link TopiaTagValues#TAG_GENERATE_STANDALONE_ENUM_FOR_DAO_HELPER} + * tag value on the given model. + * + * @param model model to seek + * @return the none empty value of the found tag value or {@code null} if not found nor empty. + * @see TopiaTagValues#TAG_GENERATE_STANDALONE_ENUM_FOR_DAO_HELPER + * @since 2.5 + */ + public static String getGenerateStandaloneEnumForDAOHelperTagValue(ObjectModel model) { + String value = findTagValue(TopiaTagValues.TAG_GENERATE_STANDALONE_ENUM_FOR_DAO_HELPER, null, model); + return value; + } + + /* Obtain the value of the {@link TopiaTagValues#TAG_GENERATE_OPERATOR_FOR_DAO_HELPER} + * tag value on the given model. + * + * @param model model to seek + * @return the none empty value of the found tag value or {@code null} if not found nor empty. + * @see TopiaTagValues#TAG_GENERATE_OPERATOR_FOR_DAO_HELPER + * @since 2.5 + */ + public static String getGenerateOperatorForDAOHelperTagValue(ObjectModel model) { + String value = findTagValue(TopiaTagValues.TAG_GENERATE_OPERATOR_FOR_DAO_HELPER, null, model); + return value; + } + + /** + * Obtain the value of the {@link TopiaTagValues#TAG_TYPE} + * tag value on the given attribute. + * + * @param attribute attribute to seek + * @return the none empty value of the found tag value or {@code null} if not found nor empty. + * @see TopiaTagValues#TAG_TYPE + * @since 2.5 + */ + public static String getTypeTagValue(ObjectModelAttribute attribute) { + String value = findTagValue(TopiaTagValues.TAG_TYPE, attribute, null); + return value; + } + + /** + * Obtain the value of the {@link TopiaTagValues#TAG_SQL_TYPE} + * tag value on the given attribute. + * + * @param attribute attribute to seek + * @return the none empty value of the found tag value or {@code null} if not found nor empty. + * @see TopiaTagValues#TAG_TYPE + * @since 2.5 + */ + public static String getSqlTypeTagValue(ObjectModelAttribute attribute) { + String value = findTagValue(TopiaTagValues.TAG_SQL_TYPE, attribute, null); + return value; + } + + /** + * Obtains the value of the {@link TopiaTagValues#TAG_DAO_IMPLEMENTATION} + * tag value on the given model. + + * + * @param model model to seek + * @return the none empty value of the found tag value or {@code null} if not found nor empty. + * @see TopiaTagValues#TAG_DAO_IMPLEMENTATION + * @since 2.5 + */ + public static String getDaoImplementationTagValue(ObjectModel model) { + String value = findTagValue(TopiaTagValues.TAG_DAO_IMPLEMENTATION, null, model); + return value; + } + + /** + * Obtains the value of the tag value + * {@link TopiaTagValues#TAG_INDEX_FOREIGN_KEYS} on the model or on the + * given attribute. + * + * @param attribute attribute to test + * @param model model to test + * @return none empty value of the found tag value or {@code null} if not found nor empty. + * @see TopiaTagValues#TAG_INDEX_FOREIGN_KEYS + * @since 2.6.5 + */ + public static String getIndexForeignKeys(ObjectModelAttribute attribute, ObjectModel model) { + String value = findTagValue(TopiaTagValues.TAG_INDEX_FOREIGN_KEYS, attribute, model); + return value; + } + + public static boolean hasUseEnumerationNameTagValue(ObjectModelAttribute attr, ObjectModel model) { + String value = findTagValue(TopiaTagValues.TAG_USE_ENUMERATION_NAME, attr, model); + return Boolean.parseBoolean(value); + } + + /** + * Search if the TagValue {@link TopiaTagValues#TAG_GENERATE_TOPIA_ID_IN_DTO} has been + * activated in the model. + * + * @param classifier classifier to seek + * @param model model to seek + * @return the none empty value of the found tag value or {@code null} if not found nor empty. + * @see TopiaTagValues#TAG_GENERATE_TOPIA_ID_IN_DTO + * @since 2.6.7 + */ + public static boolean shouldGenerateDTOTopiaIdTagValue(ObjectModelClassifier classifier, ObjectModel model) { + String tagValue = findTagValue(TopiaTagValues.TAG_GENERATE_TOPIA_ID_IN_DTO, classifier, model); + boolean generate = StringUtils.isNotEmpty(tagValue) && Boolean.valueOf(tagValue); + return generate; + } + +} // TopiaGeneratorUtil + Copied: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaJavaValidator.java (from rev 2882, trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaJavaValidator.java) =================================================================== --- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaJavaValidator.java (rev 0) +++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaJavaValidator.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,132 @@ +package org.nuiton.topia.templates; + +import org.apache.commons.lang3.StringUtils; +import org.nuiton.eugene.models.object.ObjectModel; +import org.nuiton.eugene.models.object.ObjectModelAttribute; +import org.nuiton.eugene.models.object.ObjectModelClass; +import org.nuiton.eugene.models.object.ObjectModelOperation; +import org.nuiton.eugene.models.object.validator.ObjectModelValidator; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * Validateur qui valide : + * - les types des attributs + * - les nom des attributs + * - les duplication d'attibuts + * + * @author chatellier <chatellier@codelutin.com> + * @version $Id$ + */ +public class TopiaJavaValidator extends ObjectModelValidator { + + /** + * Constructor. + * + * @param model model to validate + */ + public TopiaJavaValidator(ObjectModel model) { + super(model); + } + + @Override + protected boolean validateAttribute(ObjectModelAttribute attr) { + + boolean isValid = super.validateAttribute(attr); + + // type null ou vide + if (attr.getType() == null || attr.getType().isEmpty()) { + isValid = false; + + addError(attr, "Invalid type \"" + attr.getType() + "\""); + } + + // name = java reserved keywords + if (!isJavaIdentifier(attr.getName())) { + isValid = false; + + addError(attr, "Attribute name " + attr.getName() + + " is not valid java identifier"); + } + + // test sur les mots réservés ? + + return isValid; + + } + + @Override + protected boolean validateClass(ObjectModelClass clazz) { + + boolean isValid = super.validateClass(clazz); + + // test attribute names duplication + Set<String> attributesName = new HashSet<String>(); + for (ObjectModelAttribute attr : clazz.getAttributes()) { + if (!attr.isNavigable()) { + + // not navigable, so will not use it... + continue; + } + String attrName = attr.getName(); + if (!attributesName.add(attrName)) { + addError(attr, "Attribute name " + attrName + + " already exists"); + + isValid = false; + } + } + + if (TopiaGeneratorUtil.isEntity(clazz)) { + + Set<String> methodsName = new HashSet<String>(); + for (ObjectModelAttribute attr : clazz.getAttributes()) { + + String capitalizeAttrName = StringUtils.capitalize(attr.getName()); + methodsName.add(TopiaGeneratorUtil.OPERATION_GETTER_BOOLEAN_PREFIX + capitalizeAttrName); + methodsName.add(TopiaGeneratorUtil.OPERATION_GETTER_DEFAULT_PREFIX + capitalizeAttrName); + methodsName.add("set" + capitalizeAttrName); + } + + // test if there is a method an already reserved name + for (ObjectModelOperation operation : clazz.getOperations()) { + String operationName = operation.getName(); + if (methodsName.contains(operationName)) { + addError(operation, "Operation name " + operationName + + " is already reserved for a getter/setter of an entity attribute"); + + isValid = false; + } + } + } + + return isValid; + } + + @Override + protected boolean validateModel(ObjectModel model) { + + return super.validateModel(model); + } + + /** + * Returns true if s is a legal Java identifier. + * + * @param s string to test + * @return true if s is a legal Java identifier + */ + public static boolean isJavaIdentifier(String s) { + if (s.length() == 0 || !Character.isJavaIdentifierStart(s.charAt(0))) { + return false; + } + for (int i = 1; i < s.length(); i++) { + if (!Character.isJavaIdentifierPart(s.charAt(i))) { + return false; + } + } + return true; + } +} Copied: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaMetaTransformer.java (from rev 2882, trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaMetaTransformer.java) =================================================================== --- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaMetaTransformer.java (rev 0) +++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaMetaTransformer.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,107 @@ +package org.nuiton.topia.templates; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.eugene.AbstractMetaTransformer; +import org.nuiton.eugene.models.object.ObjectModel; +import org.nuiton.eugene.models.object.ObjectModelClass; +import org.nuiton.eugene.models.object.validator.AttributeNamesValidator; +import org.nuiton.eugene.models.object.validator.ClassNamesValidator; +import org.nuiton.eugene.models.object.validator.ObjectModelValidator; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created: 20 déc. 2009 + * + * @author tchemit <chemit@codelutin.com> + * @version $Id$ + * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.templates.TopiaMetaTransformer" + * @since 2.3.0 + */ +public class TopiaMetaTransformer extends AbstractMetaTransformer<ObjectModel> { + + /** Logger */ + private static final Log log = LogFactory.getLog(TopiaMetaTransformer.class); + + public TopiaMetaTransformer() { +// super( +// EntityTransformer.class, +// DAOTransformer.class, +// DAOImplTransformer.class, +// DAOAbstractTransformer.class, +// DAOHelperTransformer.class, +// EntityHibernateMappingGenerator.class +// ); + + setTemplateTypes( + ApplicationContextTransformer.class, + PersistenceContextTransformer.class, + EntityTransformer.class, + EntityDaoTransformer.class, +// DAOTransformer.class, +// DAOImplTransformer.class, +// DAOAbstractTransformer.class, + DAOHelperTransformer.class, + EntityHibernateMappingGenerator.class + ); + } + + protected boolean validateModel(ObjectModel model) { + List<ObjectModelValidator> validators = new ArrayList<ObjectModelValidator>(); + + AttributeNamesValidator attrValidator = new AttributeNamesValidator( + model); + attrValidator.addNameAndReason("analyze", + "Le nom d'attribut \"analyze\" est incompatible avec certains SGBD"); + attrValidator.addNameAndReason("next", + "Le nom d'attribut \"next\" est incompatible avec HSQL"); + attrValidator.addNameAndReason("value", + "Le nom d'attribut \"value\" est incompatible avec certains SGBD"); + attrValidator.addNameAndReason("values", + "Le nom d'attribut \"values\" est incompatible avec certains SGBD"); + attrValidator.addNameAndReason("begin", + "Le nom d'attribut \"begin\" est incompatible avec certains SGBD"); + attrValidator.addNameAndReason("end", + "Le nom d'attribut \"end\" est incompatible avec certains SGBD"); + attrValidator.addNameAndReason("authorization", + "Le nom d'attribut \"authorization\" est incompatible avec certains SGBD"); + attrValidator.addNameAndReason("order", + "Le nom d'attribut \"order\" est incompatible avec certains SGBD"); + validators.add(attrValidator); + + ClassNamesValidator classValidator = new ClassNamesValidator(model); + classValidator.addNameAndReason("constraint", "Nom de classe incompatible avec certains SGBD"); + classValidator.addNameAndReason("user", "Nom de classe incompatible avec certains SGBD"); + validators.add(classValidator); + + validators.add(new TopiaJavaValidator(model)); + validators.add(new TopiaRelationValidator(model)); + + for (ObjectModelValidator validator : validators) { + if (!validator.validate()) { + for (String error : validator.getErrors()) { + if (log.isWarnEnabled()) { + log.warn("[VALIDATION] " + error); + } + } + } + } + + // test before all if there is some entities to generate + List<ObjectModelClass> classes = TopiaGeneratorUtil.getEntityClasses(model, true); + + if (classes.isEmpty()) { + // no entity to generate, can stop safely + if (log.isWarnEnabled()) { + log.warn("No entity to generate, " + getClass().getName() + + " is skipped"); + } + return false; + } + //FIXME-TC20091220 seems we still generate if there is some validation errors ? not very normal + return true; + } + +} Copied: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaRelationValidator.java (from rev 2882, trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaRelationValidator.java) =================================================================== --- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaRelationValidator.java (rev 0) +++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaRelationValidator.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,95 @@ +/* * +* TopiaRelationValidator.java +* +* Created: 31 mars 2006 +* +* @author Arnaud Thimel <thimel@codelutin.com> +* @version $Revision$ +* +* Mise a jour: $Date$ +* par : $Author$ +*/ + +package org.nuiton.topia.templates; + +import org.nuiton.eugene.models.object.ObjectModel; +import org.nuiton.eugene.models.object.ObjectModelAttribute; +import org.nuiton.eugene.models.object.validator.ObjectModelValidator; + +/** + * Validateur pour les relations du modèle. + * Vérifie que : + * <ul> + * <li>Toutes les relations ont au moins une navigabilité</li> + * <li>Une relation 1-n unidirectionnelle pointant sur une classe ayant des + * sous-classes dans le modèle est incompatibe avec Hibernate</li> + * <li>Toutes les relations ont des reverseAttribute</li> + * </ul> + * + * @version $Id$ + */ +public class TopiaRelationValidator extends ObjectModelValidator { + + /** + * Constructeur de TopiaRelationValidator. + * + * @param model le modèle à valider + */ + public TopiaRelationValidator(ObjectModel model) { + super(model); + } + + /* (non-Javadoc) + * @see org.nuiton.eugene.models.object.validator.ObjectModelValidator#validateAttribute(org.nuiton.eugene.models.object.ObjectModelAttribute) + */ + @Override + protected boolean validateAttribute(ObjectModelAttribute attr) { + boolean isValid = true; + ObjectModelAttribute reverse = attr.getReverseAttribute(); + + /* Relation navigabilité */ + //Pour ne pas avoir de doublons, on ne vérifie que sur le premier + //attribut par ordre alphabétique + if (TopiaGeneratorUtil.isFirstAttribute(attr)) { + if (!attr.isNavigable() && !reverse.isNavigable()) { + addError(attr, "La relation entre " + "\"" + reverse.getType() + + "\"[" + attr.getName() + "] et " + "\"" + + attr.getType() + "\"[" + reverse.getName() + "] " + + "n'est navigable dans aucun sens"); + isValid = false; + } + } + + /* Relation héritage */ + if (TopiaGeneratorUtil.hasUnidirectionalRelationOnAbstractType(attr, model)) { + isValid = false; + addError( + attr, + "La relation entre " + + "\"" + + reverse.getType() + + "\"[" + + attr.getName() + + "] et " + + "\"" + + attr.getType() + + "\"[" + + reverse.getName() + + "] " + + "n'est navigable que dans un sens et " + + "la classe \"" + + attr.getType() + + "\" a des sous-classes. " + + "Des accesseurs doivent donc etre generes pour Hibernate."); + } + + /* Pas d'inverse */ + if (reverse == null && model.hasClass(attr.getType())) { + isValid = false; + addError(attr, "Cet attribut n'a pas d'inverse."); + } + + return isValid; + } + +} //TopiaRelationValidator Copied: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaStereoTypes.java (from rev 2882, trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaStereoTypes.java) =================================================================== --- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaStereoTypes.java (rev 0) +++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaStereoTypes.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,64 @@ +package org.nuiton.topia.templates; + +import org.nuiton.eugene.EugeneStereoTypes; +import org.nuiton.eugene.models.object.ObjectModelAttribute; +import org.nuiton.eugene.models.object.ObjectModelClassifier; +import org.nuiton.eugene.models.object.ObjectModelOperation; + +import static org.nuiton.eugene.ModelPropertiesUtil.StereotypeDefinition; + +/** + * All extra stereotypes usable in topia generators. + * + * @author tchemit <chemit@codelutin.com> + * @since 2.5 + */ +public interface TopiaStereoTypes extends EugeneStereoTypes { + + /** + * Stéréotype pour les objets devant être générées sous forme d'entités + * + * @see TopiaGeneratorUtil#isEntity(ObjectModelClassifier) + * @see TopiaGeneratorUtil#hasEntityStereotype(ObjectModelAttribute) + */ + @StereotypeDefinition(target = {ObjectModelClassifier.class, ObjectModelAttribute.class}, + documentation = "To specify that a class is an Entity") + String STEREOTYPE_ENTITY = "entity"; + + /** + * Stéréotype pour les objets devant être générées sous forme de DTO. + * + * @see TopiaGeneratorUtil#hasDtoStereotype(ObjectModelClassifier) + */ + @StereotypeDefinition(target = ObjectModelClassifier.class, + documentation = "to specify that a class is a DTO") + String STEREOTYPE_DTO = "dto"; + + /** + * Stéréotype pour les interfaces devant être générées sous forme de DAO. + * + * @see TopiaGeneratorUtil#hasDaoStereotype(ObjectModelClassifier) + * @see TopiaGeneratorUtil#hasDaoStereotype(ObjectModelOperation) + */ + @StereotypeDefinition(target = {ObjectModelClassifier.class, ObjectModelOperation.class}, + documentation = "To Specify that a classifier or an operation should be generated as (or in) a DAO") + String STEREOTYPE_DAO = "dao"; + + /** + * Stéréotype pour les collections avec unicité. + * + * @see TopiaGeneratorUtil#hasUniqueStereotype(ObjectModelAttribute) + */ + @StereotypeDefinition(target = ObjectModelAttribute.class, + documentation = "To specify that an attribute is unique (Hibernate mapping)") + String STEREOTYPE_UNIQUE = "unique"; + + /** + * Stéréotype pour les attributs étant des clés primaires. + * + * @see TopiaGeneratorUtil#hasPrimaryKeyStereotype(ObjectModelAttribute) + */ + @StereotypeDefinition(target = ObjectModelAttribute.class, + documentation = "To specify that an attribute is part of a primary key (Hibernate mapping)") + String STEREOTYPE_PRIMARYKAY = "primaryKey"; +} Copied: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaTagValues.java (from rev 2882, trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaTagValues.java) =================================================================== --- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaTagValues.java (rev 0) +++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/TopiaTagValues.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,355 @@ +package org.nuiton.topia.templates; + +import org.nuiton.eugene.EugeneTagValues; +import org.nuiton.eugene.models.object.ObjectModel; +import org.nuiton.eugene.models.object.ObjectModelAttribute; +import org.nuiton.eugene.models.object.ObjectModelClass; +import org.nuiton.eugene.models.object.ObjectModelClassifier; +import org.nuiton.eugene.models.object.ObjectModelElement; +import org.nuiton.topia.TopiaContext; +import org.nuiton.topia.persistence.TopiaEntityContextable; +import org.nuiton.topia.persistence.TopiaEntityEnum; + +import static org.nuiton.eugene.ModelPropertiesUtil.TagValueDefinition; + +/** + * All extra tag values usable in topia generators. + * + * @author tchemit <chemit@codelutin.com> + * @since 2.5 + */ +public interface TopiaTagValues extends EugeneTagValues { + + /** + * Tag pour le type de persistence. + * + * @see TopiaGeneratorUtil#getPersistenceType(ObjectModelClassifier) + * @see TopiaGeneratorUtil#getPersistenceTypeTagValue(ObjectModelClassifier) + * @since 2.5 + */ + @TagValueDefinition(target = {ObjectModelClassifier.class}, + documentation = "") + String TAG_PERSISTENCE_TYPE = "persistenceType"; + + /** + * Tag pour que les entités etendent {@link TopiaEntityContextable} et + * se fasse injecter le {@link TopiaContext} par rapport aux autres + * entités qui ne l'ont pas. + * + * @since 2.5.3 + */ + @TagValueDefinition(target = {ObjectModelClassifier.class}, documentation = "") + String TAG_CONTEXTABLE = "contextable"; + + /** + * Tag pour le nom du champ / entité en BD. + * + * @see TopiaGeneratorUtil#getDbNameTagValue(ObjectModelElement) + * @see TopiaGeneratorUtil#getDbName(ObjectModelElement) + * @see TopiaGeneratorUtil#getReverseDbName(ObjectModelAttribute) + */ + @TagValueDefinition(target = {ObjectModelElement.class}, + documentation = "Sets the database name of an element of the model (a table or a column)") + String TAG_DB_NAME = "dbName"; + + /** + * Tag pour le nom du schema en BD. + * + * @see TopiaGeneratorUtil#getDbSchemaNameTagValue(ObjectModelClassifier, ObjectModel) + * @see TopiaGeneratorUtil#getDbSchemaNameTagValue(ObjectModelAttribute, ObjectModel) + * @since 2.5 + */ + @TagValueDefinition(target = {ObjectModel.class, ObjectModelClassifier.class, ObjectModelAttribute.class}, + documentation = "Sets the database schema name") + String TAG_SCHEMA_NAME = "dbSchema"; + + /** + * Tag pour la taille du champ en BD. + * + * @see TopiaGeneratorUtil#getLengthTagValue(ObjectModelAttribute) + * @since 2.5 + */ + @TagValueDefinition(target = {ObjectModelAttribute.class}, + documentation = "Sets the length of an attribute in database") + String TAG_LENGTH = "length"; + + /** + * Tag pour ajouter une annotation à un champ. + * + * @see TopiaGeneratorUtil#getAnnotationTagValue(ObjectModelAttribute) + * @since 2.5 + */ + @TagValueDefinition(target = {ObjectModelAttribute.class}, + documentation = "Sets an annotation of an attribute") + String TAG_ANNOTATION = "annotation"; + + /** + * Tag pour specfier le type d'acces a un champ. + * + * @see TopiaGeneratorUtil#getAccessTagValue(ObjectModelAttribute) + * @since 2.5 + */ + @TagValueDefinition(target = {ObjectModelAttribute.class}, + documentation = "Sets the access type of an attribute (Hibernate mapping)") + String TAG_ACCESS = "access"; + + /** + * Tag pour ajouter un attribut dans une clef métier. + * + * @see TopiaGeneratorUtil#getNaturalIdTagValue(ObjectModelAttribute) + * @see TopiaGeneratorUtil#isNaturalId(ObjectModelAttribute) + * @since 2.5 + */ + @TagValueDefinition(target = {ObjectModelAttribute.class}, + documentation = "Sets an attribute as part of a natural id (Hibernate Mapping)") + String TAG_NATURAL_ID = "naturalId"; + + /** + * Tag pour specifier si une clef metier est mutable. + * + * @see TopiaGeneratorUtil#getNaturalIdMutableTagValue(ObjectModelClassifier) + * @see TopiaGeneratorUtil#isNaturalIdMutable(ObjectModelClass) + * @since 2.5 + */ + @TagValueDefinition(target = {ObjectModelClassifier.class}, + documentation = "Sets if natural id of a entity is mutable (hibernate mapping)") + String TAG_NATURAL_ID_MUTABLE = "naturalIdMutable"; + + /** + * Tag pour permettre de choisir qui contrôle la relation N-N + * bidirectionnelle. A utiliser sur les deux extremités de l'association. + * Mettre inverse=false sur le rôle fils et inverse=true sur le rôle père. + * Par défaut le inverse=true est placé sur le premier rôle trouvé dans + * l'ordre alphabétique. + * + * @see TopiaGeneratorUtil#getInverseTagValue(ObjectModelAttribute) + * @since 2.5 + */ + @TagValueDefinition(target = {ObjectModelAttribute.class}, + documentation = "Sets which part of a N-N relation is master (inverse=true) and slave (inverse=false) (must be put on each side on a such relation) (Hibernate mapping)") + String TAG_INVERSE = "inverse"; + + /** + * Tag pour spécifier la caractère lazy d'une association multiple. + * + * @see TopiaGeneratorUtil#getLazyTagValue(ObjectModelAttribute) + * @since 2.5 + */ + @TagValueDefinition(target = {ObjectModelAttribute.class}, + documentation = "Sets if an association should be lazy (Hibernate mapping)") + String TAG_LAZY = "lazy"; + + /** + * Tag pour spécifier la caractère fetch d'une association multiple. + * + * @see TopiaGeneratorUtil#getFetchTagValue(ObjectModelAttribute) + * @since 2.5 + */ + @TagValueDefinition(target = {ObjectModelAttribute.class}, + documentation = "Sets the fetch caracteristic of an attribute (Hibernate mapping)") + String TAG_FETCH = "fetch"; + + /** + * Tag pour spécifier la caractère order-by d'une association multiple. + * + * @see TopiaGeneratorUtil#getOrderByTagValue(ObjectModelAttribute) + * @since 2.5 + */ + @TagValueDefinition(target = {ObjectModelAttribute.class}, + documentation = "Sets the order by propertie of an multiple association (Hibernate mapping)") + String TAG_ORDER_BY = "orderBy"; + + /** + * Tag pour spécifier la caractère not-null d'un attribut. + * + * @see TopiaGeneratorUtil#getNotNullTagValue(ObjectModelAttribute) + * @since 2.5 + */ + @TagValueDefinition(target = {ObjectModelAttribute.class}, + documentation = "Sets if an attribute must be not null (Hibernate mapping)") + String TAG_NOT_NULL = "notNull"; + + /** + * Tag à placer sur un l'attribut d'une entité. Cet attribut est de type + * énumération : l'ajout de la tagValue indique qu'il faut utiliser le + * {@code name} de l'énumération et non l'ordinal pour stocker la valeur en + * base + */ + @TagValueDefinition(target = {ObjectModelAttribute.class}, + documentation = "'true' if the value of this attribute of type Enumeration should be stored with its name (instead of using ordinal)") + String TAG_USE_ENUMERATION_NAME = "useEnumerationName"; + + /** + * Tag pour configurer l'interface du proxy sur autre chose que l'implementation par defaut. + * <p/> + * Par defaut : + * null > generere le proxy sur l'interface de l'implementation + * Autre valeur : + * "none" > laisse la configuration par defaut d'hibernate + * + * @see TopiaGeneratorUtil#getPersistenceTypeTagValue(ObjectModelClassifier) + * @since 2.5 + */ + @TagValueDefinition(target = {ObjectModel.class, ObjectModelClassifier.class}, + documentation = "Configure the proxy interface on something else than the default implementation (null to use our default implementation, none to let hibernate deal it) (Hibernate mapping)") + String TAG_PROXY_INTERFACE = "hibernateProxyInterface"; + + /** + * Tag pour configurer la stategie d'heritage choisie. + * <p/> + * Par defaut : union-subclass : Table per class strategy + * Autre valeur : + * "subclass" > Single table per class hierarchy strategy + * "joined-subclass" > Joined subclass strategy + * + * @see TopiaGeneratorUtil#getPersistenceTypeTagValue(ObjectModelClassifier) + * @since 3.0 + */ + @TagValueDefinition(target = {ObjectModel.class, ObjectModelClassifier.class}, + documentation = "Configure the proxy interface on something else than the default implementation (null to use our default implementation, none to let hibernate deal it) (Hibernate mapping)") + String TAG_INHERITANCE_STRATEGY = "inheritanceStrategy"; + + /** + * Tag pour spécifier le permissions à la création. + * + * @see TopiaGeneratorUtil#getSecurityCreateTagValue(ObjectModelClassifier) + * @since 2.5 + */ + @TagValueDefinition(target = {ObjectModelClassifier.class}, + documentation = "Sets the create permission on an entity") + String TAG_SECURITY_CREATE = "securityCreate"; + + /** + * Tag pour spécifier le permissions au chargement. + * + * @see TopiaGeneratorUtil#getSecurityLoadTagValue(ObjectModelClassifier) + * @since 2.5 + */ + @TagValueDefinition(target = {ObjectModelClassifier.class}, + documentation = "Sets the load permission on an entity") + String TAG_SECURITY_LOAD = "securityLoad"; + + /** + * Tag pour spécifier le permissions à la mise à jour. + * + * @see TopiaGeneratorUtil#getSecurityUpdateTagValue(ObjectModelClassifier) + * @since 2.5 + */ + @TagValueDefinition(target = {ObjectModelClassifier.class}, + documentation = "Sets the update permission on an entity") + String TAG_SECURITY_UPDATE = "securityUpdate"; + + /** + * Tag pour spécifier le permissions à la suppression. + * + * @see TopiaGeneratorUtil#getSecurityDeleteTagValue(ObjectModelClassifier) + * @since 2.5 + */ + @TagValueDefinition(target = {ObjectModelClassifier.class}, + documentation = "sets the delete permission on an entity") + String TAG_SECURITY_DELETE = "securityDelete"; + + /** + * Tag pour specifier de ne pas generer la methode toString. + * + * @see TopiaGeneratorUtil#getNotGenerateToStringTagValue(ObjectModelClassifier, ObjectModel) + * @see TopiaGeneratorUtil#generateToString(ObjectModelClass, ObjectModel) + * @since 2.5 + */ + @TagValueDefinition(target = {ObjectModel.class, ObjectModelClassifier.class}, + documentation = "To not generate the toString method on entities") + String TAG_NOT_GENERATE_TO_STRING = "notGenerateToString"; + + /** + * Tag pour specifier de trier les attributs par nom lors de la generation. + * + * @see TopiaGeneratorUtil#getSortAttributeTagValue(ObjectModelClassifier, ObjectModel) + * @see TopiaGeneratorUtil#sortAttribute(ObjectModelClass, ObjectModel) + * @since 2.5 + */ + @TagValueDefinition(target = {ObjectModel.class, ObjectModelClassifier.class}, + documentation = "To sort attribute while generation") + String TAG_SORT_ATTRIBUTE = "sortAttribute"; + + /** + * Tag pour specfier si on doit générer la methode getOperator dans les daohelpers. + * + * @see TopiaGeneratorUtil#getGenerateOperatorForDAOHelperTagValue(ObjectModel) + * @see TopiaGeneratorUtil#shouldGenerateOperatorForDAOHelper(ObjectModel) + * @since 2.5 + */ + @TagValueDefinition(target = {ObjectModel.class}, + documentation = "To generate EntityOperation on generated DAOHelper") + String TAG_GENERATE_OPERATOR_FOR_DAO_HELPER = "generateOperatorForDAOHelper"; + + /** + * Tag pour spécifier si on doit générer le {@link TopiaEntityEnum} en tant qu'inner classe + * du dao helper ou pas. + * <p/> + * <b>Note:</b> Par défaut, on génère en tant qu'inner classe. + * + * @see TopiaGeneratorUtil#getGenerateStandaloneEnumForDAOHelperTagValue(ObjectModel) + * @see TopiaGeneratorUtil#shouldGenerateStandaloneEnumForDAOHelper(ObjectModel) + * @since 2.5 + */ + @TagValueDefinition(target = {ObjectModel.class}, + documentation = "To generate a standalon EntityEnum outside the DAOHelper") + String TAG_GENERATE_STANDALONE_ENUM_FOR_DAO_HELPER = "generateStandaloneEnumForDAOHelper"; + + /** + * Tag pour spécifier le type d'une propriété dans le mapping hibernate. + * + * @see TopiaGeneratorUtil#getTypeTagValue(ObjectModelAttribute) + * @since 2.5 + */ + @TagValueDefinition(target = {ObjectModelAttribute.class}, + documentation = "Sets the hibernate type of an attribute (Hibernate mapping)") + String TAG_TYPE = "type"; + + /** + * Tag pour spécifier le type sql d'une propriété dans le mapping hibernate. + * + * @see TopiaGeneratorUtil#getSqlTypeTagValue(ObjectModelAttribute) + * @since 2.5 + */ + @TagValueDefinition(target = {ObjectModelAttribute.class}, + documentation = "Sets the sql type of an attribute (Hibernate mapping)") + String TAG_SQL_TYPE = "sqlType"; + + /** + * To specify the abstract dao to use. + * <p/> + * If none given, will use the {@code org.nuiton.topia.persistence.TopiaDAOImpl}. + * <p/> + * Other value possible is {@code org.nuiton.topia.persistence.TopiaDAOLegacy} + * + * @see TopiaGeneratorUtil#getDaoImplementationTagValue(ObjectModel) + * @since 2.5 + */ + @TagValueDefinition(target = {ObjectModel.class}, + documentation = "Sets the fully qualified name of the DAO implementation to use in generated DAO (default is DAOImpl (base on TopiaQuery))") + String TAG_DAO_IMPLEMENTATION = "daoImplementation"; + + /** + * Stéréotype pour les attributs avec multiplicité nécessitant la création d'un index. + * + * @see TopiaGeneratorUtil#getIndexForeignKeys(ObjectModelAttribute, ObjectModel) + * @since 2.6.5 + */ + @TagValueDefinition(target = {ObjectModel.class, ObjectModelAttribute.class}, + documentation = "Specifies if an nm-multiplicity attribute (or all nm-multiplicity attributes of a given model) needs an index in db (Hibernate mapping)") + String TAG_INDEX_FOREIGN_KEYS = "indexForeignKeys"; + + /** + * Tag to specify if we want to add an "id" property in DTO generated by + * {@link EntityDTOTransformer}. + * <p/> + * + * @see EntityDTOTransformer + * @see TopiaGeneratorUtil#shouldGenerateDTOTopiaIdTagValue(ObjectModelClassifier, ObjectModel) + * @since 2.6.7 + */ + @TagValueDefinition(target = {ObjectModel.class, ObjectModelClassifier.class}, + documentation = "Add a \"id\" property with its getter/setter on a DTO.") + String TAG_GENERATE_TOPIA_ID_IN_DTO = "generateDTOTopiaId"; +} Copied: trunk/topia-templates/src/main/java/org/nuiton/topia/templates/package-info.java (from rev 2882, trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/package-info.java) =================================================================== --- trunk/topia-templates/src/main/java/org/nuiton/topia/templates/package-info.java (rev 0) +++ trunk/topia-templates/src/main/java/org/nuiton/topia/templates/package-info.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,118 @@ +/* + * #%L + * ToPIA :: Persistence + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2004 - 2010 CodeLutin + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Lesser Public License for more details. + * + * You should have received a copy of the GNU General Lesser Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/lgpl-3.0.html>. + * #L% + */ +/** + * TODO-FD20100507 : Need update this javadoc for ToPIA 2.4 + * + * <h1>Les Générateurs</h1> + * + * <h2>TopiaMetaGenerator</h2> + * + * <p>TopiaMetaGenerator permet d'enchainer les différents + * générateurs.</p> + * + * <h2>Les DAO</h2> + * + * <p>Il il y a trois générateurs pour les DAO</p> + * + * <ul> + * <li>DAOHelperGenerator</li> + * + * <li>DAOAbstractGenerator</li> + * + * <li>DAOGenerator</li> + * </ul> + * + * <p><b><i>DAOHelperGenerator</i></b> permet de récupérer les DAOs + * générés spécifiquement pour l'application sans avoir besoin de passer + * le type de l'entité en paramètre. Cette classe contient donc une + * methode get par type d'entity qui permet de récupérer le DAO associé. + * Ces méthodes sont des méthodes statiques et prennent en paramètre un + * TopiaContext.</p> + * + * <p><b><i>DAOAbstractGenerator</i></b> est une classe abstraite même si + * elle peut implanter toutes les méthodes de l'interface TopiaDAO. De + * cette façon on oblige l'existance d'une classe concrète qui en hérite + * soit développé par le développeur soit généré par DAOGenerator. + * DAOAbstractGenerator contient toutes les méthodes findBy, findAllBy, + * ... associées aux attributs existants. La classe généré hérite + * directement ou indirectement de TopiaDAODelegator.</p> + * + * <p><b><i>DAOGenerator</i></b> génère une classe vide qui permet au + * programme de compiler, si le développeur à besoin de méthode find + * supplémentaire sur son DAO, il lui suffit de d'implanter cette classe + * dans ses sources, le processus de génération écrasera alors la classe + * généré par la classe développée spécifiquement.</p> + * + * <h2>Les entités</h2> + * + * <p>Les entités sont de pure POJO et ne contiennent pas de référence en + * interne sur le TopiaContext ou le DAO qui les à créée, elle peuvent + * donc facilement migrer, être utilisé dans différents context, ... le + * but etant qu'elle reste des classes complètement déconnecté à + * l'exécution du framework.</p> + * + * <p>La seul contrainte est qu'elles implante TopiaEntity</p> + * + * <p>Il il y a trois générateurs pour les entités, plus un pour le + * mapping hibernate</p> + * + * <ul> + * <li>EntityInterfaceGenerator</li> + * + * <li>EntityAbstractGenerator</li> + * + * <li>EntityImplGenerator</li> + * + * <li>EntityHibernateMappingGenerator</li> + * </ul> + * + * <p><b><i>EntityInterfaceGenerator</i></b> génère l'interface de + * l'entité avec les méthodes d'accès aux attributs et les opérations + * définis par l'utilisateur dans son diagrammme de classe. Elle implante + * TopiaEntity</p> + * + * <p><b><i>EntityAbstractGenerator</i></b> génère une classe qui + * implante l'interface de l'entité et étend TopiaEntityAbstract qui + * implante les méthodes du framework, méthode d'accès aux attributs + * topiaId, topiaVersion et topiaCreateDate.</p> + * + * <p><b><i>EntityImplGenerator</i></b> génère une classe vide qui permet + * au programme de compiler si l'entité n'a pas d'opération spécifique. + * Si elle a des opérations spécifiques le développeur doit implanter + * cette classe dans ses sources et y mettre le code pour les opérations + * spécifiques, le processus de génération écrasera alors la classe + * généré par la classe développée spécifiquement.</p> + * + * <p><b><i>EntityHibernateMappingGenerator</i></b> génère le fichier de + * mapping pour entité. L'interface est déclaré dans le mapping et est + * mappé sur une table préfixé par I. Ensuite le Impl est déclaré en + * union-subclass de cette interface. On a besoin de l'interface car les + * méthodes l'utilise dans les signatures de méthode lorsqu'il y a un + * lien entre deux entités.</p> + * + * @author poussin <poussin@codelutin.com> + * @version $Id$ + */ +package org.nuiton.topia.templates; \ No newline at end of file Copied: trunk/topia-templates/src/main/resources/META-INF.services/org.nuiton.eugene.ModelPropertiesUtil$ModelPropertiesProvider (from rev 2882, trunk/topia-persistence/src/main/resources/META-INF/services/org.nuiton.eugene.ModelPropertiesUtil$ModelPropertiesProvider) =================================================================== --- trunk/topia-templates/src/main/resources/META-INF.services/org.nuiton.eugene.ModelPropertiesUtil$ModelPropertiesProvider (rev 0) +++ trunk/topia-templates/src/main/resources/META-INF.services/org.nuiton.eugene.ModelPropertiesUtil$ModelPropertiesProvider 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1 @@ +org.nuiton.topia.templates.TopiaGeneratorUtil$TopiaModelPropertiesProvider \ No newline at end of file Copied: trunk/topia-templates/src/test/java/org/nuiton/topia/templates/TopiaGeneratorUtilTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/TopiaGeneratorUtilTest.java) =================================================================== --- trunk/topia-templates/src/test/java/org/nuiton/topia/templates/TopiaGeneratorUtilTest.java (rev 0) +++ trunk/topia-templates/src/test/java/org/nuiton/topia/templates/TopiaGeneratorUtilTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,39 @@ +package org.nuiton.topia.templates; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +/** @author tchemit <chemit@codelutin.com> */ +public class TopiaGeneratorUtilTest { + + @Deprecated + @Test + public void testConvertVariableNameToConstantName() { + + String variableName = "abc"; + String expResult = "ABC"; + String result = TopiaGeneratorUtil.convertVariableNameToConstantName(variableName); + assertEquals(expResult, result); + + variableName = "ABC"; + expResult = "ABC"; + result = TopiaGeneratorUtil.convertVariableNameToConstantName(variableName); + assertEquals(expResult, result); + + variableName = "abC"; + expResult = "AB_C"; + result = TopiaGeneratorUtil.convertVariableNameToConstantName(variableName); + assertEquals(expResult, result); + + variableName = "AbC"; + expResult = "AB_C"; + result = TopiaGeneratorUtil.convertVariableNameToConstantName(variableName); + assertEquals(expResult, result); + + variableName = "AbC"; + expResult = "AB_C"; + result = TopiaGeneratorUtil.convertVariableNameToConstantName(variableName); + assertEquals(expResult, result); + } +} Copied: trunk/topia-templates/src/test/java/org/nuiton/topia/templates/TopiaModelPropertiesProviderTest.java (from rev 2882, trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/TopiaModelPropertiesProviderTest.java) =================================================================== --- trunk/topia-templates/src/test/java/org/nuiton/topia/templates/TopiaModelPropertiesProviderTest.java (rev 0) +++ trunk/topia-templates/src/test/java/org/nuiton/topia/templates/TopiaModelPropertiesProviderTest.java 2013-11-22 18:03:47 UTC (rev 2884) @@ -0,0 +1,56 @@ +package org.nuiton.topia.templates; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.nuiton.eugene.ModelPropertiesUtil; +import org.nuiton.eugene.models.object.ObjectModelClassifier; +import org.nuiton.eugene.models.object.ObjectModelOperation; + +/** + * To test {@link TopiaGeneratorUtil.TopiaModelPropertiesProvider}. + * + * @author tchemit <chemit@codelutin.com> + * @since 2.3 + */ +public class TopiaModelPropertiesProviderTest { + + protected ModelPropertiesUtil.ModelPropertiesProvider provider; + + @Before + public void setUp() throws Exception { + provider = new TopiaGeneratorUtil.TopiaModelPropertiesProvider(); + provider.init(); + } + + @Test + public void testGetTagValueTarget() throws Exception { + testTagValue(TopiaTagValues.TAG_PERSISTENCE_TYPE, ObjectModelClassifier.class); + //TODO Finish with other tag values... + } + + @Test + public void testGetStereotypeTarget() throws Exception { + + testStereotype(TopiaStereoTypes.STEREOTYPE_DAO, ObjectModelClassifier.class, ObjectModelOperation.class); + //TODO Finish with other stereotypes... + } + + @Test + public void testGetStore() throws Exception { + } + + protected void testStereotype(String name, Class<?>... expected) { + Class<?>[] classes = provider.getStereotypeTarget(name); + Assert.assertNotNull("Could not find target for " + name, classes); + Assert.assertEquals("Should have " + expected.length + " targets for " + name + " but had " + classes.length, classes.length, expected.length); + Assert.assertArrayEquals(expected, classes); + } + + protected void testTagValue(String name, Class<?>... expected) { + Class<?>[] classes = provider.getTagValueTarget(name); + Assert.assertNotNull("Could not find target for " + name, classes); + Assert.assertEquals("Should have " + expected.length + " targets for " + name + " but had " + classes.length, classes.length, expected.length); + Assert.assertArrayEquals(expected, classes); + } +}