Author: tchemit Date: 2010-11-28 21:17:13 +0100 (Sun, 28 Nov 2010) New Revision: 2156 Url: http://nuiton.org/repositories/revision/topia/2156 Log: Evolution #1108: Use the safe tag values and stereotype api introduced in Eugene 2.3 Evolution #1118: Remove all deprecated entities transformer Evolution #891: Update Eugene to 2.3 Anomalie #436: Some tests are on /tmp, but should be in target of modules Added: trunk/topia-persistence/src/test/java/org/nuiton/topia/TestHelper.java Removed: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/BeanTransformer.java trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityAbstractTransformer.java trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityImplTransformer.java trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityInterfaceTransformer.java trunk/topia-persistence/src/test/java/org/nuiton/topiatest/TestUtils.java Modified: trunk/pom.xml trunk/topia-persistence/pom.xml trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DAOAbstractTransformer.java trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DAOHelperTransformer.java trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DAOImplTransformer.java trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DAOTransformer.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/EntityHibernateMappingGenerator.java trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityTransformer.java trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/QueryHelperTransformer.java trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/ServiceTransformer.java trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaGeneratorUtil.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/test/java/org/nuiton/topia/TopiaContextFactoryTest.java trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaQueryTest.java trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaUtilTest.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/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/topiatest/deletetest/DeleteEntityTest.java trunk/topia-persistence/src/test/resources/TopiaContextImpl.properties trunk/topia-service-migration/pom.xml trunk/topia-service-replication/pom.xml trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/AbstractTopiaReplicationServiceTest.java trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationOperationTest.java trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplAllTest.java trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplTest.java trunk/topia-service-security/pom.xml trunk/topia-service-security/src/test/java/org/nuiton/topia/TestUtils.java trunk/topia-service-security/src/test/java/org/nuiton/topia/security/TopiaSecurityTest.java Modified: trunk/pom.xml =================================================================== --- trunk/pom.xml 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/pom.xml 2010-11-28 20:17:13 UTC (rev 2156) @@ -37,7 +37,7 @@ </parent> <artifactId>topia</artifactId> - <version>2.4.4-SNAPSHOT</version> + <version>2.5-SNAPSHOT</version> <modules> <module>topia-persistence</module> @@ -341,7 +341,7 @@ <projectId>topia</projectId> <!-- libs version --> - <eugeneVersion>2.2.1-SNAPSHOT</eugeneVersion> + <eugeneVersion>2.3-SNAPSHOT</eugeneVersion> <nuitonUtilsVersion>1.5.2-SNAPSHOT</nuitonUtilsVersion> <processorPluginVersion>1.0.4</processorPluginVersion> <nuitonI18nVersion>2.0</nuitonI18nVersion> Modified: trunk/topia-persistence/pom.xml =================================================================== --- trunk/topia-persistence/pom.xml 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-persistence/pom.xml 2010-11-28 20:17:13 UTC (rev 2156) @@ -37,7 +37,7 @@ <parent> <groupId>org.nuiton</groupId> <artifactId>topia</artifactId> - <version>2.4.4-SNAPSHOT</version> + <version>2.5-SNAPSHOT</version> </parent> <groupId>org.nuiton.topia</groupId> Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/BeanTransformer.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/BeanTransformer.java 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/BeanTransformer.java 2010-11-28 20:17:13 UTC (rev 2156) @@ -1,467 +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.lang.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.eugene.GeneratorUtil; -import org.nuiton.eugene.java.JavaBeanTransformer; -import org.nuiton.eugene.java.ObjectModelTransformerToJava; -import org.nuiton.eugene.models.object.ObjectModelAttribute; -import org.nuiton.eugene.models.object.ObjectModelClass; -import org.nuiton.eugene.models.object.ObjectModelDependency; -import org.nuiton.eugene.models.object.ObjectModelInterface; -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.persistence.TopiaEntity; - -import java.util.Collection; -import java.util.Iterator; -import java.util.List; - -/*{generator option: parentheses = false}*/ - -/*{generator option: writeString = +}*/ - -/** - * BeanTransformer - * <p/> - * Created: 28 oct. 2009 - * - * @author fdesbois <fdesbois@codelutin.com> - * @author tchemit <tchemit@codelutin.com> - * @version $Id$ - * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.generator.BeanTransformer" - * @deprecated since 2.4 use {@link JavaBeanTransformer} instead - */ -@Deprecated -public class BeanTransformer extends ObjectModelTransformerToJava { - - private static final Log log = LogFactory.getLog(BeanTransformer.class); - - @Override - public void transformFromClass(ObjectModelClass clazz) { - if (!clazz.hasStereotype(TopiaGeneratorUtil.STEREOTYPE_BEAN) && - !clazz.hasStereotype(TopiaGeneratorUtil.STEREOTYPE_DTO)) { - return; - } - - ObjectModelClass resultClass; - boolean isSuperClassSet = false; - if (clazz.hasStereotype(TopiaGeneratorUtil.STEREOTYPE_BEAN)) { - resultClass = createAbstractClass(clazz.getName(), clazz.getPackageName()); - - // Get name for Impl class - String implQualifiedName = clazz.getQualifiedName() + "Impl"; - String resourceName = "/" + implQualifiedName.replaceAll("\\.", "/"); - - // Do not generate Impl if operations exist : must have an Impl class in Resource created by developper - boolean hasOperations = !clazz.getAllOtherOperations(true).isEmpty() || !clazz.getOperations().isEmpty(); - - // Generate the Impl class if not already exist in classpath and no operation is defined in model - if (getClass().getResource(resourceName) == null && !hasOperations) { - String implName = clazz.getName() + "Impl"; - ObjectModelClass resultClassImpl = createClass(implName, clazz.getPackageName()); - // set the abstract resulClass as the resultClassImpl super class - setSuperClass(resultClassImpl, resultClass.getQualifiedName()); - isSuperClassSet = true; - } - } else { - resultClass = createClass(clazz.getName(), clazz.getPackageName()); - } - - List<ObjectModelAttribute> attributes = (List<ObjectModelAttribute>) clazz.getAttributes(); - - createForDTO(resultClass, clazz, attributes); - - // Set superclass - if (!isSuperClassSet) { - Iterator<ObjectModelClass> j = clazz.getSuperclasses().iterator(); - if (j.hasNext()) { - ObjectModelClass p = j.next(); - String qualifiedName = p.getQualifiedName(); - // We want to set the inheritance to the implementation class of the father - // Ex for model : A -> B (a inherits B) we want : A -> BImpl -> B - if (clazz.hasStereotype(TopiaGeneratorUtil.STEREOTYPE_BEAN)) { - qualifiedName = p.getQualifiedName() + "Impl"; - } - setSuperClass(resultClass, qualifiedName); - } - } - - // Add interfaces from inputModel - for (ObjectModelInterface parentInterface : clazz.getInterfaces()) { - addInterface(resultClass, parentInterface.getQualifiedName()); - } - - // Default constructor - ObjectModelOperation constructor = addConstructor(resultClass, ObjectModelModifier.PUBLIC); - - createListeners(resultClass, clazz); - - boolean hasEntity = false; - boolean hasMultipleAttribute = false; - String toStringAppend = ""; // Append pour la méthode toString() - String initTabs = ""; // initialisation des tableaux dans le constructeur - - // Add attributes with getter/setter - for (ObjectModelAttribute attr : attributes) { - - if (attr.isNavigable() || attr.hasAssociationClass()) { - String attrType = attr.getType(); - String simpleType = GeneratorUtil.getSimpleName(attrType); - String attrName = attr.getName(); - String attrNameCapitalized = StringUtils.capitalize(attrName); - - // multiple attribute - if (attr.hasStereotype(TopiaGeneratorUtil.STEREOTYPE_ARRAY)) { - - int maxSize = attr.getMaxMultiplicity(); - int maxSizeMoinsUn = maxSize - 1; - - initTabs += "\n\tthis." + attrName + " = new " + attrType + "[" + maxSize + "];"; - - // Set Value - ObjectModelOperation setValue = addOperation(resultClass, "set" + attrNameCapitalized, - "void", ObjectModelModifier.PUBLIC); - addParameter(setValue, "int", "index"); - addParameter(setValue, attrType, "value"); - addException(setValue, "java.lang.ArrayIndexOutOfBoundsException"); - setOperationBody(setValue, "" - /*{ - if (index >= <%=maxSize%> || index < 0) { - throw new ArrayIndexOutOfBoundsException("Wrong index [" + index + "] for array <%=attrName%>," + - "index must be between 0 and <%=maxSizeMoinsUn%>"); - } - <%=simpleType%>[] oldValue = get<%=attrNameCapitalized%>(); - this.<%=attrName%>[index] = value; - firePropertyChange("<%=attrName%>", oldValue, this.<%=attrName%>); - }*/ - ); - - // Get Value - ObjectModelOperation getValue = addOperation(resultClass, "get" + attrNameCapitalized, - attrType, ObjectModelModifier.PUBLIC); - addParameter(getValue, "int", "index"); - addException(setValue, "java.lang.ArrayIndexOutOfBoundsException"); - setOperationBody(getValue, "" - /*{ - if (index >= <%=maxSize%> || index < 0) { - throw new ArrayIndexOutOfBoundsException("Wrong index [" + index + "] for array <%=attrName%>," + - "index must be between 0 and <%=maxSizeMoinsUn%>"); - } - return this.<%=attrName%>[index]; - }*/ - ); - - attrType += "[]"; - simpleType = GeneratorUtil.getSimpleName(attrType); - } else if (GeneratorUtil.isNMultiplicity(attr)) { - hasMultipleAttribute = true; - - // Add getChild - ObjectModelOperation getChild = addOperation(resultClass, "get" + attrNameCapitalized, - attrType, ObjectModelModifier.PUBLIC); - addParameter(getChild, "int", "index"); - setOperationBody(getChild, "" - /*{ - <%=simpleType%> o = getChild(<%=attrName%>, index); - return o; - }*/ - ); - - // Add getEntity - ObjectModelClass attrEntity = null; - if (getModel().hasClass(attr.getType())) { - attrEntity = getModel().getClass(attr.getType()); - } - boolean isEntity = (attrEntity != null && attrEntity.hasStereotype(TopiaGeneratorUtil.STEREOTYPE_ENTITY)); - - if (isEntity) { - hasEntity = true; - ObjectModelOperation getChildEntity = addOperation(resultClass, "get" + attrNameCapitalized, - attrType, ObjectModelModifier.PUBLIC); - addParameter(getChildEntity, String.class.getName(), "topiaId"); - setOperationBody(getChildEntity, "" - /*{ - <%=simpleType%> o = getEntity(<%=attrName%>, topiaId); - return o; - }*/ - ); - } - - // Add addChild - ObjectModelOperation addChild = addOperation(resultClass, "add" + attrNameCapitalized, - attrType, ObjectModelModifier.PUBLIC); - addParameter(addChild, attrType, attrName); - setOperationBody(addChild, "" - - /*{ - get<%=attrNameCapitalized%>().add(<%=attrName%>); - firePropertyChange("<%=attrName%>", null, <%=attrName%>); - return <%=attrName%>; - }*/ - ); - - // Add removeChild - ObjectModelOperation removeChild = addOperation(resultClass, "remove" + attrNameCapitalized, - "boolean", ObjectModelModifier.PUBLIC); - addParameter(removeChild, attrType, attrName); - setOperationBody(removeChild, "" - - /*{ - boolean removed = get<%=attrNameCapitalized%>().remove(<%=attrName%>); - if (removed) { - firePropertyChange("<%=attrName%>", <%=attrName%>, null); - } - return removed; - }*/ - ); - - // Change type for Multiple attribute - if (attr.isOrdered()) { - attrType = List.class.getName() + "<" + attrType + ">"; - } else { - attrType = Collection.class.getName() + "<" + attrType + ">"; - } - simpleType = GeneratorUtil.getSimpleName(attrType); - } // end multiple attribute - - if (attr.hasAssociationClass()) { - String assocAttrName = TopiaGeneratorUtil.getAssocAttrName(attr); - attrName = GeneratorUtil.toLowerCaseFirstLetter(assocAttrName); - attrType = attr.getAssociationClass().getName(); - } - - // Add attribute to the class - String visibility = attr.getVisibility(); - addAttribute(resultClass, attrName, attrType, "", ObjectModelModifier.toValue(visibility)); - - // Add getter operation - ObjectModelOperation getter = addOperation(resultClass, "get" + attrNameCapitalized, attrType, - ObjectModelModifier.PUBLIC); - setOperationBody(getter, "" - /*{ - return this.<%=attrName%>; - }*/ - ); - - // Add setter operation - ObjectModelOperation setter = addOperation(resultClass, "set" + attrNameCapitalized, "void", - ObjectModelModifier.PUBLIC); - addParameter(setter, attrType, "newValue"); - setOperationBody(setter, "" - /*{ - <%=simpleType%> oldValue = get<%=attrNameCapitalized%>(); - this.<%=attrName%> = newValue; - firePropertyChange("<%=attrName%>", oldValue, newValue); - }*/ - ); - - // toString append for toString method - toStringAppend += "\n\t\t.append(\"" + attrName + "\", this." + attrName + ")"; - - } - } - - // Add helper operations - if (hasMultipleAttribute) { - ObjectModelOperation getChild = addOperation(resultClass, "getChild", "<T> T", - ObjectModelModifier.PROTECTED); - addParameter(getChild, "java.util.Collection<T>", "childs"); - addParameter(getChild, "int", "index"); - setOperationBody(getChild, "" - /*{ - if (childs != null) { - int i = 0; - for (T o : childs) { - if (index == i) { - return o; - } - i++; - } - } - return null; - }*/ - ); - } - - if (hasEntity) { - //FIXME-TC20091219 : there is some bugs in import managers, ... - // due to I think cache extension, sometimes, there is no more imports - addImport(resultClass, TopiaEntity.class); - ObjectModelOperation getEntity = addOperation(resultClass, "getEntity", - "<T extends org.nuiton.topia.persistence.TopiaEntity> T", ObjectModelModifier.PROTECTED); - addParameter(getEntity, "java.util.Collection<T>", "childs"); - addParameter(getEntity, "java.lang.String", "topiaId"); - setOperationBody(getEntity, "" - /*{ - if (childs != null) { - for (T o : childs) { - if (topiaId.equals(o.getTopiaId())) { - return o; - } - } - } - return null; - }*/ - ); - } - - // Set body for default constructor - setOperationBody(constructor, "" - /*{ - pcs = new PropertyChangeSupport(this);<%=initTabs%> - }*/ - ); - - // Add operations - for (ObjectModelOperation op : clazz.getOperations()) { - String visibility = op.getVisibility(); - ObjectModelOperation resultOperation = addOperation(resultClass, op.getName(), op.getReturnType(), - ObjectModelModifier.toValue(visibility), ObjectModelModifier.ABSTRACT); - - for (ObjectModelParameter param : op.getParameters()) { - addParameter(resultOperation, param.getType(), param.getName()); - } - - for (String exception : op.getExceptions()) { - addException(resultOperation, exception); - } - } - - // Add toString operation - ObjectModelOperation toString = addOperation(resultClass, "toString", "java.lang.String", - ObjectModelModifier.PUBLIC); // FIXME manque Override - addImport(resultClass, "org.apache.commons.lang.builder.ToStringBuilder"); - setOperationBody(toString, "" - /*{ - String result = new ToStringBuilder(this)<%=toStringAppend%>. - toString(); - return result; - }*/ - ); - - } - - private void createForDTO(ObjectModelClass resultClass, ObjectModelClass inputClass, List<ObjectModelAttribute> attributes) { - - // Add Serializable implements for DTO generation - if (!inputClass.hasStereotype(TopiaGeneratorUtil.STEREOTYPE_DTO)) { - return; - - } - - addInterface(resultClass, "java.io.Serializable"); - String svUID = TopiaGeneratorUtil.findTagValue("dto-serialVersionUID", inputClass, getModel()); - if (svUID != null) { - addConstant(resultClass, "serialVersionUID", "long", svUID, ObjectModelModifier.PUBLIC); - } - - for (ObjectModelDependency dependency : inputClass.getDependencies()) { - ObjectModelClass supplier = (ObjectModelClass) dependency.getSupplier(); - - // ENTITY dependency - // Copy all primitives attributes from the Entity (supplier) to the DTO - // Prepare a list to future generation of all object generated attributes - if (supplier.hasStereotype(TopiaGeneratorUtil.STEREOTYPE_ENTITY)) { - if (log.isDebugEnabled()) { - log.debug("Create primitive and date fields in DTO from Entity : " - + supplier.getQualifiedName()); - } - for (ObjectModelAttribute attr : supplier.getAttributes()) { - if (TopiaGeneratorUtil.isPrimitiveType(attr) || TopiaGeneratorUtil.isDateType(attr)) { - attributes.add(attr); - } - } - } - } - } - - protected void createListeners(ObjectModelClass resultClass, ObjectModelClass inputClass) { - - addAttribute(resultClass, "pcs", "java.beans.PropertyChangeSupport", "", - ObjectModelModifier.PROTECTED, ObjectModelModifier.FINAL); - - // Add PropertyListener - String propType = "java.beans.PropertyChangeListener"; - String strType = String.class.getName(); - String objectType = Object.class.getName(); - - ObjectModelOperation addPropertyChangeListener = addOperation(resultClass, - "addPropertyChangeListener", "void", ObjectModelModifier.PUBLIC); - addParameter(addPropertyChangeListener, propType, "listener"); - setOperationBody(addPropertyChangeListener, "" - /*{ - pcs.addPropertyChangeListener(listener); - }*/ - ); - - ObjectModelOperation addPropertyChangeListenerPlus = addOperation(resultClass, - "addPropertyChangeListener", "void", ObjectModelModifier.PUBLIC); - addParameter(addPropertyChangeListenerPlus, strType, "propertyName"); - addParameter(addPropertyChangeListenerPlus, propType, "listener"); - setOperationBody(addPropertyChangeListenerPlus, "" - /*{ - pcs.addPropertyChangeListener(propertyName, listener); - }*/ - ); - - ObjectModelOperation removePropertyChangeListener = addOperation(resultClass, - "removePropertyChangeListener", "void", ObjectModelModifier.PUBLIC); - addParameter(removePropertyChangeListener, propType, "listener"); - setOperationBody(removePropertyChangeListener, "" - /*{ - pcs.removePropertyChangeListener(listener); - }*/ - ); - - ObjectModelOperation removePropertyChangeListenerPlus = addOperation(resultClass, - "removePropertyChangeListener", "void", ObjectModelModifier.PUBLIC); - addParameter(removePropertyChangeListenerPlus, strType, "propertyName"); - addParameter(removePropertyChangeListenerPlus, propType, "listener"); - setOperationBody(removePropertyChangeListenerPlus, "" - /*{ - pcs.removePropertyChangeListener(propertyName, listener); - }*/ - ); - - ObjectModelOperation firePropertyChange = addOperation(resultClass, - "firePropertyChange", "void", ObjectModelModifier.PROTECTED); - addParameter(firePropertyChange, strType, "propertyName"); - addParameter(firePropertyChange, objectType, "oldValue"); - addParameter(firePropertyChange, objectType, "newValue"); - setOperationBody(firePropertyChange, "" - /*{ - pcs.firePropertyChange(propertyName, oldValue, newValue); - }*/ - ); - } - - -} Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DAOAbstractTransformer.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DAOAbstractTransformer.java 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DAOAbstractTransformer.java 2010-11-28 20:17:13 UTC (rev 2156) @@ -113,7 +113,7 @@ @Override public void transformFromInterface(ObjectModelInterface interfacez) { - if (!interfacez.hasStereotype(TopiaGeneratorUtil.STEREOTYPE_DAO)) { + if (!TopiaGeneratorUtil.hasDaoStereotype(interfacez)) { return; } @@ -134,7 +134,7 @@ ObjectModelClassifier classifier = dependency.getSupplier(); - if (classifier.hasStereotype(TopiaGeneratorUtil.STEREOTYPE_ENTITY)) { + if (TopiaGeneratorUtil.hasEntityStereotype(classifier)) { // Only direct operations will be used. No need to have more // operations. @@ -151,7 +151,7 @@ @Override public void transformFromClass(ObjectModelClass clazz) { - if (!clazz.hasStereotype(TopiaGeneratorUtil.STEREOTYPE_ENTITY)) { + if (!TopiaGeneratorUtil.hasEntityStereotype(clazz)) { return; } @@ -166,7 +166,7 @@ String extendClass = ""; for (ObjectModelClass parent : clazz.getSuperclasses()) { extendClass = parent.getQualifiedName(); - if (parent.hasStereotype(TopiaGeneratorUtil.STEREOTYPE_ENTITY)) { + if (TopiaGeneratorUtil.hasEntityStereotype(parent)) { extendClass += "DAOImpl<E>"; // in java no multi-inheritance break; @@ -212,10 +212,7 @@ addImport(result, TopiaException.class); addImport(result, TopiaContextImplementor.class); - boolean enableSecurity = clazz.hasTagValue(TopiaGeneratorUtil.TAG_SECURITY_CREATE) || - clazz.hasTagValue(TopiaGeneratorUtil.TAG_SECURITY_LOAD) || - clazz.hasTagValue(TopiaGeneratorUtil.TAG_SECURITY_UPDATE) || - clazz.hasTagValue(TopiaGeneratorUtil.TAG_SECURITY_DELETE); + boolean enableSecurity = TopiaGeneratorUtil.isClassWithSecurity(clazz); if (enableSecurity) { addImport(result, ArrayList.class); @@ -300,7 +297,7 @@ }*/ ); buffer.append(generateSecurity(result, clazz, - TopiaGeneratorUtil.TAG_SECURITY_CREATE)); + TopiaGeneratorUtil.getSecurityCreateTagValue(clazz))); buffer.append("" /*{ } @@ -308,7 +305,7 @@ }*/ ); buffer.append(generateSecurity(result, clazz, - TopiaGeneratorUtil.TAG_SECURITY_LOAD)); + TopiaGeneratorUtil.getSecurityLoadTagValue(clazz))); buffer.append("" /*{ } @@ -316,7 +313,7 @@ }*/ ); buffer.append(generateSecurity(result, clazz, - TopiaGeneratorUtil.TAG_SECURITY_UPDATE)); + TopiaGeneratorUtil.getSecurityUpdateTagValue(clazz))); buffer.append("" /*{ } @@ -324,7 +321,7 @@ }*/ ); buffer.append(generateSecurity(result, clazz, - TopiaGeneratorUtil.TAG_SECURITY_DELETE)); + TopiaGeneratorUtil.getSecurityDeleteTagValue(clazz))); buffer.append("" /*{ } @@ -420,10 +417,10 @@ // 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 attrDBName = TopiaGeneratorUtil.getDbName(attr); + String attrClassifierDBName = TopiaGeneratorUtil.getDbName(attr.getClassifier()); String attrJoinTableName = TopiaGeneratorUtil.getManyToManyTableName(attr); - String attrReverseDBName = TopiaGeneratorUtil.getReverseDBName(attr); + String attrReverseDBName = TopiaGeneratorUtil.getReverseDbName(attr); //FIXME_-FC-20100413 Use a TopiaQuery (use HQLin elements) // // Add DAOHelper @@ -728,11 +725,11 @@ private String generateSecurity(ObjectModelClass result, ObjectModelClass clazz, - String securityTagName) { + String tagValue) { StringBuilder buffer = new StringBuilder(); - if (clazz.hasTagValue(securityTagName)) { - String security = clazz.getTagValue(securityTagName); + if (StringUtils.isNotEmpty(tagValue)) { + String security = tagValue; Pattern propertiesPattern = Pattern .compile("((?:[_a-zA-Z0-9]+\\.)+(?:_?[A-Z][_a-zA-Z0-9]*\\.)+)attribute\\.(?:([_a-z0-9][_a-zA-Z0-9]*))#(?:(create|load|update|delete))"); String[] valuesSecurity = security.split(":"); @@ -895,7 +892,7 @@ // This code will be deprecated for (ObjectModelOperation op : clazz.getOperations()) { - if (op.hasStereotype(TopiaGeneratorUtil.STEREOTYPE_DAO)) { + if (TopiaGeneratorUtil.hasDaoStereotype(op)) { results.add(op); } } Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DAOHelperTransformer.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DAOHelperTransformer.java 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DAOHelperTransformer.java 2010-11-28 20:17:13 UTC (rev 2156) @@ -73,10 +73,10 @@ List<ObjectModelClass> classes = TopiaGeneratorUtil.getEntityClasses(model, true); boolean generateOperator = - TopiaGeneratorUtil.shouldgenerateOperatorForDAOHelper(null, model); + TopiaGeneratorUtil.shouldGenerateOperatorForDAOHelper(model); boolean generateStandaloneEnum = - TopiaGeneratorUtil.shouldGnerateStandaloneEnumForDAOHelper(null, model); + TopiaGeneratorUtil.shouldGenerateStandaloneEnumForDAOHelper(model); ObjectModelClass daoHelper = createClass(daoHelperClazzName, packageName); Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DAOImplTransformer.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DAOImplTransformer.java 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DAOImplTransformer.java 2010-11-28 20:17:13 UTC (rev 2156) @@ -54,7 +54,7 @@ @Override public void transformFromInterface(ObjectModelInterface interfacez) { - if (!interfacez.hasStereotype(TopiaGeneratorUtil.STEREOTYPE_DAO)) { + if (!TopiaGeneratorUtil.hasDaoStereotype(interfacez)) { return; } @@ -69,14 +69,14 @@ ObjectModelClassifier classifier = dependency.getSupplier(); - if (classifier.hasStereotype(TopiaGeneratorUtil.STEREOTYPE_ENTITY)) { + if (TopiaGeneratorUtil.hasEntityStereotype(classifier)) { noGenerationNeeded.add(classifier.getQualifiedName()); } } @Override public void transformFromClass(ObjectModelClass clazz) { - if (!clazz.hasStereotype(TopiaGeneratorUtil.STEREOTYPE_ENTITY) || hasDAOOperations(clazz)) { + if (!TopiaGeneratorUtil.hasEntityStereotype(clazz) || hasDAOOperations(clazz)) { return; } String clazzName = clazz.getName(); @@ -100,14 +100,11 @@ public boolean hasDAOOperations(ObjectModelClass clazz) { // This code will be deprecated for (ObjectModelOperation op : clazz.getOperations()) { - if (op.hasStereotype(TopiaGeneratorUtil.STEREOTYPE_DAO)) { + if (TopiaGeneratorUtil.hasDaoStereotype(op)) { return true; } } // New method : interface dependency - if (noGenerationNeeded.contains(clazz.getQualifiedName())) { - return true; - } - return false; + return noGenerationNeeded.contains(clazz.getQualifiedName()); } } Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DAOTransformer.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DAOTransformer.java 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DAOTransformer.java 2010-11-28 20:17:13 UTC (rev 2156) @@ -43,7 +43,7 @@ @Override public void transformFromClass(ObjectModelClass clazz) { - if (!clazz.hasStereotype(TopiaGeneratorUtil.STEREOTYPE_ENTITY)) { + if (!TopiaGeneratorUtil.hasEntityStereotype(clazz)) { return; } String clazzName = clazz.getName(); Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DTOTransformer.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DTOTransformer.java 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/DTOTransformer.java 2010-11-28 20:17:13 UTC (rev 2156) @@ -32,7 +32,6 @@ import org.nuiton.eugene.GeneratorUtil; import org.nuiton.eugene.java.ObjectModelTransformerToJava; import org.nuiton.eugene.models.object.*; -import static org.nuiton.topia.generator.TopiaGeneratorUtil.TAG_ANNOTATION; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; @@ -62,7 +61,7 @@ @Override public void transformFromClass(ObjectModelClass clazz) { - if (!clazz.hasStereotype(TopiaGeneratorUtil.STEREOTYPE_DTO)) { + if (!TopiaGeneratorUtil.hasDtoStereotype(clazz)) { return; } String clazzName = clazz.getName(); @@ -84,7 +83,7 @@ addInterface(result, Serializable.class); for (ObjectModelInterface parentInterface : clazz.getInterfaces()) { - if (parentInterface.hasStereotype(TopiaGeneratorUtil.STEREOTYPE_DTO)) { + if (TopiaGeneratorUtil.hasDtoStereotype(parentInterface)) { addInterface(result, parentInterface.getName() + "DTO"); } else { addInterface(result, parentInterface.getName()); @@ -175,7 +174,7 @@ if (TopiaGeneratorUtil.hasDocumentation(attr)) { setDocumentation(attr2, attr.getDocumentation()); } - String annotation = attr.getTagValue(TAG_ANNOTATION); + String annotation = TopiaGeneratorUtil.getAnnotationTagValue(attr); if (StringUtils.isNotEmpty(annotation)) { addAnnotation(result, attr2, annotation); } @@ -435,9 +434,9 @@ attrEntity = model.getClass(attr.getType()); } boolean isDTO = attrEntity != null && - attrEntity.hasStereotype(TopiaGeneratorUtil.STEREOTYPE_ENTITY); //THIMEL : STEREOTYPE ENTITY ??? + TopiaGeneratorUtil.hasEntityStereotype(attrEntity); //THIMEL : STEREOTYPE ENTITY ??? ObjectModelAttribute reverse = attr.getReverseAttribute(); - if (isDTO && (reverse == null || !reverse.isNavigable()) && !attr.hasAssociationClass() || (!isDTO)) { + if (isDTO && (reverse == null || !reverse.isNavigable()) && !attr.hasAssociationClass() || !isDTO) { String attrName = attr.getName(); buffer.append("" /*{ append("<%=attrName%>", this.<%=attrName%>). @@ -455,7 +454,7 @@ public boolean isDTO(String type) { ObjectModelClassifier clazz = model.getClassifier(type); - return clazz != null && clazz.hasStereotype(TopiaGeneratorUtil.STEREOTYPE_DTO); + return clazz != null && TopiaGeneratorUtil.hasDtoStereotype(clazz); } Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityAbstractTransformer.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityAbstractTransformer.java 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityAbstractTransformer.java 2010-11-28 20:17:13 UTC (rev 2156) @@ -1,1270 +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.lang.StringUtils; -import org.apache.commons.lang.builder.ToStringBuilder; -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.*; -import org.nuiton.topia.TopiaException; -import org.nuiton.topia.framework.TopiaContextImplementor; -import static org.nuiton.topia.generator.TopiaGeneratorUtil.*; -import org.nuiton.topia.persistence.EntityVisitor; -import org.nuiton.topia.persistence.TopiaEntity; -import org.nuiton.topia.persistence.TopiaEntityAbstract; - -import java.beans.Introspector; -import java.util.ArrayList; -import java.util.List; - -/*{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.EntityAbstractTransformer" - * @deprecated since 2.4 : all transformations needed for Entity is in {@link EntityTransformer} included in {@link TopiaMetaTransformer} - */ -@Deprecated -public class EntityAbstractTransformer extends ObjectModelTransformerToJava { - - /** - * Logger - */ - private static final Log log = - LogFactory.getLog(EntityAbstractTransformer.class); - - @Override - public void transformFromClass(ObjectModelClass clazz) { - if (!clazz.hasStereotype(STEREOTYPE_ENTITY)) { - return; - } - - String clazzName = clazz.getName(); - String clazzFQN = TopiaGeneratorUtil.getSimpleName( - clazz.getQualifiedName()); - - ObjectModelClass result; - - if (log.isDebugEnabled()) { - log.debug("for entity : " + clazz.getQualifiedName()); - } - - result = createAbstractClass(clazzName + "Abstract", - clazz.getPackageName()); - - addInterface(result, clazzName); - - addImport(result, ArrayList.class); - addImport(result, List.class); - addImport(result, ToStringBuilder.class); - addImport(result, TopiaEntity.class); - addImport(result, TopiaContextImplementor.class); - - 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); - - // javadoc - - StringBuilder doc = new StringBuilder(); - doc.append("Implantation POJO pour l'entité {@link "); - doc.append(StringUtils.capitalize(clazzFQN)); - doc.append("}\n"); - - { - String dbName = clazz.getTagValue(TAG_DB_NAME); - if (dbName != null) { - doc.append("<p>Nom de l'entité en BD : "); - doc.append(dbName); - doc.append(".</p>"); - } - } - - setDocumentation(result, doc.toString()); - - // super classes - - for (ObjectModelClass parent : clazz.getSuperclasses()) { - String extendClass = parent.getQualifiedName(); - //Si une des classes parentes définies des méthodes abstraites, son - // impl ne sera pas créé - boolean abstractParent = shouldBeAbstract(parent); - if (parent.hasStereotype(STEREOTYPE_ENTITY)) { - if (abstractParent) { - extendClass += "Abstract"; - } else { - extendClass += "Impl"; - } - } - setSuperClass(result, extendClass); - } - - if (result.getSuperclasses().isEmpty()) { - setSuperClass(result, TopiaEntityAbstract.class); - } - - // serialVersionUID - - String svUID = TopiaGeneratorUtil.findTagValue("serialVersionUID", - clazz, model); - if (svUID != null) { - addAttribute(result, "serialVersionUID", long.class, svUID, - ObjectModelModifier.PRIVATE, - ObjectModelModifier.STATIC, - ObjectModelModifier.FINAL); - - } - - ObjectModelParameter 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 type; - String name; - - if (!attr.hasAssociationClass()) { - String attrName = attr.getName(); - name = attrName; - type = attr.getType(); -// type = TopiaGeneratorUtil.getSimpleName(attr.getType()); - } else { - String assocAttrName = GeneratorUtil.getAssocAttrName(attr); - //TODO THIMEL : Je pense que les GeneratorUtil.toLowerCaseFirstLetter sont inutiles ici, ou alors il faudrait le faire partout - name = GeneratorUtil.toLowerCaseFirstLetter(assocAttrName); - type = attr.getAssociationClass().getQualifiedName(); -// type = TopiaGeneratorUtil.getSimpleName(attr.getAssociationClass().getQualifiedName()); - } - - if (GeneratorUtil.isNMultiplicity(attr)) { - String collectionType = - TopiaGeneratorUtil.getNMultiplicityInterfaceType(attr); - type = collectionType + '<' + type + '>'; - } - - String attrVisibility = attr.getVisibility(); - - attr2 = addAttribute(result, name, type, null, - ObjectModelModifier.toValue(attrVisibility), - ObjectModelModifier.PROTECTED - ); - - doc = new StringBuilder(); - - if (TopiaGeneratorUtil.hasDocumentation(attr) || - attr.hasTagValue(TAG_DB_NAME)) { - if (TopiaGeneratorUtil.hasDocumentation(attr)) { - String attrDocumentation = attr.getDocumentation(); - doc.append(attrDocumentation).append('\n'); - } - if (attr.hasTagValue(TAG_DB_NAME)) { - String dbName = - attr.getTagValue(TAG_DB_NAME); - doc.append("Nom de l'attribut en BD : "); - doc.append(dbName); - doc.append('\n'); - } - } - - setDocumentation(attr2, doc.toString()); - - - if (attr.hasTagValue(TAG_ANNOTATION)) { - String annotation = attr.getTagValue(TAG_ANNOTATION); - //FIXME Make annotation works... - //TODO tchemit 20100513 Test if it still works - 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(); - String attrType = attr.getType(); - String attrName = attr.getName(); - addAttribute(result, - GeneratorUtil.toLowerCaseFirstLetter(attrName), - attrType, null, - ObjectModelModifier.toValue(attrVisibility)); - } - } - } - - ObjectModelOperation op = addOperation(result, "update", "void", - ObjectModelModifier.PUBLIC); - addException(op, TopiaException.class); - setOperationBody(op, "" -/*{ - ((TopiaContextImplementor)getTopiaContext()).getDAO(<%=clazzName%>.class).update(this); -}*/ - ); - - op = addOperation(result, "delete", "void", ObjectModelModifier.PUBLIC); - addException(op, TopiaException.class); - setOperationBody(op, "" -/*{ - ((TopiaContextImplementor)getTopiaContext()).getDAO(<%=clazzName%>.class).delete(this); -}*/ - ); - - generateAcceptMethod(result, clazz); - - generateAggregateMethod(result, clazz); - - generateCompositeMethod(result, clazz); - - - for (ObjectModelAttribute attr : clazz.getAttributes()) { - ObjectModelAttribute reverse = attr.getReverseAttribute(); - - if (!(attr.isNavigable() - || hasUnidirectionalRelationOnAbstractType(reverse, model))) - { - continue; - } - - transformAttribute(result, attr, reverse); - } - - - //Méthodes d'accès aux attributs d'une classe d'associations - if (clazz instanceof ObjectModelAssociationClass) { - generateAssociationAccessors(result, - (ObjectModelAssociationClass) clazz); - } - - generateAbstractMethods(result, clazz); - - boolean doGenerateToString = TopiaGeneratorUtil.generateToString(clazz, - model); - if (doGenerateToString) { - generateToStringMethod(result, clazz); - } - - String i18nPrefix = JavaGeneratorUtil.getI18nPrefix(clazz, model); - if (!StringUtils.isEmpty(i18nPrefix)) { - // generate i18n prefix - generateI18nBlock(clazz, result, i18nPrefix); - } - } - - protected void transformAttribute(ObjectModelClass result, - ObjectModelAttribute attr, - ObjectModelAttribute reverse) { - - String attrName = attr.getName(); - String attrType = TopiaGeneratorUtil.getSimpleName(attr.getType()); - addImport(result, attrType); - - attrType = TopiaGeneratorUtil.getSimpleName(attrType); - - ObjectModelOperation op; - - if (!GeneratorUtil.isNMultiplicity(attr)) { - - if (attr.hasAssociationClass()) { - String assocAttrName = GeneratorUtil.getAssocAttrName(attr); - String assocClassFQN = attr.getAssociationClass().getQualifiedName(); - addImport(result, assocClassFQN); - assocClassFQN = TopiaGeneratorUtil.getSimpleName(assocClassFQN); - String name = GeneratorUtil.toLowerCaseFirstLetter(assocAttrName); - - // setXXX - - op = addOperation(result, - "set" + StringUtils.capitalize(assocAttrName), - "void", - ObjectModelModifier.PUBLIC); - addParameter(op, assocClassFQN, "association"); - setOperationBody(op, "" -/*{ - <%=assocClassFQN%> _oldValue = this.<%=name%>; - fireOnPreWrite(<%=getConstantName(name)%>, _oldValue, association); - this.<%=name%> = association; - fireOnPostWrite(<%=getConstantName(name)%>, _oldValue, association); -}*/ - ); - - // getXXX - - op = addOperation(result, - "get" + StringUtils.capitalize(assocAttrName), - assocClassFQN, ObjectModelModifier.PUBLIC); - setOperationBody(op, "" -/*{ - return <%=name%>; -}*/ - ); - } else { - - // setXXX - - op = addOperation(result, - "set" + StringUtils.capitalize(attrName), - "void", - ObjectModelModifier.PUBLIC); - addParameter(op, attrType, "value"); - setOperationBody(op, "" -/*{ - <%=attrType%> _oldValue = this.<%=attrName%>; - fireOnPreWrite(<%=getConstantName(attrName)%>, _oldValue, value); - this.<%=attrName%> = value; - fireOnPostWrite(<%=getConstantName(attrName)%>, _oldValue, value); -}*/ - - ); - - // getXXX - - op = addOperation(result, - "get" + StringUtils.capitalize(attrName), - attrType, - ObjectModelModifier.PUBLIC); - setOperationBody(op, "" -/*{ - fireOnPreRead(<%=getConstantName(attrName)%>, <%=attrName%>); - <%=attrType%> result = this.<%=attrName%>; - fireOnPostRead(<%=getConstantName(attrName)%>, <%=attrName%>); - return result; -}*/ - ); - } - } else { //NMultiplicity - String collectionInterface = TopiaGeneratorUtil.getNMultiplicityInterfaceType(attr); - String collectionObject = TopiaGeneratorUtil.getNMultiplicityObjectType(attr); - addImport(result, collectionInterface); - addImport(result, collectionObject); - collectionInterface = TopiaGeneratorUtil.getSimpleName(collectionInterface); - collectionObject = getSimpleName(collectionObject); - - if (!attr.hasAssociationClass()) { - //Méthodes remplacées par des accesseurs sur les classes d'assoc - - // addXXX - - op = addOperation(result, - "add" + StringUtils.capitalize(attrName), - "void", - ObjectModelModifier.PUBLIC); - addParameter(op, attrType, attrName); - StringBuilder body = new StringBuilder(); - - body.append("" -/*{ - fireOnPreWrite(<%=getConstantName(attrName)%>, null, <%=attrName%>); - if (this.<%=attrName%> == null) { - this.<%=attrName%> = new <%=collectionObject%><<%=attrType%>>(); - } -}*/ - ); - - if (reverse != null && (reverse.isNavigable() || - hasUnidirectionalRelationOnAbstractType(attr, model))) { - String reverseAttrName = reverse.getName(); - String reverseAttrType = TopiaGeneratorUtil.getSimpleName(reverse.getType()); - if (!GeneratorUtil.isNMultiplicity(reverse)) { - body.append("" -/*{ <%=attrName%>.set<%=StringUtils.capitalize(reverseAttrName)%>(this); -}*/ - ); - } else { - body.append("" -/*{ if (<%=attrName%>.get<%=StringUtils.capitalize(reverseAttrName)%>() == null) { - <%=attrName%>.set<%=StringUtils.capitalize(reverseAttrName)%>(new <%=collectionObject%><<%=reverseAttrType%>>()); - } - <%=attrName%>.get<%=StringUtils.capitalize(reverseAttrName)%>().add(this); -}*/ - ); - } - } - body.append("" -/*{ this.<%=attrName%>.add(<%=attrName%>); - fireOnPostWrite(<%=getConstantName(attrName)%>, this.<%=attrName%>.size(), null, <%=attrName%>); -}*/ - ); - setOperationBody(op, body.toString()); - - // addAllXXX - - op = addOperation(result, - "addAll" + StringUtils.capitalize(attrName), - "void", - ObjectModelModifier.PUBLIC); - addParameter(op, collectionInterface + '<' + attrType + '>', "values"); - - setOperationBody(op, "" -/*{ - if (values == null) { - return; - } - for (<%=attrType%> item : values) { - add<%=StringUtils.capitalize(attrName)%>(item); - } -}*/ - ); - - if (!isPrimitiveType(attr) && !isDateType(attr)) { - - op = addOperation(result, - "get" + StringUtils.capitalize(attrName) + "ByTopiaId", - attrType, - ObjectModelModifier.PUBLIC); - addParameter(op, String.class, "topiaId"); - setOperationBody(op, "" -/*{ - return org.nuiton.topia.persistence.util.TopiaEntityHelper.getEntityByTopiaId(<%=attrName%>, topiaId); - }*/ - ); - - } - - // setXXX - - op = addOperation(result, - "set" + StringUtils.capitalize(attrName), - "void", - ObjectModelModifier.PUBLIC); - addParameter(op, collectionInterface + '<' + attrType + '>', "values"); - - setOperationBody(op, "" -/*{ - <%=collectionInterface%><<%=attrType%>> _oldValue = <%=attrName%>; - fireOnPreWrite(<%=getConstantName(attrName)%>, _oldValue, values); - <%=attrName%> = values; - fireOnPostWrite(<%=getConstantName(attrName)%>, _oldValue, values); -}*/ - ); - - - // removeXXX - - - op = addOperation(result, - "remove" + StringUtils.capitalize(attrName), - "void", - ObjectModelModifier.PUBLIC); - addParameter(op, attrType, "value"); - body = new StringBuilder(); - - body.append("" -/*{ - fireOnPreWrite(<%=getConstantName(attrName)%>, value, null); - if ((this.<%=attrName%> == null) || (!this.<%=attrName%>.remove(value))) { - throw new IllegalArgumentException("List does not contain given element"); - } -}*/ - ); - - if (reverse != null && (reverse.isNavigable() || - hasUnidirectionalRelationOnAbstractType(attr, model))) { - String reverseAttrName = reverse.getName(); - if (!GeneratorUtil.isNMultiplicity(reverse)) { - body.append("" -/*{ value.set<%=StringUtils.capitalize(reverseAttrName)%>(null); -}*/ - ); - } else { - body.append("" -/*{ value.get<%=StringUtils.capitalize(reverseAttrName)%>().remove(this); -}*/ - ); - } - } - body.append("" -/*{ fireOnPostWrite(<%=getConstantName(attrName)%>, this.<%=attrName%>.size()+1, value, null); -}*/ - ); - setOperationBody(op, body.toString()); - - - // clearXXX - - op = addOperation(result, - "clear" + StringUtils.capitalize(attrName), - "void", - ObjectModelModifier.PUBLIC); - - body = new StringBuilder(); - - body.append("" -/*{ - if (this.<%=attrName%> == null) { - return; - } -}*/ - ); - - if (reverse != null && (reverse.isNavigable() || - hasUnidirectionalRelationOnAbstractType(attr, model))) { - String reverseAttrName = reverse.getName(); - body.append("" -/*{ for (<%=attrType%> item : this.<%=attrName%>) { -}*/ - ); - if (!GeneratorUtil.isNMultiplicity(reverse)) { - body.append("" -/*{ item.set<%=StringUtils.capitalize(reverseAttrName)%>(null); -}*/ - ); - } else { - body.append("" -/*{ item.get<%=StringUtils.capitalize(reverseAttrName)%>().remove(this); -}*/ - ); - } - body.append("" -/*{ } -}*/ - ); - } - body.append("" -/*{ <%=collectionInterface%><<%=attrType%>> _oldValue = new <%=collectionObject%><<%=attrType%>>(this.<%=attrName%>); - fireOnPreWrite(<%=getConstantName(attrName)%>, _oldValue, this.<%=attrName%>); - this.<%=attrName%>.clear(); - fireOnPostWrite(<%=getConstantName(attrName)%>, _oldValue, this.<%=attrName%>); -}*/ - ); - - setOperationBody(op, body.toString()); - - } else { - - - String assocAttrName = GeneratorUtil.getAssocAttrName(attr); - String assocClassFQN = attr.getAssociationClass().getQualifiedName(); -// String assocClassFQN = TopiaGeneratorUtil.getSimpleName(attr.getAssociationClass().getQualifiedName()); - - // addXXX - - op = addOperation(result, - "add" + StringUtils.capitalize(assocAttrName), - "void", - ObjectModelModifier.PUBLIC); - addParameter(op, assocClassFQN, "value"); - - StringBuilder body = new StringBuilder(); - - body.append("" -/*{ - fireOnPreWrite(<%=getConstantName(GeneratorUtil.toLowerCaseFirstLetter(assocAttrName))%>, null, value); - if (this.<%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%> == null) { - this.<%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%> = new <%=collectionObject%><<%=assocClassFQN%>>(); - } -}*/ - ); - if (reverse != null && (reverse.isNavigable() || - hasUnidirectionalRelationOnAbstractType(attr, model))) { - String reverseAttrName = reverse.getName(); - body.append("" -/*{ value.set<%=StringUtils.capitalize(reverseAttrName)%>(this); -}*/ - ); - } - body.append("" -/*{ this.<%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%>.add(value); - fireOnPostWrite(<%=getConstantName(GeneratorUtil.toLowerCaseFirstLetter(assocAttrName))%>, this.<%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%>.size(), null, value); -}*/ - ); - setOperationBody(op, body.toString()); - - - if (!isPrimitiveType(attr) && !isDateType(attr)) { - - // getXXXByTopiaId - - op = addOperation(result, - "get" + StringUtils.capitalize(assocAttrName) + "ByTopiaId", - assocClassFQN, - ObjectModelModifier.PUBLIC); - addParameter(op, String.class, "topiaId"); - setOperationBody(op, "" -/*{ - return org.nuiton.topia.persistence.util.TopiaEntityHelper.getEntityByTopiaId(<%=assocAttrName%>, topiaId); -}*/ - ); - - } - - // addAllXXX - - op = addOperation(result, - "addAll" + StringUtils.capitalize(assocAttrName), - "void", - ObjectModelModifier.PUBLIC); - addParameter(op, collectionInterface + '<' + assocClassFQN + '>', "values"); - setOperationBody(op, "" -/*{ - if (values == null) { - return; - } - for (<%=assocClassFQN%> item : values) { - add<%=StringUtils.capitalize(assocAttrName)%>(item); - } -}*/ - ); - - // setXXX - - op = addOperation(result, - "set" + StringUtils.capitalize(assocAttrName), - "void", - ObjectModelModifier.PUBLIC); - addParameter(op, collectionInterface + '<' + assocClassFQN + '>', "values"); - setOperationBody(op, "" -/*{ -// clear<%=StringUtils.capitalize(assocAttrName)%>(); -// addAll<%=StringUtils.capitalize(assocAttrName)%>(values); -// FIXME - <%=collectionInterface%><<%=assocClassFQN%>> _oldValue = <%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%>; - fireOnPreWrite(<%=getConstantName(GeneratorUtil.toLowerCaseFirstLetter(assocAttrName))%>, _oldValue, values); - <%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%> = values; - fireOnPostWrite(<%=getConstantName(GeneratorUtil.toLowerCaseFirstLetter(assocAttrName))%>, _oldValue, values); -}*/ - ); - - // removeXXX - - op = addOperation(result, - "remove" + StringUtils.capitalize(assocAttrName), - "void", - ObjectModelModifier.PUBLIC); - addParameter(op, assocClassFQN, "value"); - - body = new StringBuilder(); - - body.append("" -/*{ - fireOnPreWrite(<%=getConstantName(GeneratorUtil.toLowerCaseFirstLetter(assocAttrName))%>, value, null); - if ((this.<%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%> == null) || (!this.<%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%>.remove(value))) { - throw new IllegalArgumentException("List does not contain given element"); - } -}*/ - ); - if (reverse != null && (reverse.isNavigable() || - hasUnidirectionalRelationOnAbstractType(attr, model))) { - String reverseAttrName = reverse.getName(); - body.append("" -/*{ value.set<%=StringUtils.capitalize(reverseAttrName)%>(null); -}*/ - ); - } - body.append("" -/*{ fireOnPostWrite(<%=getConstantName(GeneratorUtil.toLowerCaseFirstLetter(assocAttrName))%>, this.<%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%>.size()+1, value, null); -}*/ - ); - - setOperationBody(op, body.toString()); - - // clearXXX - - op = addOperation(result, - "clear" + StringUtils.capitalize(assocAttrName), - "void", - ObjectModelModifier.PUBLIC); - - body = new StringBuilder(); - - body.append("" -/*{ - if (this.<%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%> == null) { - return; - } -}*/ - ); - - if (reverse != null && (reverse.isNavigable() || - hasUnidirectionalRelationOnAbstractType(attr, model))) { - String reverseAttrName = reverse.getName(); - body.append("" -/*{ for (<%=assocClassFQN%> item : this.<%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%>) { - item.set<%=StringUtils.capitalize(reverseAttrName)%>(null); - } -}*/ - ); - } - body.append("" -/*{ <%=collectionInterface%><<%=assocClassFQN%>> _oldValue = new <%=collectionObject%><<%=assocClassFQN%>>(this.<%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%>); - fireOnPreWrite(<%=getConstantName(GeneratorUtil.toLowerCaseFirstLetter(assocAttrName))%>, _oldValue, null); - this.<%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%>.clear(); - fireOnPostWrite(<%=getConstantName(GeneratorUtil.toLowerCaseFirstLetter(assocAttrName))%>, _oldValue, null); -}*/ - ); - setOperationBody(op, body.toString()); - } - - if (!attr.hasAssociationClass()) { - - // getXXX - - op = addOperation(result, - "get" + StringUtils.capitalize(attrName), - collectionInterface + '<' + attrType + '>', - ObjectModelModifier.PUBLIC); - setOperationBody(op, "" -/*{ - return <%=attrName%>; -}*/ - ); - - // sizeXXX - - op = addOperation(result, - "size" + StringUtils.capitalize(attrName), - int.class, - ObjectModelModifier.PUBLIC); - setOperationBody(op, "" -/*{ - if (<%=attrName%> == null) { - return 0; - } - return <%=attrName%>.size(); -}*/ - ); - - // isXXXEmpty - - op = addOperation(result, - "is" + StringUtils.capitalize(attrName) + "Empty", - boolean.class, - ObjectModelModifier.PUBLIC); - setOperationBody(op, "" -/*{ - int size = size<%=StringUtils.capitalize(attrName)%>(); - return size == 0; -}*/ - ); - - } else { - String assocAttrName = GeneratorUtil.getAssocAttrName(attr); - String assocClassFQN = attr.getAssociationClass().getQualifiedName(); -// String assocClassFQN = TopiaGeneratorUtil.getSimpleName(attr.getAssociationClass().getQualifiedName()); - - // getXXX - - op = addOperation(result, - "get" + StringUtils.capitalize(assocAttrName), - collectionInterface + '<' + assocClassFQN + '>', - ObjectModelModifier.PUBLIC); - setOperationBody(op, "" -/*{ - return <%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%>; -}*/ - ); - - // getXXX - - op = addOperation(result, - "get" + StringUtils.capitalize(assocAttrName), - assocClassFQN, - ObjectModelModifier.PUBLIC); - addParameter(op, attrType, "value"); - setOperationBody(op, "" -/*{ - if (value == null || <%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%> == null) { - return null; - } - for (<%=assocClassFQN%> item : <%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%>) { - if (value.equals(item.get<%=StringUtils.capitalize(attrName)%>())) { - return item; - } - } - return null; -}*/ - ); - - - // sizeXXX - - op = addOperation(result, - "size" + StringUtils.capitalize(assocAttrName), - int.class, - ObjectModelModifier.PUBLIC); - setOperationBody(op, "" -/*{ - if (<%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%> == null) { - return 0; - } - return <%=GeneratorUtil.toLowerCaseFirstLetter(assocAttrName)%>.size(); -}*/ - ); - - //isXXXEmpty - - op = addOperation(result, - "is" + StringUtils.capitalize(assocAttrName) + "Empty", - boolean.class, - ObjectModelModifier.PUBLIC); - setOperationBody(op, "" -/*{ - int size = size<%=StringUtils.capitalize(assocAttrName)%>(); - return size == 0; -}*/ - ); - - } - } - } - - protected void generateAssociationAccessors( - ObjectModelClass result, - ObjectModelAssociationClass assoc) { - for (ObjectModelAttribute attr : assoc.getParticipantsAttributes()) { - if (attr != null) { - String attrType = TopiaGeneratorUtil.getSimpleName(attr.getType()); - String attrName = attr.getName(); - generateAssociationAccessors(result, attrName, attrType); -// //Ne sert plus à rien normalement avec la navigabilité -// ObjectModelAttribute reverse = attr.getReverseAttribute(); -// if (reverse == null) { -// attrType = ((ObjectModelClassifier)attr.getDeclaringElement()).getQualifiedName(); -// attrName = attr.getDeclaringElement().getName(); -// generateAssociationAccessors(output, attrName, attrType); -// } - } - } - } - - protected void generateToStringMethod(ObjectModelClass result, - ObjectModelClass clazz) { - if (log.isDebugEnabled()) { - log.debug("generate toString method for clazz " + - clazz.getQualifiedName()); - } - ObjectModelOperation op = addOperation(result, - "toString", - String.class, - ObjectModelModifier.PUBLIC); - addAnnotation(result, op, Override.class.getSimpleName()); - StringBuilder body = new StringBuilder(); - - - body.append("" -/*{ - String result = new ToStringBuilder(this). -}*/ - ); - for (ObjectModelAttribute attr : clazz.getAttributes()) { - //FIXME possibilité de boucles (non directes) - ObjectModelClass attrEntity = null; - if (model.hasClass(attr.getType())) { - attrEntity = model.getClass(attr.getType()); - } - boolean isEntity = attrEntity != null && - attrEntity.hasStereotype(STEREOTYPE_ENTITY); - ObjectModelAttribute reverse = attr.getReverseAttribute(); - if (isEntity && (reverse == null || !reverse.isNavigable()) - && !attr.hasAssociationClass() || !isEntity) { - String attrName = attr.getName(); - body.append("" -/*{ append(<%=getConstantName(attrName)%>, this.<%=attrName%>). -}*/ - ); - } - } - body.append("" -/*{ toString(); - return result; -}*/ - ); - setOperationBody(op, body.length() == 0 ? " " : body.toString()); - - } - - protected void generateCompositeMethod(ObjectModelClass result, - ObjectModelClass clazz) { - - ObjectModelOperation op = addOperation(result, - "getComposite", - List.class.getName() + '<' + TopiaEntity.class.getName() + '>', - ObjectModelModifier.PUBLIC); - addException(op, TopiaException.class); - StringBuilder body = new StringBuilder(); - 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 : clazz.getAttributes()) { - if (attr.referenceClassifier() && - attr.getClassifier().hasStereotype( - STEREOTYPE_ENTITY)) { - if (attr.isComposite()) { - String attrName = attr.getName(); - String getterName = "get" + StringUtils.capitalize(attrName); - if (GeneratorUtil.isNMultiplicity(attr)) { - body.append("" -/*{ if (<%=getterName%>() != null) { - tmp.addAll(<%=getterName%>()); - } -}*/ - ); - } else { - body.append("" -/*{ tmp.add(<%=getterName%>()); -}*/ - ); - } - } else if (attr.hasAssociationClass()) { - String assocAttrName = GeneratorUtil.getAssocAttrName( - attr); - String assocClassFQN = TopiaGeneratorUtil.getSimpleName( - attr.getAssociationClass().getQualifiedName()); - String ref = "this." + GeneratorUtil.toLowerCaseFirstLetter( - assocAttrName); - if (!GeneratorUtil.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 = ((TopiaContextImplementor) 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(op, body.length() == 0 ? " " : body.toString()); - } - - protected void generateAggregateMethod(ObjectModelClass result, - ObjectModelClass clazz) { - - ObjectModelOperation op = addOperation(result, - "accept", - List.class.getName() + '<' + TopiaEntity.class.getName() + '>', - ObjectModelModifier.PUBLIC); - addException(op, TopiaException.class); - - StringBuilder body = new StringBuilder(); - 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 : clazz.getAttributes()) { - if (attr.referenceClassifier() && - attr.getClassifier().hasStereotype( - STEREOTYPE_ENTITY)) { - if (attr.isAggregate()) { - String attrName = attr.getName(); - String getterName = "get" + StringUtils.capitalize(attrName); - if (GeneratorUtil.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(op, body.length() == 0 ? " " : body.toString()); - } - - protected void generateAcceptMethod(ObjectModelClass result, - ObjectModelClass clazz) { - - ObjectModelOperation op = addOperation(result, - "accept", - "void", - ObjectModelModifier.PUBLIC); - addException(op, TopiaException.class); - setDocumentation(op, "Envoi via les methodes du visitor l'ensemble des " + - "champs de l'entity\n" + - "avec leur nom, type et valeur."); - { - ObjectModelParameter attr = addParameter(op, EntityVisitor.class, - "visitor"); - setDocumentation(attr, "le visiteur de l'entite."); - } - StringBuilder body = new StringBuilder(); - body.append("" -/*{ - visitor.start(this); -}*/ - ); - 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; - } - - if (!attr.hasAssociationClass()) { - String attrType = TopiaGeneratorUtil.getSimpleName(attr.getType()); - String attrName = attr.getName(); - if (!GeneratorUtil.isNMultiplicity(attr)) { - body.append("" -/*{ visitor.visit(this, <%=getConstantName(attrName)%>, <%=attrType%>.class, <%=attrName%>); -}*/ - ); - } else { - String collectionType = TopiaGeneratorUtil.getSimpleName( - TopiaGeneratorUtil.getNMultiplicityInterfaceType( - attr)); - body.append("" -/*{ visitor.visit(this, <%=getConstantName(attrName)%>, <%=collectionType%>.class, <%=attrType%>.class, <%=attrName%>); -}*/ - ); - } - } else { - String assocAttrName = GeneratorUtil.getAssocAttrName(attr); - assocAttrName = GeneratorUtil.toLowerCaseFirstLetter(assocAttrName); - String assocClassFQN = TopiaGeneratorUtil.getSimpleName( - attr.getAssociationClass().getQualifiedName()); - if (!GeneratorUtil.isNMultiplicity(attr)) { - body.append("" -/*{ visitor.visit(this, <%=getConstantName(assocAttrName)%>, <%=assocClassFQN%>.class, <%=assocAttrName%>); -}*/ - ); - } else { - String collectionType = TopiaGeneratorUtil.getNMultiplicityInterfaceType(attr); - body.append("" -/*{ visitor.visit(this, <%=getConstantName(assocAttrName)%>, <%=collectionType%>.class, <%=assocClassFQN%>.class, <%=assocAttrName%>); -}*/ - ); - } - } - } - - //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 attrType = TopiaGeneratorUtil.getSimpleName( - attr.getType()); - String attrName = attr.getName(); - attrName = GeneratorUtil.toLowerCaseFirstLetter(attrName); - body.append("" -/*{ visitor.visit(this, <%=getConstantName(attrName)%>, <%=attrType%>.class, <%=attrName%>); -}*/ - ); - } - } - } - body.append("" -/*{ visitor.end(this); -}*/ - ); - - setOperationBody(op, body.length() == 0 ? " " : body.toString()); - } - - - private void generateAssociationAccessors(ObjectModelClass result, - String name, String type) { - ObjectModelOperation op; - op = addOperation(result, - "set" + StringUtils.capitalize(name), - "void", - ObjectModelModifier.PUBLIC); - ObjectModelParameter param = addParameter(op, type, "value"); - setDocumentation(param, "La valeur de l'attribut " + name + - " à positionner."); - setOperationBody(op, "" -/*{ - <%=type%> _oldValue = this.<%=GeneratorUtil.toLowerCaseFirstLetter(name)%>; - fireOnPreWrite("<%=name%>", _oldValue, value); - this.<%=GeneratorUtil.toLowerCaseFirstLetter(name)%> = value; - fireOnPostWrite("<%=name%>", _oldValue, value); -}*/ - ); - - op = addOperation(result, - "get" + StringUtils.capitalize(name), - type, - ObjectModelModifier.PUBLIC); - setOperationBody(op, "" -/*{ - return <%=GeneratorUtil.toLowerCaseFirstLetter(name)%>; -}*/ - ); - - } - - /** - * Generate entity methods which have not a public visibility. In this case, they will not be - * generated in the EntityInterface, so they will be generated here, in the EntityAbstract - * with abstract modifier to keep consistency with the model. - * @param result ObjectModelClass result corresponding to the EntityAbstract - * @param clazz ObjectModelClass source from ObjectModel - */ - private void generateAbstractMethods(ObjectModelClass result, - ObjectModelClass clazz) { - for (ObjectModelOperation op : clazz.getOperations()) { - if (log.isDebugEnabled()) { - log.debug("clazz : " + clazz.getQualifiedName() + - " - method : " + op.getName() + - " - visibility : " + op.getVisibility()); - } - String visibility = op.getVisibility(); - ObjectModelModifier visibilityModifier = ObjectModelModifier.toValue(visibility); - if (!visibilityModifier.equals(ObjectModelModifier.PUBLIC)) { - addOperation(result, - op.getName(), - op.getReturnType(), - visibilityModifier, - ObjectModelModifier.ABSTRACT); - } - } - } - - /** - * - * @deprecated since 2.4.4, use the metohd {@link ObjectModelTransformerToJava#generateI18nBlock(ObjectModelClassifier, ObjectModelClassifier, String)} - */ - @Deprecated - private void enerateI18n(ObjectModelClass result, - String i18nPrefix, - ObjectModelClass clazz) { - - StringBuilder buffer = new StringBuilder(300); - addI18n(buffer, i18nPrefix, Introspector.decapitalize(clazz.getName())); - for (ObjectModelAttribute attr : clazz.getAttributes()) { - //TC-20100225 only treate navigable relations - if (attr.isNavigable()) { - addI18n(buffer, i18nPrefix, Introspector.decapitalize(attr.getName())); - } - } - - //FIXME : use a block extension for java - ObjectModelOperation op = addBlock(result, ObjectModelModifier.STATIC); - setOperationBody(op, buffer.toString()); - } - - /** - * - * @deprecated since 2.4.4, use the metohd {@link ObjectModelTransformerToJava#addI18n(StringBuilder, String, String)} - */ - @Deprecated - protected void addI18n(StringBuilder buffer, String i18nPrefix, - String suffix) { - buffer.append("\n org.nuiton.i18n.I18n.n_(\""); - buffer.append(i18nPrefix); - buffer.append(suffix); - buffer.append("\");"); - } -} Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityDTOTransformer.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityDTOTransformer.java 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityDTOTransformer.java 2010-11-28 20:17:13 UTC (rev 2156) @@ -53,12 +53,12 @@ public boolean isEntity(String type) { ObjectModelClassifier clazz = model.getClassifier(type); - return clazz != null && clazz.hasStereotype(TopiaGeneratorUtil.STEREOTYPE_ENTITY); + return clazz != null && TopiaGeneratorUtil.hasEntityStereotype(clazz); } @Override public void transformFromClass(ObjectModelClass clazz) { - if (!clazz.hasStereotype(TopiaGeneratorUtil.STEREOTYPE_ENTITY)) { + if (!TopiaGeneratorUtil.hasEntityStereotype(clazz)) { return; } String clazzName = clazz.getName(); @@ -133,8 +133,8 @@ setDocumentation(attr2, attr.getDocumentation()); } - if (attr.hasTagValue(TopiaGeneratorUtil.TAG_ANNOTATION)) { - String annotation = attr.getTagValue(TopiaGeneratorUtil.TAG_ANNOTATION); + String annotation = TopiaGeneratorUtil.getAnnotationTagValue(attr); + if (!StringUtils.isEmpty(annotation)) { addAnnotation(result, attr2, annotation); } } @@ -310,9 +310,9 @@ if (model.hasClass(attr.getType())) { attrEntity = model.getClass(attr.getType()); } - boolean isEntity = (attrEntity != null && attrEntity.hasStereotype(TopiaGeneratorUtil.STEREOTYPE_ENTITY)); + boolean isEntity = attrEntity != null && TopiaGeneratorUtil.hasEntityStereotype(attrEntity); ObjectModelAttribute reverse = attr.getReverseAttribute(); - if ((isEntity && (reverse == null || !reverse.isNavigable()) && !attr.hasAssociationClass()) || (!isEntity)) { + if (isEntity && (reverse == null || !reverse.isNavigable()) && !attr.hasAssociationClass() || !isEntity) { String attrName = attr.getName(); buffer.append("" /*{ append("<%=attrName%>", this.<%=attrName%>). Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityHibernateMappingGenerator.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityHibernateMappingGenerator.java 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityHibernateMappingGenerator.java 2010-11-28 20:17:13 UTC (rev 2156) @@ -45,14 +45,12 @@ import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.nuiton.eugene.java.JavaGeneratorUtil; import org.nuiton.eugene.models.object.ObjectModelGenerator; import org.nuiton.eugene.GeneratorUtil; import org.nuiton.eugene.models.object.ObjectModelAssociationClass; import org.nuiton.eugene.models.object.ObjectModelAttribute; import org.nuiton.eugene.models.object.ObjectModelClass; -import static org.nuiton.topia.generator.TopiaGeneratorUtil.PERSISTENCE_TYPE_HIBERNATE; -import static org.nuiton.topia.generator.TopiaGeneratorUtil.STEREOTYPE_ENTITY; -import static org.nuiton.topia.generator.TopiaGeneratorUtil.TAG_ACCESS; import static org.nuiton.topia.generator.TopiaGeneratorUtil.hasUnidirectionalRelationOnAbstractType; import java.io.File; @@ -74,13 +72,23 @@ public class EntityHibernateMappingGenerator extends ObjectModelGenerator { /** - * Logger for this class + * Logger. */ private static final Log log = LogFactory .getLog(EntityHibernateMappingGenerator.class); 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_LENGTH = "length"; + + public static final String HIBERNATE_ATTRIBUTE_ORDER_BY = "order-by"; + @Override public String getFilenameForClass(ObjectModelClass clazz) { String DOName = TopiaGeneratorUtil.getDOType(clazz, model); @@ -90,7 +98,8 @@ @Override public void generateFromClass(Writer output, ObjectModelClass input) throws IOException { String persistenceType = TopiaGeneratorUtil.getPersistenceType(input); - if (!input.hasStereotype(STEREOTYPE_ENTITY) && PERSISTENCE_TYPE_HIBERNATE.equals(persistenceType)) { + if (!TopiaGeneratorUtil.hasEntityStereotype(input) && + TopiaGeneratorUtil.PERSISTENCE_TYPE_HIBERNATE.equals(persistenceType)) { return; } /*{<?xml version="1.0" encoding="UTF-8"?> @@ -104,19 +113,19 @@ List<ObjectModelAttribute> noneNaturalAttributes = new ArrayList<ObjectModelAttribute>(); String clazzDOType = TopiaGeneratorUtil.getDOType(input, model); - String tableName = TopiaGeneratorUtil.getDBName(input); + String tableName = TopiaGeneratorUtil.getDbName(input); String isAbstract = BooleanUtils.toStringTrueFalse(input.isAbstract()); String clazzFQN = input.getQualifiedName(); String optionalAttributes = ""; - String schema = TopiaGeneratorUtil.getSchemaName(input, model); + 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.findTagValue(TopiaGeneratorUtil.TAG_PROXY_INTERFACE, input, model); - if (proxyTagValue == null || !proxyTagValue.equals("none")) { + String proxyTagValue = TopiaGeneratorUtil.getProxyInterfaceTagValue(input, model); + if (StringUtils.isEmpty(proxyTagValue) || !proxyTagValue.equals("none")) { optionalAttributes += "proxy=\"" + clazzFQN + "\" "; } @@ -189,7 +198,7 @@ || hasUnidirectionalRelationOnAbstractType(reverse, model) || attr.hasAssociationClass()) { if (!GeneratorUtil.isNMultiplicity(attr)) { - if (attr.getClassifier() != null && attr.getClassifier().hasStereotype(STEREOTYPE_ENTITY)) { + if (attr.getClassifier() != null && TopiaGeneratorUtil.hasEntityStereotype(attr.getClassifier())) { if (GeneratorUtil.isNMultiplicity(attr.getReverseMaxMultiplicity()) && !attr.hasAssociationClass()) { generateHibernateManyToOne(output, attr, prefix); } else { @@ -199,7 +208,7 @@ generateHibernateProperty(output, attr, prefix); } } else { - if (attr.getClassifier() != null && attr.getClassifier().hasStereotype(STEREOTYPE_ENTITY)) { + if (attr.getClassifier() != null && TopiaGeneratorUtil.hasEntityStereotype(attr.getClassifier())) { if (GeneratorUtil.isNMultiplicity(attr.getReverseMaxMultiplicity()) && !attr.hasAssociationClass()) { generateHibernateManyToMany(output, attr, prefix); } else { @@ -224,11 +233,11 @@ // / *{ <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(attr, TopiaGeneratorUtil.TAG_NOT_NULL, "not-null"); + String notNull = " " + generateFromTagValue(HIBERNATE_ATTRIBUTE_NOT_NULL, TopiaGeneratorUtil.getNotNullTagValue(attr)); String attrName = getName(attr, true); String attrType = getType(attr, true); - String lazy = generateFromTagValue(attr, TopiaGeneratorUtil.TAG_LAZY, "lazy"); - String attrColumn = TopiaGeneratorUtil.getDBName(attr); + 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" embed-xml="false" <%=notNull%>/> }*/ // } @@ -268,15 +277,15 @@ protected String getType(ObjectModelAttribute attr, boolean isAssoc) { String type = attr.getType(); - String attrType = attr.getTagValue(TopiaGeneratorUtil.TAG_TYPE); - if (TopiaGeneratorUtil.notEmpty(attrType)) { + String attrType = TopiaGeneratorUtil.getTypeTagValue(attr); + if (StringUtils.isNotEmpty(attrType)) { // tag value detected of the attribute type = attrType; } else { String modelType = model.getTagValue(type); - if (TopiaGeneratorUtil.notEmpty(modelType)) { + if (StringUtils.isNotEmpty(modelType)) { // tag value detected of the model @@ -307,23 +316,24 @@ String attrType = getType(attr); String accessField = "field"; - if (attr.hasTagValue(TAG_ACCESS)) { - accessField = attr.getTagValue(TAG_ACCESS); + String tagValue = TopiaGeneratorUtil.getAccessTagValue(attr); + if (StringUtils.isNotEmpty(tagValue)) { + accessField = tagValue; } String attrName = attr.getName(); - String declaringElementDBName = TopiaGeneratorUtil.getDBName(attr.getDeclaringElement()); + String declaringElementDBName = TopiaGeneratorUtil.getDbName(attr.getDeclaringElement()); String tableName = declaringElementDBName + "_" + attrName; if (attrType.trim().endsWith("[]")) { attrType = attrType.trim().substring(0, attrType.trim().length()-2); String optionalAttributes = ""; - String schema = TopiaGeneratorUtil.getSchemaName(attr, model); + String schema = TopiaGeneratorUtil.getDbSchemaNameTagValue(attr, model); if (schema != null) { optionalAttributes += "schema=\"" + schema + "\" "; } - if (attr.isIndexed()) { + if (JavaGeneratorUtil.hasIndexedStereotype(attr)) { String indexName = tableName + "_idx"; optionalAttributes += "index=\"" + indexName + "\" "; } @@ -336,21 +346,21 @@ }*/ } else { String optionalAttributes = ""; - if (attr.isIndexed()) { + if (JavaGeneratorUtil.hasIndexedStereotype(attr)) { String indexName = tableName + "_idx"; optionalAttributes += "index=\"" + indexName + "\""; } - if (attr.hasStereotype(TopiaGeneratorUtil.STEREOTYPE_UNIQUE)) { + 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 += " unique=\"true\""; } - optionalAttributes += generateFromTagValue(attr, TopiaGeneratorUtil.TAG_NOT_NULL, "not-null"); + optionalAttributes += generateFromTagValue(HIBERNATE_ATTRIBUTE_NOT_NULL, TopiaGeneratorUtil.getNotNullTagValue(attr)); /*{<%=prefix%> <property name="<%=attrName%>" type="<%=attrType%>" access="<%=accessField%>" }*/ optionalAttributes = optionalAttributes.trim(); String[] columnNames = columnNamesMap.get(attrType); if (columnNames == null || columnNames.length == 0) { - optionalAttributes += generateFromTagValue(attr, TopiaGeneratorUtil.TAG_LENGTH, "length"); - String attrColumn = TopiaGeneratorUtil.getDBName(attr); + optionalAttributes += generateFromTagValue(HIBERNATE_ATTRIBUTE_LENGTH, TopiaGeneratorUtil.getLengthTagValue(attr)); + String attrColumn = TopiaGeneratorUtil.getDbName(attr); optionalAttributes = optionalAttributes.trim(); if (!optionalAttributes.isEmpty()) { optionalAttributes = " " + optionalAttributes; @@ -397,23 +407,23 @@ } protected void generateHibernateOneToMany(Writer output, ObjectModelAttribute attr, String prefix) throws IOException { - boolean needsIndex = attr.isIndexed(); + boolean needsIndex = JavaGeneratorUtil.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(attr, TopiaGeneratorUtil.TAG_ORDER_BY, "order-by"); + 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(attr, TopiaGeneratorUtil.TAG_LAZY, "lazy", "true"); + String lazy = generateFromTagValue(HIBERNATE_ATTRIBUTE_LAZY, TopiaGeneratorUtil.getLazyTagValue(attr), "true"); - String fetch = generateFromTagValue(attr, TopiaGeneratorUtil.TAG_FETCH, "fetch"); + String fetch = generateFromTagValue(HIBERNATE_ATTRIBUTE_FETCH, TopiaGeneratorUtil.getFetchTagValue(attr)); String collType = TopiaGeneratorUtil.getNMultiplicityHibernateType(attr); String inverse = ""; @@ -439,36 +449,43 @@ } } - private String generateFromTagValue(ObjectModelAttribute attr, - String tagName, String attributeName) { - return generateFromTagValue(attr, tagName, attributeName, null); + 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(ObjectModelAttribute attr, - String tagName, String attributeName, String defaultValue) { + private String generateFromTagValue(String attributeName, String tagValue, String defaultValue) { String result = ""; - if (attr.hasTagValue(tagName) || defaultValue != null) { - result+= attributeName + "=\""; - if (attr.hasTagValue(tagName)) { - result += attr.getTagValue(tagName); - } else { - result += defaultValue; - } - 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 = attr.isIndexed(); + boolean needsIndex = JavaGeneratorUtil.hasIndexedStereotype(attr); String attrName = getName(attr); String attrType = getType(attr); String collType = TopiaGeneratorUtil.getNMultiplicityHibernateType(attr); - String lazy = generateFromTagValue(attr, TopiaGeneratorUtil.TAG_LAZY, "lazy"); - String attrColumn = TopiaGeneratorUtil.getDBName(attr); + String lazy = generateFromTagValue(HIBERNATE_ATTRIBUTE_LAZY, TopiaGeneratorUtil.getLazyTagValue(attr)); + String attrColumn = TopiaGeneratorUtil.getDbName(attr); /*{<%=prefix%> <<%=collType%> name="<%=attrName%>" <%=lazy%>node="<%=attrName%>" embed-xml="true"> <%=prefix%> <key column="OWNER"/> @@ -489,7 +506,7 @@ 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); + String attrColumn = TopiaGeneratorUtil.getDbName(attr); /*{<%=prefix%> <many-to-one name="<%=attrName%>" class="<%=attrType%>" column="<%=attrColumn%>" }*/ if (attr.isComposite() || attr.hasAssociationClass()) { /*{cascade="delete" }*/ @@ -501,9 +518,9 @@ /*{access="field" }*/ } // vérifier si le tag lazy est defini par defaut dans le fichier de proprietes - String lazy = generateFromTagValue(attr, TopiaGeneratorUtil.TAG_LAZY, "lazy"); + String lazy = generateFromTagValue(HIBERNATE_ATTRIBUTE_LAZY, TopiaGeneratorUtil.getLazyTagValue(attr)); /*{<%=lazy%>}*/ - String notNull = " " + generateFromTagValue(attr, TopiaGeneratorUtil.TAG_NOT_NULL, "not-null"); + String notNull = " " + generateFromTagValue(HIBERNATE_ATTRIBUTE_NOT_NULL, TopiaGeneratorUtil.getNotNullTagValue(attr)); /*{<%=notNull%>}*/ if (isUnique) { /*{unique="true" }*/ @@ -526,9 +543,9 @@ // 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. - if (attr.hasTagValue(TopiaGeneratorUtil.TAG_INVERSE)) { - isInverse &= Boolean.parseBoolean( - attr.getTagValue(TopiaGeneratorUtil.TAG_INVERSE)); + 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" @@ -536,7 +553,7 @@ isInverse &= GeneratorUtil.isFirstAttribute(attr); } - boolean needsIndex = attr.isIndexed(); + boolean needsIndex = JavaGeneratorUtil.hasIndexedStereotype(attr); String cascade = ""; if (attr.isComposite() || attr.hasAssociationClass()) { cascade = " cascade=\"delete,delete-orphan\""; @@ -544,16 +561,16 @@ String attrType = getType(attr); String attrName = getName(attr); - String attrColumn = TopiaGeneratorUtil.getDBName(attr); - String lazy = generateFromTagValue(attr, TopiaGeneratorUtil.TAG_LAZY, "lazy", "true"); - String orderBy = generateFromTagValue(attr, TopiaGeneratorUtil.TAG_ORDER_BY, "order-by"); + 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); + String reverseAttrDBName = TopiaGeneratorUtil.getReverseDbName(attr); /*{<%=prefix%> <<%=collType%> name="<%=attrName%>" table="<%=tableName%>" <%=inverse%><%=lazy%><%=cascade%> node="<%=attrName%>" embed-xml="true"> <%=prefix%> <key column="<%=reverseAttrDBName%>"/> Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityImplTransformer.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityImplTransformer.java 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityImplTransformer.java 2010-11-28 20:17:13 UTC (rev 2156) @@ -1,143 +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.java.ObjectModelTransformerToJava; -import org.nuiton.eugene.models.object.ObjectModelClass; -import org.nuiton.eugene.models.object.ObjectModelOperation; - -import java.util.Collection; - -/** - * 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.EntityImplTransformer" - * @deprecated since 2.4 : all transformations needed for Entity is in {@link EntityTransformer} included in {@link TopiaMetaTransformer} - */ -@Deprecated -public class EntityImplTransformer extends ObjectModelTransformerToJava { - - /** - * Logger - */ - private static final Log log = LogFactory.getLog(EntityImplTransformer.class); - - @Override - public void transformFromClass(ObjectModelClass clazz) { - if (!clazz.hasStereotype(TopiaGeneratorUtil.STEREOTYPE_ENTITY)) { - return; - } - // On ne génère pas le impl si l'entité a des opérations qui ne sont - // pas seulement pour le DAO - if (clazz.getOperations().size() > 0 && !hasOnlyDAOOperations(clazz)) { - return; - } - //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 : clazz.getAllOtherOperations(false)) { - if (otherOp.isAbstract()) { - return; - } - } - String clazzName = clazz.getName(); - String clazzFQN = clazz.getQualifiedName(); - ObjectModelClass result; - if (isAbstract(clazz)) { - result = createAbstractClass(clazzName + "Impl", - clazz.getPackageName()); - } else { - result = createClass(clazzName + "Impl", clazz.getPackageName()); - } - setDocumentation(result, "Implantation des operations pour l'entité " + - clazzName + "."); - setSuperClass(result, clazzFQN + "Abstract"); - //TC-20100413 - // Evolution #505: Do not generate redundant interface declaration -// addInterface(result, Serializable.class); -// addInterface(result, clazzFQN); - - } - - 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; - } - - /** - * Detect if the clazz has only operations for DAO implementation. - * These operations are identified with the stereotype <<dao>>. - * - * @param clazz The ObjectModelClass with all operations. - * @return true if there is only dao operations, false if there is no operations or some without - * dao stereotype. - */ - public static boolean hasOnlyDAOOperations(ObjectModelClass clazz) { - boolean res = true; - Collection<ObjectModelOperation> operations = clazz.getOperations(); - if (operations.size() == 0) { - res = false; - } - for (ObjectModelOperation op : operations) { - res &= op.hasStereotype(TopiaGeneratorUtil.STEREOTYPE_DAO); - } - return res; - } -} Deleted: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityInterfaceTransformer.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityInterfaceTransformer.java 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityInterfaceTransformer.java 2010-11-28 20:17:13 UTC (rev 2156) @@ -1,622 +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.lang.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.SearchFields; -import org.nuiton.topia.persistence.TopiaEntity; - -import java.util.*; - - -/*{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.EntityInterfaceTransformer" - * @deprecated since 2.4 : all transformations needed for Entity is in {@link EntityTransformer} included in {@link TopiaMetaTransformer} - */ -@Deprecated -public class EntityInterfaceTransformer extends ObjectModelTransformerToJava { - - /** - * Logger - */ - private static final Log log = LogFactory.getLog(EntityInterfaceTransformer.class); - - @Override - public void transformFromClass(ObjectModelClass clazz) { - if (!clazz.hasStereotype(TopiaGeneratorUtil.STEREOTYPE_ENTITY)) { - return; - } - - String clazzName = clazz.getName(); - - ObjectModelInterface result; - - if (log.isDebugEnabled()) { - log.debug("for entity : "+clazz.getQualifiedName()); - } - - result = createInterface(clazzName, clazz.getPackageName()); - - addImport(result, SearchFields.class); - addImport(result, TopiaEntity.class); - if (TopiaGeneratorUtil.hasDocumentation(clazz)) { - setDocumentation(result,clazz.getDocumentation()); - } - - 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); - - generateSearchFields(result, clazz); - - // super classes - - for (ObjectModelClassifier parent : clazz.getInterfaces()) { - addInterface(result,parent.getQualifiedName()); - } - - for (ObjectModelClassifier parent : clazz.getSuperclasses()) { - if (parent.hasStereotype(TopiaGeneratorUtil.STEREOTYPE_ENTITY)) { - addInterface(result,parent.getQualifiedName()); - break; - } - } - - addInterface(result, TopiaEntity.class); - - generateStaticColumnNames(result, clazz); - - for (ObjectModelAttribute attr : clazz.getAttributes()) { - ObjectModelAttribute reverse = attr.getReverseAttribute(); - if (!attr.isNavigable() && - !TopiaGeneratorUtil.hasUnidirectionalRelationOnAbstractType( - reverse, model)) { - continue; - } - - if (attr.hasAssociationClass()) { - - addAssociationAttribute(result, attr); - - } else { - - addNoneAssociationAttribute(result, attr); - } - } - - //Méthodes d'accès aux attributs d'une classe d'associations - generateAssociationAttributes(result, clazz); - - generateInterfaceOperations(result, clazz); - } - - protected void generateAssociationAttributes(ObjectModelInterface result, - ObjectModelClass clazz) { - if (clazz instanceof ObjectModelAssociationClass) { - ObjectModelAssociationClass assoc = - (ObjectModelAssociationClass) clazz; - for (ObjectModelAttribute attr : - assoc.getParticipantsAttributes()) { - if (attr != null) { - String type = attr.getType(); - String name = attr.getName(); - generateAssociationAccessors(result, name, type); - if (attr.getReverseAttribute() == null) { - type = ((ObjectModelClassifier) - attr.getDeclaringElement()).getQualifiedName(); - name = attr.getDeclaringElement().getName(); - generateAssociationAccessors(result, name, type); - } - } - } - } - } - - - protected void addNoneAssociationAttribute(ObjectModelInterface result, - ObjectModelAttribute attr) { - String attrName = attr.getName(); - String attrType = attr.getType(); - ObjectModelOperation op; - ObjectModelParameter attr2; - - if (!GeneratorUtil.isNMultiplicity(attr)) { - - // setXXX - - op = addOperation(result, - "set" + StringUtils.capitalize(attrName), - "void", - ObjectModelModifier.PACKAGE); - if (TopiaGeneratorUtil.hasDocumentation(attr)) { - setDocumentation(op, attr.getDocumentation()); - } - attr2 = addParameter(op, attrType, - GeneratorUtil.toLowerCaseFirstLetter(attrName)); - setDocumentation(attr2, "La valeur de l'attribut " + attrName - + " à positionner."); - - // getXXX - - op = addOperation(result, - "get" + StringUtils.capitalize(attrName), - attrType, - ObjectModelModifier.PACKAGE); - if (TopiaGeneratorUtil.hasDocumentation(attr)) { - setDocumentation(op, attr.getDocumentation()); - } - } else { - String collectionInterface = - TopiaGeneratorUtil.getNMultiplicityInterfaceType(attr); - - // addXXX - - op = addOperation(result, - "add" + StringUtils.capitalize(attrName), - "void", - ObjectModelModifier.PACKAGE); - if (TopiaGeneratorUtil.hasDocumentation(attr)) { - setDocumentation(op, attr.getDocumentation()); - } - attr2 = addParameter(op, attrType, - GeneratorUtil.toLowerCaseFirstLetter(attrName)); - setDocumentation(attr2, - "L'instance de " + attrName + " à ajouter"); - - // addAllXXX - - op = addOperation(result, - "addAll" + StringUtils.capitalize(attrName), - "void", - ObjectModelModifier.PACKAGE); - if (TopiaGeneratorUtil.hasDocumentation(attr)) { - setDocumentation(op, attr.getDocumentation()); - } - attr2 = addParameter(op, - collectionInterface + "<" + attrType + ">", - GeneratorUtil.toLowerCaseFirstLetter(attrName)); - setDocumentation(attr2, - "Les instances de " + attrName + " à ajouter"); - - // setXXX - - op = addOperation(result, - "set" + StringUtils.capitalize(attrName), - "void", - ObjectModelModifier.PACKAGE); - if (TopiaGeneratorUtil.hasDocumentation(attr)) { - setDocumentation(op, attr.getDocumentation()); - } - attr2 = addParameter(op, - collectionInterface + "<" + attrType + ">", - GeneratorUtil.toLowerCaseFirstLetter(attrName)); - setDocumentation(attr2, - "La Collection de " + attrName + " à ajouter"); - - // removeXXX - - op = addOperation(result, - "remove" + StringUtils.capitalize(attrName), - "void", - ObjectModelModifier.PACKAGE); - if (TopiaGeneratorUtil.hasDocumentation(attr)) { - setDocumentation(op, attr.getDocumentation()); - } - attr2 = addParameter(op, - attrType, - GeneratorUtil.toLowerCaseFirstLetter(attrName)); - setDocumentation(attr2, - "L'instance de " + attrName + " à retirer"); - - // clearXXX - - op = addOperation(result, - "clear" + StringUtils.capitalize(attrName), - "void", - ObjectModelModifier.PACKAGE); - if (TopiaGeneratorUtil.hasDocumentation(attr)) { - setDocumentation(op, attr.getDocumentation()); - } - setDocumentation(attr2, "Vide la Collection de " + attrName); - - // getXXX - - op = addOperation(result, - "get" + StringUtils.capitalize(attrName), - collectionInterface + "<" + attrType + ">", - ObjectModelModifier.PACKAGE); - if (TopiaGeneratorUtil.hasDocumentation(attr)) { - setDocumentation(op, "Retourne la collection."); - } - - if (!TopiaGeneratorUtil.isPrimitiveType(attr) && - !TopiaGeneratorUtil.isDateType(attr)) { - - // getXXXByTopiaId - - op = addOperation(result, - "get" + StringUtils.capitalize(attrName) + "ByTopiaId", - attrType, - ObjectModelModifier.PACKAGE); - setDocumentation(op, "Recupère l'attribut " + attrName + " à partir de son topiaId"); - attr2 = addParameter(op, String.class, "topiaId"); - setDocumentation(attr2, "le topia id de l'entité recherchée"); - } - - // sizeXXX - - op = addOperation(result, - "size" + StringUtils.capitalize(attrName), - int.class, - ObjectModelModifier.PACKAGE); - setDocumentation(op, "Retourne le nombre d'éléments de la collection " + attrName); - - // isXXXEmpty - - op = addOperation(result, - "is" + StringUtils.capitalize(attrName) + "Empty", - boolean.class, - ObjectModelModifier.PACKAGE); - setDocumentation(op, "Retourne {@code true} si la collection " + attrName + " est vide."); - } - } - - protected void addAssociationAttribute(ObjectModelInterface result, ObjectModelAttribute attr) { - String attrName = attr.getName(); - String attrType = attr.getType(); - String assocAttrName = GeneratorUtil.getAssocAttrName(attr); - String assocClassFQN = attr.getAssociationClass().getQualifiedName(); - String assocClassName = attr.getAssociationClass().getName(); - - ObjectModelOperation op; - ObjectModelParameter attr2; - - if (!GeneratorUtil.isNMultiplicity(attr)) { - - // setXXX - - op = addOperation(result, - "set" + StringUtils.capitalize(assocAttrName), - "void", - ObjectModelModifier.PACKAGE); - attr2 = addParameter(op, assocClassFQN, GeneratorUtil.toLowerCaseFirstLetter(assocClassName)); - setDocumentation(attr2, "La valeur de l'attribut " + assocClassName + " à positionner"); - - // getXXX - - addOperation(result, - "get" + StringUtils.capitalize(assocAttrName), - assocClassFQN, - ObjectModelModifier.PACKAGE); - - } else { - String collectionInterface = TopiaGeneratorUtil.getNMultiplicityInterfaceType(attr); - - // addXXX - - op = addOperation(result, - "add" + StringUtils.capitalize(assocAttrName), - "void", - ObjectModelModifier.PACKAGE); - attr2 = addParameter(op, assocClassFQN, GeneratorUtil.toLowerCaseFirstLetter(assocClassName)); - setDocumentation(attr2, "L'instance de " + assocClassName + " à ajouter"); - - // addAllXXX - - op = addOperation(result, - "addAll" + StringUtils.capitalize(assocAttrName), - "void", - ObjectModelModifier.PACKAGE); - attr2 = addParameter(op, collectionInterface + "<" + assocClassFQN + ">", GeneratorUtil.toLowerCaseFirstLetter(assocClassName)); - setDocumentation(attr2, "Les instances de " + assocClassName + " à ajouter"); - - // setXXX - - op = addOperation(result, - "set" + StringUtils.capitalize(assocAttrName), - "void", - ObjectModelModifier.PACKAGE); - attr2 = addParameter(op, collectionInterface + "<" + assocClassFQN + ">", GeneratorUtil.toLowerCaseFirstLetter(assocClassName)); - setDocumentation(attr2, "La Collection de " + assocClassName + " à ajouter"); - - // removeXXX - - op = addOperation(result, - "remove" + StringUtils.capitalize(assocAttrName), - "void", - ObjectModelModifier.PACKAGE); - attr2 = addParameter(op, assocClassFQN, GeneratorUtil.toLowerCaseFirstLetter(assocClassName)); - setDocumentation(attr2, "L'instance de " + assocClassName + " à retirer"); - - // clearXXX - - op = addOperation(result, - "clear" + StringUtils.capitalize(assocAttrName), - "void", - ObjectModelModifier.PACKAGE); - setDocumentation(op, "Vide la Collection de " + assocClassName + " ."); - - // getXXX - - addOperation(result, - "get" + StringUtils.capitalize(assocAttrName), - collectionInterface + "<" + assocClassFQN + ">", - ObjectModelModifier.PACKAGE); - - if (!TopiaGeneratorUtil.isPrimitiveType(attr) && !TopiaGeneratorUtil.isDateType(attr)) { - - // getXXXByTopiaId - - op = addOperation(result, - "get" + StringUtils.capitalize(assocAttrName) + "ByTopiaId", - assocClassFQN, - ObjectModelModifier.PACKAGE); - setDocumentation(op, "Recupère l'attribut " + attrName + " à partir de son topiaId"); - attr2 = addParameter(op, String.class, "topiaId"); - setDocumentation(attr2, "le topia id de l'entité recherchée"); - } - - // getXXX - - op = addOperation(result, - "get" + StringUtils.capitalize(assocAttrName), - assocClassFQN); - addParameter(op, attrType, "value"); - - - // sizeXXX - - addOperation(result, - "size" + StringUtils.capitalize(assocAttrName), - int.class, - ObjectModelModifier.PACKAGE); - - - // isXXXEmpty - - addOperation(result, - "is" + StringUtils.capitalize(assocAttrName) + "Empty", - boolean.class, - ObjectModelModifier.PACKAGE); - } - } - - private void generateInterfaceOperations(ObjectModelInterface output, ObjectModelClassifier classifier) { - - for (ObjectModelOperation op : classifier.getOperations()) { - - String visibility = op.getVisibility(); - if (op.hasStereotype(TopiaGeneratorUtil.STEREOTYPE_DAO) || - !visibility.equals(ObjectModelModifier.PUBLIC.toString())) { - // Pas de génération des signatures de méthodes pour celles à intégrer au DAO de l'entité - continue; - } - - String opName = op.getName(); - String opType = op.getReturnType(); - - ObjectModelOperation op2 = addOperation(output, opName, opType, ObjectModelModifier.PACKAGE); - if (TopiaGeneratorUtil.hasDocumentation(op)) { - setDocumentation(op2, op.getDocumentation()); - } - - for (ObjectModelParameter param : op.getParameters()) { - String paramName = param.getName(); - String paramType = param.getType(); - ObjectModelParameter param2 = addParameter(op2, paramType, paramName); - if (TopiaGeneratorUtil.hasDocumentation(param)) { - setDocumentation(param2, param.getDocumentation()); - } - } - for (String exception : op.getExceptions()) { - addException(op2, exception); - } - } - } - - private void generateAssociationAccessors(ObjectModelInterface output, String attrName, String attrType) { - - ObjectModelOperation op; - ObjectModelParameter param; - - op = addOperation(output, - "set" + StringUtils.capitalize(attrName), - "void", - ObjectModelModifier.PACKAGE); - param = addParameter(op, attrType, "value"); - setDocumentation(param, "La valeur de l'attribut " + attrName + " à positionner."); - - op = addOperation(output, - "get" + StringUtils.capitalize(attrName), - attrType, - ObjectModelModifier.PACKAGE); - setDocumentation(op, "Retourne la valeur de l'attribut " + attrName + "."); - } - -// private static final String doubleQuote = "\""; - private static final String comma = ", "; - - private String getStringRepresentation(ObjectModelInterface output,List<String> strings) { - StringBuilder result = new StringBuilder(); - - Iterator<String> it = strings.iterator(); - if (it.hasNext()) { - result.append(output.getName()); - result.append('.'); - result.append(getConstantName(it.next())); -// result.append(doubleQuote).append(it.next()).append(doubleQuote); - } - while (it.hasNext()) { - result.append(comma); - result.append(output.getName()); - result.append('.'); - result.append(getConstantName(it.next())); -// result.append(comma).append(doubleQuote).append(it.next()).append(doubleQuote); - } - return result.toString(); - } - - private void generateSearchFields(ObjectModelInterface result, ObjectModelClass clazz) { - List<String> txtFields = new ArrayList<String>(); - List<String> numFields = new ArrayList<String>(); - List<String> boolFields = new ArrayList<String>(); - List<String> dateFields = new ArrayList<String>(); - List<ObjectModelAttribute> allAttrs = new ArrayList<ObjectModelAttribute>(); - allAttrs.addAll(clazz.getAttributes()); - allAttrs.addAll(clazz.getAllOtherAttributes()); - boolean needAnnotation = false; - for (ObjectModelAttribute attr : allAttrs) { - String name = GeneratorUtil.toLowerCaseFirstLetter(attr.getName()); - if (TopiaGeneratorUtil.isTextType(attr)) { - txtFields.add(name); - needAnnotation = true; - } else if (TopiaGeneratorUtil.isNumericType(attr)) { - numFields.add(name); - needAnnotation = true; - } else if (TopiaGeneratorUtil.isBooleanType(attr)) { - boolFields.add(name); - needAnnotation = true; - } else if (TopiaGeneratorUtil.isDateType(attr)) { - dateFields.add(name); - needAnnotation = true; - } - } - - // generate @SearchFields annotation - - StringBuilder annotationCode = new StringBuilder(); - annotationCode.append("" -/*{SearchFields (}*/ - ); - if (needAnnotation) { - StringBuilder buffer = new StringBuilder(); - if (!txtFields.isEmpty()) { - buffer.append("\n txtFields={"); - buffer.append(getStringRepresentation(result,txtFields)); - buffer.append("}"); - if (!numFields.isEmpty() || !boolFields.isEmpty() || - !dateFields.isEmpty()) { - buffer.append(","); - } - } - if (!numFields.isEmpty()) { - buffer.append("\n numFields={"); - buffer.append(getStringRepresentation(result,numFields)); - buffer.append("}"); - if (!boolFields.isEmpty() || !dateFields.isEmpty()) { - buffer.append(","); - } - } - if (!boolFields.isEmpty()) { - buffer.append("\n boolFields={"); - buffer.append(getStringRepresentation(result,boolFields)); - buffer.append("}"); - if (!dateFields.isEmpty()) { - buffer.append(","); - } - } - if (!dateFields.isEmpty()) { - buffer.append("\n dateFields={"); - buffer.append(getStringRepresentation(result,dateFields)); - buffer.append("}"); - } - annotationCode.append("" -/*{<%=buffer.toString()%> -}*/ - ); - } - annotationCode.append("" -/*{)}*/ - ); - addAnnotation(result, result, annotationCode.toString()); - } - - private void generateStaticColumnNames(ObjectModelInterface result, - ObjectModelClass clazz) { - for (ObjectModelAttribute attr : clazz.getAttributes()) { - ObjectModelAttribute reverse = attr.getReverseAttribute(); - if (!(attr.isNavigable() || - TopiaGeneratorUtil.hasUnidirectionalRelationOnAbstractType( - reverse, model) - || attr.hasAssociationClass())) { - continue; - } - String attrName; - if (!attr.hasAssociationClass()) { - attrName = attr.getName(); - } else { - String assocAttrName = GeneratorUtil.getAssocAttrName(attr); - attrName = GeneratorUtil.toLowerCaseFirstLetter(assocAttrName); - } - String attrColName = getConstantName(attrName); -// String attrColName = TopiaGeneratorUtil.convertVariableNameToConstantName(attrName); - addAttribute(result, - attrColName, - String.class, - "\"" + attrName + "\"", - ObjectModelModifier.PACKAGE); - } - - //Déclaration des noms des champs 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 attrColName = getConstantName(attrName); -// String attrColName = TopiaGeneratorUtil.convertVariableNameToConstantName(attrName); - addAttribute(result, - attrColName, - String.class, - "\"" + attrName + "\"", - ObjectModelModifier.PACKAGE); - } - } - } - } -} Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityTransformer.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityTransformer.java 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/EntityTransformer.java 2010-11-28 20:17:13 UTC (rev 2156) @@ -52,9 +52,6 @@ import java.util.List; import java.util.Set; -import static org.nuiton.topia.generator.TopiaGeneratorUtil.STEREOTYPE_ENTITY; -import static org.nuiton.topia.generator.TopiaGeneratorUtil.TAG_ANNOTATION; -import static org.nuiton.topia.generator.TopiaGeneratorUtil.TAG_DB_NAME; import static org.nuiton.topia.generator.TopiaGeneratorUtil.hasUnidirectionalRelationOnAbstractType; @@ -105,7 +102,7 @@ @Override public void transformFromClass(ObjectModelClass input) { - if (!input.hasStereotype(STEREOTYPE_ENTITY)) { + if (!TopiaGeneratorUtil.hasEntityStereotype(input)) { // not an entity, skip class. return; @@ -134,7 +131,7 @@ createEntityAbstractClass(input); // Generate i18n block - String i18nPrefix = JavaGeneratorUtil.getI18nPrefix(input, model); + String i18nPrefix = JavaGeneratorUtil.getI18nPrefixTagValue(input, model); if (!StringUtils.isEmpty(i18nPrefix)) { generateI18nBlock(input, outputAbstract, i18nPrefix); } @@ -198,7 +195,7 @@ // Extends from inheritance boolean needTopiaEntity = true; for (ObjectModelClassifier parent : input.getSuperclasses()) { - if (parent.hasStereotype(STEREOTYPE_ENTITY)) { + if (TopiaGeneratorUtil.hasEntityStereotype(parent)) { addInterface(outputInterface, parent.getQualifiedName()); needTopiaEntity = false; break; @@ -222,7 +219,7 @@ doc.append(StringUtils.capitalize(outputInterface.getName())); doc.append("}\n"); - String dbName = input.getTagValue(TAG_DB_NAME); + String dbName = TopiaGeneratorUtil.getDbName(input); if (dbName != null) { doc.append("<p>Nom de l'entité en BD : "); doc.append(dbName); @@ -240,7 +237,7 @@ //Si une des classes parentes définies des méthodes abstraites, son // impl ne sera pas créé boolean abstractParent = TopiaGeneratorUtil.shouldBeAbstract(parent); - if (parent.hasStereotype(STEREOTYPE_ENTITY)) { + if (TopiaGeneratorUtil.hasEntityStereotype(parent)) { if (abstractParent) { extendClass += "Abstract"; } else { @@ -347,7 +344,7 @@ // 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 (operation.hasStereotype(TopiaGeneratorUtil.STEREOTYPE_DAO)) { + if (TopiaGeneratorUtil.hasDaoStereotype(operation)) { return; // Generate entity methods which have not a public visibility. @@ -451,15 +448,16 @@ String attrDocumentation = attribute.getDocumentation(); buffer.append(attrDocumentation).append('\n'); } - if (attribute.hasTagValue(TAG_DB_NAME)) { - String dbName = attribute.getTagValue(TAG_DB_NAME); + + 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 - if (attribute.hasTagValue(TAG_ANNOTATION)) { - String annotation = attribute.getTagValue(TAG_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); @@ -1177,7 +1175,7 @@ } boolean isEntity = attrEntity != null && - attrEntity.hasStereotype(STEREOTYPE_ENTITY); + TopiaGeneratorUtil.hasEntityStereotype(attrEntity); ObjectModelAttribute reverse = attr.getReverseAttribute(); if (isEntity && (reverse == null || !reverse.isNavigable()) @@ -1221,8 +1219,7 @@ for (ObjectModelAttribute attr : input.getAttributes()) { if (attr.referenceClassifier() && - attr.getClassifier().hasStereotype( - STEREOTYPE_ENTITY)) { + TopiaGeneratorUtil.hasEntityStereotype(attr.getClassifier())) { if (attr.isComposite()) { String attrName = attr.getName(); @@ -1327,7 +1324,7 @@ for (ObjectModelAttribute attr : input.getAttributes()) { if (attr.referenceClassifier() && - attr.getClassifier().hasStereotype(STEREOTYPE_ENTITY) && + TopiaGeneratorUtil.hasEntityStereotype(attr.getClassifier()) && attr.isAggregate()) { String attrName = attr.getName(); Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/QueryHelperTransformer.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/QueryHelperTransformer.java 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/QueryHelperTransformer.java 2010-11-28 20:17:13 UTC (rev 2156) @@ -87,7 +87,7 @@ addImport(helperClass, TopiaQuery.class); addImport(helperClass, TopiaEntity.class); - String exception = model.getTagValue(TopiaGeneratorUtil.TAG_EXCEPTION_CLASS); + String exception = TopiaGeneratorUtil.getExceptionClassTagValue(model); if (exception != null) { addImport(helperClass, exception); mainException = TopiaGeneratorUtil.getSimpleName(exception); @@ -301,7 +301,7 @@ @Override public void transformFromClass(ObjectModelClass clazz) { - if (!TopiaGeneratorUtil.hasStereotype(clazz, TopiaGeneratorUtil.STEREOTYPE_ENTITY)) { + if (!TopiaGeneratorUtil.hasEntityStereotype(clazz)) { return; } Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/ServiceTransformer.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/ServiceTransformer.java 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/ServiceTransformer.java 2010-11-28 20:17:13 UTC (rev 2156) @@ -37,7 +37,6 @@ 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.ObjectModelElement; import org.nuiton.eugene.models.object.ObjectModelInterface; import org.nuiton.eugene.models.object.ObjectModelModifier; import org.nuiton.eugene.models.object.ObjectModelOperation; @@ -185,7 +184,6 @@ * @since 2.3.1 * @plexus.component role="org.nuiton.eugene.Template" role-hint="org.nuiton.topia.generator.ServiceTransformer" */ -//TODO : find a good way to change log level // TODO : may be refactor to integrate JTA or webservice or may be not in this transformer. public class ServiceTransformer extends ObjectModelTransformerToJava { @@ -222,14 +220,14 @@ @Override public void transformFromModel(ObjectModel model) { exceptionName = - model.getTagValue(TopiaGeneratorUtil.TAG_EXCEPTION_CLASS); + TopiaGeneratorUtil.getExceptionClassTagValue(model); modelName = model.getName(); noLog = isNoLog(null, model); } @Override public void transformFromInterface(ObjectModelInterface input) { - if (!input.hasStereotype(TopiaGeneratorUtil.STEREOTYPE_SERVICE)) { + if (!TopiaGeneratorUtil.hasServiceStereotype(input)) { return; } @@ -296,9 +294,7 @@ addException(operation, TopiaException.class); } - protected void createCommitTransactionMethod(ObjectModelInterface source, - ObjectModelInterface serviceContract, - ObjectModelClass serviceAbstract) { + protected void createCommitTransactionMethod(ObjectModelClass serviceAbstract) { ObjectModelOperation operation = addOperation(serviceAbstract, OP_NAME_COMMIT_TRANSACTION, @@ -417,9 +413,7 @@ serviceContract, serviceAbstract); - createCommitTransactionMethod(source, - serviceContract, - serviceAbstract); + createCommitTransactionMethod(serviceAbstract); createCloseTransactionMethod(source, serviceContract, @@ -479,7 +473,8 @@ * @param needTransaction flag to know if service globally use transaction * @return the abstract operation created * @see #isErrorArgsNeeded(ObjectModelOperation) - * @see #isTransactionNeeded(ObjectModelElement) + * @see #isTransactionNeeded(ObjectModelOperation) + * @see #isTransactionNeeded(ObjectModelInterface) */ protected ObjectModelOperation createOperationExecuteAbstract( ObjectModelClass serviceAbstract, @@ -529,7 +524,7 @@ * @param needTransaction flag to know if service globally use transaction * @param noLog a flag to not add any log inside method * @see #isErrorArgsNeeded(ObjectModelOperation) - * @see #isTransactionNeeded(ObjectModelElement) + * @see #isTransactionNeeded(ObjectModelInterface) */ protected void createOperationImplementation( ObjectModelClass serviceAbstract, @@ -732,17 +727,32 @@ * @param op where the tagvalue is set * @return {@code true} if transaction is needed */ - protected boolean isTransactionNeeded(ObjectModelElement op) { + protected boolean isTransactionNeeded(ObjectModelInterface op) { boolean needTransaction = true; - String transactionTag = - op.getTagValue(TopiaGeneratorUtil.TAG_TRANSACTION); + String transactionTag = TopiaGeneratorUtil.getTransactionTagValue(op); if (transactionTag != null) { needTransaction = Boolean.parseBoolean(transactionTag); } - if (isVerbose()) { - log.info("transaction needed for op [" + op.getName() + "] : " + needTransaction); + return needTransaction; + } + + /** + * boolean to specify if the method need a transaction or not. + * Default set to true but can be override using a tagvalue "transaction" + * on the method from model. + * + * @param op where the tagvalue is set + * @return {@code true} if transaction is needed + */ + protected boolean isTransactionNeeded(ObjectModelOperation op) { + boolean needTransaction = true; + + String transactionTag = TopiaGeneratorUtil.getTransactionTagValue(op); + + if (transactionTag != null) { + needTransaction = Boolean.parseBoolean(transactionTag); } return needTransaction; } @@ -750,17 +760,17 @@ /** * boolean to specify if inside the method body we should add log informations. * - * @param op model element where the tagvalue is set + * @param anInterface model element where the tagvalue is set * @param model model where to tagvalue can be also set * @return {@code true} if no log will be generated insde body's method - * @see TopiaGeneratorUtil#TAG_NO_LOG_IN_SERVICE + * @see TopiaTagValues#TAG_NO_LOG_IN_SERVICE */ - protected boolean isNoLog(ObjectModelElement op, ObjectModel model) { + protected boolean isNoLog(ObjectModelInterface anInterface, + ObjectModel model) { boolean noLog = false; - String tagValue = GeneratorUtil.findTagValue( - TopiaGeneratorUtil.TAG_NO_LOG_IN_SERVICE, - op, + String tagValue = TopiaGeneratorUtil.getNoLogInServiceTagValue( + anInterface, model ); @@ -776,14 +786,13 @@ * @param op model element where the tagvalue is set * @param model model where to tagvalue can be also set * @return {@code true} if a commit must be generated after the executeXXX invocation - * @see TopiaGeneratorUtil#TAG_DO_COMMIT + * @see TopiaTagValues#TAG_DO_COMMIT * @since 2.4.4 */ - protected boolean isCommit(ObjectModelElement op, ObjectModel model) { + protected boolean isCommit(ObjectModelOperation op, ObjectModel model) { boolean needCommit = false; - String tagValue = GeneratorUtil.findTagValue( - TopiaGeneratorUtil.TAG_DO_COMMIT, + String tagValue = TopiaGeneratorUtil.getDoCommitTagValue( op, model ); @@ -808,8 +817,7 @@ // boolean needErrorArgs = false; - String errorArgsTag = - op.getTagValue(TopiaGeneratorUtil.TAG_ERROR_ARGS); + String errorArgsTag = TopiaGeneratorUtil.getErrorArgsTagValue(op); if (errorArgsTag != null) { needErrorArgs = Boolean.parseBoolean(errorArgsTag); Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaGeneratorUtil.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaGeneratorUtil.java 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaGeneratorUtil.java 2010-11-28 20:17:13 UTC (rev 2156) @@ -25,6 +25,7 @@ package org.nuiton.topia.generator; +import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.nuiton.eugene.AbstractGenerator; @@ -35,6 +36,7 @@ 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; @@ -56,22 +58,17 @@ /** * 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> - * - * @version $Revision$ - * - * Mise a jour: $Date$ par : $Author$ - * * @author tchemit <tchemit@codelutin.com> * @author fdesbois <fdesbois@codelutin.com> * @author chatellier <chatellier@codelutin.com> * @author thimel <thimel@codelutin.com> * @version $Id$ */ -public class TopiaGeneratorUtil extends JavaGeneratorUtil implements TopiaTagValues, TopiaStereoTypes { +public class TopiaGeneratorUtil extends JavaGeneratorUtil { /** Logger */ private static final Log log = LogFactory.getLog(TopiaGeneratorUtil.class); @@ -124,7 +121,7 @@ for (Object o : model.getInterfaces()) { ObjectModelInterface daoInterface = (ObjectModelInterface) o; if (daoInterface.getName().equals(clazz.getName() + "DAO")) { - if (daoInterface.hasStereotype(STEREOTYPE_DAO)) { + if (hasDaoStereotype(daoInterface)) { return daoInterface; } } @@ -138,20 +135,58 @@ * * @param element l'élément à tester * @return le type de persitence pour l'élément donné. + * @deprecated since 2.4.4, prefer use the method {@link #getPersistenceType(ObjectModelClassifier)} */ + @Deprecated public static String getPersistenceType(ObjectModelElement element) { - String tag = element.getTagValue(TAG_PERSISTENCE_TYPE); + String tag = element.getTagValue(TopiaTagValues.TAG_PERSISTENCE_TYPE); if (tag == null) { tag = PERSISTENCE_TYPE_DEFAULT; } return tag; } + /** + * 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.4.4 + */ + public static String getPersistenceType(ObjectModelClassifier classifier) { + String tag = getPersistenceTypeTagValue(classifier); + if (StringUtils.isEmpty(tag)) { + tag = PERSISTENCE_TYPE_DEFAULT; + } + return tag; + } + + /** + * @param attr + * @return + * @deprecated since 2.4.4, prefer use the methode {@link #getReverseDbName(ObjectModelAttribute)} + */ + @Deprecated public static String getReverseDBName(ObjectModelAttribute attr) { + return getReverseDbName(attr); + } + + /** + * 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.4.4 + */ + public static String getReverseDbName(ObjectModelAttribute attr) { if (attr.getReverseAttribute() != null) { - return getDBName(attr.getReverseAttribute()); + return getDbName(attr.getReverseAttribute()); } else { - return getDBName(attr) + "_id"; + return getDbName(attr) + "_id"; } } @@ -161,13 +196,27 @@ * * @param element l'élément à tester * @return le nom de table + * @deprecated since 2.4.4, prefer use the method {@link #getDbName(ObjectModelElement)} */ + @Deprecated public static String getDBName(ObjectModelElement element) { + return getDbName(element); + } + + /** + * 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; } - if (notEmpty(element.getTagValue(TAG_DB_NAME))) { - return element.getTagValue(TAG_DB_NAME); + String value = getDbNameTagValue(element); + if (!StringUtils.isEmpty(value)) { + return value; } return toLowerCaseFirstLetter(element.getName()); } @@ -179,10 +228,12 @@ * @param element l'élément à tester * @param model le modele utilisé * @return le nom du schema ou null + * @deprecated since 2.4.4, prefer use the method {@link #getDbSchemaNameTagValue(ObjectModelClassifier, ObjectModel)} or {@link #getDbSchemaNameTagValue(ObjectModelAttribute, ObjectModel)} */ + @Deprecated public static String getSchemaName(ObjectModelElement element, ObjectModel model) { - return findTagValue(TAG_SCHEMA_NAME, element, model); + return findTagValue(TopiaTagValues.TAG_SCHEMA_NAME, element, model); } /** @@ -192,35 +243,53 @@ * @param element l'élément à tester * @param model le modele utilisé * @return le prefix i18n ou <code>null</code> si non spécifié - * @deprecated since 2.4.4, prefer use the {@link JavaGeneratorUtil#getI18nPrefix(ObjectModelElement, ObjectModel)} + * @deprecated since 2.4.4, prefer use the {@link JavaGeneratorUtil#getI18nPrefixTagValue(ObjectModelElement, ObjectModel)} */ @Deprecated public static String getI18nPrefix(ObjectModelElement element, ObjectModel model) { - return JavaGeneratorUtil.getI18nPrefix(element, model); + return JavaGeneratorUtil.getI18nPrefixTagValue(element, model); } /** - * Cherche si le tagvalue {@link #TAG_GENERATE_OPERATOR_FOR_DAO_HELPER} a été + * Cherche si le tagvalue {@link TopiaTagValues#TAG_GENERATE_OPERATOR_FOR_DAO_HELPER} a été * activé dans le model. * * @param element l'élément à tester * @param model le modele utilisé * @return {@code true} si le tag value trouvé dans le modèle, {@code false} * sinon. + * @deprecated since 2.4.4, use now the method {@link #shouldGenerateOperatorForDAOHelper(ObjectModel)} */ + @Deprecated public static boolean shouldgenerateOperatorForDAOHelper( - ObjectModelElement element, - ObjectModel model) { - String tagValue = GeneratorUtil.findTagValue( - TAG_GENERATE_OPERATOR_FOR_DAO_HELPER, element, model); - boolean generate = GeneratorUtil.notEmpty(tagValue) && + ObjectModelElement element,ObjectModel model) { + return shouldGenerateOperatorForDAOHelper(model); +// String tagValue = GeneratorUtil.findTagValue( +// TopiaTagValues.TAG_GENERATE_OPERATOR_FOR_DAO_HELPER, element, 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.4.4 + */ + 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 #TAG_GENERATE_OPERATOR_FOR_DAO_HELPER} a été + * Cherche si le tagvalue {@link TopiaTagValues#TAG_GENERATE_OPERATOR_FOR_DAO_HELPER} a été * activé dans le model. * * @param element l'élément à tester @@ -228,13 +297,32 @@ * @return {@code true} si le tag value trouvé dans le modèle, {@code false} * sinon. * @since 2.4.1 + * @deprecated since 2.4.4, prefer use the method {@link #shouldGenerateStandaloneEnumForDAOHelper(ObjectModel)} */ + @Deprecated public static boolean shouldGnerateStandaloneEnumForDAOHelper( ObjectModelElement element, ObjectModel model) { - String tagValue = GeneratorUtil.findTagValue( - TAG_GENERATE_STANDALONE_ENUM_FOR_DAO_HELPER, element, model); - boolean generate = GeneratorUtil.notEmpty(tagValue) && + return shouldGenerateStandaloneEnumForDAOHelper(model); +// String tagValue = GeneratorUtil.findTagValue( +// TopiaTagValues.TAG_GENERATE_STANDALONE_ENUM_FOR_DAO_HELPER, element, model); +// boolean generate = GeneratorUtil.notEmpty(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.4.4 + */ + public static boolean shouldGenerateStandaloneEnumForDAOHelper(ObjectModel model) { + String tagValue = getGenerateStandaloneEnumForDAOHelperTagValue(model); + boolean generate = StringUtils.isNotEmpty(tagValue) && Boolean.valueOf(tagValue); return generate; } @@ -259,25 +347,27 @@ } /** - * Cherche et renvoie la liste des attributs constituant la clef metier - * d'une classe. + * Test if we need to generate {@code toString} method for the given class. * - * @param clazz la classe à tester - * @param model le modele - * @return la liste des attributs de la clef métier ou null si pas de + * @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; - value = model.getTagValue(TAG_NOT_GENERATE_TO_STRING); - if (value != null && !value.trim().isEmpty()) { - return false; - } - value = clazz.getTagValue(TAG_NOT_GENERATE_TO_STRING); - return value == null || value.trim().isEmpty(); + String value = getNotGenerateToStringTagValue(clazz, model); + return StringUtils.isEmpty(value); +// String value; +// value = model.getTagValue(TAG_NOT_GENERATE_TO_STRING); +// if (value != null && !value.trim().isEmpty()) { +// return false; +// } +// value = clazz.getTagValue(TAG_NOT_GENERATE_TO_STRING); +// return value == null || value.trim().isEmpty(); } + /** * Cherche et renvoie la liste des attributs constituant la clef metier * d'une classe. @@ -289,25 +379,27 @@ */ public static boolean sortAttribute(ObjectModelClass clazz, ObjectModel model) { - String value; - value = clazz.getTagValue(TAG_SORT_ATTRIBUTE); - if (value == null || value.trim().isEmpty() || - "false".equals(value.trim())) { - return false; - } - if ("true".equals(value.trim())) { - return true; - } - - value = model.getTagValue(TAG_SORT_ATTRIBUTE); - if (value == null || value.trim().isEmpty() || - "false".equals(value.trim())) { - return false; - } - if ("true".equals(value.trim())) { - return true; - } - return true; + String value = getSortAttributeTagValue(clazz, model); + return "true".equals(value); +// String value; +// value = clazz.getTagValue(TopiaTagValues.TAG_SORT_ATTRIBUTE); +// if (value == null || value.trim().isEmpty() || +// "false".equals(value.trim())) { +// return false; +// } +// if ("true".equals(value.trim())) { +// return true; +// } +// +// value = model.getTagValue(TopiaTagValues.TAG_SORT_ATTRIBUTE); +// if (value == null || value.trim().isEmpty() || +// "false".equals(value.trim())) { +// return false; +// } +// if ("true".equals(value.trim())) { +// return true; +// } +// return true; } /** @@ -318,8 +410,8 @@ * <code>false</cdoe> sinon. */ public static boolean isNaturalId(ObjectModelAttribute attribute) { - String value = attribute.getTagValue(TAG_NATURAL_ID); - if (!GeneratorUtil.notEmpty(value)) { + String value = getNaturalIdTagValue(attribute); + if (StringUtils.isEmpty(value)) { // valeur null, donc pas positionnee return false; } @@ -336,34 +428,14 @@ * Cherches et renvoie le copyright a utiliser sur le model. * * @param model le modele utilisé - * @return le texte du copyright ou null + * @return le texte du copyright ou null$ + * @deprecated since 2.4.4 never use anywhere */ + @Deprecated public static String getCopyright(Model model) { - return findTagValue(TAG_COPYRIGHT, null, model); + return findTagValue(TopiaTagValues.TAG_COPYRIGHT, null, model); } -// /** -// * @see GeneratorUtil#findTagValue -// * @deprecated -// */ -// @Deprecated -// public static String findTagValue(String tagName, -// ObjectModelElement element, Model model) { -// if (element == null) { -// if (model != null) { -// if (notEmpty(model.getTagValue(tagName))) { -// return model.getTagValue(tagName); -// } -// } -// return null; -// } -// if (notEmpty(element.getTagValue(tagName))) { -// return element.getTagValue(tagName); -// } -// //On va chercher sur l'element declarant -// return findTagValue(tagName, element.getDeclaringElement(), model); -// } - public static <Type extends ObjectModelElement> Collection<Type> getElementsWithStereotype( Collection<Type> elements, String... stereotypes) { Collection<Type> result = new ArrayList<Type>(); @@ -390,7 +462,7 @@ String attributes = ""; Collection<ObjectModelAttribute> attributeCollection; attributeCollection = getElementsWithStereotype(clazz.getAttributes(), - STEREOTYPE_PRIMARYKAY); + TopiaStereoTypes.STEREOTYPE_PRIMARYKAY); for (ObjectModelAttribute attr : attributeCollection) { attributes += attr.getType(); if (includeName) { @@ -431,7 +503,7 @@ return type; } ObjectModelClass clazz = model.getClass(type); - if (clazz.hasStereotype(STEREOTYPE_ENTITY)) { + if (hasEntityStereotype(clazz)) { if (shouldBeAbstract(clazz)) { type += "Abstract"; } else { @@ -560,7 +632,7 @@ if (!reverse.isNavigable()) { //Il s'agit d'une entity ObjectModelClass clazz = model.getClass(attr.getType()); - if (clazz != null && clazz.hasStereotype(STEREOTYPE_ENTITY)) { + if (clazz != null && hasEntityStereotype(clazz)) { //Cette classe a des sous-classes dans le modèle for (ObjectModelClass subClass : model.getClasses()) { if (subClass.getSuperclasses().contains(clazz)) { @@ -587,7 +659,7 @@ String result; if (attr.hasAssociationClass()) { - result = getDBName(attr.getAssociationClass()); + result = getDbName(attr.getAssociationClass()); } else { String name = attr.getName(); String revers = attr.getReverseAttributeName(); @@ -609,9 +681,9 @@ */ public static String getNMultiplicityInterfaceType( ObjectModelAttribute attr) { - if (attr.hasStereotype(STEREOTYPE_UNIQUE)) { + if (hasUniqueStereotype(attr)) { return Set.class.getName(); - } else if (attr.isIndexed() || attr.isOrdered()) { + } else if (JavaGeneratorUtil.hasIndexedStereotype(attr) || attr.isOrdered()) { return List.class.getName(); } return Collection.class.getName(); @@ -624,9 +696,9 @@ * @return String */ public static String getNMultiplicityObjectType(ObjectModelAttribute attr) { - if (attr.hasStereotype(STEREOTYPE_UNIQUE)) { + if (hasUniqueStereotype(attr)) { return HashSet.class.getName(); - } else if (attr.isIndexed() || attr.isOrdered()) { + } 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 @@ -644,9 +716,9 @@ */ public static String getNMultiplicityHibernateType( ObjectModelAttribute attr) { - if (attr.hasStereotype(STEREOTYPE_UNIQUE)) { + if (hasUniqueStereotype(attr)) { return "set"; - } else if (attr.isIndexed()) { + } else if (JavaGeneratorUtil.hasIndexedStereotype(attr)) { return "list"; } //attr.isOrdered() - On génère le ordered en bag @@ -663,7 +735,7 @@ */ public static List<ObjectModelClass> getEntityClasses(ObjectModel model, boolean sort) { - return getClassesByStereotype(STEREOTYPE_ENTITY, model, sort); + return getClassesByStereotype(TopiaStereoTypes.STEREOTYPE_ENTITY, model, sort); } /** @@ -710,12 +782,12 @@ * * @param clazz la classe a tester * @return {@code true} si le tag value a ete positionne sur la classe - * via le tag {@link #TAG_NATURAL_ID_MUTABLE}, {@code false} + * via le tag {@link TopiaTagValues#TAG_NATURAL_ID_MUTABLE}, {@code false} * sinon. */ public static boolean isNaturalIdMutable(ObjectModelClass clazz) { - String value = clazz.getTagValue(TAG_NATURAL_ID_MUTABLE); - if (!notEmpty(value)) { + String value = getNaturalIdMutableTagValue(clazz); + if (StringUtils.isEmpty(value)) { // valeur null, donc par default positionnee return false; } @@ -942,5 +1014,611 @@ classes.add(klass); } } -} // GeneratorUtil + /** + * Check if the given classifier has the + * {@link TopiaStereoTypes#STEREOTYPE_FACADE} stereotype. + * + * @param classifier classifier to test + * @return {@code true} if stereotype was found, {@code false otherwise} + * @see TopiaStereoTypes#STEREOTYPE_FACADE + * @since 2.4.4 + */ + public static boolean hasFacadeStereotype(ObjectModelClassifier classifier) { + return classifier.hasStereotype(TopiaStereoTypes.STEREOTYPE_FACADE); + } + + /** + * 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.4.4 + */ + public static boolean hasEntityStereotype(ObjectModelClassifier classifier) { + return classifier.hasStereotype(TopiaStereoTypes.STEREOTYPE_ENTITY); + } + + + /** + * 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.4.4 + */ + 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.4.4 + */ + public static boolean hasDtoStereotype(ObjectModelClassifier classifier) { + return classifier.hasStereotype(TopiaStereoTypes.STEREOTYPE_DTO); + } + + /** + * Check if the given classifier has the + * {@link TopiaStereoTypes#STEREOTYPE_SERVICE} stereotype. + * + * @param classifier classifier to test + * @return {@code true} if stereotype was found, {@code false otherwise} + * @see TopiaStereoTypes#STEREOTYPE_SERVICE + * @since 2.4.4 + */ + public static boolean hasServiceStereotype(ObjectModelClassifier classifier) { + return classifier.hasStereotype(TopiaStereoTypes.STEREOTYPE_SERVICE); + } + + /** + * 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.4.4 + */ + 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.4.4 + */ + 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.4.4 + */ + 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.4.4 + */ + public static boolean hasPrimaryKeyStereotype(ObjectModelAttribute attribute) { + return attribute.hasStereotype(TopiaStereoTypes.STEREOTYPE_PRIMARYKAY); + } + + /** + * Check if the given attribute has the + * {@link TopiaStereoTypes#STEREOTYPE_ARRAY} stereotype. + * + * @param attribute attribute to test + * @return {@code true} if stereotype was found, {@code false otherwise} + * @see TopiaStereoTypes#STEREOTYPE_ARRAY + * @since 2.4.4 + * @deprecated since 2.4.4 , only BeanTransformer use it and it is a deprecated transformer, will be remove in version 3.0 + */ + @Deprecated + public static boolean hasArrayStereotype(ObjectModelAttribute attribute) { + return attribute.hasStereotype(TopiaStereoTypes.STEREOTYPE_ARRAY); + } + + /** + * Obtain the value of the {@link TopiaTagValues#TAG_PERSISTENCE_TYPE} + * tag value on the given classifier. + * <p/> + * + * @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.4.4 + */ + 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_DB_NAME} + * tag value on the given classifier. + * <p/> + * + * @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.4.4 + */ + 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. + * <p/> + * + * @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.4.4 + */ + 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. + * <p/> + * + * @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.4.4 + */ + 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. + * <p/> + * + * @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.4.4 + */ + 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. + * <p/> + * + * @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.4.4 + */ + 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. + * <p/> + * + * @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.4.4 + */ + 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. + * <p/> + * + * @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.4.4 + */ + 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. + * <p/> + * + * @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.4.4 + */ + 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. + * <p/> + * + * @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.4.4 + */ + 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. + * <p/> + * + * @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.4.4 + */ + 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. + * <p/> + * + * @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.4.4 + */ + 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. + * <p/> + * + * @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.4.4 + */ + 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. + * <p/> + * + * @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.4.4 + */ + 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. + * <p/> + * + * @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.4.4 + */ + 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.4.4 + */ + 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. + * <p/> + * + * @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.4.4 + */ + 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. + * <p/> + * + * @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.4.4 + */ + 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. + * <p/> + * + * @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.4.4 + */ + 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. + * <p/> + * + * @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.4.4 + */ + 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. + * <p/> + * + * @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.4.4 + */ + public static String getNotGenerateToStringTagValue(ObjectModelClass 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 class. + * <p/> + * + * @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_SORT_ATTRIBUTE + * @since 2.4.4 + */ + public static String getSortAttributeTagValue(ObjectModelClass clazz, ObjectModel model) { + String value = findTagValue(TopiaTagValues.TAG_SORT_ATTRIBUTE, clazz, model); + return value; + } + + /** + * Obtain the value of the {@link TopiaTagValues#TAG_GENERATE_STANDALONE_ENUM_FOR_DAO_HELPER} + * tag value on the given model. + * <p/> + * + * @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.4.4 + */ + 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. + * <p/> + * + * @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.4.4 + */ + + 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. + * <p/> + * + * @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.4.4 + */ + public static String getTypeTagValue(ObjectModelAttribute attribute) { + String value = findTagValue(TopiaTagValues.TAG_TYPE, attribute, null); + return value; + } + + /** + * Obtain the value of the {@link TopiaTagValues#TAG_EXCEPTION_CLASS} + * tag value on the given interface. + * <p/> + * + * @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_EXCEPTION_CLASS + * @since 2.4.4 + */ + public static String getExceptionClassTagValue(ObjectModel model) { + String value = findTagValue(TopiaTagValues.TAG_EXCEPTION_CLASS, null, model); + return value; + } + + /** + * Obtain the value of the {@link TopiaTagValues#TAG_TRANSACTION} + * tag value on the given operation. + * <p/> + * + * @param operation operation to seek + * @return the none empty value of the found tag value or {@code null} if not found nor empty. + * @see TopiaTagValues#TAG_TRANSACTION + * @since 2.4.4 + */ + public static String getTransactionTagValue(ObjectModelOperation operation) { + String value = findTagValue(TopiaTagValues.TAG_TRANSACTION, operation, null); + return value; + } + + /** + * Obtain the value of the {@link TopiaTagValues#TAG_TRANSACTION} + * tag value on the given interface. + * <p/> + * + * @param interfaze operation to seek + * @return the none empty value of the found tag value or {@code null} if not found nor empty. + * @see TopiaTagValues#TAG_TRANSACTION + * @since 2.4.4 + */ + public static String getTransactionTagValue(ObjectModelInterface interfaze) { + String value = findTagValue(TopiaTagValues.TAG_TRANSACTION, interfaze, null); + return value; + } + + /** + * Obtain the value of the {@link TopiaTagValues#TAG_DO_COMMIT} + * tag value on the given operation. + * <p/> + * + * @param operation operation 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_DO_COMMIT + * @since 2.4.4 + */ + public static String getDoCommitTagValue(ObjectModelOperation operation, ObjectModel model) { + String value = findTagValue(TopiaTagValues.TAG_DO_COMMIT, operation, model); + return value; + } + + /** + * Obtain the value of the {@link TopiaTagValues#TAG_ERROR_ARGS} + * tag value on the given operation. + * <p/> + * + * @param operation operation to seek + * @return the none empty value of the found tag value or {@code null} if not found nor empty. + * @see TopiaTagValues#TAG_ERROR_ARGS + * @since 2.4.4 + */ + public static String getErrorArgsTagValue(ObjectModelOperation operation) { + String value = findTagValue(TopiaTagValues.TAG_ERROR_ARGS, operation, null); + return value; + } + + /** + * Obtain the value of the {@link TopiaTagValues#TAG_NO_LOG_IN_SERVICE} + * tag value on the given interface. + * <p/> + * + * @param interfaze operation 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_NO_LOG_IN_SERVICE + * @since 2.4.4 + */ + public static String getNoLogInServiceTagValue(ObjectModelInterface interfaze, ObjectModel model) { + String value = findTagValue(TopiaTagValues.TAG_NO_LOG_IN_SERVICE, interfaze, model); + return value; + } + +} // TopiaGeneratorUtil + Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaStereoTypes.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaStereoTypes.java 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaStereoTypes.java 2010-11-28 20:17:13 UTC (rev 2156) @@ -1,41 +1,110 @@ +/* + * #%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.StereotypeDefinition; +import org.nuiton.eugene.models.object.ObjectModelAttribute; +import org.nuiton.eugene.models.object.ObjectModelClassifier; +import org.nuiton.eugene.models.object.ObjectModelOperation; + /** * All extra stereotypes usable in topia generators. * * @author tchemit <chemit@codelutin.com> * @since 2.4.4 */ -public interface TopiaStereoTypes { +public interface TopiaStereoTypes extends EugeneStereoTypes { - /** Stéréotype pour les interfaces devant être générées sous forme de facades */ + /** + * Stéréotype pour les attributs considérés comme des tableaux. + * + * @see TopiaGeneratorUtil#hasArrayStereotype(ObjectModelAttribute) + * @deprecated since 2.4.4 : only BeanTransformer use it and it is a deprecated transformer, will be remove in version 3.0 + */ + @Deprecated + @StereotypeDefinition(target = ObjectModelClassifier.class) + String STEREOTYPE_ARRAY = "array"; + + /** + * Stéréotype pour les interfaces devant être générées sous forme de facades. + * + * @deprecated since 2.4.4 : nobydy use it, will be remove in version 3.0 + */ + @Deprecated String STEREOTYPE_FACADE = "facade"; - /** Stéréotype pour les objets devant être générées sous forme d'entités */ + /** + * Stéréotype pour les objets devant être générées sous forme d'entités + * + * @see TopiaGeneratorUtil#hasEntityStereotype(ObjectModelClassifier) + * @see TopiaGeneratorUtil#hasEntityStereotype(ObjectModelAttribute) + */ + @StereotypeDefinition(target = {ObjectModelClassifier.class, ObjectModelAttribute.class}) String STEREOTYPE_ENTITY = "entity"; - /** Stéréotype pour les objets devant être générées sous forme de DTO */ + /** + * Stéréotype pour les objets devant être générées sous forme de DTO. + * + * @see TopiaGeneratorUtil#hasDtoStereotype(ObjectModelClassifier) + */ + @StereotypeDefinition(target = ObjectModelClassifier.class) String STEREOTYPE_DTO = "dto"; /** * Stéréotype pour les interfaces devant être générées sous forme de * services. + * * @see ServiceTransformer + * @see TopiaGeneratorUtil#hasServiceStereotype(ObjectModelClassifier) */ + @StereotypeDefinition(target = ObjectModelClassifier.class) String STEREOTYPE_SERVICE = "service"; - /** Stéréotype pour les interfaces devant être générées sous forme de DAO */ + /** + * 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}) String STEREOTYPE_DAO = "dao"; - /** Stéréotype pour les attributs à indexer en base */ - String STEREOTYPE_INDEXED = "indexed"; - - /** Stéréotype pour les collections avec unicité */ + /** + * Stéréotype pour les collections avec unicité. + * + * @see TopiaGeneratorUtil#hasUniqueStereotype(ObjectModelAttribute) + */ + @StereotypeDefinition(target = ObjectModelAttribute.class) String STEREOTYPE_UNIQUE = "unique"; - /** Stéréotype pour les attributs étant des clés primaires */ + /** + * Stéréotype pour les attributs étant des clés primaires. + * + * @see TopiaGeneratorUtil#hasPrimaryKeyStereotype(ObjectModelAttribute) + */ + @StereotypeDefinition(target = ObjectModelAttribute.class) String STEREOTYPE_PRIMARYKAY = "primaryKey"; - - /** Stéréotype pour les attributs considérés comme des tableaux */ - String STEREOTYPE_ARRAY = "array"; } Modified: trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaTagValues.java =================================================================== --- trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaTagValues.java 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-persistence/src/main/java/org/nuiton/topia/generator/TopiaTagValues.java 2010-11-28 20:17:13 UTC (rev 2156) @@ -1,5 +1,39 @@ +/* + * #%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.TagValueDefinition; +import org.nuiton.eugene.models.Model; +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.eugene.models.object.ObjectModelInterface; +import org.nuiton.eugene.models.object.ObjectModelOperation; import org.nuiton.topia.persistence.TopiaEntityEnum; /** @@ -8,36 +42,101 @@ * @author tchemit <chemit@codelutin.com> * @since 2.4.4 */ -public interface TopiaTagValues { +public interface TopiaTagValues extends EugeneTagValues { - /** Tag pour le type de persistence */ + /** + * Tag pour ajouter specifier le copyright d'un fichier. + * + * @since 2.4.4 + * @deprecated since 2.4.4 only use in a deprecated method {@link TopiaGeneratorUtil#getCopyright(Model)} + */ + @Deprecated + String TAG_COPYRIGHT = "copyright"; + + /** + * Tag pour le type de persistence. + * + * @see TopiaGeneratorUtil#getPersistenceType(ObjectModelClassifier) + * @see TopiaGeneratorUtil#getPersistenceTypeTagValue(ObjectModelClassifier) + * @since 2.4.4 + */ + @TagValueDefinition(target = {ObjectModelClassifier.class}) String TAG_PERSISTENCE_TYPE = "persistenceType"; - /** Tag pour le nom du champ / entité en BD */ + /** + * 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}) String TAG_DB_NAME = "dbName"; - /** Tag pour le nom du schema en BD */ + /** + * Tag pour le nom du schema en BD. + * + * @see TopiaGeneratorUtil#getDbSchemaNameTagValue(ObjectModelClassifier, ObjectModel) + * @see TopiaGeneratorUtil#getDbSchemaNameTagValue(ObjectModelAttribute, ObjectModel) + * @since 2.4.4 + */ + @TagValueDefinition(target = {ObjectModel.class, ObjectModelClassifier.class, ObjectModelAttribute.class}) String TAG_SCHEMA_NAME = "dbSchema"; - /** Tag pour la taille du champ en BD */ + /** + * Tag pour spécifier la caractère embed-xml d'une association. + * + * @see TopiaGeneratorUtil#getPersistenceTypeTagValue(ObjectModelClassifier) + * @deprecated @since 2.4.4, use nowhere, will be remove soon + */ + @Deprecated + String TAG_EMBED_XML = "embedXml"; + + /** + * Tag pour la taille du champ en BD. + * + * @see TopiaGeneratorUtil#getLengthTagValue(ObjectModelAttribute) + * @since 2.4.4 + */ + @TagValueDefinition(target = {ObjectModelAttribute.class}) String TAG_LENGTH = "length"; - /** Tag pour ajouter une annotation à un champ */ + /** + * Tag pour ajouter une annotation à un champ. + * + * @see TopiaGeneratorUtil#getAnnotationTagValue(ObjectModelAttribute) + * @since 2.4.4 + */ + @TagValueDefinition(target = {ObjectModelAttribute.class}) String TAG_ANNOTATION = "annotation"; - /** Tag pour ajouter specifier le copyright d'un fichier */ - String TAG_COPYRIGHT = "copyright"; - - /** Tag pour specfier le type d'acces a un champ */ + /** + * Tag pour specfier le type d'acces a un champ. + * + * @see TopiaGeneratorUtil#getAccessTagValue(ObjectModelAttribute) + * @since 2.4.4 + */ + @TagValueDefinition(target = {ObjectModelAttribute.class}) String TAG_ACCESS = "access"; - /** Tag pour specfier si on doit générer i18n */ - String TAG_I18N_PREFIX = "i18n"; - - /** Tag pour ajouter un attribut dans une clef métier */ + /** + * Tag pour ajouter un attribut dans une clef métier. + * + * @see TopiaGeneratorUtil#getNaturalIdTagValue(ObjectModelAttribute) + * @see TopiaGeneratorUtil#isNaturalId(ObjectModelAttribute) + * @since 2.4.4 + */ + @TagValueDefinition(target = {ObjectModelAttribute.class}) String TAG_NATURAL_ID = "naturalId"; - /** Tag pour specifier si une clef metier est mutable */ + /** + * Tag pour specifier si une clef metier est mutable. + * + * @see TopiaGeneratorUtil#getNaturalIdMutableTagValue(ObjectModelClassifier) + * @see TopiaGeneratorUtil#isNaturalIdMutable(ObjectModelClass) + * @since 2.4.4 + */ + @TagValueDefinition(target = {ObjectModelClass.class}) String TAG_NATURAL_ID_MUTABLE = "naturalIdMutable"; /** @@ -47,25 +146,48 @@ * Par défaut le inverse=true est placé sur le premier rôle trouvé dans * l'ordre alphabétique. * - * @since 2.3.2 + * @see TopiaGeneratorUtil#getInverseTagValue(ObjectModelAttribute) + * @since 2.4.4 */ + @TagValueDefinition(target = {ObjectModelAttribute.class}) String TAG_INVERSE = "inverse"; - /** Tag pour spécifier la caractère lazy d'une association multiple */ + /** + * Tag pour spécifier la caractère lazy d'une association multiple. + * + * @see TopiaGeneratorUtil#getLazyTagValue(ObjectModelAttribute) + * @since 2.4.4 + */ + @TagValueDefinition(target = {ObjectModelAttribute.class}) String TAG_LAZY = "lazy"; - /** Tag pour spécifier la caractère fetch d'une association multiple */ + /** + * Tag pour spécifier la caractère fetch d'une association multiple. + * + * @see TopiaGeneratorUtil#getFetchTagValue(ObjectModelAttribute) + * @since 2.4.4 + */ + @TagValueDefinition(target = {ObjectModelAttribute.class}) String TAG_FETCH = "fetch"; - /** Tag pour spécifier la caractère order-by d'une association multiple */ + /** + * Tag pour spécifier la caractère order-by d'une association multiple. + * + * @see TopiaGeneratorUtil#getOrderByTagValue(ObjectModelAttribute) + * @since 2.4.4 + */ + @TagValueDefinition(target = {ObjectModelAttribute.class}) String TAG_ORDER_BY = "orderBy"; - /** Tag pour spécifier la caractère not-null d'un attribut */ + /** + * Tag pour spécifier la caractère not-null d'un attribut. + * + * @see TopiaGeneratorUtil#getNotNullTagValue(ObjectModelAttribute) + * @since 2.4.4 + */ + @TagValueDefinition(target = {ObjectModelAttribute.class}) String TAG_NOT_NULL = "notNull"; - /** Tag pour spécifier la caractère embed-xml d'une association */ - String TAG_EMBED_XML = "embedXml"; - /** * Tag pour configurer l'interface du proxy sur autre chose que l'implementation par defaut. * <p/> @@ -73,28 +195,77 @@ * 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.4.4 */ + @TagValueDefinition(target = {ObjectModel.class, ObjectModelClassifier.class}) String TAG_PROXY_INTERFACE = "hibernateProxyInterface"; - /** Tag pour spécifier le permissions à la création */ + /** + * Tag pour spécifier le permissions à la création. + * + * @see TopiaGeneratorUtil#getSecurityCreateTagValue(ObjectModelClassifier) + * @since 2.4.4 + */ + @TagValueDefinition(target = {ObjectModelClassifier.class}) String TAG_SECURITY_CREATE = "securityCreate"; - /** Tag pour spécifier le permissions au chargement */ + /** + * Tag pour spécifier le permissions au chargement. + * + * @see TopiaGeneratorUtil#getSecurityLoadTagValue(ObjectModelClassifier) + * @since 2.4.4 + */ + @TagValueDefinition(target = {ObjectModelClassifier.class}) String TAG_SECURITY_LOAD = "securityLoad"; - /** Tag pour spécifier le permissions à la mise à jour */ + /** + * Tag pour spécifier le permissions à la mise à jour. + * + * @see TopiaGeneratorUtil#getSecurityUpdateTagValue(ObjectModelClassifier) + * @since 2.4.4 + */ + @TagValueDefinition(target = {ObjectModelClassifier.class}) String TAG_SECURITY_UPDATE = "securityUpdate"; - /** Tag pour spécifier le permissions à la suppression */ + /** + * Tag pour spécifier le permissions à la suppression. + * + * @see TopiaGeneratorUtil#getSecurityDeleteTagValue(ObjectModelClassifier) + * @since 2.4.4 + */ + @TagValueDefinition(target = {ObjectModelClassifier.class}) String TAG_SECURITY_DELETE = "securityDelete"; - /** Tag pour specifier de ne pas generer la methode toString */ + /** + * Tag pour specifier de ne pas generer la methode toString. + * + * @see TopiaGeneratorUtil#getNotGenerateToStringTagValue(ObjectModelClass,ObjectModel) + * @see TopiaGeneratorUtil#generateToString(ObjectModelClass, ObjectModel) + * @since 2.4.4 + */ + @TagValueDefinition(target = {ObjectModel.class, ObjectModelClass.class}) String TAG_NOT_GENERATE_TO_STRING = "notGenerateToString"; - /** Tag pour specifier de trier les attributs par nom lors de la generation */ + /** + * Tag pour specifier de trier les attributs par nom lors de la generation. + * + * @see TopiaGeneratorUtil#getSortAttributeTagValue(ObjectModelClass, ObjectModel) + * @see TopiaGeneratorUtil#sortAttribute(ObjectModelClass, ObjectModel) + * @since 2.4.4 + */ + @TagValueDefinition(target = {ObjectModel.class, ObjectModelClassifier.class}) String TAG_SORT_ATTRIBUTE = "sortAttribute"; - /** Tag pour specfier si on doit générer la methode getOperator dans les daohelpers ) */ + /** + * 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.4.4 + */ + @TagValueDefinition(target = {ObjectModel.class}) String TAG_GENERATE_OPERATOR_FOR_DAO_HELPER = "generateOperatorForDAOHelper"; /** @@ -103,13 +274,37 @@ * <p/> * <b>Note:</b> Par défaut, on génère en tant qu'inner classe. * - * @since 2.4.1 + * @see TopiaGeneratorUtil#getGenerateStandaloneEnumForDAOHelperTagValue(ObjectModel) + * @see TopiaGeneratorUtil#shouldGenerateStandaloneEnumForDAOHelper(ObjectModel) + * @since 2.4.4 */ + @TagValueDefinition(target = {ObjectModel.class}) String TAG_GENERATE_STANDALONE_ENUM_FOR_DAO_HELPER = "generateStandaloneEnumForDAOHelper"; - /** Tag pour spécifier le type d'une propriété dans le mapping hibernate */ + /** + * Tag pour spécifier le type d'une propriété dans le mapping hibernate. + * + * @see TopiaGeneratorUtil#getTypeTagValue(ObjectModelAttribute) + * @since 2.4.4 + */ + @TagValueDefinition(target = {ObjectModelAttribute.class}) String TAG_TYPE = "type"; + + /** + * Tag pour specifier l'exception principale de l'application. + * Utiliser dans le ServiceTransformer ou QueryHelperTransformer pour etre + * automatiquement jeter + * depuis les methodes des services. + * + * @see ServiceTransformer + * @see QueryHelperTransformer + * @see TopiaGeneratorUtil#getExceptionClassTagValue(ObjectModel) + * @since 2.3.2 + */ + @TagValueDefinition(target = {ObjectModel.class}) + String TAG_EXCEPTION_CLASS = "exceptionClass"; + // ------------------------------------------------------------------------- // ServiceTransformer specific tag values // ------------------------------------------------------------------------- @@ -119,8 +314,11 @@ * (TopiaContext) ou non * * @see ServiceTransformer + * @see TopiaGeneratorUtil#getTransactionTagValue(ObjectModelInterface) + * @see TopiaGeneratorUtil#getTransactionTagValue(ObjectModelOperation) * @since 2.3.1 */ + @TagValueDefinition(target = {ObjectModelInterface.class, ObjectModelOperation.class}) String TAG_TRANSACTION = "transaction"; /** @@ -128,8 +326,10 @@ * exécution. * * @see ServiceTransformer + * @see TopiaGeneratorUtil#getDoCommitTagValue(ObjectModelOperation, ObjectModel) * @since 2.4.4 */ + @TagValueDefinition(target = {ObjectModel.class, ObjectModelOperation.class}) String TAG_DO_COMMIT = "doCommit"; /** @@ -137,21 +337,13 @@ * le message d'erreur ou non * * @see ServiceTransformer + * @see TopiaGeneratorUtil#getErrorArgsTagValue(ObjectModelOperation) * @since 2.3.1 */ + @TagValueDefinition(target = {ObjectModelOperation.class}) String TAG_ERROR_ARGS = "errorArgs"; /** - * Tag pour specifier l'exception principale de l'application. - * Utiliser dans le ServiceTransformer pour etre automatiquement jeter - * depuis les methodes des services. - * - * @see ServiceTransformer - * @since 2.3.2 - */ - String TAG_EXCEPTION_CLASS = "exceptionClass"; - - /** * Tag to specify if we want to add logs in any method of service * generated by {@link ServiceTransformer}. * <p/> @@ -159,7 +351,9 @@ * on model (for all services). * * @see ServiceTransformer + * @see TopiaGeneratorUtil#getNoLogInServiceTagValue(ObjectModelInterface, ObjectModel) * @since 2.4.4 */ + @TagValueDefinition(target = {ObjectModel.class, ObjectModelInterface.class}) String TAG_NO_LOG_IN_SERVICE = "noLogInService"; } Added: trunk/topia-persistence/src/test/java/org/nuiton/topia/TestHelper.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/TestHelper.java (rev 0) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/TestHelper.java 2010-11-28 20:17:13 UTC (rev 2156) @@ -0,0 +1,144 @@ +/* + * #%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.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.4.4 + */ +@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 + FileUtil.deleteRecursively(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 { + + InputStream stream = TestHelper.class.getResourceAsStream(dbPropertiesPath); + + Properties configuration = new Properties(); + + configuration.load(stream); + configuration.setProperty( + "topia.persistence.classes", + TopiaTestDAOHelper.getImplementationClassesAsString()); + + // make sure we always use a different directory + + String dbPath = new File(testDirectory, + dbname + '_' + System.nanoTime()).getAbsolutePath(); + + if (log.isInfoEnabled()) { + log.info("dbPath = " + dbPath); + } + configuration.setProperty( + "hibernate.connection.url", + "jdbc:h2:file:" + dbPath); + + return configuration; + } + + public static Properties initTopiaContextConfiguration(File testDirectory, + String dbname) + throws IOException { + + return initTopiaContextConfiguration(testDirectory, DEFAULT_CONFIGURATION_LOCATION, dbname); + } +} Property changes on: trunk/topia-persistence/src/test/java/org/nuiton/topia/TestHelper.java ___________________________________________________________________ Added: svn:keywords + Author Date Id Revision Added: svn:eol-style + native Modified: trunk/topia-persistence/src/test/java/org/nuiton/topia/TopiaContextFactoryTest.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/TopiaContextFactoryTest.java 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/TopiaContextFactoryTest.java 2010-11-28 20:17:13 UTC (rev 2156) @@ -26,12 +26,14 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.junit.After; import org.junit.Assert; import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; import org.nuiton.topia.framework.TopiaContextImpl; +import java.io.File; +import java.io.IOException; import java.util.List; import java.util.Properties; @@ -46,8 +48,17 @@ private static final Log log = LogFactory.getLog(TopiaContextFactoryTest.class); + protected static File testBasedir; + protected Properties properties; + @BeforeClass + public static void init() throws IOException { + + testBasedir = TestHelper.getTestBasedir(TopiaContextFactoryTest.class); + + } + @Before public void setUp() throws Exception { properties = new Properties(); @@ -56,17 +67,14 @@ TopiaContextFactory.contextCache.clear(); } - @After - public void tearDown() throws Exception { - } - @Test public void testGetContextOpened() throws Exception { - log.info("## testGetContextOpened"); + log.debug("## testGetContextOpened"); /** PREPARE DATA **/ String databaseName = "h2data-testGetContextByPropertie"; - String url = "jdbc:h2:file:target/surefire-data/" + databaseName; + File dbDirectory = new File(testBasedir, databaseName); + String url = "jdbc:h2:file:" + dbDirectory; properties.setProperty("hibernate.connection.url", url); TopiaContextImpl test = new TopiaContextImpl(properties); @@ -80,7 +88,7 @@ @Test public void testRemoveContext() throws Exception { - log.info("## testRemoveContext"); + log.debug("## testRemoveContext"); /** PREPARE DATA **/ TopiaContextImpl test = new TopiaContextImpl(properties); @@ -92,13 +100,14 @@ } //@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.info("## testGetContextByProperties"); + log.debug("## testGetContextByProperties"); /** PREPARE DATA **/ Properties propertiesParent = new Properties(properties); @@ -119,19 +128,19 @@ } log.info("test 1 : add new properties, will instantiate a new" + - " TopiaContext"); + " 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"); 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"); TopiaContext test3 = TopiaContextFactory.getContext(properties); log.debug("cache size : " + TopiaContextFactory.contextCache.size()); log.debug("result : " + test1); @@ -140,7 +149,7 @@ Assert.assertEquals(2, TopiaContextFactory.contextCache.size()); log.info("test 4 : use other properties but equivalent to existing " + - "TopiaContext"); + "TopiaContext"); // Test flating of properties TopiaContext test4 = TopiaContextFactory.getContext(propertiesAll); Assert.assertEquals(test1, test4); @@ -155,11 +164,13 @@ // 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:target/surefire-data/" + databaseName); + "jdbc:h2:file:" + f.getAbsolutePath()); TopiaContext test5 = TopiaContextFactory.getContext(properties); @@ -174,7 +185,5 @@ TopiaContext result = TopiaContextFactory.getContext(properties); Assert.assertNotSame(test5, result); Assert.assertEquals(3, TopiaContextFactory.contextCache.size()); - - } } Modified: trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaQueryTest.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaQueryTest.java 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaQueryTest.java 2010-11-28 20:17:13 UTC (rev 2156) @@ -52,7 +52,7 @@ // Test with null paramValue //String nullValue = null; query = new TopiaQuery(QueriedEntity.class); - query.addEquals(QueriedEntity.PROPERTY_TEST_ADD, null); + query.addEquals(QueriedEntity.PROPERTY_TEST_ADD, new Object[]{null}); Assert.assertEquals( "FROM org.nuiton.topiatest.QueriedEntity " + "WHERE testAdd IS NULL", Modified: trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaUtilTest.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaUtilTest.java 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/framework/TopiaUtilTest.java 2010-11-28 20:17:13 UTC (rev 2156) @@ -25,66 +25,58 @@ package org.nuiton.topia.framework; -import java.net.URL; -import java.util.Properties; -import org.hibernate.cfg.Configuration; -import static org.junit.Assert.*; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.hibernate.cfg.Configuration; import org.junit.AfterClass; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topiatest.Personne; import org.junit.BeforeClass; import org.junit.Test; -import org.nuiton.topia.TopiaContextFactory; -import org.nuiton.topia.TopiaTestDAOHelper; +import org.nuiton.topia.TestHelper; +import org.nuiton.topia.TopiaContext; import org.nuiton.topia.test.entities.PersonImpl; -import org.nuiton.util.Resource; +import org.nuiton.topiatest.Personne; -/** +import java.io.File; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +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$ - * - * Last update: $Date$ - * by : $Author$ + * <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"; - private static TopiaContextImplementor rootContext; + + private static TopiaContext rootContext; + private static final Log log = LogFactory.getLog(TopiaUtilTest.class); @BeforeClass public static void setUpClass() throws Exception { - try { - Properties conf = new Properties(); - URL url = Resource.getURL("TopiaContextImpl.properties"); - if (log.isDebugEnabled()) { - log.debug(url); - } - conf.load(url.openStream()); - conf.setProperty("hibernate.connection.url", "jdbc:h2:file://tmp/topiautiltest_" + System.currentTimeMillis()); - conf.setProperty("topia.persistence.classes", TopiaTestDAOHelper.getImplementationClassesAsString()); - rootContext = (TopiaContextImplementor) TopiaContextFactory.getContext(conf); - if (log.isInfoEnabled()) { - log.info("Context Ready !"); - } - } catch (Exception ex) { - log.error("Initialize error !!", ex); - } + + File testBasedir = TestHelper.getTestBasedir(TopiaUtilTest.class); + + rootContext = TestHelper.initTopiaContext(testBasedir, "topiautilest"); } @AfterClass public static void tearDownClass() throws Exception { - rootContext.closeContext(); + if (rootContext != null) { + rootContext.closeContext(); + } } @Test @@ -122,19 +114,18 @@ @Test(expected = IllegalArgumentException.class) public void testIsSchemaExistFailed() throws Exception { - Configuration conf = rootContext.getHibernateConfiguration(); + Configuration conf = ((TopiaContextImplementor) rootContext).getHibernateConfiguration(); TopiaUtil.isSchemaExist(conf, "fake"); } @Test public void testIsSchemaExist() throws Exception { - Configuration conf = rootContext.getHibernateConfiguration(); + Configuration conf = ((TopiaContextImplementor) rootContext).getHibernateConfiguration(); boolean actual = TopiaUtil.isSchemaExist(conf, PersonImpl.class.getName()); assertFalse(actual); - TopiaContext tx = null; + TopiaContext tx = rootContext.beginTransaction(); try { - tx = rootContext.beginTransaction(); tx.createSchema(); actual = TopiaUtil.isSchemaExist(conf, PersonImpl.class.getName()); Modified: trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/TopiaTestCase.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/TopiaTestCase.java 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/generator/TopiaTestCase.java 2010-11-28 20:17:13 UTC (rev 2156) @@ -27,12 +27,12 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.hibernate.cfg.Environment; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; +import org.nuiton.topia.TestHelper; import org.nuiton.topia.TopiaContext; import org.nuiton.topia.TopiaContextFactory; import org.nuiton.topia.TopiaException; @@ -43,6 +43,8 @@ import org.nuiton.topiatest.Department; import org.nuiton.topiatest.DepartmentDAO; +import java.io.File; +import java.io.IOException; import java.util.Properties; /** @@ -65,24 +67,34 @@ /** TopiaContext */ protected static TopiaContext context; - /** Init les proprietes de connection a la base */ + /** + * Init les proprietes de connection a la base + * + * @throws IOException for any IO error while getting configuration. + */ @BeforeClass - public static void init() { - config = new Properties(); - config.setProperty("topia.persistence.classes", TopiaTestDAOHelper.getImplementationClassesAsString()); + public static void init() throws IOException { - 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:target/" + TopiaTestCase.class.getSimpleName() + "/db/data_" + System.currentTimeMillis()); + 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(true); + context.clear(false); // TODO directory target/TopiaTestCase is not deleted } @@ -91,8 +103,8 @@ @Before public void setUp() { - if (log.isInfoEnabled()) { - log.info("Junit beforeTest"); + if (log.isDebugEnabled()) { + log.debug("Junit beforeTest"); } try { @@ -110,8 +122,8 @@ @Test public void testCompositeAssociations() { - if (log.isInfoEnabled()) { - log.info("Junit Test testCompositeAssociations"); + if (log.isDebugEnabled()) { + log.debug("Junit Test testCompositeAssociations"); } try { Modified: trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/EntityVisitorExportXmlTest.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/EntityVisitorExportXmlTest.java 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/EntityVisitorExportXmlTest.java 2010-11-28 20:17:13 UTC (rev 2156) @@ -25,12 +25,15 @@ package org.nuiton.topia.persistence; -import java.io.File; -import java.io.IOException; -import java.util.Properties; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; +import org.hibernate.cfg.Environment; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.nuiton.topia.TestHelper; import org.nuiton.topia.TopiaContext; import org.nuiton.topia.TopiaContextFactory; import org.nuiton.topia.TopiaException; @@ -44,92 +47,94 @@ import org.nuiton.topiatest.Employe; import org.nuiton.topiatest.EmployeDAO; import org.nuiton.util.FileUtil; -import org.hibernate.cfg.Environment; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import java.io.File; +import java.io.IOException; +import java.util.Properties; + /** * Test de visitor. * * @author chatellier * @version $Revision$ - * - * Last update : $Date$ - * By : $Author$ + * <p/> + * Last update : $Date$ + * By : $Author$ */ public class EntityVisitorExportXmlTest { private static Log log = LogFactory.getLog(EntityVisitorExportXmlTest.class); - + protected static File tempDir; - + protected static Properties config; - + /** * Init les données de tous les tests. - * @throws IOException + * + * @throws IOException */ @BeforeClass public static void init() throws IOException { - - File tmpDirectory = new File("target"); - tempDir = FileUtil.createTempDirectory("h2", "-exportxml", tmpDirectory); - + + + File testBasedir = TestHelper.getTestBasedir(EntityVisitorExportXmlTest.class); + + tempDir = FileUtil.createTempDirectory("h2", "-exportxml", testBasedir); + // init dburl String dburl = "file:" + tempDir.getAbsolutePath() + File.separator + "data"; - + // init config - + config = new Properties(); - config.setProperty("topia.persistence.classes",TopiaTestDAOHelper.getImplementationClassesAsString()); + 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:" + dburl); + config.setProperty(Environment.DIALECT, "org.hibernate.dialect.H2Dialect"); + config.setProperty(Environment.DRIVER, "org.h2.Driver"); + config.setProperty(Environment.URL, "jdbc:h2:" + dburl); } - /** - * Remove temp directory - */ + /** Remove temp directory */ @AfterClass public static void clear() { - FileUtil.deleteRecursively(tempDir); + // tchemit 2010-11-28 No! never delete tests data, how to see what's happening if something is wrong ??? +// FileUtil.deleteRecursively(tempDir); } - + /** * Prepare test. - * + * <p/> * Add all tests commons data - * @throws TopiaException + * + * @throws TopiaException */ @Before public void setUp() throws TopiaException { TopiaContext context = TopiaContextFactory.getContext(config); context.createSchema(); - + addData(context); } - + /** * Add tests data. + * * @param context the context to add * @throws TopiaException */ protected void addData(TopiaContext context) throws TopiaException { - + TopiaContext newContext = context.beginTransaction(); // company CompanyDAO companyDAO = TopiaTestDAOHelper.getCompanyDAO(newContext); Company clCompany = companyDAO.create(); clCompany.setName("CodeLutin"); - + // employe EmployeDAO employeDAO = TopiaTestDAOHelper.getEmployeDAO(newContext); Employe empl1 = employeDAO.create(); @@ -141,7 +146,7 @@ addr1.setCity("nantes"); addr1.setAdress("bd des pas enchantés"); empl1.setAddress(addr1); - + Employe empl2 = employeDAO.create(); empl2.setName("boss2"); empl2.setSalary(29000); @@ -149,55 +154,54 @@ addr2.setCity("nantes"); addr2.setAdress("bd des pas enchantés"); empl2.setAddress(addr2); - + // departement DepartmentDAO departmentDAO = TopiaTestDAOHelper.getDepartmentDAO(newContext); Department depComm = departmentDAO.create(); depComm.setName("Commercial"); depComm.setLeader(empl1); - + Department depDev = departmentDAO.create(); depDev.setName("Dev"); depDev.setLeader(empl2); clCompany.addDepartment(depComm); clCompany.addDepartment(depDev); - + newContext.commitTransaction(); newContext.closeContext(); } - /** - * Clean tests. - */ + /** Clean tests. */ @After public void tearDown() { - if(tempDir.exists()) { - tempDir.delete(); - } + // tchemit 2010-11-28 No! never delete tests data, how to see what's happening if something is wrong ??? +// if(tempDir.exists()) { +// tempDir.delete(); +// } } - + /** * Test l'export XML via un visiteur. - * + * <p/> * Parcourt en profondeur. - * - * @throws TopiaException + * + * @throws TopiaException */ @Test public void testExportXMLDepth() throws TopiaException { TopiaContext rootContext = TopiaContextFactory.getContext(config); - + TopiaContext context = rootContext.beginTransaction(); - + CompanyDAO companyDAO = TopiaTestDAOHelper.getCompanyDAO(context); Company clCompany = companyDAO.findByName("CodeLutin"); - + EntityVisitor delegateVisitor = new ExportXMLVisitor(); EntityVisitor visitor = new DepthEntityVisitor(delegateVisitor); clCompany.accept(visitor); context.closeContext(); - - if(log.isInfoEnabled()) { + + if (log.isInfoEnabled()) { log.info("Export XML = \n" + delegateVisitor.toString()); } } Modified: trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/NaturalIdTest.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/NaturalIdTest.java 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/NaturalIdTest.java 2010-11-28 20:17:13 UTC (rev 2156) @@ -28,54 +28,54 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.PropertyValueException; -import org.junit.After; -import org.junit.AfterClass; import org.junit.Assert; -import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; +import org.nuiton.topia.TestHelper; import org.nuiton.topia.TopiaContext; import org.nuiton.topia.TopiaException; +import org.nuiton.topia.TopiaNotFoundException; import org.nuiton.topia.TopiaTestDAOHelper; import org.nuiton.topiatest.NaturalizedEntity; import org.nuiton.topiatest.NaturalizedEntityDAO; -import org.nuiton.topiatest.TestUtils; +import java.io.File; +import java.io.IOException; + /** * NaturalIdTest - * + * <p/> * Created: 18 févr. 2010 * * @author fdesbois * @version $Revision$ - * - * Mise a jour: $Date$ - * par : $Author$ + * <p/> + * Mise a jour: $Date$ + * par : $Author$ */ public class NaturalIdTest { private static final Log log = LogFactory.getLog(NaturalIdTest.class); + protected static File testBasedir; + @BeforeClass public static void setUpClass() throws Exception { - } - @AfterClass - public static void tearDownClass() throws Exception { + testBasedir = TestHelper.getTestBasedir(NaturalIdTest.class); } - @Before - public void setUp() throws Exception { + protected TopiaContext initTopiaContext(String testName) throws IOException, TopiaNotFoundException { + TopiaContext root = TestHelper.initTopiaContext(testBasedir, + "/TopiaContextImpl.properties", + testName); + return root; } - @After - public void tearDown() throws Exception { - } - @Test public void testCreateSucessfull() throws Exception { - log.info("Test naturalId : create succesfull"); - TopiaContext root = TestUtils.start("naturalIdTest/createSucessfull"); + log.debug("Test naturalId : create succesfull"); + TopiaContext root = initTopiaContext("createSucessfull"); TopiaContext transaction = root.beginTransaction(); NaturalizedEntityDAO dao = @@ -90,14 +90,14 @@ dao.create(NaturalizedEntity.PROPERTY_NATURAL_ID_NOT_NULL, 3); transaction.commitTransaction(); - transaction.closeContext(); + transaction.closeContext(); root.closeContext(); } @Test public void testCreateFailed() throws Exception { - log.info("Test naturalId : create failed"); - TopiaContext root = TestUtils.start("naturalIdTest/createFailed"); + log.debug("Test naturalId : create failed"); + TopiaContext root = initTopiaContext("createFailed"); TopiaContext transaction = root.beginTransaction(); NaturalizedEntityDAO dao = @@ -113,22 +113,22 @@ } catch (PropertyValueException eee) { Assert.assertEquals("naturalIdNotNull", eee.getPropertyName()); } - + transaction.closeContext(); root.closeContext(); } @Test public void testUpdateFailed() throws Exception { - log.info("Test naturalId : update failed"); - TopiaContext root = TestUtils.start("naturalIdTest/updateFailed"); + log.debug("Test naturalId : update failed"); + TopiaContext root = initTopiaContext("updateFailed"); TopiaContext transaction = root.beginTransaction(); NaturalizedEntityDAO dao = TopiaTestDAOHelper.getNaturalizedEntityDAO(transaction); - NaturalizedEntity entity = + NaturalizedEntity entity = dao.create(NaturalizedEntity.PROPERTY_NATURAL_ID_NOT_NULL, 5, NaturalizedEntity.PROPERTY_NATURAL_ID_NULL, "str"); transaction.commitTransaction(); @@ -137,9 +137,9 @@ try { entity.setNaturalIdNotNull(8); transaction.commitTransaction(); - } catch(TopiaException eee) { + } catch (TopiaException eee) { Assert.assertEquals("org.hibernate.HibernateException", - eee.getCause().getClass().getName()); + eee.getCause().getClass().getName()); } finally { transaction.closeContext(); root.closeContext(); @@ -148,8 +148,8 @@ @Test public void testFindByNaturalId() throws Exception { - log.info("Test naturalId : findByNaturalId"); - TopiaContext root = TestUtils.start("naturalIdTest/findByNaturalId"); + log.debug("Test naturalId : findByNaturalId"); + TopiaContext root = initTopiaContext("findByNaturalId"); TopiaContext transaction = root.beginTransaction(); NaturalizedEntityDAO dao = @@ -163,15 +163,15 @@ NaturalizedEntity result = dao.findByNaturalId(5, "str"); Assert.assertEquals(entity, result); - + transaction.closeContext(); root.closeContext(); } @Test public void testExistNaturalId() throws Exception { - log.info("Test naturalId : existNaturalId"); - TopiaContext root = TestUtils.start("naturalIdTest/existNaturalId"); + log.debug("Test naturalId : existNaturalId"); + TopiaContext root = initTopiaContext("existNaturalId"); TopiaContext transaction = root.beginTransaction(); NaturalizedEntityDAO dao = @@ -189,7 +189,7 @@ result = dao.existByNaturalId(8, "str"); Assert.assertFalse(result); - + transaction.closeContext(); root.closeContext(); } Modified: trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/TopiaDAOTest.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/TopiaDAOTest.java 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/TopiaDAOTest.java 2010-11-28 20:17:13 UTC (rev 2156) @@ -25,63 +25,75 @@ package org.nuiton.topia.persistence; -import java.io.IOException; -import java.net.URL; -import java.util.List; -import java.util.Properties; - import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.junit.Assert; +import org.junit.BeforeClass; import org.junit.Test; import org.junit.matchers.JUnitMatchers; +import org.nuiton.topia.TestHelper; import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaContextFactory; import org.nuiton.topia.TopiaException; import org.nuiton.topia.TopiaTestDAOHelper; import org.nuiton.topia.framework.TopiaUtilTest; import org.nuiton.topia.test.entities.Person; import org.nuiton.topia.test.entities.PersonDAO; -import org.nuiton.util.Resource; +import java.io.File; +import java.io.IOException; +import java.util.List; + /** * Test on {@link TopiaDAO}. - * + * * @author chatellier * @version $Revision$ - * - * Last update : $Date$ - * By : $Author$ + * <p/> + * Last update : $Date$ + * By : $Author$ */ public class TopiaDAOTest { private static final Log log = LogFactory.getLog(TopiaUtilTest.class); - protected TopiaContext getRootContext() throws TopiaException, IOException { - Properties conf = new Properties(); - URL url = Resource.getURL("TopiaContextImpl.properties"); - if (log.isDebugEnabled()) { - log.debug(url); - } - conf.load(url.openStream()); - conf.setProperty("hibernate.connection.url", "jdbc:h2:file://tmp/topiautiltest_" + System.currentTimeMillis()); - conf.setProperty("topia.persistence.classes", TopiaTestDAOHelper.getImplementationClassesAsString()); + protected static File testBasedir; - TopiaContext rootContext = (TopiaContext) TopiaContextFactory.getContext(conf); - return rootContext; + @BeforeClass + public static void setUpClass() throws Exception { + + testBasedir = TestHelper.getTestBasedir(TopiaDAOTest.class); } - + +// protected TopiaContext getRootContext() throws TopiaException, IOException { +// Properties conf = new Properties(); +// URL url = Resource.getURL("TopiaContextImpl.properties"); +// if (log.isDebugEnabled()) { +// log.debug(url); +// } +// conf.load(url.openStream()); +// conf.setProperty("hibernate.connection.url", "jdbc:h2:file://tmp/topiautiltest_" + System.currentTimeMillis()); +// conf.setProperty("topia.persistence.classes", TopiaTestDAOHelper.getImplementationClassesAsString()); +// +// TopiaContext rootContext = TopiaContextFactory.getContext(conf); +// return rootContext; +// } + /** * Test de creer une entité et de verifier qu'elle est * présente dans la persistence au sein de la transaction. - * - * @throws TopiaException - * @throws IOException + * + * @throws TopiaException + * @throws IOException */ @Test public void testCreateAndFindInTransaction() throws TopiaException, IOException { - TopiaContext rootContext = getRootContext(); + TopiaContext rootContext = TestHelper.initTopiaContext( + testBasedir, + "/TopiaContextImpl.properties", + "testCreateAndFindInTransaction" + ); + TopiaContext context = rootContext.beginTransaction(); PersonDAO personDAO = TopiaTestDAOHelper.getPersonDAO(context); Modified: 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 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-persistence/src/test/java/org/nuiton/topia/persistence/util/CollectorTest.java 2010-11-28 20:17:13 UTC (rev 2156) @@ -25,27 +25,29 @@ 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.junit.Assert; 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.topia.persistence.TopiaEntity; -import org.nuiton.topia.persistence.util.Collector.CollectorVisitor; 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> - */ +/** @author tchemit <chemit@codelutin.com> */ public class CollectorTest { + + private static Log log = LogFactory.getLog(CollectorTest.class); + + static TopiaEntityEnum[] contracts; @BeforeClass @@ -77,19 +79,19 @@ } @Override - protected void onStarted(TopiaEntity e,boolean enter) { - super.onStarted(e,enter); + protected void onStarted(TopiaEntity e, boolean enter) { + super.onStarted(e, enter); int level = stackSize(); - System.out.println(String.format("(%1$2d) %2$" + level * 2 + "s %3$s", level, ">>", getStack())); + 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); + protected void onEnded(TopiaEntity e, boolean enter) { + super.onEnded(e, enter); int level = stackSize() + 1; - System.out.println(String.format("(%1$2d) %2$" + level * 2 + "s %3$s", level, "<<", getStack())); + log.info(String.format("(%1$2d) %2$" + level * 2 + "s %3$s", level, "<<", getStack())); } }; @@ -112,7 +114,9 @@ detect(detector, 1, company); } - protected void detect(Collector<Integer> detector, int expectedResult, TopiaEntity... entities) throws TopiaException { + 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/topiatest/TestUtils.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topiatest/TestUtils.java 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-persistence/src/test/java/org/nuiton/topiatest/TestUtils.java 2010-11-28 20:17:13 UTC (rev 2156) @@ -1,82 +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.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.Ignore; -import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaContextFactory; -import org.nuiton.topia.TopiaNotFoundException; -import org.nuiton.topia.TopiaTestDAOHelper; - -import java.io.IOException; -import java.io.InputStream; -import java.util.Properties; - -/** - * TestUtils - * <p/> - * Created: 18 févr. 2010 - * - * @author fdesbois - * @version $Revision$ - * <p/> - * Mise a jour: $Date$ - * par : $Author$ - */ -@Ignore -public class TestUtils { - - /** Logger */ - private static final Log log = LogFactory.getLog(TestUtils.class); - - public static TopiaContext start(String dbname) - throws IOException, TopiaNotFoundException { - - InputStream stream = TestUtils.class.getResourceAsStream( - "/TopiaContextImpl.properties"); - - Properties configuration = new Properties(); - - configuration.load(stream); - configuration.setProperty( - "topia.persistence.classes", - TopiaTestDAOHelper.getImplementationClassesAsString()); - - // make sure we always use a different directory - - String dbPath = "target/surefire-data/" + dbname + '_' + - System.nanoTime(); - if (log.isInfoEnabled()) { - log.info("dbPath = " + dbPath); - } - configuration.setProperty( - "hibernate.connection.url", - "jdbc:h2:file:" + dbPath); - return TopiaContextFactory.getContext(configuration); - } -} Modified: trunk/topia-persistence/src/test/java/org/nuiton/topiatest/deletetest/DeleteEntityTest.java =================================================================== --- trunk/topia-persistence/src/test/java/org/nuiton/topiatest/deletetest/DeleteEntityTest.java 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-persistence/src/test/java/org/nuiton/topiatest/deletetest/DeleteEntityTest.java 2010-11-28 20:17:13 UTC (rev 2156) @@ -40,22 +40,18 @@ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.junit.After; import org.junit.AfterClass; -import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; +import org.nuiton.topia.TestHelper; import org.nuiton.topia.TopiaContext; -import org.nuiton.topia.TopiaContextFactory; import org.nuiton.topia.TopiaException; import org.nuiton.topia.TopiaTestDAOHelper; import org.nuiton.topia.generator.DAOAbstractTransformer; import org.nuiton.topiatest.Personne; import org.nuiton.topiatest.PersonneDAO; -import org.nuiton.util.Resource; -import java.net.URL; -import java.util.Properties; +import java.io.File; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -74,27 +70,34 @@ private static final Log log = LogFactory.getLog(DeleteEntityTest.class); - public DeleteEntityTest() { - } + protected static File testBasedir; + @BeforeClass public static void setUpClass() throws Exception { - try { - Properties conf = new Properties(); - URL url = Resource.getURL("TopiaContextImpl.properties"); - if (log.isDebugEnabled()) { - log.debug(url); - } - conf.load(url.openStream()); - conf.setProperty("topia.persistence.classes", TopiaTestDAOHelper.getImplementationClassesAsString()); - rootContext = TopiaContextFactory.getContext(conf); - if (log.isInfoEnabled()) { - log.info("Context Ready !"); - } - } catch (Exception ex) { - log.error("Initialize error !!", ex); - } + testBasedir = TestHelper.getTestBasedir(DeleteEntityTest.class); + + rootContext = TestHelper.initTopiaContext(testBasedir, + "/TopiaContextImpl.properties", + "deleteEntityDb"); +// +// try { +// Properties conf = new Properties(); +// URL url = Resource.getURL("TopiaContextImpl.properties"); +// if (log.isDebugEnabled()) { +// log.debug(url); +// } +// conf.load(url.openStream()); +// conf.setProperty("topia.persistence.classes", TopiaTestDAOHelper.getImplementationClassesAsString()); +// +// rootContext = TopiaContextFactory.getContext(conf); +// if (log.isInfoEnabled()) { +// log.info("Context Ready !"); +// } +// } catch (Exception ex) { +// log.error("Initialize error !!", ex); +// } } @@ -103,14 +106,6 @@ rootContext.closeContext(); } - @Before - public void setUp() { - } - - @After - public void tearDown() { - } - /** * Test for deleting entities with inheritance. Delete from the DAO linked * with the subclass entity and from the DAO linked with the superclass Modified: trunk/topia-persistence/src/test/resources/TopiaContextImpl.properties =================================================================== --- trunk/topia-persistence/src/test/resources/TopiaContextImpl.properties 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-persistence/src/test/resources/TopiaContextImpl.properties 2010-11-28 20:17:13 UTC (rev 2156) @@ -30,4 +30,5 @@ hibernate.connection.username=sa hibernate.connection.password= hibernate.connection.driver_class=org.h2.Driver -hibernate.connection.url=jdbc:h2:file:target/surefire-data/h2data \ No newline at end of file +# tchemit 2010-11-28 : comment this line, each test must define his own db path +#hibernate.connection.url=jdbc:h2:file:target/surefire-workdir/h2data \ No newline at end of file Modified: trunk/topia-service-migration/pom.xml =================================================================== --- trunk/topia-service-migration/pom.xml 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-service-migration/pom.xml 2010-11-28 20:17:13 UTC (rev 2156) @@ -37,7 +37,7 @@ <parent> <groupId>org.nuiton</groupId> <artifactId>topia</artifactId> - <version>2.4.4-SNAPSHOT</version> + <version>2.5-SNAPSHOT</version> </parent> <groupId>org.nuiton.topia</groupId> Modified: trunk/topia-service-replication/pom.xml =================================================================== --- trunk/topia-service-replication/pom.xml 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-service-replication/pom.xml 2010-11-28 20:17:13 UTC (rev 2156) @@ -37,7 +37,7 @@ <parent> <groupId>org.nuiton</groupId> <artifactId>topia</artifactId> - <version>2.4.4-SNAPSHOT</version> + <version>2.5-SNAPSHOT</version> </parent> <groupId>org.nuiton.topia</groupId> Modified: trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/AbstractTopiaReplicationServiceTest.java =================================================================== --- trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/AbstractTopiaReplicationServiceTest.java 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/AbstractTopiaReplicationServiceTest.java 2010-11-28 20:17:13 UTC (rev 2156) @@ -124,7 +124,7 @@ protected TopiaReplicationModelBuilder getModelBuilder() { - return (TopiaReplicationModelBuilder) service.getModelBuilder(); + return service.getModelBuilder(); } protected abstract TopiaContext createDb2(String name) throws Exception; @@ -220,7 +220,7 @@ Set<?> detectTypes; - detectTypes = ((TopiaReplicationModelBuilder) service.getModelBuilder()).detectTypes(context, getContracts(), entity.getTopiaId()); + detectTypes = service.getModelBuilder().detectTypes(context, getContracts(), entity.getTopiaId()); assertEquals("expected types : " + Arrays.toString(expectedCouple) + " but was " + detectTypes, Modified: trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationOperationTest.java =================================================================== --- trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationOperationTest.java 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationOperationTest.java 2010-11-28 20:17:13 UTC (rev 2156) @@ -30,7 +30,9 @@ import org.junit.After; import org.junit.AfterClass; import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; +import org.nuiton.topia.TestHelper; import org.nuiton.topia.TopiaContext; import org.nuiton.topia.TopiaContextFactory; import org.nuiton.topia.TopiaTestDAOHelper.TopiaTestEntityEnum; @@ -51,6 +53,7 @@ import org.nuiton.topia.test.entities.RaceImpl; import java.io.File; +import java.io.IOException; import java.util.Properties; /** @@ -84,6 +87,14 @@ static protected Race race, race2; + protected static File tesDir; + + @BeforeClass + public static void beforeClass() throws IOException { + tesDir = TestHelper.getTestBasedir(TopiaReplicationOperationTest.class); + + } + @AfterClass public static void after() throws Exception { AbstractTopiaReplicationServiceTest.after(); @@ -267,9 +278,9 @@ @Override protected TopiaContext createDb(String name) throws Exception { - File localDB = new File(getTestDir(getClass()), "db_" + name); +// File localDB = new File(getTestDir(getClass()), "db_" + name); - Properties config = getH2Properties(localDB); + Properties config = getH2Properties(name); context = TopiaContextFactory.getContext(config); @@ -299,18 +310,19 @@ return log; } - protected Properties getH2Properties(File f) { + protected Properties getH2Properties(String dbName) throws IOException { - Properties config = new Properties(); - config.setProperty("hibernate.show_sql", "false"); - config.setProperty("hibernate.hbm2ddl.auto", "create"); + Properties config = TestHelper.initTopiaContextConfiguration(tesDir, dbName); +// config.setProperty("hibernate.show_sql", "false"); +// config.setProperty("hibernate.hbm2ddl.auto", "create"); + config.setProperty("topia.persistence.classes", entitiesList); - config.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); - config.setProperty("hibernate.connection.driver_class", "org.h2.Driver"); - config.setProperty("hibernate.connection.url", "jdbc:h2:file:" + f.getAbsolutePath() + ";create=true"); - config.setProperty("hibernate.connection.username", "sa"); - config.setProperty("hibernate.connection.password", ""); +// config.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); +// config.setProperty("hibernate.connection.driver_class", "org.h2.Driver"); +// config.setProperty("hibernate.connection.url", "jdbc:h2:file:" + f.getAbsolutePath() + ";create=true"); +// config.setProperty("hibernate.connection.username", "sa"); +// config.setProperty("hibernate.connection.password", ""); config.setProperty("topia.service.replication", TopiaReplicationServiceImpl.class.getName()); Modified: trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplAllTest.java =================================================================== --- trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplAllTest.java 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplAllTest.java 2010-11-28 20:17:13 UTC (rev 2156) @@ -30,7 +30,9 @@ import org.junit.After; import org.junit.AfterClass; import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; +import org.nuiton.topia.TestHelper; import org.nuiton.topia.TopiaContext; import org.nuiton.topia.TopiaContextFactory; import org.nuiton.topia.TopiaException; @@ -46,6 +48,7 @@ import org.nuiton.topia.test.entities.RaceImpl; import java.io.File; +import java.io.IOException; import java.util.Properties; /** @@ -78,6 +81,13 @@ static protected Race race, race2, race3; + protected static File tesDir; + + @BeforeClass + public static void beforeClass() throws IOException { + tesDir = TestHelper.getTestBasedir(TopiaReplicationServiceImplAllTest.class); + } + @AfterClass public static void after() throws Exception { AbstractTopiaReplicationServiceTest.after(); @@ -218,9 +228,9 @@ @Override protected TopiaContext createDb(String name) throws Exception { - File localDB = new File(getTestDir(getClass()), "db_" + name); +// File localDB = new File(getTestDir(getClass()), "db_" + name); - Properties config = getH2Properties(localDB); + Properties config = getH2Properties(name); context = TopiaContextFactory.getContext(config); @@ -245,9 +255,9 @@ @Override protected TopiaContext createDb2(String name) throws Exception { - File localDB = new File(getTestDir(getClass()), "db_" + name); +// File localDB = new File(getTestDir(getClass()), "db_" + name); - Properties config = getH2Properties(localDB); + Properties config = getH2Properties(name); return TopiaContextFactory.getContext(config); } @@ -262,18 +272,19 @@ return log; } - protected Properties getH2Properties(File f) { + protected Properties getH2Properties(String dbName) throws IOException { - Properties config = new Properties(); - config.setProperty("hibernate.show_sql", "false"); - config.setProperty("hibernate.hbm2ddl.auto", "create"); + Properties config = TestHelper.initTopiaContextConfiguration(tesDir, dbName); +// config.setProperty("hibernate.show_sql", "false"); +// config.setProperty("hibernate.hbm2ddl.auto", "create"); + config.setProperty("topia.persistence.classes", entitiesList); - config.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); - config.setProperty("hibernate.connection.driver_class", "org.h2.Driver"); - config.setProperty("hibernate.connection.url", "jdbc:h2:file:" + f.getAbsolutePath() + ";create=true"); - config.setProperty("hibernate.connection.username", "sa"); - config.setProperty("hibernate.connection.password", ""); +// config.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); +// config.setProperty("hibernate.connection.driver_class", "org.h2.Driver"); +// config.setProperty("hibernate.connection.url", "jdbc:h2:file:" + f.getAbsolutePath() + ";create=true"); +// config.setProperty("hibernate.connection.username", "sa"); +// config.setProperty("hibernate.connection.password", ""); config.setProperty(TopiaReplicationServiceImpl.TOPIA_SERVICE_NAME, TopiaReplicationServiceImpl.class.getName()); Modified: trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplTest.java =================================================================== --- trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplTest.java 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-service-replication/src/test/java/org/nuiton/topia/replication/TopiaReplicationServiceImplTest.java 2010-11-28 20:17:13 UTC (rev 2156) @@ -30,7 +30,9 @@ import org.junit.After; import org.junit.AfterClass; import org.junit.Before; +import org.junit.BeforeClass; import org.junit.Test; +import org.nuiton.topia.TestHelper; import org.nuiton.topia.TopiaContext; import org.nuiton.topia.TopiaContextFactory; import org.nuiton.topia.TopiaException; @@ -53,6 +55,7 @@ import org.nuiton.topia.test.entities.RaceImpl; import java.io.File; +import java.io.IOException; import java.util.Properties; /** @@ -79,6 +82,14 @@ static protected Race race, race2, race3; + protected static File tesDir; + + @BeforeClass + public static void beforeClass() throws IOException { + tesDir = TestHelper.getTestBasedir( + TopiaReplicationServiceImplTest.class); + } + @AfterClass public static void after() throws Exception { AbstractTopiaReplicationServiceTest.after(); @@ -378,9 +389,9 @@ @Override protected TopiaContext createDb(String name) throws Exception { - File localDB = new File(getTestDir(getClass()), "db_" + name); +// File localDB = new File(getTestDir(getClass()), "db_" + name); - Properties config = getH2Properties(localDB); + Properties config = getH2Properties(name); context = TopiaContextFactory.getContext(config); @@ -405,12 +416,12 @@ @Override protected TopiaContext createDb2(String name) throws Exception { - File localDB = new File(getTestDir(getClass()), "db_" + name); +// File localDB = new File(getTestDir(getClass()), "db_" + name); +// +// log.info("db dir :\n" + localDB.getAbsolutePath()); - log.info("db dir :\n" + localDB.getAbsolutePath()); + Properties config = getH2Properties(name); - Properties config = getH2Properties(localDB); - return TopiaContextFactory.getContext(config); } @@ -424,18 +435,20 @@ return log; } - protected Properties getH2Properties(File f) { + protected Properties getH2Properties(String dbName) throws IOException { - Properties config = new Properties(); - config.setProperty("hibernate.show_sql", "false"); - config.setProperty("hibernate.hbm2ddl.auto", "create"); + Properties config = TestHelper.initTopiaContextConfiguration(tesDir, dbName); + +// config.setProperty("hibernate.show_sql", "false"); +// config.setProperty("hibernate.hbm2ddl.auto", "create"); + config.setProperty("topia.persistence.classes", entitiesList); - config.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); - config.setProperty("hibernate.connection.driver_class", "org.h2.Driver"); - config.setProperty("hibernate.connection.url", "jdbc:h2:file:" + f.getAbsolutePath() + "/db;create=true"); - config.setProperty("hibernate.connection.username", "sa"); - config.setProperty("hibernate.connection.password", ""); +// config.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect"); +// config.setProperty("hibernate.connection.driver_class", "org.h2.Driver"); +// config.setProperty("hibernate.connection.url", "jdbc:h2:file:" + f.getAbsolutePath() + "/db;create=true"); +// config.setProperty("hibernate.connection.username", "sa"); +// config.setProperty("hibernate.connection.password", ""); config.setProperty(TopiaReplicationServiceImpl.TOPIA_SERVICE_NAME, TopiaReplicationServiceImpl.class.getName()); Modified: trunk/topia-service-security/pom.xml =================================================================== --- trunk/topia-service-security/pom.xml 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-service-security/pom.xml 2010-11-28 20:17:13 UTC (rev 2156) @@ -37,7 +37,7 @@ <parent> <groupId>org.nuiton</groupId> <artifactId>topia</artifactId> - <version>2.4.4-SNAPSHOT</version> + <version>2.5-SNAPSHOT</version> </parent> <groupId>org.nuiton.topia</groupId> Modified: trunk/topia-service-security/src/test/java/org/nuiton/topia/TestUtils.java =================================================================== --- trunk/topia-service-security/src/test/java/org/nuiton/topia/TestUtils.java 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-service-security/src/test/java/org/nuiton/topia/TestUtils.java 2010-11-28 20:17:13 UTC (rev 2156) @@ -35,7 +35,9 @@ * @author Chatellier Eric * * Last update : $Date$ + * @deprecated since 2.5, everything usefull already exists in the class {@link TestHelper} from {@code topia-persistence module}. */ +@Deprecated public abstract class TestUtils { protected static File basedir; Modified: trunk/topia-service-security/src/test/java/org/nuiton/topia/security/TopiaSecurityTest.java =================================================================== --- trunk/topia-service-security/src/test/java/org/nuiton/topia/security/TopiaSecurityTest.java 2010-11-27 18:35:20 UTC (rev 2155) +++ trunk/topia-service-security/src/test/java/org/nuiton/topia/security/TopiaSecurityTest.java 2010-11-28 20:17:13 UTC (rev 2156) @@ -34,7 +34,8 @@ import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; -import org.nuiton.topia.TestUtils; +import org.nuiton.i18n.I18n; +import org.nuiton.topia.TestHelper; import org.nuiton.topia.TopiaContext; import org.nuiton.topia.TopiaContextFactory; import org.nuiton.topia.TopiaException; @@ -63,9 +64,11 @@ import javax.security.auth.Subject; import javax.security.auth.login.LoginContext; import java.io.File; +import java.io.IOException; import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.List; +import java.util.Locale; import java.util.Properties; import static org.nuiton.topia.security.util.TopiaSecurityUtil.LOAD; @@ -89,24 +92,32 @@ // FIXME comment il trouve les autres tout seul ? // The grande question !!! + + protected static File tesDir; + protected static String entitiesList = PersonImpl.class.getName() + "," + - PetImpl.class.getName() + "," + - RaceImpl.class.getName(); + PetImpl.class.getName() + "," + + RaceImpl.class.getName(); @BeforeClass public static void init() throws Exception { - TestUtils.init(); + I18n.init(Locale.FRANCE); + tesDir = TestHelper.getTestBasedir(TopiaSecurityTest.class); + } @AfterClass public static void clean() { - TestUtils.clean(); + // tchemit 2010-11-28 : no never delete data after a test... +// TestUtils.clean(); } @Ignore protected Properties getProperties() { Properties config = new Properties(); +// Properties config = TestHelper.initTopiaContextConfiguration(tesDir,"topia-security"); + if (log.isDebugEnabled()) { config.setProperty("hibernate.show_sql", "true"); } @@ -118,7 +129,7 @@ config.setProperty("hibernate.connection.password", ""); config.setProperty("hibernate.connection.driver_class", "org.h2.Driver"); - config.setProperty("hibernate.connection.url", "jdbc:h2:" + TestUtils.getDirDatabase().getAbsolutePath() + File.separator + "topia-security"); + config.setProperty("hibernate.connection.url", "jdbc:h2:" + new File(tesDir, "topia-security")); // add this to use security service config.setProperty("topia.service.security", "org.nuiton.topia.security.TopiaSecurityServiceImpl");