Author: bleny Date: 2010-08-09 16:12:47 +0200 (Mon, 09 Aug 2010) New Revision: 241 Url: http://nuiton.org/repositories/revision/wikitty/241 Log: migrating generators using new EUGene feature : transformers Removed: branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/BusinessEntityAbstractGenerator.java branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/BusinessEntityImplGenerator.java branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/BusinessEntityInterfaceGenerator.java branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/EnumGenerator.java branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/EugengoConstants.java branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/EugengoUtils.java branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/InterfaceGenerator.java branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/WikengoCommonGenerator.java branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/WikittyHelperGenerator.java Modified: branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/WikittyMetaGenerator.java Deleted: branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/BusinessEntityAbstractGenerator.java =================================================================== --- branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/BusinessEntityAbstractGenerator.java 2010-08-06 14:41:51 UTC (rev 240) +++ branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/BusinessEntityAbstractGenerator.java 2010-08-09 14:12:47 UTC (rev 241) @@ -1,472 +0,0 @@ -package org.nuiton.wikitty.generator; - -import java.io.File; -import java.io.IOException; -import java.io.Writer; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.eugene.GeneratorUtil; -import org.nuiton.eugene.models.object.ObjectModelAttribute; -import org.nuiton.eugene.models.object.ObjectModelClass; - -/** - * Possible enhancement: - * - generateParentMethod can generate attribut method access that call - * the same method on parent instance class. For that we must have one attribut - * instance by parent. This attribut we must be created in setWikitty method - * and used same wikitty object. - * - * @author poussin - */ -public class BusinessEntityAbstractGenerator extends WikengoCommonGenerator { - - private static final Log log = LogFactory.getLog(BusinessEntityAbstractGenerator.class); - - static protected Pattern extractTypeOnCollection = Pattern.compile("\\w*<(\\w+)>"); - - protected String EXT_NAME; - - @Override - public String getFilenameForClass(ObjectModelClass clazz) { - String fqn = clazz.getQualifiedName(); - log.info( "Filename for " + clazz.getName() + " is " + fqn.replace('.', File.separatorChar) + ".java"); - return fqn.replace('.', File.separatorChar) + "Abstract.java"; - } - - public void generateFromClass(Writer output, ObjectModelClass clazz) - throws IOException { - if (!EugengoUtils.isBusinessEntity(clazz)) { - log.info( clazz.getName() + " is not a business entity"); - return; - } - - log.info("Generate Business entity abstract" + clazz.getName() + "... "); - generateCopyright(output); - - EXT_NAME = "EXT_" + clazz.getName().toUpperCase(); - - String packageName = clazz.getPackageName(); - String name = clazz.getName() + "Abstract"; -/*{package <%=packageName%>; - -}*/ - ObjectModelClass superClass = findSuperClass(clazz); - - clearImports(); - addImport(clazz); - addImport(superClass); - addImport("org.nuiton.wikitty.WikittyUtil"); - addImport("org.nuiton.wikitty.Wikitty"); - addImport("org.nuiton.wikitty.BusinessEntityWikitty"); - addImport("org.nuiton.wikitty.WikittyExtension"); - addImport(Collection.class); - addImport(Collections.class); - addImport(List.class); - addImport(ArrayList.class); - String parentImpl = null; - for (ObjectModelClass parent : clazz.getSuperclasses()) { - if (EugengoUtils.isBusinessEntity(parent)) { - addImport(parent); - parentImpl = parent.getQualifiedName() + "Impl"; - addImport(parentImpl); - addImport(parent.getQualifiedName() + "Abstract"); - } - } - lookForAttributeImports(clazz); - generateImports(output, packageName); - - generateClazzDocumentation(output, clazz); - String extendsString = " extends " + getType( parentImpl != null ? parentImpl : "org.nuiton.wikitty.BusinessEntityWikitty" ); - - String implementsString = "implements " + getType(clazz.getQualifiedName()); - for (ObjectModelClass parent : clazz.getSuperclasses()) { - if (EugengoUtils.isBusinessEntity(parent)) { - implementsString += ", " + getType(parent.getQualifiedName()); - } - } - -/*{public abstract class <%=name%><%=extendsString%> <%=implementsString%> { - -}*/ - - String svUID = GeneratorUtil.computeSerialVersionUID(clazz); -/*{ private static final long serialVersionUID = <%=svUID%>; - -}*/ - - generateWikittyExtension(output, clazz); - - generateStaticAttributes(output, clazz); - -/*{ - public <%=name%>() { - super(); - } - - public <%=name%>(BusinessEntityWikitty wi) { - super(wi.getWikitty()); - } - - public <%=name%>(Wikitty wi) { - super(wi); - } - -}*/ - - generateAttributeAccessMethod(output, clazz); - - for (ObjectModelClass parent : clazz.getSuperclasses()) { - if (EugengoUtils.isBusinessEntity(parent)) { - generateParentMethod(output, parent); - } - } - -/*{ @Override - public Collection<WikittyExtension> getStaticExtensions() { - return extensions; - } - - /** - * Check equality on all field of this extension, and only those. - *) - static public boolean equals(Wikitty w1, Wikitty w2) { - boolean result = true; -}*/ - for (ObjectModelAttribute attr : clazz.getAttributes()) { - if (attr.isNavigable() && !attr.isStatic() && - (attr.getStereotypes() == null || attr.getStereotypes().isEmpty())) { -/*{ if (result) { - Object f1 = w1.getFieldAsObject(<%=EXT_NAME%>, FIELD_<%=clazz.getName().toUpperCase()%>_<%=attr.getName().toUpperCase()%>); - Object f2 = w2.getFieldAsObject(<%=EXT_NAME%>, FIELD_<%=clazz.getName().toUpperCase()%>_<%=attr.getName().toUpperCase()%>); - result = f1 == f2 || (f1 != null && f1.equals(f2)); - } -}*/ - } - } -/*{ - return result; - } - -} //<%=name%> -}*/ - - } - - - - // Utilitarian methods - - public void generateAttributeAccessMethod(Writer output, ObjectModelClass clazz) throws IOException { - for (ObjectModelAttribute attr : clazz.getAttributes()) { - if (attr.isNavigable() && !attr.isStatic() - && (attr.getStereotypes() == null || attr.getStereotypes().isEmpty())) { - if ((attr.getMaxMultiplicity() != 0 && attr.getMaxMultiplicity() != 1)) { - //TODO ymartel 20090812: when dataType "List", "Set" or "Collection" in model, must be here! - generateCollectionAttributeAccessors(output, clazz, attr); - } else { - generateWikittyAttributeAccessors(output, clazz, attr); - } - } - } - } - - private void generateWikittyExtension(Writer output, - ObjectModelClass clazz) throws IOException { - String version = clazz.getTagValue("version"); - - // Since wikitty 1.3, version need to be dotted - if ( version == null ) { - version = "1.0"; - } - - // get requires from parent - String requires = null; - String separator = ""; - for (ObjectModelClass parent : clazz.getSuperclasses()) { - if (EugengoUtils.isBusinessEntity(parent)) { - String parentExtName = "EXT_" + parent.getName().toUpperCase(); - - if (requires == null) { - requires = ""; - } - - requires += separator + parent.getName() + "." + parentExtName; - // dans le cas où on aurait un heritage multiple :) - // FIXME EC-20100420 gerer les extensions multiples - separator = " + \",\" /* FIXME Multiples extentions are not yet supported */ + "; - } - } - -/*{ static final public List<WikittyExtension> extensions; - static final public WikittyExtension extension<%=clazz.getName()%> = - new WikittyExtension(<%=EXT_NAME%>, "<%=version%>", <%=requires%>, - WikittyUtil.buildFieldMapExtension(}*/ - - separator = ""; - for (ObjectModelAttribute attr : clazz.getAttributes()) { - if (attr.isNavigable() && !attr.isStatic() && - (attr.getStereotypes() == null || attr.getStereotypes().isEmpty())) { -/*{<%=separator%> - }*/ - generateAttribute(output, attr); - separator = ","; - } - } -/*{)); - static { - List<WikittyExtension> exts = new ArrayList<WikittyExtension>(); -}*/ - for (ObjectModelClass parent : clazz.getSuperclasses()) { - if (EugengoUtils.isBusinessEntity(parent)) { -/*{ - exts.addAll(<%=parent.getName()%>Abstract.extensions); -}*/ - } - } - - // EC-20100420 add current extension after parent ones - // if current is loaded before required extension - // load failed because required extension is missing -/*{ // current after requires ones - exts.add(extension<%=clazz.getName()%>); - - extensions = Collections.unmodifiableList(exts); - } -}*/ - } - - private void generateAttribute(Writer output, ObjectModelAttribute attr) - throws IOException { - String attrType = computeType(attr); - if (EugengoUtils.notEmpty(attrType)) { - attrType = getType(attrType); - } else { - return; - } - - String attrName = attr.getName(); - String card = ""; - - //TODO ymartel 20090812: a better way to manage those DataTypes in the model? - if (attrType.contains("Collection") || attrType.contains("List") || attrType.contains("Set")) { - card = "[0-*]"; - // List<String> - Matcher match = extractTypeOnCollection.matcher(attrType); - if (match.matches()) { - attrType = match.group(1); - } - } - - if (!commonTypes.contains(attrType)) { - attrType = "Wikitty"; - } else if(commonNumerics.contains(attrType)) { - attrType = "Numeric"; - } else if(commonStrings.contains(attrType)) { - attrType = "String"; - } - - - int maxMultiplicity = attr.getMaxMultiplicity(); - if ((maxMultiplicity != 0 && maxMultiplicity != 1)){ - card = "[" + attr.getMinMultiplicity() + "-"; - if (maxMultiplicity == -1) { - card += "*]"; - } else { - card += maxMultiplicity + "]"; - } - } - - // FIXME EC-20100420 attr.isUnique() always return true for - // attributes (maybe use tagValue instead) - String unique = ""; - boolean isCollection = (attr.getMaxMultiplicity() != 0 - && attr.getMaxMultiplicity() != 1); - if (isCollection && attr.isUnique()) { - unique = " unique=true"; - } - - String tagValues = ""; - for (String tag : attr.getTagValues().keySet()) { - String value = attr.getTagValue(tag); - value = value.replaceAll("\n", "\\n"); - value = value.replaceAll("\"", "\\\""); - - tagValues += " " + tag + "=\\\"" + value + "\\\""; - } - -/*{"<%=attrType%> <%=attrName%><%=card%><%=unique%><%=tagValues%>"}*/ - } - - private void generateParentMethod(Writer output, - ObjectModelClass clazz) throws IOException { - - // we must generate method for parent of parent - for (ObjectModelClass parent : clazz.getSuperclasses()) { - if (EugengoUtils.isBusinessEntity(parent)) { - generateParentMethod(output, parent); - } - } - - // generate method acces for parent attribut - generateAttributeAccessMethod(output, clazz); - } - - protected void generateWikittyAttributeAccessors(Writer output, - ObjectModelClass clazz, ObjectModelAttribute attr) throws IOException { - - EXT_NAME = "EXT_" + attr.getDeclaringElement().getName().toUpperCase(); - - String attrType = computeType(attr); - if (EugengoUtils.notEmpty(attrType)) { - attrType = getType(attrType, true); - } else { - return; - } - - // FIXME EC-20100421 cette methode peut retourner List<String> - // et generer la methode getWikitty().getFieldAsList<String>() - // qui ne peut pas compiler - String methodAccessName = getFieldAccessMethodName(attr); - - String attrName = attr.getName(); - String attrNameCapitalized = EugengoUtils.toUpperCaseFirstLetter(attrName); - -/*{ - public void set<%=attrNameCapitalized%>(<%=attrType%> <%=attrName%>) { - Object oldValue = getField(<%=EXT_NAME%>, FIELD_<%=clazz.getName().toUpperCase()%>_<%=attr.getName().toUpperCase()%>); - getWikitty().setField(<%=EXT_NAME%>, FIELD_<%=clazz.getName().toUpperCase()%>_<%=attr.getName().toUpperCase()%>, <%=attrName%>); - getPropertyChangeSupport().firePropertyChange(FIELD_<%=clazz.getName().toUpperCase()%>_<%=attr.getName().toUpperCase()%>, oldValue, <%=attrName%>); - } - - public <%=attrType%> get<%=attrNameCapitalized%>() { - <%=attrType%> result = getWikitty().getFieldAs<%=methodAccessName%>(<%=EXT_NAME%>, FIELD_<%=clazz.getName().toUpperCase()%>_<%=attr.getName().toUpperCase()%>); - return result; - } - -}*/ - } - - /** - * Give the string to put after getFieldAs???, only some type is accepted - * and we must convert BusinessEntity to Wikitty string - * @param type - * @return - */ - protected String getFieldAccessMethodName(ObjectModelAttribute attr) { - String result = computeType(attr); - result = getType(result, true); - - boolean isCollection = (attr.getMaxMultiplicity() != 0 - && attr.getMaxMultiplicity() != 1); - if (isCollection) { - if (attr.isUnique()) { - result = "Set"; - } else { - result = "List"; - } - } else { - // test for Date - if ("java.util.Date".equals(result) || "Date".equals(result)) { - result = "Date"; - } else if (getModel().hasClass(result)) { // test for Wikitty object - ObjectModelClass fieldClass = getModel().getClass(result); - if (EugengoUtils.isBusinessEntity(fieldClass)) { - // for wikittyDto we use String for Id - result = "Wikitty"; - } - } else if (null != getModel().getEnumeration(result)) { - result = "String"; - } - } - result = EugengoUtils.toUpperCaseFirstLetter(result); - - return result; - } - - protected void generateCollectionAttributeAccessors(Writer output, - ObjectModelClass clazz, ObjectModelAttribute attr) throws IOException { - - EXT_NAME = "EXT_" + attr.getDeclaringElement().getName().toUpperCase(); - - String attrType = computeType(attr); - if (EugengoUtils.notEmpty(attrType)) { - attrType = getType(attrType, true); - } else { - return; - } - - // get collection element type for add and remove method arguement type - String elementType = getType(attr.getType(), true); - - String methodAccessName = getFieldAccessMethodName(attr); - - String attrName = attr.getName(); - String attrNameCapitalized = EugengoUtils.toUpperCaseFirstLetter(attrName); -/*{ public <%=attrType%> get<%=attrNameCapitalized%>() { - <%=attrType%> result = getWikitty().getFieldAs<%=methodAccessName%>(<%=EXT_NAME%>, FIELD_<%=clazz.getName().toUpperCase()%>_<%=attr.getName().toUpperCase()%>, <%=getClassAndGeneric(attrType)[1]%>.class); - return result; - } - - public void add<%=attrNameCapitalized%>(<%=elementType%> element) { - getWikitty().addToField(<%=EXT_NAME%>, FIELD_<%=clazz.getName().toUpperCase()%>_<%=attr.getName().toUpperCase()%>, element); - getPropertyChangeSupport().firePropertyChange(FIELD_<%=clazz.getName().toUpperCase()%>_<%=attr.getName().toUpperCase()%>, null, get<%=attrNameCapitalized%>()); - } - - public void remove<%=attrNameCapitalized%>(<%=elementType%> element) { - getWikitty().removeFromField(<%=EXT_NAME%>, FIELD_<%=clazz.getName().toUpperCase()%>_<%=attr.getName().toUpperCase()%>, element); - getPropertyChangeSupport().firePropertyChange(FIELD_<%=clazz.getName().toUpperCase()%>_<%=attr.getName().toUpperCase()%>, null, get<%=attrNameCapitalized%>()); - } - - public void clear<%=attrNameCapitalized%>() { - getWikitty().clearField(<%=EXT_NAME%>, FIELD_<%=clazz.getName().toUpperCase()%>_<%=attr.getName().toUpperCase()%>); - getPropertyChangeSupport().firePropertyChange(FIELD_<%=clazz.getName().toUpperCase()%>_<%=attr.getName().toUpperCase()%>, null, get<%=attrNameCapitalized%>()); - } - -}*/ - } - - private static Set<String> commonNumerics; - static { - commonNumerics = new HashSet<String>(); - commonNumerics.add("byte"); - commonNumerics.add("Byte"); - commonNumerics.add("short"); - commonNumerics.add("Short"); - commonNumerics.add("int"); - commonNumerics.add("Integer"); - commonNumerics.add("long"); - commonNumerics.add("Long"); - commonNumerics.add("float"); - commonNumerics.add("Float"); - commonNumerics.add("double"); - commonNumerics.add("Double"); - } - - private static Set<String> commonStrings; - static { - commonStrings = new HashSet<String>(); - commonStrings.add("char"); - commonStrings.add("Char"); - commonStrings.add("String"); - } - - private static Set<String> commonTypes; - static { - commonTypes = new HashSet<String>(); - commonTypes.addAll(commonNumerics); - commonTypes.addAll(commonStrings); - commonTypes.add("boolean"); - commonTypes.add("Boolean"); - commonTypes.add("Date"); - } - -} Deleted: branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/BusinessEntityImplGenerator.java =================================================================== --- branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/BusinessEntityImplGenerator.java 2010-08-06 14:41:51 UTC (rev 240) +++ branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/BusinessEntityImplGenerator.java 2010-08-09 14:12:47 UTC (rev 241) @@ -1,147 +0,0 @@ -package org.nuiton.wikitty.generator; - -import java.io.File; -import java.io.IOException; -import java.io.Writer; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.eugene.GeneratorUtil; -import org.nuiton.eugene.models.object.ObjectModelClass; - -/** - * Possible enhancement: - * - generateParentMethod can generate attribut method access that call - * the same method on parent instance class. For that we must have one attribut - * instance by parent. This attribut we must be created in setWikitty method - * and used same wikitty object. - * - * @author poussin - */ -public class BusinessEntityImplGenerator extends WikengoCommonGenerator { - - private static final Log log = LogFactory.getLog(BusinessEntityImplGenerator.class); - - @Override - public String getFilenameForClass(ObjectModelClass clazz) { - String fqn = clazz.getQualifiedName(); - log.info( "Filename for " + clazz.getName() + " is " + fqn.replace('.', File.separatorChar) + ".java"); - return fqn.replace('.', File.separatorChar) + "Impl.java"; - } - - public void generateFromClass(Writer output, ObjectModelClass clazz) - throws IOException { - if (!EugengoUtils.isBusinessEntity(clazz)) { - log.info( clazz.getName() + " is not a business entity"); - return; - } - - // On ne génère pas le impl si l'entité a des opérations - if (clazz.getOperations().size() > 0) { - return; - } - - log.info("Generate Business entity impl" + clazz.getName() + "... "); - generateCopyright(output); - - String packageName = clazz.getPackageName(); - String className = clazz.getName(); - String name = className + "Impl"; -/*{package <%=packageName%>; - -}*/ - ObjectModelClass superClass = findSuperClass(clazz); - - clearImports(); - addImport(clazz); - addImport(superClass); - addImport("org.nuiton.wikitty.WikittyUtil"); - addImport("org.nuiton.wikitty.Wikitty"); - addImport("org.nuiton.wikitty.BusinessEntityWikitty"); - addImport("org.nuiton.wikitty.WikittyExtension"); - addImport(Collection.class); - addImport(Collections.class); - addImport(List.class); - addImport(ArrayList.class); - String parentImpl = null; - for (ObjectModelClass parent : clazz.getSuperclasses()) { - if (EugengoUtils.isBusinessEntity(parent)) { - addImport(parent); - parentImpl = parent.getQualifiedName() + "Impl"; - addImport( parentImpl ); - } - } - lookForAttributeImports(clazz); - generateImports(output, packageName); - - generateClazzDocumentation(output, clazz); - String abstractString = ""; - if (clazz.isAbstract()) { - abstractString += "abstract "; - } - -/*{public <%=abstractString%>class <%=className%>Impl extends <%=className%>Abstract { - -}*/ - - String svUID = GeneratorUtil.computeSerialVersionUID(clazz); -/*{ private static final long serialVersionUID = <%=svUID%>; - - public <%=name%>() { - super(); - } - - public <%=name%>(BusinessEntityWikitty wi) { - super(wi.getWikitty()); - } - - public <%=name%>(Wikitty wi) { - super(wi); - } - -} //<%=name%> -}*/ - } - - private static Set<String> commonNumerics; - static { - commonNumerics = new HashSet<String>(); - commonNumerics.add("byte"); - commonNumerics.add("Byte"); - commonNumerics.add("short"); - commonNumerics.add("Short"); - commonNumerics.add("int"); - commonNumerics.add("Integer"); - commonNumerics.add("long"); - commonNumerics.add("Long"); - commonNumerics.add("float"); - commonNumerics.add("Float"); - commonNumerics.add("double"); - commonNumerics.add("Double"); - } - - private static Set<String> commonStrings; - static { - commonStrings = new HashSet<String>(); - commonStrings.add("char"); - commonStrings.add("Char"); - commonStrings.add("String"); - } - - private static Set<String> commonTypes; - static { - commonTypes = new HashSet<String>(); - commonTypes.addAll(commonNumerics); - commonTypes.addAll(commonStrings); - commonTypes.add("boolean"); - commonTypes.add("Boolean"); - commonTypes.add("Date"); - } - -} Deleted: branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/BusinessEntityInterfaceGenerator.java =================================================================== --- branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/BusinessEntityInterfaceGenerator.java 2010-08-06 14:41:51 UTC (rev 240) +++ branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/BusinessEntityInterfaceGenerator.java 2010-08-09 14:12:47 UTC (rev 241) @@ -1,202 +0,0 @@ -package org.nuiton.wikitty.generator; - -import java.io.File; -import java.io.IOException; -import java.io.Writer; -import java.util.Collection; -import java.util.Set; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -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.ObjectModelOperation; -import org.nuiton.eugene.models.object.ObjectModelParameter; - -/** - * Interface for BusinessEntity, interfaces are needed for multiple inheritance - * - * @author poussin - */ -public class BusinessEntityInterfaceGenerator extends WikengoCommonGenerator { - - private static final Log log = LogFactory.getLog(BusinessEntityInterfaceGenerator.class); - - protected String EXT_NAME; - - @Override - public String getFilenameForClass(ObjectModelClass clazz) { - String fqn = clazz.getQualifiedName(); - log.info( "Filename for " + clazz.getName() + " is " + fqn.replace('.', File.separatorChar) + ".java"); - return fqn.replace('.', File.separatorChar) + ".java"; - } - - public void generateFromClass(Writer output, ObjectModelClass clazz) - throws IOException { - if (!EugengoUtils.isBusinessEntity(clazz)) { - log.info( clazz.getName() + " is not a business entity"); - return; - } - - log.info("Generate Business entity " + clazz.getName() + "... "); - generateCopyright(output); - - EXT_NAME = "EXT_" + clazz.getName().toUpperCase(); - String packageName = clazz.getPackageName(); - String name = clazz.getName(); -/*{package <%=packageName%>; - -}*/ - ObjectModelClass superClass = findSuperClass(clazz); - - clearImports(); - addImport(superClass); - addImport("org.nuiton.wikitty.BusinessEntity"); - - for (ObjectModelClass parent : clazz.getSuperclasses()) { - if (EugengoUtils.isBusinessEntity(parent)) { - addImport(parent); - } - } - lookForAttributeImports(clazz); - generateImports(output, packageName); - - generateClazzDocumentation(output, clazz); - - String extendsString = "extends " + getType("org.nuiton.wikitty.BusinessEntity"); - for (ObjectModelClass parent : clazz.getSuperclasses()) { - if (EugengoUtils.isBusinessEntity(parent)) { - extendsString += ", " + getType(parent.getName()); - } - } - -/*{public interface <%=name%> <%=extendsString%> { - - static final public String <%=EXT_NAME%> = "<%=clazz.getName()%>"; - -}*/ - generateFieldNameConstant(output, clazz); - - generateStaticAttributes(output, clazz); - - generateAttributeAccessMethod(output, clazz); - - generateInterfaceOperations(output, clazz); - -/*{ -} //<%=name%> -}*/ - - } - - // Utilitarian methods - private void generateFieldNameConstant(Writer output, - ObjectModelClass clazz) throws IOException { - for (ObjectModelAttribute attr : clazz.getAttributes()) { - if (attr.isNavigable() && !attr.isStatic() && - (attr.getStereotypes() == null || attr.getStereotypes().isEmpty())) { -/*{ static final public String FIELD_<%=clazz.getName().toUpperCase()%>_<%=attr.getName().toUpperCase()%> = "<%=attr.getName()%>"; - static final public String FQ_FIELD_<%=clazz.getName().toUpperCase()%>_<%=attr.getName().toUpperCase()%> = <%=EXT_NAME%> + ".<%=attr.getName()%>"; -}*/ - } - } - } - - public void generateAttributeAccessMethod(Writer output, ObjectModelClass clazz) throws IOException { - for (ObjectModelAttribute attr : clazz.getAttributes()) { - if (attr.isNavigable() && !attr.isStatic() - && (attr.getStereotypes() == null || attr.getStereotypes().isEmpty())) { - if ((attr.getMaxMultiplicity() != 0 && attr.getMaxMultiplicity() != 1)) { - //TODO ymartel 20090812: when dataType "List", "Set" or "Collection" in model, must be here! - generateCollectionAttributeAccessors(output, attr); - } else { - generateWikittyAttributeAccessors(output, attr); - } - } - } - } - - protected void generateWikittyAttributeAccessors(Writer output, - ObjectModelAttribute attr) throws IOException { - String attrType = computeType(attr); - if (EugengoUtils.notEmpty(attrType)) { - attrType = getType(attrType, true); - } else { - return; - } - - String attrName = attr.getName(); - String attrNameCapitalized = EugengoUtils.toUpperCaseFirstLetter(attrName); - -/*{ - public void set<%=attrNameCapitalized%>(<%=attrType%> <%=attrName%>); - public <%=attrType%> get<%=attrNameCapitalized%>(); - -}*/ - } - - protected void generateCollectionAttributeAccessors(Writer output, - ObjectModelAttribute attr) throws IOException { - String attrType = computeType(attr); - if (EugengoUtils.notEmpty(attrType)) { - attrType = getType(attrType, true); - } else { - return; - } - - // get collection element type for add and remove method arguement type - String elementType = getType(attr.getType(), true); - - String attrName = attr.getName(); - String attrNameCapitalized = EugengoUtils.toUpperCaseFirstLetter(attrName); -/*{ public <%=attrType%> get<%=attrNameCapitalized%>(); - public void add<%=attrNameCapitalized%>(<%=elementType%> element); - public void remove<%=attrNameCapitalized%>(<%=elementType%> element); - public void clear<%=attrNameCapitalized%>(); - -}*/ - } - - private void generateInterfaceOperations(Writer output, ObjectModelClassifier classifier) throws IOException { - for (ObjectModelOperation op : classifier.getOperations()) { - String opName = op.getName(); -/*{ /** -}*/ - if (EugengoUtils.hasDocumentation(op)) { - String opDocumentation = op.getDocumentation(); -/*{ * <%=opName%> : <%=opDocumentation%> -}*/ - } - Collection<ObjectModelParameter> params = op.getParameters(); - for (ObjectModelParameter param : params) { - String paramName = param.getName(); - String paramDocumentation = param.getDocumentation(); -/*{ * @param <%=paramName%> <%=paramDocumentation%> - }*/ - } - String opVisibility = op.getVisibility(); - String opType = op.getReturnType(); -/*{ *) - <%=opVisibility%> <%=opType%> <%=opName%>(}*/ - String comma = ""; - for (ObjectModelParameter param : params) { - String paramName = param.getName(); - String paramType = param.getType(); -/*{<%=comma%><%=paramType%> <%=paramName%>}*/ - comma = ", "; - } -/*{)}*/ - Set<String> exceptions = op.getExceptions(); - comma = " throws "; - for (String exception : exceptions) { -/*{<%=comma%><%=exception%>}*/ - comma = ", "; - } -/*{; - -}*/ - } - } - -} Deleted: branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/EnumGenerator.java =================================================================== --- branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/EnumGenerator.java 2010-08-06 14:41:51 UTC (rev 240) +++ branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/EnumGenerator.java 2010-08-09 14:12:47 UTC (rev 241) @@ -1,53 +0,0 @@ -package org.nuiton.wikitty.generator; - -import java.io.File; -import java.io.IOException; -import java.io.Writer; - -import org.nuiton.eugene.models.object.ObjectModelEnumeration; - -public class EnumGenerator extends WikengoCommonGenerator { - - @Override - public String getFilenameForEnumeration(ObjectModelEnumeration enumeration) { - String fqn = enumeration.getQualifiedName(); - return fqn.replace('.', File.separatorChar) + ".java"; - } - - @Override - public void generateFromEnumeration(Writer output, - ObjectModelEnumeration enumeration) throws IOException { - - generateCopyright(output); - - String packageName = enumeration.getPackageName(); - String enumName = enumeration.getName(); - -/*{package <%=packageName%>; - -}*/ - generateDocumentation(output, enumeration, ""); -/*{public enum <%=enumName%> { - -}*/ - - boolean isFirst = true; - for (String literal: enumeration.getLiterals()) { - if (isFirst) { -/*{ }*/ - } else { -/*{, }*/ - } - isFirst = false; -/*{<%=literal%>}*/ - } - -/*{ - -}*/ - -/*{} //<%=enumName%> -}*/ - } - -} Deleted: branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/EugengoConstants.java =================================================================== --- branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/EugengoConstants.java 2010-08-06 14:41:51 UTC (rev 240) +++ branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/EugengoConstants.java 2010-08-09 14:12:47 UTC (rev 241) @@ -1,21 +0,0 @@ -package org.nuiton.wikitty.generator; - -public class EugengoConstants { - - public final static String STEREOTYPE_SERVICE = "Service"; - public final static String STEREOTYPE_CRUD_SERVICE = "CrudService"; - public final static String STEREOTYPE_DTO = "Dto"; - public final static String STEREOTYPE_BUSINESS_ENTITY = "BusinessEntity"; - public final static String STEREOTYPE_DAO = "Dao"; - public final static String STEREOTYPE_ENTITY = "Entity"; - public final static String STEREOTYPE_EXCEPTION = "Exception"; - public final static String STEREOTYPE_BUSINESS_EXCEPTION = "BusinessException"; - public final static String STEREOTYPE_REMOTE = "Remote"; - - public final static String TAG_COPYRIGHT = "copyright"; - public final static String TAG_LENGTH = "length"; - public static final String TAG_LAZY = "lazy"; - - public final static String PREFIX_DATATYPE = "dataType-"; - -} // EugengoConstants Deleted: branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/EugengoUtils.java =================================================================== --- branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/EugengoUtils.java 2010-08-06 14:41:51 UTC (rev 240) +++ branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/EugengoUtils.java 2010-08-09 14:12:47 UTC (rev 241) @@ -1,157 +0,0 @@ -package org.nuiton.wikitty.generator; - -import java.util.HashSet; -import java.util.Set; - -import org.nuiton.eugene.GeneratorUtil; -import org.nuiton.eugene.models.Model; -import org.nuiton.eugene.models.object.ObjectModelAttribute; -import org.nuiton.eugene.models.object.ObjectModelClassifier; -import org.nuiton.eugene.models.object.ObjectModelOperation; - -public class EugengoUtils extends GeneratorUtil { - - /** - * Cherches et renvoie le copyright a utiliser sur le model. - * - * @param model le modele utilise - * @return le texte du copyright ou null - */ - public static String getCopyright(Model model) { - return GeneratorUtil.findTagValue(EugengoConstants.TAG_COPYRIGHT, null, model); - } - - public static boolean isService(ObjectModelClassifier classifier) { - return hasStereotype(classifier, EugengoConstants.STEREOTYPE_SERVICE) || isCrudService(classifier); - } - - public static boolean isCrudService(ObjectModelClassifier classifier) { - return hasStereotype(classifier, EugengoConstants.STEREOTYPE_CRUD_SERVICE); - } - - public static boolean isWebService(ObjectModelClassifier classifier) { - // any crud service is remote - if (isCrudService(classifier)) { - return true; - } - // cannot be a webservice if class is not a service - if (!isService(classifier)) { - return false; - } - // Look for an operation that has the stereotype remote - for (ObjectModelOperation op : classifier.getOperations()) { - if (isRemote(op)) { - return true; - } - } - return false; - } - - public static boolean isDto(ObjectModelClassifier classifier) { - return hasStereotype(classifier, EugengoConstants.STEREOTYPE_DTO); - } - - public static boolean isBusinessEntity(ObjectModelClassifier classifier) { - return hasStereotype(classifier, EugengoConstants.STEREOTYPE_BUSINESS_ENTITY); - } - - public static boolean isDao(ObjectModelClassifier classifier) { - return hasStereotype(classifier, EugengoConstants.STEREOTYPE_DAO); - } - - public static boolean isEntity(ObjectModelClassifier classifier) { - return hasStereotype(classifier, EugengoConstants.STEREOTYPE_ENTITY); - } - - public static boolean isException(ObjectModelClassifier classifier) { - return hasStereotype(classifier, EugengoConstants.STEREOTYPE_EXCEPTION) || isBusinessException(classifier); - } - - public static boolean isBusinessException(ObjectModelClassifier classifier) { - return hasStereotype(classifier, EugengoConstants.STEREOTYPE_BUSINESS_EXCEPTION); - } - - public static boolean isRemote(ObjectModelOperation op) { - return hasStereotype(op, EugengoConstants.STEREOTYPE_REMOTE); - } - - private static Set<String> simpleTypes; - static { - simpleTypes = new HashSet<String>(); - simpleTypes.add("void"); - simpleTypes.add("boolean"); - simpleTypes.add("byte"); - simpleTypes.add("short"); - simpleTypes.add("int"); - simpleTypes.add("long"); - simpleTypes.add("float"); - simpleTypes.add("double"); - } - - - private static Set<String> primitiveTypes; - static { - primitiveTypes = new HashSet<String>(); - primitiveTypes.add("byte"); - primitiveTypes.add("Byte"); - primitiveTypes.add("short"); - primitiveTypes.add("Short"); - primitiveTypes.add("int"); - primitiveTypes.add("Integer"); - primitiveTypes.add("long"); - primitiveTypes.add("Long"); - primitiveTypes.add("float"); - primitiveTypes.add("Float"); - primitiveTypes.add("double"); - primitiveTypes.add("Double"); - - primitiveTypes.add("char"); - primitiveTypes.add("Char"); - - primitiveTypes.add("boolean"); - primitiveTypes.add("Boolean"); - } - - public static String extractModelName(Model model) { - String result = model.getName(); - if (result.contains("::")) { - result = result.replaceAll("::", "."); - } - if (result.endsWith(".")) { - result = result.substring(0, result.length() - 1); - } - return result; - } - - public static String normalizeCapitalName(String name) { - String result = ""; - for (int idx = 0; idx < name.length(); idx++) { - char c = name.charAt(idx); - if (Character.isUpperCase(c)) { - result += "_"; - } - result += Character.toUpperCase(c); - } - if (result.startsWith("_")) { - result = result.substring(1); - } - return result; - } - - public static String getTagValue(ObjectModelAttribute attr, String tagName, String defaultValue) { - String value = attr.getTagValue(tagName); - if (value == null) { - value = defaultValue; - } - return value; - } - - public static boolean isPrimitiveType(ObjectModelAttribute attr) { - String type = attr.getType(); - if (type.startsWith("java.lang.")) { - type = type.substring(11); - } - return primitiveTypes.contains(type); - } - -} //EugengoUtils Deleted: branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/InterfaceGenerator.java =================================================================== --- branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/InterfaceGenerator.java 2010-08-06 14:41:51 UTC (rev 240) +++ branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/InterfaceGenerator.java 2010-08-09 14:12:47 UTC (rev 241) @@ -1,52 +0,0 @@ -package org.nuiton.wikitty.generator; - -import java.io.File; -import java.io.IOException; -import java.io.Writer; - -import org.nuiton.eugene.models.object.ObjectModelInterface; -import org.nuiton.eugene.models.object.ObjectModelOperation; - -public class InterfaceGenerator extends WikengoCommonGenerator { - - @Override - public String getFilenameForInterface(ObjectModelInterface interfacez) { - String fqn = interfacez.getQualifiedName(); - return fqn.replace('.', File.separatorChar) + ".java"; - } - - @Override - public void generateFromInterface(Writer output, - ObjectModelInterface interfacez) throws IOException { - // Generate only is not stereotype is specified - if (!interfacez.getStereotypes().isEmpty()) { - return; - } - - generateCopyright(output); - - String packageName = interfacez.getPackageName(); - String name = interfacez.getName(); -/*{package <%=packageName%>; - -}*/ - - clearImports(); - lookForOperationImports(interfacez); - generateImports(output, packageName); - - generateClazzDocumentation(output, interfacez); -/*{public interface <%=name%> { - -}*/ - - for (ObjectModelOperation op : interfacez.getOperations()) { - generateOperationHeader(output, op, true); - } - -/*{} //<%=name%> -}*/ - - } - -} Deleted: branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/WikengoCommonGenerator.java =================================================================== --- branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/WikengoCommonGenerator.java 2010-08-06 14:41:51 UTC (rev 240) +++ branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/WikengoCommonGenerator.java 2010-08-09 14:12:47 UTC (rev 241) @@ -1,727 +0,0 @@ -package org.nuiton.wikitty.generator; - -import java.io.IOException; -import java.io.Writer; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.eugene.GeneratorUtil; -import org.nuiton.eugene.java.ImportsManager; -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.ObjectModelDependency; -import org.nuiton.eugene.models.object.ObjectModelElement; -import org.nuiton.eugene.models.object.ObjectModelGenerator; -import org.nuiton.eugene.models.object.ObjectModelOperation; -import org.nuiton.eugene.models.object.ObjectModelParameter; - -public class WikengoCommonGenerator extends ObjectModelGenerator { - - private static final Log log = LogFactory.getLog(WikengoCommonGenerator.class); - - protected ImportsManager imports; - - protected void clearImports() { - if (imports == null) { - imports = new ImportsManager(); - } else { - imports.clearImports(); - } - } - - @Override - protected boolean canGenerateElement(Object element) { - - boolean canGenerate = true; - - if (element instanceof ObjectModel) { - // fail with no model name - canGenerate = false; - } - else { - canGenerate = super.canGenerateElement(element); - } - return canGenerate; - } - - protected void addImport(String fqn) { - if (containsClassAndGeneric(fqn)) { - String[] type = getClassAndGeneric(fqn); - imports.addImport(checkForDatatype(type[0])); - addImport(checkForDatatype(type[1])); - } else if (isArray(fqn)) { - imports.addImport(checkForDatatype(fqn.substring(0, fqn.length() - 2))); - } else if (containsComma(fqn)) { - String[] fqnCommaSeparated = splitByComma(fqn); - for (String str : fqnCommaSeparated) { - if (str != null && !str.isEmpty()) { - addImport(str.trim()); - } - } - } else { - fqn = checkForDatatype(fqn); - imports.addImport(fqn); - } - } - - private String[] splitByComma(String fqn) { - return fqn.split(","); - } - - private boolean containsComma(String fqn) { - return fqn != null && fqn.indexOf(",") != -1; - } - - protected void addImport(Class<?> clazz) { - imports.addImport(clazz); - } - - protected void addImport(ObjectModelClass clazz) { - if (clazz != null) { - addImport(clazz.getQualifiedName()); - } - } - - /** - * Return the minimum syntax for the type. The result depend of import added - * by addImport. - * - * @param fqn the fully qualified name of type - * @return minimum needed type - */ - protected String getType(String fqn) { - String result = getType(fqn, false); - return result; - } - - /** - * Return the minimum syntax for the type. The result depend of import added - * by addImport. - * - * @param fqn the fully qualified name of type - * @param convert if true try to convert some type to other - * (ex: enum to string, dto to string) - * @return minimum needed type - */ - protected String getType(String fqn, boolean convert) { - // if type is Wikitty then we used String - if ("org.nuiton.wikitty.Wikitty".equals(fqn) - || "Wikitty".equals(fqn)) { - fqn = "String"; - } else if (convert && null != getModel().getEnumeration(fqn)) { - // if type is Wikitty then we used String - fqn = "String"; - } else if (convert && getModel().hasClass(fqn) - && EugengoUtils.isBusinessEntity(getModel().getClass(fqn))) { - // for wikittyDto we use String for Id - fqn = "String"; - } - - if (containsClassAndGeneric(fqn)) { - String[] type = getClassAndGeneric(fqn); - return imports.getType(checkForDatatype(type[0])) + "<" + getType(type[1], convert) + ">"; - } else if (containsComma(fqn)) { - String result = ""; - for (String str : splitByComma(fqn)) { - if (str != null && !str.isEmpty()) { - if (!result.isEmpty()) { - result += ", "; - } - result += str.trim(); - } - } - return result; - } else { - return imports.getType(checkForDatatype(fqn)); - } - } - - protected boolean isArray(String fqn) { - return fqn != null && fqn.trim().endsWith("[]"); - } - - protected boolean containsClassAndGeneric(String fqn) { - return fqn != null && fqn.indexOf("<") != -1; - } - - protected String[] getClassAndGeneric(String fqn) { - int idx = fqn.indexOf("<"); - String[] result = new String[2]; - result[0] = fqn.substring(0, idx); - result[1] = fqn.substring(idx+1, fqn.length() - 1); - return result; - } - - protected void generateImports(Writer output, String currentPackage) throws IOException { - List<String> imports = this.imports.getImports(currentPackage); - if (!imports.isEmpty()) { - for (String importLine : imports) { -/*{import <%=importLine%>; -}*/ - } -/*{ -}*/ - } - } - - protected void generateCopyright(Writer output) throws IOException { - String copyright = EugengoUtils.getCopyright(model); - if (GeneratorUtil.notEmpty(copyright)) { -/*{<%=copyright%> -}*/ - } - } - - protected void generateClazzDocumentation(Writer output, ObjectModelClassifier classifier, String ... defaultDoc) - throws IOException { - generateDocumentation(output, classifier, "", defaultDoc); - } - - protected void generateDocumentation(Writer output, ObjectModelElement element, String prefix, String ... defaultDoc) - throws IOException { - String doc = null; - if (GeneratorUtil.hasDocumentation(element)) { - doc = element.getDocumentation(); - } /*else { - TODO Manage defaultDoc - }*/ - - if (doc != null) { - // Manage RC in the doc - Pattern p = Pattern.compile("(\n)"); - Matcher m = p.matcher(doc); - String docOk = m.replaceAll("\n"+prefix+" * "); - -/*{<%=prefix%>/** -<%=prefix%> * <%=docOk%> -<%=prefix%> *) -}*/ - } - } - - /** - * Generates a header for the given operation. - * @param output The stream to write inside - * @param op the operation which header is to generate - * @param hasBody need to generate a body ? - * <li>true (for classes) : generates ' {' at the end</li> - * <li>false (for interfaces) : generates ';' at the end</li> - * @param hasBody - * @throws IOException - */ - protected void generateOperationHeader(Writer output, ObjectModelOperation op, - boolean generateForInterface, String ... additionalExceptions) throws IOException { - String opVisibility = op.getVisibility(); - //If generate for interface, only public methods are allowed - if (generateForInterface && !"".equals(opVisibility) && !"public".equals(opVisibility)) { - return; - } - String opName = op.getName(); -/*{ // Operation "<%=opName%>" -}*/ - generateDocumentation(output, op, " "); - if (generateForInterface || "package".equals(opVisibility)) { - opVisibility = ""; - } else { - opVisibility += " "; - } - String opType = computeType(op.getReturnParameter()); - opType = getType(opType); - String opAbstract = ""; - if (!generateForInterface && op.isAbstract()) { - opAbstract = "abstract "; - } -/*{ <%=opVisibility%><%=opAbstract%><%=opType%> <%=opName%>(}*/ - boolean isFirst = true; - for (ObjectModelParameter opParam : op.getParameters()) { - String paramName = opParam.getName(); - String paramType = computeType(opParam); - paramType = getType(paramType); - if (!isFirst) { -/*{, }*/ - } - isFirst = false; -/*{<%=paramType%> <%=paramName%>}*/ - } -/*{)}*/ - if ((op.getExceptions() != null && !op.getExceptions().isEmpty()) || (additionalExceptions != null && additionalExceptions.length > 0)) { -/*{ throws}*/ - isFirst = true; - Set<String> exceptions = new LinkedHashSet<String>(); - - if (additionalExceptions != null) { - for (String exception : additionalExceptions) { - exceptions.add(exception); - } - } - if (op.getExceptions() != null) { - for (String exception : op.getExceptions()) { - exceptions.add(exception); - } - } - for (String exception : exceptions) { - exception = getType(exception); - if (!isFirst) { -/*{,}*/ - } - isFirst = false; -/*{ <%=exception%>}*/ - } - } - if (generateForInterface || op.isAbstract()) { -/*{; - -}*/ - } else { -/*{ { -}*/ - } - } - - /** - * Generates a ioc name and injection. Will generate the class attribute - * and getter/setter. - * The name used is the name specified in the dependency class name. - * @param output The stream to write inside - * @param dep the dependency to generate. - * @throws IOException - */ - protected void generateIocDependency(Writer output, ObjectModelDependency dep) - throws IOException { - ObjectModelClassifier supplier = dep.getSupplier(); - if (supplier == null || EugengoUtils.isDao(supplier)) { - return; - } - String supplierType = getType(supplier.getQualifiedName()); - String supplierVarName = EugengoUtils.toLowerCaseFirstLetter(supplier.getName()); - String supplierMethodSuffix = EugengoUtils.toUpperCaseFirstLetter(supplier.getName()); -/*{ // Dependency injection for "<%=supplierVarName%>" - private <%=supplierType%> <%=supplierVarName%>; - - public <%=supplierType%> get<%=supplierMethodSuffix%>() { - return <%=supplierVarName%>; - } - - public void set<%=supplierMethodSuffix%>(<%=supplierType%> <%=supplierVarName%>) { - this.<%=supplierVarName%> = <%=supplierVarName%>; - } - -}*/ - } - - protected void generateAttributesDeclaration(Writer output, - ObjectModelClass clazz) throws IOException { - for (ObjectModelAttribute attr : clazz.getAttributes()) { - if (attr.isNavigable() && !attr.isStatic() && (attr.getStereotypes() == null || attr.getStereotypes().isEmpty())) { - generateAttributeDeclaration(output, attr); - } - } - } - - protected void generateAttributeDeclaration(Writer output, ObjectModelAttribute attr) - throws IOException { - String attrType = computeType(attr); - if (EugengoUtils.notEmpty(attrType)) { - attrType = getType(attrType); - } else { - return; - } - String attrVisibility = attr.getVisibility(); - String attrName = attr.getName(); -/*{ // Declaration of attribute "<%=attrName%>" -}*/ - generateDocumentation(output, attr, " "); - String value = computeDefaultValue(attr); -/*{ <%=attrVisibility%> <%=attrType%> <%=attrName%><%=value%>; - -}*/ - } - - /** - * Compute correct type of param. If param is - * <li> null : void - * <li> cardinality > 1 : Collection of type - * <li> cardinality > 1 and ordered: List of type - * <li> cardinality > 1 and unique: Set of type - * <li> other : the type - * @param param - * @return - */ - protected String computeType(ObjectModelParameter param) { - if (param == null) { - return "void"; - } - String result = param.getType(); - - // if type is Wikitty then we used String - if ("org.nuiton.wikitty.Wikitty".equals(result) - || "Wikitty".equals(result)) { - result = "String"; - } - - boolean isCollection = (param.getMaxMultiplicity() != 0 - && param.getMaxMultiplicity() != 1); - if (isCollection) { - Class<?> type = Collection.class; - if (param.isOrdered()) { - type = List.class; - } - if (param.isUnique()) { - type = Set.class; - } - result = type.getName() + "<" + result + ">"; - } - return result; - } - - protected void generateAttributesAccessors(Writer output, - ObjectModelClass clazz) throws IOException { - for (ObjectModelAttribute attr : clazz.getAttributes()) { - if (attr.isNavigable() && !attr.isStatic() && (attr.getStereotypes() == null || attr.getStereotypes().isEmpty())) { - generateAttributeAccessors(output, attr); - } - } - } - - protected void generateAttributeAccessors(Writer output, ObjectModelAttribute attr) - throws IOException { - String attrType = computeType(attr); - if (EugengoUtils.notEmpty(attrType)) { - attrType = getType(attrType); - } else { - return; - } - String attrName = attr.getName(); - String attrNameCapitalized = EugengoUtils.toUpperCaseFirstLetter(attrName); -/*{ // Accessors for attribute "<%=attrName%>" - public void set<%=attrNameCapitalized%>(<%=attrType%> <%=attrName%>) { - this.<%=attrName%> = <%=attrName%>; - } - - public <%=attrType%> get<%=attrNameCapitalized%>() { - return this.<%=attrName%>; - } - -}*/ - } - - protected void generateStaticAttributes(Writer output, ObjectModelClass clazz) - throws IOException { - for (ObjectModelAttribute attr : clazz.getAttributes()) { - if (attr.isStatic() && "public".equals(attr.getVisibility())) { - String type = computeType(attr); - type = getType(type); - String name = attr.getName(); - String value = computeDefaultValue(attr); -/*{ // static attribute "<%=name%>" - public static <%=type%> <%=name%><%=value%>; - -}*/ - } - } - } - - protected String computeDefaultValue(ObjectModelAttribute attr) { - String result = ""; - String value = attr.getDefaultValue(); - if (value != null) { - String type = computeType(attr); - type = getType(type); - if ("String".equals(type)) { - result = "\"" + value + "\""; - } else if ("boolean".equalsIgnoreCase(type)) { - result = "Boolean." + ("true".equalsIgnoreCase(value) + "").toUpperCase(); - } else if ("byte".equalsIgnoreCase(type) || "short".equalsIgnoreCase(type) || "int".equalsIgnoreCase(type) || "integer".equalsIgnoreCase(type)) { - result = value; - } else if ("long".equalsIgnoreCase(type)) { - result = value + "L"; - } else if ("float".equalsIgnoreCase(type)) { - result = value + "F"; - } else if ("double".equalsIgnoreCase(type)) { - result = value + "D"; - } else if ("Date".equals(type)) { - try { - Date d = new SimpleDateFormat().parse(value); - result = "new Date(" + d.getTime() + "l)"; - } catch (ParseException pe) { - log.warn("Unable to parse date", pe); - // Nothing else to do - } - } else { - result = value; - } - result = " = " + result; - } - return result; - } - - protected void generateDefaultConstructor(Writer output, String name) - throws IOException { -/*{ /** - * Default constructor - *) - public <%=name%>() { - super(); - } - -}*/ - } - - protected void generateExceptionConstructors(Writer output, ObjectModelClass clazz) - throws IOException { - String name = clazz.getName(); - generateDefaultConstructor(output, name); - -/*{ public <%=name%>(Throwable cause) { - super(); - initCause(cause); - } - -}*/ - } - - protected void generateFullConstructor(Writer output, - String name, Collection<ObjectModelAttribute> attrs) throws IOException { - int nb = 0; - int total = 0; - if (hasNavigableAndNonStaticAttributes(attrs)) { -/*{ /** - * Constructor with all parameters initialized - * -}*/ - for (ObjectModelAttribute attr : attrs) { - if (attr.isNavigable() && !attr.isStatic() && (attr.getStereotypes() == null || attr.getStereotypes().isEmpty())) { - total ++; - String attName = attr.getName(); -/*{ * @param <%=attName%> -}*/ - } - } - -/*{ *) - public <%=name%>(}*/ - for (ObjectModelAttribute attr : attrs) { - if (attr.isNavigable() && !attr.isStatic() && (attr.getStereotypes() == null || attr.getStereotypes().isEmpty())) { - String attrName = attr.getName(); - String attrType = getType(computeType(attr)); - if (EugengoUtils.notEmpty(attrType)) { - attrType = getType(attrType); - } else { - return; - } -/*{<%=attrType%> <%=attrName%>}*/ - nb ++; - if (nb < total){ -/*{, }*/ - } - } - } -/*{) { - super(); -}*/ - for (ObjectModelAttribute attr : attrs) { - if (attr.isNavigable() && !attr.isStatic() && (attr.getStereotypes() == null || attr.getStereotypes().isEmpty())) { - String attrName = attr.getName(); -/*{ this.<%=attrName%> = <%=attrName%>; -}*/ - } - } - -/*{ } - -}*/ - } - } - - protected boolean hasNavigableAndNonStaticAttributes(ObjectModelClass clazz) { - return hasNavigableAndNonStaticAttributes(clazz.getAttributes()); - } - - protected boolean hasNavigableAndNonStaticAttributes(Collection<ObjectModelAttribute> attrs) { - if (attrs != null && !attrs.isEmpty()) { - for (ObjectModelAttribute attr : attrs) { - if (attr.isNavigable() && !attr.isStatic()) { - return true; - } - } - } - return false; - } - - /** - * Run throw the given ObjectModelClass and declare as an import each found - * attribute type - * @param clazz the class to run throw - */ - protected void lookForAttributeImports(ObjectModelClass clazz) { - for (ObjectModelAttribute attr : clazz.getAttributes()) { - if (attr.isNavigable() && (attr.getStereotypes() == null || attr.getStereotypes().isEmpty())) { - String type = computeType(attr); - addImport(type); - } - } - } - - /** - * Run throw the given ObjectModelClass and declare as an import each found - * static attribute type - * @param clazz the class to run throw - */ - protected void lookForStaticAttributeImports(ObjectModelClass clazz) { - for (ObjectModelAttribute attr : clazz.getAttributes()) { - if (attr.isNavigable() && attr.isStatic() && (attr.getStereotypes() == null || attr.getStereotypes().isEmpty())) { - String type = computeType(attr); - addImport(type); - } - } - } - - /** - * Run throw the given ObjectModelClassifier and declare each type found on - * the operation declaration (return type, parameters type, exception - * thrown) - * @param classifier the classifier to run throw - */ - protected void lookForOperationImports(ObjectModelClassifier classifier) { - for (ObjectModelOperation op : classifier.getOperations()) { - String returnType = computeType(op.getReturnParameter()); - addImport(returnType); - for (ObjectModelParameter param : op.getParameters()) { - String paramType = computeType(param); - addImport(paramType); - } - for (String exceptionType : op.getExceptions()) { - addImport(exceptionType); - } - } - } - - /** - * Run throw the given ObjectModelClassifier and declare as an import each - * dependency's type found. The import is added only if the dependency's - * supplier is a service or a dao - * @param classifier the classifier to run throw - */ - protected void lookForIocImports(ObjectModelClassifier classifier) { - for (ObjectModelDependency dep : classifier.getDependencies()) { - ObjectModelClassifier supplier = dep.getSupplier(); - if (supplier != null && EugengoUtils.isService(supplier)) { - addImport(supplier.getQualifiedName()); - } - } - } - - /** - * Look on the model for a tag value that indicates an implementation for - * a specific datatype - * @param type the type to look for a declared implementation - * @return the found type or the original type - */ - protected String checkForDatatype(String type) { - if (type != null) { - // Look for simple dataType - String tag = model.getTagValue(EugengoConstants.PREFIX_DATATYPE + type); - if (tag != null) { - return tag; - } - // Look for generic dataType - int idx = type.indexOf("<"); - if (idx != -1) { - tag = model.getTagValue(EugengoConstants.PREFIX_DATATYPE + type.substring(0, idx)); - } - if (tag != null) { - return tag; - } - } - // No dataType found, return type - return type; - } - - /** - * Run throw the superclasses to get the first one. - * - * @param clazz the class to run throw - * @return the first found superClass or null - */ - protected ObjectModelClass findSuperClass(ObjectModelClass clazz) { - if (clazz.getSuperclasses() != null && !clazz.getSuperclasses().isEmpty()) { - return clazz.getSuperclasses().iterator().next(); - } - return null; - } - - protected Collection<ObjectModelClass> findSubClasses(ObjectModelClass clazz) { - Collection<ObjectModelClass> result = new ArrayList<ObjectModelClass>(); - for (ObjectModelClass potentialSubClass : model.getClasses()) { - if (clazz.equals(findSuperClass(potentialSubClass))) { - result.add(potentialSubClass); - } - } - return result; - } - - protected void generateHashCode(Writer output, ObjectModelClass clazz) throws IOException { -/*{ public int hashCode() { - int result = 0; -}*/ - String prefix = ""; - if (EugengoUtils.isEntity(clazz)) { -/*{ if (id != null) { - result = id.hashCode(); - } else { -}*/ - prefix = " "; - } - generateHashCodeFromAttributes(output, clazz, prefix); - if (EugengoUtils.isEntity(clazz)) { -/*{ } -}*/ - } -/*{ return result; - } - -}*/ - } - - private void generateHashCodeFromAttributes(Writer output, ObjectModelClass clazz, String prefix) throws IOException { - for (ObjectModelAttribute attr : clazz.getAttributes()) { - if (attr.isNavigable() && (attr.getStereotypes() == null || attr.getStereotypes().isEmpty())) { - String attrName = attr.getName(); - String attrType = getType(attr.getType()); - if (EugengoUtils.isPrimitiveType(attr)) { - // If the leading character is an uppercased letter... - if (attrType.charAt(0) == attrType.toUpperCase().charAt(0)) { -/*{<%=prefix%> if (<%=attrName%> != null) { -<%=prefix%> result = 29 * result + <%=attrName%>.hashCode(); -<%=prefix%> } -}*/ - } else { - attrType = EugengoUtils.toUpperCaseFirstLetter(attrType); - if ("Int".equals(attrType)) { - attrType = "Integer"; - } -/*{<%=prefix%> result = 29 * result + new <%=attrType%>(<%=attrName%>).hashCode(); -}*/ - } - } else { -/*{<%=prefix%> if (<%=attrName%> != null) { -<%=prefix%> result = 29 * result + <%=attrName%>.hashCode(); -<%=prefix%> } -}*/ - } - } - } - } -} Deleted: branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/WikittyHelperGenerator.java =================================================================== --- branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/WikittyHelperGenerator.java 2010-08-06 14:41:51 UTC (rev 240) +++ branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/WikittyHelperGenerator.java 2010-08-09 14:12:47 UTC (rev 241) @@ -1,328 +0,0 @@ -package org.nuiton.wikitty.generator; - -import java.io.File; -import java.io.IOException; -import java.io.Writer; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import java.util.regex.Pattern; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.eugene.GeneratorUtil; -import org.nuiton.eugene.models.object.ObjectModelAttribute; -import org.nuiton.eugene.models.object.ObjectModelClass; - -/** - * Possible enhancement: - * - generateParentMethod can generate attribut method access that call - * the same method on parent instance class. For that we must have one attribut - * instance by parent. This attribut we must be created in setWikitty method - * and used same wikitty object. - * - * @author poussin - */ -public class WikittyHelperGenerator extends WikengoCommonGenerator { - - private static final Log log = LogFactory.getLog(WikittyHelperGenerator.class); - - static protected Pattern extractTypeOnCollection = Pattern.compile("\\w*<(\\w+)>"); - - protected String EXT_NAME; - - @Override - public String getFilenameForClass(ObjectModelClass clazz) { - String fqn = clazz.getQualifiedName(); - log.info( "Filename for " + clazz.getName() + " is " + fqn.replace('.', File.separatorChar) + ".java"); - return fqn.replace('.', File.separatorChar) + "Helper.java"; - } - - public void generateFromClass(Writer output, ObjectModelClass clazz) - throws IOException { - if (!EugengoUtils.isBusinessEntity(clazz)) { - log.info( clazz.getName() + " is not a business entity"); - return; - } - - log.info("Generate Business entity abstract" + clazz.getName() + "... "); - generateCopyright(output); - - EXT_NAME = "EXT_" + clazz.getName().toUpperCase(); - - String packageName = clazz.getPackageName(); - String name = clazz.getName() + "Helper"; - String nameImpl = clazz.getName() + "Impl"; -/*{package <%=packageName%>; - -}*/ - ObjectModelClass superClass = findSuperClass(clazz); - - clearImports(); - addImport(clazz); - addImport(superClass); - addImport("org.nuiton.wikitty.WikittyUtil"); - addImport("org.nuiton.wikitty.Wikitty"); - addImport("org.nuiton.wikitty.BusinessEntityWikitty"); - addImport("org.nuiton.wikitty.WikittyExtension"); - addImport(Collection.class); - addImport(Collections.class); - addImport(List.class); - addImport(ArrayList.class); - - lookForAttributeImports(clazz); - generateImports(output, packageName); - - generateClazzDocumentation(output, clazz); - - // l'heritage sur le Impl n'est la que pour profiter des constantes deja definies -/*{public class <%=name%> extends <%=nameImpl%> { - -}*/ - - String svUID = GeneratorUtil.computeSerialVersionUID(clazz); -/*{ private static final long serialVersionUID = <%=svUID%>; - -}*/ - -/*{ - /** - * This class is not instanciable, it's just helper - *) - private <%=name%>() { - } - -}*/ - - generateAttributeAccessMethod(output, clazz); - - for (ObjectModelClass parent : clazz.getSuperclasses()) { - if (EugengoUtils.isBusinessEntity(parent)) { - generateParentMethod(output, parent); - } - } - -/*{ - /** - * Check if wikitty has current extension - *) - static public boolean isExtension(Wikitty w) { - boolean result = w.hasExtension(<%=EXT_NAME%>); - return result; - } - - /** - * ajout les extensions static de cette classe au wikitty en argument - *) - static public void addExtension(Wikitty w) { - for (WikittyExtension ext : extensions) { - w.addExtension(ext); - } - } - - /** - * Check equality on all field of this extension, and only those. - *) - static public boolean equals(Wikitty w1, Wikitty w2) { - boolean result = true; -}*/ - for (ObjectModelAttribute attr : clazz.getAttributes()) { - if (attr.isNavigable() && !attr.isStatic() && - (attr.getStereotypes() == null || attr.getStereotypes().isEmpty())) { -/*{ if (result) { - Object f1 = w1.getFieldAsObject(<%=EXT_NAME%>, <%=clazz.getName()%>.FIELD_<%=clazz.getName().toUpperCase()%>_<%=attr.getName().toUpperCase()%>); - Object f2 = w2.getFieldAsObject(<%=EXT_NAME%>, <%=clazz.getName()%>.FIELD_<%=clazz.getName().toUpperCase()%>_<%=attr.getName().toUpperCase()%>); - result = f1 == f2 || (f1 != null && f1.equals(f2)); - } -}*/ - } - } -/*{ - return result; - } - -} //<%=name%> -}*/ - - } - - - - // Utilitarian methods - - public void generateAttributeAccessMethod(Writer output, ObjectModelClass clazz) throws IOException { - for (ObjectModelAttribute attr : clazz.getAttributes()) { - if (attr.isNavigable() && !attr.isStatic() - && (attr.getStereotypes() == null || attr.getStereotypes().isEmpty())) { - if ((attr.getMaxMultiplicity() != 0 && attr.getMaxMultiplicity() != 1)) { - //TODO ymartel 20090812: when dataType "List", "Set" or "Collection" in model, must be here! - generateCollectionAttributeAccessors(output, clazz, attr); - } else { - generateWikittyAttributeAccessors(output, clazz, attr); - } - } - } - } - - private void generateParentMethod(Writer output, - ObjectModelClass clazz) throws IOException { - - // we must generate method for parent of parent - for (ObjectModelClass parent : clazz.getSuperclasses()) { - if (EugengoUtils.isBusinessEntity(parent)) { - generateParentMethod(output, parent); - } - } - - // generate method acces for parent attribut - generateAttributeAccessMethod(output, clazz); - } - - protected void generateWikittyAttributeAccessors(Writer output, - ObjectModelClass clazz, ObjectModelAttribute attr) throws IOException { - - EXT_NAME = "EXT_" + attr.getDeclaringElement().getName().toUpperCase(); - - String attrType = computeType(attr); - if (EugengoUtils.notEmpty(attrType)) { - attrType = getType(attrType, true); - } else { - return; - } - - // FIXME EC-20100421 cette methode peut retourner List<String> - // et generer la methode getWikitty().getFieldAsList<String>() - // qui ne peut pas compiler - String methodAccessName = getFieldAccessMethodName(attr); - - String attrName = attr.getName(); - String attrNameCapitalized = EugengoUtils.toUpperCaseFirstLetter(attrName); - -/*{ - static public void set<%=attrNameCapitalized%>(Wikitty w, <%=attrType%> <%=attrName%>) { - w.setField(<%=EXT_NAME%>, <%=clazz.getName()%>.FIELD_<%=clazz.getName().toUpperCase()%>_<%=attr.getName().toUpperCase()%>, <%=attrName%>); - } - - static public <%=attrType%> get<%=attrNameCapitalized%>(Wikitty w) { - <%=attrType%> result = w.getFieldAs<%=methodAccessName%>(<%=EXT_NAME%>, <%=clazz.getName()%>.FIELD_<%=clazz.getName().toUpperCase()%>_<%=attr.getName().toUpperCase()%>); - return result; - } - -}*/ - } - - /** - * Give the string to put after getFieldAs???, only some type is accepted - * and we must convert BusinessEntity to Wikitty string - * @param type - * @return - */ - protected String getFieldAccessMethodName(ObjectModelAttribute attr) { - String result = computeType(attr); - result = getType(result, true); - - boolean isCollection = (attr.getMaxMultiplicity() != 0 - && attr.getMaxMultiplicity() != 1); - if (isCollection) { - if (attr.isUnique()) { - result = "Set"; - } else { - result = "List"; - } - } else { - // test for Date - if ("java.util.Date".equals(result) || "Date".equals(result)) { - result = "Date"; - } else if (getModel().hasClass(result)) { // test for Wikitty object - ObjectModelClass fieldClass = getModel().getClass(result); - if (EugengoUtils.isBusinessEntity(fieldClass)) { - // for wikittyDto we use String for Id - result = "Wikitty"; - } - } else if (null != getModel().getEnumeration(result)) { - result = "String"; - } - } - result = EugengoUtils.toUpperCaseFirstLetter(result); - - return result; - } - - protected void generateCollectionAttributeAccessors(Writer output, - ObjectModelClass clazz, ObjectModelAttribute attr) throws IOException { - - EXT_NAME = "EXT_" + attr.getDeclaringElement().getName().toUpperCase(); - - String attrType = computeType(attr); - if (EugengoUtils.notEmpty(attrType)) { - attrType = getType(attrType, true); - } else { - return; - } - - // get collection element type for add and remove method arguement type - String elementType = getType(attr.getType(), true); - - String methodAccessName = getFieldAccessMethodName(attr); - - String attrName = attr.getName(); - String attrNameCapitalized = EugengoUtils.toUpperCaseFirstLetter(attrName); -/*{ static public <%=attrType%> get<%=attrNameCapitalized%>(Wikitty w) { - <%=attrType%> result = w.getFieldAs<%=methodAccessName%>(<%=EXT_NAME%>, <%=clazz.getName()%>.FIELD_<%=clazz.getName().toUpperCase()%>_<%=attr.getName().toUpperCase()%>, <%=getClassAndGeneric(attrType)[1]%>.class); - return result; - } - - static public void add<%=attrNameCapitalized%>(Wikitty w, <%=elementType%> element) { - w.addToField(<%=EXT_NAME%>, <%=clazz.getName()%>.FIELD_<%=clazz.getName().toUpperCase()%>_<%=attr.getName().toUpperCase()%>, element); - } - - static public void remove<%=attrNameCapitalized%>(Wikitty w, <%=elementType%> element) { - w.removeFromField(<%=EXT_NAME%>, <%=clazz.getName()%>.FIELD_<%=clazz.getName().toUpperCase()%>_<%=attr.getName().toUpperCase()%>, element); - } - - static public void clear<%=attrNameCapitalized%>(Wikitty w) { - w.clearField(<%=EXT_NAME%>, <%=clazz.getName()%>.FIELD_<%=clazz.getName().toUpperCase()%>_<%=attr.getName().toUpperCase()%>); - } - -}*/ - } - - private static Set<String> commonNumerics; - static { - commonNumerics = new HashSet<String>(); - commonNumerics.add("byte"); - commonNumerics.add("Byte"); - commonNumerics.add("short"); - commonNumerics.add("Short"); - commonNumerics.add("int"); - commonNumerics.add("Integer"); - commonNumerics.add("long"); - commonNumerics.add("Long"); - commonNumerics.add("float"); - commonNumerics.add("Float"); - commonNumerics.add("double"); - commonNumerics.add("Double"); - } - - private static Set<String> commonStrings; - static { - commonStrings = new HashSet<String>(); - commonStrings.add("char"); - commonStrings.add("Char"); - commonStrings.add("String"); - } - - private static Set<String> commonTypes; - static { - commonTypes = new HashSet<String>(); - commonTypes.addAll(commonNumerics); - commonTypes.addAll(commonStrings); - commonTypes.add("boolean"); - commonTypes.add("Boolean"); - commonTypes.add("Date"); - } - -} Modified: branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/WikittyMetaGenerator.java =================================================================== --- branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/WikittyMetaGenerator.java 2010-08-06 14:41:51 UTC (rev 240) +++ branches/wikitty-eugene-migration/wikitty-generators/src/main/java/org/nuiton/wikitty/generator/WikittyMetaGenerator.java 2010-08-09 14:12:47 UTC (rev 241) @@ -1,136 +1,275 @@ package org.nuiton.wikitty.generator; -import java.io.File; -import java.io.IOException; import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Enumeration; +import java.util.Collection; import java.util.List; -import java.util.Properties; +import java.util.Random; +import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; -import org.nuiton.eugene.models.object.ObjectModel; -import org.nuiton.eugene.models.object.ObjectModelGenerator; -import org.nuiton.util.Resource; +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.ObjectModelInterface; +import org.nuiton.eugene.models.object.ObjectModelModifier; +import org.nuiton.eugene.models.object.ObjectModelOperation; +import org.nuiton.util.StringUtil; -public class WikittyMetaGenerator extends ObjectModelGenerator { +public class WikittyMetaGenerator extends ObjectModelTransformerToJava { - protected static Log log = LogFactory.getLog(WikittyMetaGenerator.class); + private static final Log log = LogFactory.getLog(WikittyMetaGenerator.class); - /** - * la liste des generateurs par defaut a utiliser - */ - protected static final List<Class<? extends WikengoCommonGenerator>> DEFAULT_GENERATORS = - Collections.unmodifiableList(Arrays.asList( + protected static final String BUSINESS_ENTITY_STEREOTYPE_NAME = "BusinessEntity"; + protected static final String BUSINESS_ENTITY_CLASS_FQN = "org.nuiton.wikitty.BusinessEntity"; + protected static final String BUSINESS_ENTITY_WIKITTY_CLASS_FQN = "org.nuiton.wikitty.BusinessEntity"; + protected static final String WIKITTY_CLASS_FQN = "org.nuiton.wikitty.Wikitty"; - // Enum - InterfaceGenerator.class, - EnumGenerator.class, + /** current class read from model */ + protected ObjectModelClass clazz; + + /** contract for this business entity */ + protected ObjectModelInterface contract; - // Wikitty (Interface, impl...) - BusinessEntityInterfaceGenerator.class, - BusinessEntityAbstractGenerator.class, - BusinessEntityImplGenerator.class, - WikittyHelperGenerator.class + /** abstract class for this business entity */ + protected ObjectModelClass abstractClass; - )); + /** implementation class for this business entity */ + protected ObjectModelClass implementation; - protected List<Class<? extends WikengoCommonGenerator>> getGenerators() { - List<Class<? extends WikengoCommonGenerator>> result = DEFAULT_GENERATORS; - Properties props = null; - try { - Properties tmpProperties = Resource.getConfigProperties("WikittyMetaGenerator.properties"); + /** implementation class for this business entity */ + protected ObjectModelClass helper; - props = new Properties(); + /** the body of the equals method, will be assembled while reading attributes */ + protected String equalsBody; + + @Override + public void transformFromClass(ObjectModelClass clazz) { + this.clazz = clazz; + + Collection<ObjectModelClass> superClasses = clazz.getSuperclasses(); + if (superClasses.size() > 1) { + log.error("Java doesn't support multiple inheritance for class " + clazz.getName()); + return ; + } - // Mise à plat du fichier (sans parent) - for (Enumeration<?> e = tmpProperties.propertyNames(); e.hasMoreElements();) { - String key = e.nextElement() + ""; - String value = tmpProperties.getProperty(key); - props.setProperty(key, value); - } + if (clazz.getStereotypes().contains(BUSINESS_ENTITY_STEREOTYPE_NAME)) { + + // for a single business entity, we create a contract, an abstract and an implementation + contract = createInterface(clazz.getName(), clazz.getPackageName()); + abstractClass = createAbstractClass(clazz.getName() + "Abstract", clazz.getPackageName()); + implementation = createClass(clazz.getName() + "Impl", clazz.getPackageName()); + helper = createClass(clazz.getName() + "Helper", clazz.getPackageName()); - } catch (IOException ioe) { - log.error("Unable to load file WikengoMetaGenerator.properties : " + ioe.getMessage()); - } + // now, deal with inheritance + + // implementation extends abstract and abstract realizes contract + addInterface(contract, BUSINESS_ENTITY_CLASS_FQN); + addInterface(abstractClass, contract.getQualifiedName()); + setSuperClass(implementation, abstractClass.getQualifiedName()); + setSuperClass(helper, implementation.getQualifiedName()); // as it was in the old templates - if (props != null) { - List<Class<? extends WikengoCommonGenerator>> propsGenerators = new ArrayList<Class<? extends WikengoCommonGenerator>>(); - String basePackage = props.getProperty("basePackage"); - String suffix = props.getProperty("suffix"); - if (basePackage != null && !basePackage.endsWith(".")) { - basePackage += "."; + // dealing with inheritance between entities specified in the model + for (ObjectModelClass superClass : superClasses) { + // using "for" but there will be 0 or 1 iteration + addInterface(contract, superClass.getQualifiedName()); + addInterface(abstractClass, superClass.getQualifiedName()); + setSuperClass(abstractClass, superClass.getQualifiedName() + "Impl"); } - for (Object key : props.keySet()) { - String className = (String)key; - if ( suffix != null ) className += suffix; - // Try with "className" - Class<? extends WikengoCommonGenerator> clazz = getClass(className); + // adding public static final String EXT_CLIENT = "Client"; + addConstant(contract, + "EXT_" + clazz.getName().toUpperCase(), + "String", + clazz.getName(), + ObjectModelModifier.PUBLIC); - // Try with "baseName.className" - if (clazz == null && basePackage != null) { - clazz = getClass(basePackage + className); - } + // adding serialVersionUIDs + Random random = new Random(); + Long serialVersionUIDs = random.nextLong(); + addConstant(abstractClass, + "serialVersionUID", + "long", + serialVersionUIDs.toString() + "L", + ObjectModelModifier.PRIVATE); + serialVersionUIDs = random.nextLong(); + addConstant(implementation, + "serialVersionUID", + "long", + serialVersionUIDs.toString() + "L", + ObjectModelModifier.PRIVATE); + + // making constructors for abstract and implementation (both are same) + addConstructors(abstractClass); + addConstructors(implementation); - if (clazz != null) { - propsGenerators.add(clazz); - } else { - log.warn("No generator found for property '" + className + "'"); - } + // making constructor for helper class (empty and private) + ObjectModelOperation constructor = addConstructor(helper, ObjectModelModifier.PRIVATE); + setOperationBody(constructor, ""); // empty implementation + + // adding some constants about extension to abstract + addConstant(abstractClass, "extensions", "List<WikittyExtension>", null, ObjectModelModifier.PUBLIC); + addConstant(abstractClass, "extension" + clazz.getName(), "WikittyExtension", null, ObjectModelModifier.PUBLIC); + + // ... and a getter + ObjectModelOperation getStaticExtensions = addOperation(abstractClass, "getStaticExtensions", "Collection<WikittyExtension>", ObjectModelModifier.PUBLIC); + setOperationBody(getStaticExtensions, "\nreturn extensions;\n"); + addAnnotation(abstractClass, getStaticExtensions, "Override"); + + // preparing a static block to initialize those constants + ObjectModelOperation staticInitialization = addBlock(abstractClass, ObjectModelModifier.STATIC); + String staticInitializationBody = "\nList<WikittyExtension> exts = new ArrayList<WikittyExtension>();"; + + for (ObjectModelClass superClass : superClasses) { + // using "for" but there will be 0 or 1 iteration + staticInitializationBody += "\nexts.addAll(" + superClass.getName() + "Abstract.extensions);\n" + + "// current after requires ones\n"; } - if (!propsGenerators.isEmpty()) { - result = propsGenerators; - } - } + staticInitializationBody += "exts.add(extension" + clazz.getName()+ ");\n" + + "extensions = Collections.unmodifiableList(exts);\n"; + + // generating constructor call for extensionClient + // we will build a string to write a call + List<String> buildFieldMapExtensionParameters = new ArrayList<String>(); - log.warn("Enabled generators: " + result); - return result; - } + // preparing static equals(w1, w2) + ObjectModelOperation equals = addOperation(abstractClass, "equals", "boolean", ObjectModelModifier.STATIC); + addParameter(equals, WIKITTY_CLASS_FQN, "w1"); + addParameter(equals, WIKITTY_CLASS_FQN, "w2"); + equalsBody = "\nboolean result = true;\n"; + + // now process attributes + for(ObjectModelAttribute attribute : clazz.getAttributes()) { + processAttribute(attribute); - protected Class<? extends WikengoCommonGenerator> getClass(String className) { - Class<? extends WikengoCommonGenerator> result = null; - try { - Class<?> clazz = Class.forName(className); - if (WikengoCommonGenerator.class.isAssignableFrom(clazz)) { - result = (Class<? extends WikengoCommonGenerator>)clazz; + // equalsBody will be updated in processAttribute + buildFieldMapExtensionParameters.add("\"" + attribute.getType() + " " + attribute.getName() + "\""); } - } catch (ClassNotFoundException e) { - // Nothing to do + + // finishing equals body + equalsBody += "\nreturn result;\n"; + setOperationBody(equals, equalsBody); + + // finishing static block + String extensionVersion = clazz.getTagValue("version"); + if (extensionVersion == null || "".equals(extensionVersion)) { + extensionVersion = "0.1"; + log.warn("no version specified in model for " + clazz.getQualifiedName() + " using " + extensionVersion); + } + staticInitializationBody += "\n\n extensionClient = new WikittyExtension(" + + "EXT_" + clazz.getName().toUpperCase() + ", " + + extensionVersion + ", "; + String requires = null; + for (ObjectModelClass superClass : superClasses) { + // using "for" but there will be 0 or 1 iteration + requires = superClass.getName() + ".EXT_" + superClass.getName().toUpperCase(); + } + + staticInitializationBody += requires + ", " + + "WikittyUtil.buildFieldMapExtension(" + + StringUtils.join(buildFieldMapExtensionParameters, ", \n") + "));"; + setOperationBody(staticInitialization, staticInitializationBody); } - return result; } - @Override - public void applyTemplate(ObjectModel model, File destDir) throws IOException { - for (Class<? extends ObjectModelGenerator> generatorClass : getGenerators()) { - ObjectModelGenerator generator; - if (excludeTemplates != null && excludeTemplates.contains(generatorClass.getName())) { - // exclude generator - log.info("exclude generator " + generatorClass); - continue; - } - try { + /** add three constructors : empty, from business entity wikitty, from wikitty */ + protected void addConstructors(ObjectModelClass clazz) { + ObjectModelOperation constructor = addConstructor(clazz, ObjectModelModifier.PUBLIC); + setOperationBody(constructor, "\nsuper();\n"); - generator = generatorClass.newInstance(); - generator.setParent(this); + constructor = addConstructor(clazz, ObjectModelModifier.PUBLIC); + addParameter(constructor, BUSINESS_ENTITY_WIKITTY_CLASS_FQN, "businessEntityWikitty"); + setOperationBody(constructor, "\nsuper(businessEntityWikitty.getWikitty());\n"); - } catch (Exception e) { - // should never happens - if (log.isErrorEnabled()) { - log.error("An error occurs when generating persistence", e); + constructor = addConstructor(clazz, ObjectModelModifier.PUBLIC); + addParameter(constructor, WIKITTY_CLASS_FQN, "wikitty"); + setOperationBody(constructor, "\nsuper(wikitty);\n"); + } + + + protected void processAttribute(ObjectModelAttribute attribute) { + // two variables needed below + String extensionVariableName = "EXT_" + clazz.getName().toUpperCase(); + String fieldVariableName = "FIELD_" + clazz.getName().toUpperCase() + "_" + attribute.getName().toUpperCase(); + + // adding constants to contract + { + addConstant(contract, + fieldVariableName, + "String", + "\"" + attribute.getName() + "\"", + ObjectModelModifier.PUBLIC); + // adding public static final String FQ_FIELD_CLIENT_NAME = EXT_CLIENT + ".name"; + addConstant(contract, + "FQ_" + fieldVariableName, + "String", + extensionVariableName + " + \"." + attribute.getName() + "\"", + ObjectModelModifier.PUBLIC); + } + + // getters and setters + { + // adding a getter + String getterName = attribute.getTagValue("getter"); + if (getterName == null) { // no name specified + getterName = "get" + StringUtils.capitalize(attribute.getName()); + if (! contract.getOperations(getterName).isEmpty()) { + getterName += "From" + clazz.getName(); } - throw new RuntimeException(e); - } + } // TODO 20100609 bleny deal with conflicts + + + // adding a setter + String setterName = attribute.getTagValue("setter"); + if (setterName == null) { // no name specified + setterName = "set" + StringUtils.capitalize(attribute.getName()); + if (! contract.getOperations(setterName).isEmpty()) { + setterName += "From" + clazz.getName(); + } + } // TODO 20100609 bleny deal with conflicts - // log - if (log.isDebugEnabled()) { - log.debug("call template : " + generatorClass.getSimpleName()); - } - generator.applyTemplate(model, destDir); + // adding getter and setter to contract + addOperation(contract, getterName, attribute.getType()); + ObjectModelOperation setter = addOperation(contract, setterName, "void"); + addParameter(setter, attribute.getType(), attribute.getName()); + + + // adding getter and setter to abstract with bodies + ObjectModelOperation getter = addOperation(abstractClass, getterName, attribute.getType()); + String getterBody = "\n" + attribute.getType() + + " result = getWikitty().getFieldAs" + + attribute.getType() + "(" + extensionVariableName + ", " + fieldVariableName + ");\n" + + "return result;\n"; + setOperationBody(getter, getterBody); + + setter = addOperation(abstractClass, setterName, "void"); + addParameter(setter, attribute.getType(), attribute.getName()); + String setterBody = "\nObject oldValue = getField("+extensionVariableName+", " + fieldVariableName + ");\n" + + "getWikitty().setField("+extensionVariableName+", " + fieldVariableName + ", "+attribute.getName()+");\n" + + "getPropertyChangeSupport().firePropertyChange(" + fieldVariableName + ", oldValue, "+attribute.getName()+");\n"; + setOperationBody(setter, setterBody); + + // adding getter and setter to Helper with bodies + getter = addOperation(helper, getterName, attribute.getType(), ObjectModelModifier.STATIC); + addParameter(getter, WIKITTY_CLASS_FQN, "wikitty"); + getterBody = "\n" + attribute.getType() + " result = wikitty.getFieldAs" + attribute.getType() + "(" + extensionVariableName + ", " + fieldVariableName + ");\n" + + "return result;\n"; + setOperationBody(getter, getterBody); + + setter = addOperation(helper, setterName, "void", ObjectModelModifier.STATIC); + addParameter(setter, WIKITTY_CLASS_FQN, "wikitty"); + addParameter(setter, attribute.getType(), attribute.getName()); + setterBody = "wikitty.setField("+extensionVariableName+", " + clazz.getName() + "."+fieldVariableName+", " + attribute.getName() + ");\n"; + setOperationBody(setter, setterBody); } + + // considering field in equals body + { + equalsBody += "\nif (result) {\n" + + "Object f1 = w1.getFieldAsObject(" + extensionVariableName + ", " + fieldVariableName + ");\n" + + "Object f2 = w2.getFieldAsObject(" + extensionVariableName + ", " + fieldVariableName + ");\n" + + "result = f1 == f2 || (f1 != null && f1.equals(f2));\n" + + "}"; + } } - }