[lib-update][cleanup] Rewrite generate.entities to use freemarker.
authorStefan Hühner <stefan.huehner@openbravo.com>
Mon, 18 Apr 2011 15:27:23 +0200
changeset 11851 88b0fe1357f8
parent 11850 8df723d2423d
child 11852 706976b77cb0
[lib-update][cleanup] Rewrite generate.entities to use freemarker.
As the new UI relies heavily on the freemarker template engine a rewrite of
generate.entities was done to not need to carry and maintain another template
engine (xpand2). Other side-effect: faster generation
Changes:
- Rewrite GenerateEntitiesTask using freemarker
- Change small parts of base/model to not output fully qualified java type-names
always but just classnames & generate matching java import statements.
- simplify build.xml: generate.entities is now just clean of src-gen &
generate.entities.quick which in that case does full generation
- change build files to fork a new jvm for the task (as implicitely done before)
- remove old implementation/template files and their dependencies (jars)
build.xml
lib/runtime/hybridlabs-beautifier-1.1.9.jar
lib/runtime/jalopy-1.5-rc3p1.jar
lib/runtime/org.eclipse.emf.common_2.4.0.v200806091234.jar
lib/runtime/org.eclipse.emf.ecore.xmi_2.4.0.v200806091234.jar
lib/runtime/org.eclipse.emf.ecore_2.4.0.v200806091234.jar
lib/runtime/org.eclipse.equinox.common_3.4.0.v20080421-2006.jar
lib/runtime/org.eclipse.text_3.4.0.v20080605-1800.jar
lib/runtime/org.openarchitectureware.core.emftools_4.3.1.20080910-1400PRD.jar
lib/runtime/org.openarchitectureware.core.expressions_4.3.1.20080910-1400PRD.jar
lib/runtime/org.openarchitectureware.core.workflow_4.3.1.20080910-1400PRD.jar
lib/runtime/org.openarchitectureware.core.xpand2_4.3.1.20080910-1400PRD.jar
src/build.xml
src/org/openbravo/base/gen/GenerateEntitiesTask.java
src/org/openbravo/base/gen/ModelProviderComponent.java
src/org/openbravo/base/gen/OBJavaBeautifier.java
src/org/openbravo/base/gen/base.xpt
src/org/openbravo/base/gen/entity.ftl
src/org/openbravo/base/gen/entity.xpt
src/org/openbravo/base/gen/gen_entity.oaw
src/org/openbravo/base/gen/gen_util.ext
src/org/openbravo/base/gen/model.xpt
src/org/openbravo/base/model/Entity.java
src/org/openbravo/base/model/Property.java
--- a/build.xml	Mon Apr 18 14:36:42 2011 +0200
+++ b/build.xml	Mon Apr 18 15:27:23 2011 +0200
@@ -543,6 +543,11 @@
     <ant dir="${base.src}" target="generate.entities.quick" inheritAll="true" inheritRefs="true" />
   </target>
 
+  <!-- build-internal forking helper -->
+  <target name="generate.entities.quick.forked">
+    <ant dir="${base.src}" target="generate.entities.quick.forked" inheritAll="true" inheritRefs="true" />
+  </target>
+
   <target name="run.tests" depends="init">
     <ant dir="${base.src}" target="run.tests" inheritAll="true" inheritRefs="true" />
   </target>
Binary file lib/runtime/hybridlabs-beautifier-1.1.9.jar has changed
Binary file lib/runtime/jalopy-1.5-rc3p1.jar has changed
Binary file lib/runtime/org.eclipse.emf.common_2.4.0.v200806091234.jar has changed
Binary file lib/runtime/org.eclipse.emf.ecore.xmi_2.4.0.v200806091234.jar has changed
Binary file lib/runtime/org.eclipse.emf.ecore_2.4.0.v200806091234.jar has changed
Binary file lib/runtime/org.eclipse.equinox.common_3.4.0.v20080421-2006.jar has changed
Binary file lib/runtime/org.eclipse.text_3.4.0.v20080605-1800.jar has changed
Binary file lib/runtime/org.openarchitectureware.core.emftools_4.3.1.20080910-1400PRD.jar has changed
Binary file lib/runtime/org.openarchitectureware.core.expressions_4.3.1.20080910-1400PRD.jar has changed
Binary file lib/runtime/org.openarchitectureware.core.workflow_4.3.1.20080910-1400PRD.jar has changed
Binary file lib/runtime/org.openarchitectureware.core.xpand2_4.3.1.20080910-1400PRD.jar has changed
--- a/src/build.xml	Mon Apr 18 14:36:42 2011 +0200
+++ b/src/build.xml	Mon Apr 18 15:27:23 2011 +0200
@@ -13,7 +13,7 @@
  * and  limitations under the License. 
  * The Original Code is Openbravo ERP. 
  * The Initial Developer of the Original Code is Openbravo SLU 
- * All portions are Copyright (C) 2005-2010 Openbravo SLU 
+ * All portions are Copyright (C) 2005-2011 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s): Openbravo S.L.U.
  ************************************************************************
@@ -238,34 +238,8 @@
     <ant dir="${base.db}" target="database.postupdate.${bbdd.rdbms}" inheritAll="true" inheritRefs="true" />
   </target>
 
-  <target name="generate.entities" depends="compile.src.gen,clean.src.gen">
-    <taskdef name="workflow" classpathref="project.class.path" classname="org.openbravo.base.gen.GenerateEntitiesTask" />
-    <!-- debug="true" will perform the in-memory model initialization before generating entities
-	if an error occurs then, then a stacktrace is printed. -->
-    <workflow debug="false" friendlyWarnings="${friendlyWarnings}" srcGenPath="${base.src.gen}" propertiesFile="${base.config}/Openbravo.properties" file="${base.src}/org/openbravo/base/gen/gen_entity.oaw" fork="true" maxmemory="${build.maxmemory}">
-      <param name="ob.properties.location" value="${base.config}/Openbravo.properties" />
-      <param name="base.src.gen" value="${base.src.gen}" />
-      <param name="friendlyWarnings" value="${friendlyWarnings}"/>
-      <classpath>
-        <path refid="project.class.path" />
-      </classpath>
-    </workflow>
-
-    <!--
-    see issue: https://issues.openbravo.com/view.php?id=9331
-    Custom columns in standard tables should support a reference to a table in the module
-    if this occurs then possible the following javac has to be enabled instead of the two javacs below
-    <javac srcdir="${base.src}:${base.src.gen}" excludes="org/openbravo/base/*,org/openbravo/base/secureApp/**,org/openbravo/erpCommon/**,org/openbravo/erpReports/**,org/openbravo/scheduling/**,org/openbravo/service/web/**,org/openbravo/service/system/**,org/openbravo/service/rest/**,org/openbravo/service/db/**,org/openbravo/authentication/**,org/openbravo/services/**" destdir="${build}" encoding="UTF-8" fork="true" memorymaximumsize="${build.maxmemory}" debug="true" debuglevel="lines,vars,source" deprecation="on">
-      <classpath refid="project.class.path" />
-    </javac>
-    -->
-    <javac srcdir="${base.src}:${base.src.gen}" includes="org/openbravo/model/**,org/openbravo/base/structure/**,org/openbravo/dal/**,org/openbravo/service/dataset/**" destdir="${build}" encoding="UTF-8" fork="true" memorymaximumsize="${build.maxmemory}" debug="true" debuglevel="lines,vars,source" deprecation="on">
-      <classpath refid="project.class.path" />
-    </javac>
-    <javac srcdir="${base.src.gen}" excludes="org/openbravo/model/**,org/openbravo/base/structure/**,org/openbravo/dal/**,org/openbravo/service/dataset/**" destdir="${build}" encoding="UTF-8" fork="true" memorymaximumsize="${build.maxmemory}" debug="true" debuglevel="lines,vars,source" deprecation="on">
-      <classpath refid="project.class.path" />
-    </javac>
-  </target>
+  <!-- full generate.entities -> clean + .quick -->
+  <target name="generate.entities" depends="clean.src.gen,generate.entities.quick" />
 
   <!-- 
 		Generates entities only when the application dictionary has changed.
@@ -275,36 +249,33 @@
 		is a source older than the last updated time of the Application Dictionary then the sources need to be regenerated.		
 	-->
   <target name="generate.entities.quick" depends="compile.src.gen">
-
-    <taskdef name="workflow" classpathref="project.class.path" classname="org.openbravo.base.gen.GenerateEntitiesTask" />
-    <!-- debug="true" will perform the in-memory model initialization before generating entities
-	if an error occurs then, then a stacktrace is printed. -->
-    <workflow debug="false" friendlyWarnings="${friendlyWarnings}" srcGenPath="${base.src.gen}" propertiesFile="${base.config}/Openbravo.properties" file="${base.src}/org/openbravo/base/gen/gen_entity.oaw" fork="true" maxmemory="${build.maxmemory}">
-      <param name="ob.properties.location" value="${base.config}/Openbravo.properties" />
-      <param name="base.src.gen" value="${base.src.gen}" />
-      <param name="friendlyWarnings" value="${friendlyWarnings}"/>
+    <java classname="org.openbravo.base.gen.GenerateEntitiesTask" fork="yes" jvm="${env.JAVA_HOME}/bin/java" maxmemory="${build.maxmemory}" failonerror="true">
+      <arg line="'${base.src}' '${friendlyWarnings}'" />
+      <classpath refid="project.class.path" />
       <syspropertyset>
          <propertyref name="java.security.egd" />
       </syspropertyset>
-      <classpath>
-        <path refid="project.class.path" />
-      </classpath>
-    </workflow>
+    </java>
+      <!--
+        see issue: https://issues.openbravo.com/view.php?id=9331
+        Custom columns in standard tables should support a reference to a table in the module
+        if this occurs then possible the following javac has to be enabled instead of the two javacs below
+      <javac srcdir="${base.src}:${base.src.gen}" destdir="${build}" encoding="UTF-8" fork="true" memorymaximumsize="${build.maxmemory}" debug="true" debuglevel="lines,vars,source" deprecation="on">
+        <classpath refid="project.class.path" />      
+      </javac>
+      -->
+      <javac srcdir="${base.src}:${base.src.gen}" includes="org/openbravo/model/**,org/openbravo/base/structure/**,org/openbravo/dal/**,org/openbravo/service/dataset/**" destdir="${build}" encoding="UTF-8" fork="true" memorymaximumsize="${build.maxmemory}" debug="true" debuglevel="lines,vars,source" deprecation="on">
+        <classpath refid="project.class.path" />      
+      </javac>
+      <javac srcdir="${base.src.gen}" excludes="org/openbravo/model/**,org/openbravo/base/structure/**,org/openbravo/dal/**,org/openbravo/service/dataset/**" destdir="${build}" encoding="UTF-8" fork="true" memorymaximumsize="${build.maxmemory}" debug="true" debuglevel="lines,vars,source" deprecation="on">
+        <classpath refid="project.class.path" />
+      </javac>
+  </target>
 
-    <!--
-      see issue: https://issues.openbravo.com/view.php?id=9331
-      Custom columns in standard tables should support a reference to a table in the module
-      if this occurs then possible the following javac has to be enabled instead of the two javacs below
-    <javac srcdir="${base.src}:${base.src.gen}" destdir="${build}" encoding="UTF-8" fork="true" memorymaximumsize="${build.maxmemory}" debug="true" debuglevel="lines,vars,source" deprecation="on">
-      <classpath refid="project.class.path" />      
-    </javac>
-    -->
-    <javac srcdir="${base.src}:${base.src.gen}" includes="org/openbravo/model/**,org/openbravo/base/structure/**,org/openbravo/dal/**,org/openbravo/service/dataset/**" destdir="${build}" encoding="UTF-8" fork="true" memorymaximumsize="${build.maxmemory}" debug="true" debuglevel="lines,vars,source" deprecation="on">
-      <classpath refid="project.class.path" />      
-    </javac>
-    <javac srcdir="${base.src.gen}" excludes="org/openbravo/model/**,org/openbravo/base/structure/**,org/openbravo/dal/**,org/openbravo/service/dataset/**" destdir="${build}" encoding="UTF-8" fork="true" memorymaximumsize="${build.maxmemory}" debug="true" debuglevel="lines,vars,source" deprecation="on">
-      <classpath refid="project.class.path" />
-    </javac>
+  <!-- build-internal forking helper -->
+  <target name="generate.entities.quick.forked" depends="compile.src.gen">
+    <taskdef name="workflow" classpathref="project.class.path" classname="org.openbravo.base.gen.GenerateEntitiesTaskFreemarker" />
+    <workflow friendlyWarnings="${friendlyWarnings}" srcGenPath="${base.src.gen}" propertiesFile="${base.config}/Openbravo.properties" />
   </target>
 
   <target name="run.tests" depends="compileSqlc,generate.entities.quick">
--- a/src/org/openbravo/base/gen/GenerateEntitiesTask.java	Mon Apr 18 14:36:42 2011 +0200
+++ b/src/org/openbravo/base/gen/GenerateEntitiesTask.java	Mon Apr 18 15:27:23 2011 +0200
@@ -11,7 +11,7 @@
  * under the License. 
  * The Original Code is Openbravo ERP. 
  * The Initial Developer of the Original Code is Openbravo SLU 
- * All portions are Copyright (C) 2008 Openbravo SLU 
+ * All portions are Copyright (C) 2008-2011 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -19,41 +19,67 @@
 
 package org.openbravo.base.gen;
 
+import java.io.BufferedWriter;
 import java.io.File;
+import java.io.FileOutputStream;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.io.Writer;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
 
 import org.apache.log4j.Logger;
-import org.openarchitectureware.workflow.ant.WorkflowAntTask;
+import org.apache.tools.ant.Task;
+import org.openbravo.base.AntExecutor;
 import org.openbravo.base.exception.OBException;
+import org.openbravo.base.model.Entity;
 import org.openbravo.base.model.ModelProvider;
-import org.openbravo.base.provider.OBConfigFileProvider;
-import org.openbravo.base.provider.OBProvider;
 import org.openbravo.base.session.OBPropertiesProvider;
-import org.openbravo.base.util.OBClassLoader;
+
+import freemarker.template.Configuration;
+import freemarker.template.DefaultObjectWrapper;
+import freemarker.template.TemplateException;
 
 /**
- * Task generates the entities using OpenArchitectureWare. It initializes the dal/model layer, the
- * rest of the work is done by the superclass.
+ * Task generates the entities using the freemarker template engine.
  * 
  * @author Martin Taal
+ * @author Stefan Huehner
  */
-public class GenerateEntitiesTask extends WorkflowAntTask {
+public class GenerateEntitiesTask extends Task {
   private static final Logger log = Logger.getLogger(GenerateEntitiesTask.class);
 
-  private static String basePath;
+  private String basePath;
   private String srcGenPath;
+  private String propertiesFile;
 
-  public static String getBasePath() {
+  public static void main(String[] args) {
+    final String srcPath = args[0];
+    String friendlyWarnings = "false";
+    if (args.length >= 2) {
+      friendlyWarnings = args[0];
+    }
+    final File srcDir = new File(srcPath);
+    final File baseDir = srcDir.getParentFile();
+    try {
+      final AntExecutor antExecutor = new AntExecutor(baseDir.getAbsolutePath());
+      antExecutor.setProperty("friendlyWarnings", friendlyWarnings);
+      antExecutor.runTask("generate.entities.quick.forked");
+    } catch (final Exception e) {
+      throw new OBException(e);
+    }
+  }
+
+  public String getBasePath() {
     return basePath;
   }
 
-  public static void setBasePath(String basePath) {
-    GenerateEntitiesTask.basePath = basePath;
+  public void setBasePath(String basePath) {
+    this.basePath = basePath;
   }
 
-  private String propertiesFile;
-  private String providerConfigDirectory;
-  private boolean debug;
-
   public boolean getFriendlyWarnings() {
     return OBPropertiesProvider.isFriendlyWarnings();
   }
@@ -70,37 +96,56 @@
     this.propertiesFile = propertiesFile;
   }
 
+  public String getSrcGenPath() {
+    return srcGenPath;
+  }
+
+  public void setSrcGenPath(String srcGenPath) {
+    this.srcGenPath = srcGenPath;
+  }
+
   @Override
   public void execute() {
-
     if (getBasePath() == null) {
       setBasePath(super.getProject().getBaseDir().getAbsolutePath());
     }
 
+    // the beautifier uses the source.path if it is not set
+    log.debug("initializating dal layer, getting properties from " + getPropertiesFile());
+    OBPropertiesProvider.getInstance().setProperties(getPropertiesFile());
+
     if (!hasChanged()) {
       log.info("Model has not changed since last run, not re-generating entities");
       return;
     }
 
-    if (debug) {
-      OBProvider.getInstance().register(OBClassLoader.class,
-          OBClassLoader.ClassOBClassLoader.class, false);
+    // read and parse template
+    String ftlFilename = "org/openbravo/base/gen/entity.ftl";
+    File ftlFile = new File(getBasePath(), ftlFilename);
+    freemarker.template.Template template = createTemplateImplementation(ftlFile);
 
-      // the beautifier uses the source.path if it is not set
-      log.debug("initializating dal layer, getting properties from " + getPropertiesFile());
-      OBPropertiesProvider.getInstance().setProperties(getPropertiesFile());
+    // process template & write file for each entity
+    List<Entity> entities = ModelProvider.getInstance().getModel();
+    for (Entity entity : entities) {
+      String classfileName = entity.getClassName().replaceAll("\\.", "/") + ".java";
+      log.debug("Generating file: " + classfileName);
+      File outFile = new File(srcGenPath, classfileName);
+      new File(outFile.getParent()).mkdirs();
 
-      if (getProviderConfigDirectory() != null) {
-        OBConfigFileProvider.getInstance().setFileLocation(getProviderConfigDirectory());
+      Writer outWriter;
+      try {
+        outWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),
+            "UTF-8"));
+        Map<String, Object> data = new HashMap<String, Object>();
+
+        data.put("entity", entity);
+        processTemplate(template, data, outWriter);
+      } catch (IOException e) {
+        log.error("Error generating file: " + classfileName, e);
       }
 
-      try {
-        ModelProvider.getInstance().getModel();
-      } catch (final Exception e) {
-        throw new OBException(e);
-      }
     }
-    super.execute();
+    log.info("Generated " + entities.size() + " entities");
   }
 
   private boolean hasChanged() {
@@ -113,17 +158,6 @@
       return true;
     }
 
-    OBProvider.getInstance().register(OBClassLoader.class, OBClassLoader.ClassOBClassLoader.class,
-        false);
-
-    // the beautifier uses the source.path if it is not set
-    log.debug("initializating dal layer, getting properties from " + getPropertiesFile());
-    OBPropertiesProvider.getInstance().setProperties(getPropertiesFile());
-
-    if (getProviderConfigDirectory() != null) {
-      OBConfigFileProvider.getInstance().setFileLocation(getProviderConfigDirectory());
-    }
-
     // check if the logic to generate has changed...
     final String sourceDir = getBasePath();
     long lastModifiedPackage = 0;
@@ -181,27 +215,29 @@
     return lastModified;
   }
 
-  public String getProviderConfigDirectory() {
-    return providerConfigDirectory;
+  private void processTemplate(freemarker.template.Template templateImplementation,
+      Map<String, Object> data, Writer output) {
+    try {
+      templateImplementation.process(data, output);
+    } catch (IOException e) {
+      throw new IllegalStateException(e);
+    } catch (TemplateException e) {
+      throw new IllegalStateException(e);
+    }
   }
 
-  public void setProviderConfigDirectory(String providerConfigDirectory) {
-    this.providerConfigDirectory = providerConfigDirectory;
+  private freemarker.template.Template createTemplateImplementation(File file) {
+    try {
+      return new freemarker.template.Template("template", new FileReader(file),
+          getNewConfiguration());
+    } catch (IOException e) {
+      throw new IllegalStateException(e);
+    }
   }
 
-  public boolean isDebug() {
-    return debug;
-  }
-
-  public void setDebug(boolean debug) {
-    this.debug = debug;
-  }
-
-  public String getSrcGenPath() {
-    return srcGenPath;
-  }
-
-  public void setSrcGenPath(String srcGenPath) {
-    this.srcGenPath = srcGenPath;
+  private Configuration getNewConfiguration() {
+    final Configuration cfg = new Configuration();
+    cfg.setObjectWrapper(new DefaultObjectWrapper());
+    return cfg;
   }
 }
--- a/src/org/openbravo/base/gen/ModelProviderComponent.java	Mon Apr 18 14:36:42 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,78 +0,0 @@
-/*
- *************************************************************************
- * The contents of this file are subject to the Openbravo  Public  License
- * Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
- * Version 1.1  with a permitted attribution clause; you may not  use this
- * file except in compliance with the License. You  may  obtain  a copy of
- * the License at http://www.openbravo.com/legal/license.html 
- * Software distributed under the License  is  distributed  on  an "AS IS"
- * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
- * License for the specific  language  governing  rights  and  limitations
- * under the License. 
- * The Original Code is Openbravo ERP. 
- * The Initial Developer of the Original Code is Openbravo SLU 
- * All portions are Copyright (C) 2008 Openbravo SLU 
- * All Rights Reserved. 
- * Contributor(s):  ______________________________________.
- ************************************************************************
- */
-
-package org.openbravo.base.gen;
-
-import org.openarchitectureware.workflow.WorkflowComponent;
-import org.openarchitectureware.workflow.WorkflowContext;
-import org.openarchitectureware.workflow.ast.parser.Location;
-import org.openarchitectureware.workflow.container.CompositeComponent;
-import org.openarchitectureware.workflow.issues.Issues;
-import org.openarchitectureware.workflow.monitor.ProgressMonitor;
-import org.openbravo.base.model.ModelProvider;
-import org.openbravo.base.session.OBPropertiesProvider;
-
-/**
- * Sets the model in the work flow context, so that the generator can pick it up from there.
- * 
- * @author mtaal
- */
-
-public class ModelProviderComponent implements WorkflowComponent {
-
-  private String propFile;
-
-  public void checkConfiguration(Issues arg0) {
-  }
-
-  public CompositeComponent getContainer() {
-    return null;
-  }
-
-  public Location getLocation() {
-    return null;
-  }
-
-  public void invoke(WorkflowContext wc, ProgressMonitor pm, Issues issues) {
-    wc.set("model", ModelProvider.getInstance());
-  }
-
-  public boolean getFriendlyWarnings() {
-    return OBPropertiesProvider.isFriendlyWarnings();
-  }
-
-  public void setFriendlyWarnings(boolean doFriendlyWarnings) {
-    OBPropertiesProvider.setFriendlyWarnings(doFriendlyWarnings);
-  }
-
-  public void setContainer(CompositeComponent arg0) {
-  }
-
-  public void setLocation(Location arg0) {
-  }
-
-  public void setPropFile(String propFile) {
-    OBPropertiesProvider.getInstance().setProperties(propFile);
-    this.propFile = propFile;
-  }
-
-  public String getPropFile() {
-    return propFile;
-  }
-}
--- a/src/org/openbravo/base/gen/OBJavaBeautifier.java	Mon Apr 18 14:36:42 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,57 +0,0 @@
-/*
- *************************************************************************
- * The contents of this file are subject to the Openbravo  Public  License
- * Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
- * Version 1.1  with a permitted attribution clause; you may not  use this
- * file except in compliance with the License. You  may  obtain  a copy of
- * the License at http://www.openbravo.com/legal/license.html 
- * Software distributed under the License  is  distributed  on  an "AS IS"
- * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
- * License for the specific  language  governing  rights  and  limitations
- * under the License. 
- * The Original Code is Openbravo ERP. 
- * The Initial Developer of the Original Code is Openbravo SLU 
- * All portions are Copyright (C) 2008 Openbravo SLU 
- * All Rights Reserved. 
- * Contributor(s):  ______________________________________.
- ************************************************************************
- */
-
-package org.openbravo.base.gen;
-
-import java.io.File;
-
-import org.hybridlabs.source.beautifier.CharacterSequence;
-import org.hybridlabs.source.formatter.JavaImportBeautifier;
-
-/**
- * Sets the user.home system variable to the source.path/temp directory. This so that the hybridlabs
- * beautifier creates its preferences directory in the correct location.
- * 
- * @author Martin Taal
- */
-
-public class OBJavaBeautifier extends JavaImportBeautifier {
-
-  @Override
-  public void beautify(CharacterSequence characterSequence) {
-    final String userHome = System.getProperty("user.home");
-    // final String sourcePath = OBPropertiesProvider.getInstance()
-    // .getOpenbravoProperties().getProperty("source.path");
-    // Check.isNotNull(sourcePath,
-    // "The source.path parameter is not defined "
-    // + "in Openbravo.properties");
-    final String sourcePath = GenerateEntitiesTask.getBasePath();
-    final File tempDir = new File(sourcePath, "../temp");
-    if (!tempDir.exists()) {
-      tempDir.mkdirs();
-    }
-    try {
-      System.setProperty("user.home", tempDir.getAbsolutePath());
-      super.beautify(characterSequence);
-    } finally {
-      System.setProperty("user.home", userHome);
-    }
-  }
-
-}
--- a/src/org/openbravo/base/gen/base.xpt	Mon Apr 18 14:36:42 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,33 +0,0 @@
-«IMPORT org::openbravo::base::model»
-«IMPORT org::openbravo::base::gen»
-
-#  *************************************************************************
-#  * The contents of this file are subject to the Openbravo  Public  License
-#  * Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
-#  * Version 1.1  with a permitted attribution clause; you may not  use this
-#  * file except in compliance with the License. You  may  obtain  a copy of
-#  * the License at http://www.openbravo.com/legal/license.html 
-#  * Software distributed under the License  is  distributed  on  an "AS IS"
-#  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
-#  * License for the specific  language  governing  rights  and  limitations
-#  * under the License. 
-#  * The Original Code is Openbravo ERP. 
-#  * The Initial Developer of the Original Code is Openbravo SLU 
-#  * All portions are Copyright (C) 2008 Openbravo SLU 
-#  * All Rights Reserved. 
-#  * Contributor(s):  ______________________________________.
-#  ************************************************************************
- 
-«EXTENSION org::openbravo::base::gen::gen_util» 
- 
-«DEFINE root FOR ModelProvider»
-  «EXPAND org::openbravo::base::gen::entity::EntityTemplate FOREACH model»
-«ENDDEFINE» 
-
-# this define is there to get rid of the error
-# displayed by the editor because for the 
-# statement EXPAND Entity FOREACH model
-# it can determine the type for model
-«DEFINE EntityTemplate FOR Object»
-«ENDDEFINE»
- 
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/org/openbravo/base/gen/entity.ftl	Mon Apr 18 15:27:23 2011 +0200
@@ -0,0 +1,173 @@
+<#function getter p>
+  <#if p.boolean>
+    <#return "is" + p.getterSetterName?cap_first>
+  <#else>
+    <#return "get" + p.getterSetterName?cap_first>
+  </#if>
+</#function>
+
+<#function theList entity>
+  <#if entity.simpleClassName == "List">
+    <#return "java.util.List">
+  <#else>
+    <#return "List">
+  </#if>
+</#function>
+/*
+ *************************************************************************
+ * The contents of this file are subject to the Openbravo  Public  License
+ * Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
+ * Version 1.1  with a permitted attribution clause; you may not  use this
+ * file except in compliance with the License. You  may  obtain  a copy of
+ * the License at http://www.openbravo.com/legal/license.html
+ * Software distributed under the License  is  distributed  on  an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+ * License for the specific  language  governing  rights  and  limitations
+ * under the License.
+ * The Original Code is Openbravo ERP.
+ * The Initial Developer of the Original Code is Openbravo SLU
+ * All portions are Copyright (C) 2008-2011 Openbravo SLU
+ * All Rights Reserved.
+ * Contributor(s):  ______________________________________.
+ ************************************************************************
+*/
+package ${entity.packageName};
+<#list entity.javaImports as i>
+${i}
+</#list>
+/**
+ * Entity class for entity ${entity.name} (stored in table ${entity.tableName}).
+ *
+ * NOTE: This class should not be instantiated directly. To instantiate this
+ * class the {@link org.openbravo.base.provider.OBProvider} should be used.
+ */
+public class ${entity.simpleClassName} extends BaseOBObject ${entity.implementsStatement} {
+    private static final long serialVersionUID = 1L;
+    public static final String TABLE_NAME = "${entity.tableName}";
+    public static final String ENTITY_NAME = "${entity.name}";
+    <#list entity.properties as p>
+    public static final String PROPERTY_${p.name?upper_case} = "${p.name}";
+    </#list>
+
+    public ${entity.simpleClassName}() {
+    <#list entity.properties as p>
+        <#if p.hasDefaultValue()>
+        setDefaultValue(PROPERTY_${p.name?upper_case}, ${p.formattedDefaultValue});
+        </#if>
+    </#list>
+    }
+
+    @Override
+    public String getEntityName() {
+        return ENTITY_NAME;
+    }
+
+    <#list entity.properties as p>
+    <#if !p.oneToMany>
+    <#if p.name?matches("Id")>
+    @Override
+    </#if>
+    public ${p.shorterTypeName} ${getter(p)}() {
+    <#if p.partOfCompositeId>
+        return ((Id)getId()).«getter((Property)p)»();
+    <#else>
+        return (${p.shorterTypeName}) get(PROPERTY_${p.name?upper_case});
+    </#if>
+    }
+
+    <#if p.name?matches("Id")>
+    @Override
+    </#if>
+    public void set${p.getterSetterName?cap_first}(${p.shorterTypeName} ${p.javaName}) {
+    <#if p.partOfCompositeId>
+	    ((Id)getId()).set${p.getterSetterName?cap_first}(${p.javaName});
+	<#else>
+        set(PROPERTY_${p.name?upper_case}, ${p.javaName});
+	</#if>
+    }
+
+    </#if>
+	</#list>
+	<#list entity.properties as p>
+	<#if p.oneToMany>
+    @SuppressWarnings("unchecked")
+    public ${theList(entity)}<${p.shorterNameTargetEntity}> get${p.name?cap_first}() {
+        return (${theList(entity)}<${p.shorterNameTargetEntity}>) get(PROPERTY_${p.name?upper_case});
+    }
+
+    public void set${p.getterSetterName?cap_first}(${theList(entity)}<${p.shorterNameTargetEntity}> ${p.name}) {
+        set(PROPERTY_${p.name?upper_case}, ${p.name});
+    }
+
+    </#if>
+    </#list>
+    <#if entity.hasCompositeId()>
+	public static class Id implements java.io.Serializable {
+	    private static final long serialVersionUID = 1L;
+
+		<#list entity.properties as p>
+		<#if p.partOfCompositeId>
+		<#if p.hasDefaultValue()>
+		private ${p.typeName} ${p.javaName} = ${p.formattedDefaultValue};
+		<#else>
+		private ${p.typeName} ${p.javaName};
+		</#if>
+		</#if>
+		</#list>
+
+		<#list entity.properties as p>
+		<#if p.partOfCompositeId>
+		public ${p.typeName} «getter((Property)p)»() {
+			return ${p.javaName};
+		}
+		
+		public void set${p.getterSetterName?cap_first}(${p.typeName} ${p.javaName}) {
+			this.${p.javaName} = ${p.javaName};
+		}
+		</#if>
+		</#list>
+		
+	    public boolean equals(Object obj) {
+			if (this == obj) {
+    			return true;
+			}
+			if (!(obj instanceof Id)) {
+				return false;
+			}
+			final Id otherId = (Id)obj;
+		<#list entity.properties as p>
+		<#if p.partOfCompositeId>
+			if (!areEqual(«getter((Property)p)»(), otherId.«getter((Property)p)»())) {
+				return false;
+			} 
+		</#if>
+		</#list>
+			return true;
+		}
+
+		// hashCode assumes that keys can not change!
+    	public int hashCode() {
+    		int result = 0;
+    		<#list entity.properties as p>
+    		<#if p.partOfCompositeId>
+			if («getter((Property)p)»() != null) {
+				result +=«getter((Property)p)»().hashCode(); 
+			}
+			</#if>
+			</#list>
+    		
+    		if (result == 0) {
+    			return super.hashCode();
+    		}
+    		return result;
+    	}
+
+		private boolean areEqual(Object v1, Object v2) {
+			if (v1 == null || v2 == null) {
+				return v1 == v2;
+			}
+			return v1.equals(v2);
+		}		
+	}
+	</#if>
+}
--- a/src/org/openbravo/base/gen/entity.xpt	Mon Apr 18 14:36:42 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,175 +0,0 @@
-«IMPORT org::openbravo::base::model»
- 
-«EXTENSION org::openbravo::base::gen::gen_util» 
- 
-«DEFINE EntityTemplate FOR Entity»
-	«FILE classFileName(this)-»
-/*
- *************************************************************************
- * The contents of this file are subject to the Openbravo  Public  License
- * Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
- * Version 1.1  with a permitted attribution clause; you may not  use this
- * file except in compliance with the License. You  may  obtain  a copy of
- * the License at http://www.openbravo.com/legal/license.html 
- * Software distributed under the License  is  distributed  on  an "AS IS"
- * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
- * License for the specific  language  governing  rights  and  limitations
- * under the License.
- * The Original Code is Openbravo ERP.
- * The Initial Developer of the Original Code is Openbravo SLU
- * All portions are Copyright (C) 2008-2010 Openbravo SLU
- * All Rights Reserved.
- * Contributor(s):  ______________________________________.
- ************************************************************************
-*/
-
-package «packageName»;
-
-/** 
- * Entity class for entity «name» (stored in table «tableName»).
- *
- * NOTE: This class should not be instantiated directly. To instantiate this
- * class the {@link org.openbravo.base.provider.OBProvider} should be used. 
- */
-public class «simpleClassName» extends org.openbravo.base.structure.BaseOBObject «implementsStatement» {
-
-    private static final long serialVersionUID = 1L;
-
-	public final static String TABLE_NAME = "«tableName»";
-	public final static String ENTITY_NAME = "«name»";
-	«FOREACH properties AS p-»
-	public final static String PROPERTY_«((Property)p).name.toUpperCase()» = "«((Property)p).name»";
-	«ENDFOREACH-»
-	
-	public «simpleClassName»() {
-	«FOREACH properties AS p-»
-		«IF ((Property)p).hasDefaultValue()-»
-			setDefaultValue(PROPERTY_«((Property)p).name.toUpperCase()»,  «((Property)p).formattedDefaultValue»);
-		«ENDIF-»
-	«ENDFOREACH-»
-	}
-	
-    @Override
-	public String getEntityName() {
-		return ENTITY_NAME;
-	}
-	
-	«FOREACH properties AS p-»
-	«IF !((Property)p).oneToMany»
-	«IF ((Property)p).name.matches("Id") -»
-    @Override
-    «ENDIF-»
-	public «((Property)p).typeName» «getter((Property)p)»() {
-	«IF ((Property)p).partOfCompositeId-»
-		return ((Id)getId()).«getter((Property)p)»();
-	«ELSE-»
-		return («((Property)p).typeName»)get(PROPERTY_«((Property)p).name.toUpperCase()»);
-	«ENDIF-»
-	}
-	
-	«IF ((Property)p).name.matches("Id") -»
-    @Override
-    «ENDIF-»
-	public void set«((Property)p).getterSetterName.toFirstUpper()»(«((Property)p).typeName» «((Property)p).javaName») {
-	«IF ((Property)p).partOfCompositeId-»
-		((Id)getId()).set«((Property)p).getterSetterName.toFirstUpper()»(«((Property)p).javaName»);
-	«ELSE-»
-		set(PROPERTY_«((Property)p).name.toUpperCase()», «((Property)p).javaName»);
-	«ENDIF-»
-	}
-	«ENDIF»
-	«ENDFOREACH-»
-	
-	«FOREACH properties AS p-»
-	«IF ((Property)p).oneToMany-»
-	@SuppressWarnings("unchecked")
-	public java.util.List<«((Property)p).targetEntity.className»> get«((Property)p).name.toFirstUpper()»() {
-		return (java.util.List<«((Property)p).targetEntity.className»>) get(PROPERTY_«((Property)p).name.toUpperCase()»);
-	}
-	
-	public void set«((Property)p).getterSetterName.toFirstUpper()»(java.util.List<«((Property)p).targetEntity.className»> «((Property)p).name») {
-		set(PROPERTY_«((Property)p).name.toUpperCase()», «((Property)p).name»);
-	}
-	«ENDIF»
-	«ENDFOREACH»
-
-	«IF hasCompositeId()»
-	public static class Id implements java.io.Serializable {
-	    private static final long serialVersionUID = 1L;
-
-		«FOREACH properties AS p-»
-		«IF ((Property)p).partOfCompositeId-»
-		«IF ((Property)p).hasDefaultValue()»
-		private «((Property)p).typeName» «((Property)p).javaName» = «((Property)p).formattedDefaultValue»;
-		«ELSE-»
-		private «((Property)p).typeName» «((Property)p).javaName»;
-		«ENDIF-»
-		«ENDIF-»
-		«ENDFOREACH-»
-
-		«FOREACH properties AS p-»
-		«IF ((Property)p).partOfCompositeId-»
-		public «((Property)p).typeName» «getter((Property)p)»() {
-			return «((Property)p).javaName»;
-		}
-		
-		public void set«((Property)p).getterSetterName.toFirstUpper()»(«((Property)p).typeName» «((Property)p).javaName») {
-			this.«((Property)p).javaName» = «((Property)p).javaName»;
-		}
-		«ENDIF»
-		«ENDFOREACH-»
-		
-	    public boolean equals(Object obj) {
-			if (this == obj) {
-    			return true;
-			}
-			if (!(obj instanceof Id)) {
-				return false;
-			}
-			final Id otherId = (Id)obj;
-		«FOREACH properties AS p-»
-		«IF ((Property)p).partOfCompositeId-»
-			if (!areEqual(«getter((Property)p)»(), otherId.«getter((Property)p)»())) {
-				return false;
-			} 
-		«ENDIF»
-		«ENDFOREACH-»
-			return true;
-		}
-
-		// hashCode assumes that keys can not change!
-    	public int hashCode() {
-    		int result = 0;
-    		«FOREACH properties AS p-»
-			«IF ((Property)p).partOfCompositeId-»
-			if («getter((Property)p)»() != null) {
-				result +=«getter((Property)p)»().hashCode(); 
-			}
-			«ENDIF-»
-			«ENDFOREACH-»
-    		
-    		if (result == 0) {
-    			return super.hashCode();
-    		}
-    		return result;
-    	}
-
-		private boolean areEqual(Object v1, Object v2) {
-			if (v1 == null || v2 == null) {
-				return v1 == v2;
-			}
-			return v1.equals(v2);
-		}		
-	}
-	«ENDIF»
-}
-	«ENDFILE»
-«ENDDEFINE»
-
-# this define is there to get rid of the error
-# displayed by the editor because for the 
-# statement EXPAND Entity FOREACH model
-# it can determine the type for model
-«DEFINE EntityTemplate FOR Object»
-«ENDDEFINE»
- 
\ No newline at end of file
--- a/src/org/openbravo/base/gen/gen_entity.oaw	Mon Apr 18 14:36:42 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,44 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
-/*
- *************************************************************************
- * The contents of this file are subject to the Openbravo  Public  License
- * Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
- * Version 1.1  with a permitted attribution clause; you may not  use this
- * file except in compliance with the License. You  may  obtain  a copy of
- * the License at http://www.openbravo.com/legal/license.html 
- * Software distributed under the License  is  distributed  on  an "AS IS"
- * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
- * License for the specific  language  governing  rights  and  limitations
- * under the License. 
- * The Original Code is Openbravo ERP. 
- * The Initial Developer of the Original Code is Openbravo SLU 
- * All portions are Copyright (C) 2008 Openbravo SLU 
- * All Rights Reserved. 
- * Contributor(s):  ______________________________________.
- ************************************************************************
-*/
--->
-<workflow>
-	<!-- sets the list of Tables in the model slot -->
-	<component class="org.openbravo.base.gen.ModelProviderComponent">
-		<propFile value="${ob.properties.location}" />
-    <friendlyWarnings value="${friendlyWarnings}" />
-	</component>	
-	<component class="oaw.xpand2.Generator">
-		 <metaModel class="oaw.type.impl.java.JavaMetaModel"/>
-		 <expand value="org::openbravo::base::gen::base::root FOR model"/>
-	
-		 <!--  output configuration -->
-		 <outlet path="${base.src.gen}"/>
-		 <beautifier class="org.openbravo.base.gen.OBJavaBeautifier"
-			organizeImports="true" format="true"/>
-<!--		 <beautifier class="org.hybridlabs.source.formatter.JavaImportBeautifier"
-			organizeImports="true" format="true"/>-->
-
-		 <!--<beautifier class="oaw.xpand2.output.JavaBeautifier"/>-->
-	 
-		 <!-- TBD: protected regions configuration -->
-	</component>
-</workflow> 
- 
\ No newline at end of file
--- a/src/org/openbravo/base/gen/gen_util.ext	Mon Apr 18 14:36:42 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,6 +0,0 @@
-import org::openbravo::base::model;
-
-classFileName( Entity this ): className.replaceAll("\\.","/")+".java";	
-
-getter(Property this) :
- 	boolean ? "is" + getterSetterName.toFirstUpper() : "get" + getterSetterName.toFirstUpper();
--- a/src/org/openbravo/base/gen/model.xpt	Mon Apr 18 14:36:42 2011 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,61 +0,0 @@
-«IMPORT org::openbravo::base::model»
-
-#  *************************************************************************
-#  * The contents of this file are subject to the Openbravo  Public  License
-#  * Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
-#  * Version 1.1  with a permitted attribution clause; you may not  use this
-#  * file except in compliance with the License. You  may  obtain  a copy of
-#  * the License at http://www.openbravo.com/legal/license.html 
-#  * Software distributed under the License  is  distributed  on  an "AS IS"
-#  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
-#  * License for the specific  language  governing  rights  and  limitations
-#  * under the License. 
-#  * The Original Code is Openbravo ERP. 
-#  * The Initial Developer of the Original Code is Openbravo SLU 
-#  * All portions are Copyright (C) 2008 Openbravo SLU 
-#  * All Rights Reserved. 
-#  * Contributor(s):  ______________________________________.
-#  ************************************************************************
- 
-«EXTENSION org::openbravo::base::gen::gen_util» 
- 
-«DEFINE ModelTemplate FOR ModelProvider»
-  «EXPAND EntityTemplate FOREACH model»
-  	«FOREACH model AS entity-»
-  
-  	«FILE "org/openbravo/model/definition/" + ((Entity)entity).name + ".java"-»
-/*   
- *  
- * Copyright (C) 2001-2008 Openbravo S.L.U. Licensed under the Apache Software
- * License version 2.0 You may obtain a copy of the License at
- * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
- * or agreed to in writing, software distributed under the License is
- * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the specific language
- * governing permissions and limitations under the License.
- */
-package org.openbravo.model.definition;
-
-/** 
- * Static references to names of entity: «((Entity)entity).name»
- */
-public class «((Entity)entity).name» {	
-		// Entity: «((Entity)entity).name»
-		public static final String ENTITYNAME = "«((Entity)entity).name»";
-		«FOREACH ((Entity)entity).properties AS p-»
-		public static final String «((Entity)entity).name.toUpperCase()»_«((Property)p).name» = "«((Property)p).name»";
-		«ENDFOREACH-»
-}
-
-	«ENDFILE»
-	«ENDFOREACH-»
-  
-«ENDDEFINE» 
-
-# this define is there to get rid of the error
-# displayed by the editor because for the 
-# statement EXPAND Entity FOREACH model
-# it can determine the type for model
-«DEFINE EntityTemplate FOR Object»
-«ENDDEFINE»
- 
\ No newline at end of file
--- a/src/org/openbravo/base/model/Entity.java	Mon Apr 18 14:36:42 2011 +0200
+++ b/src/org/openbravo/base/model/Entity.java	Mon Apr 18 15:27:23 2011 +0200
@@ -20,9 +20,12 @@
 package org.openbravo.base.model;
 
 import java.util.ArrayList;
+import java.util.Collections;
 import java.util.HashMap;
+import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
+import java.util.Set;
 
 import org.apache.log4j.Logger;
 import org.openbravo.base.exception.OBException;
@@ -330,25 +333,25 @@
     // to prevent binary dependency
     final StringBuilder sb = new StringBuilder();
     if (isTraceable()) {
-      sb.append("org.openbravo.base.structure.Traceable");
+      sb.append("Traceable");
     }
     if (isClientEnabled()) {
       if (sb.length() > 0) {
         sb.append(", ");
       }
-      sb.append("org.openbravo.base.structure.ClientEnabled");
+      sb.append("ClientEnabled");
     }
     if (isOrganizationEnabled()) {
       if (sb.length() > 0) {
         sb.append(", ");
       }
-      sb.append("org.openbravo.base.structure.OrganizationEnabled");
+      sb.append("OrganizationEnabled");
     }
     if (isActiveEnabled()) {
       if (sb.length() > 0) {
         sb.append(", ");
       }
-      sb.append("org.openbravo.base.structure.ActiveEnabled");
+      sb.append("ActiveEnabled");
     }
     if (sb.length() == 0) {
       return "";
@@ -632,4 +635,110 @@
   public void setView(boolean isView) {
     this.isView = isView;
   }
+
+  List<String> getJavaImportsInternal() {
+    List<String> imports = new ArrayList<String>();
+    Set<String> simpleImports = new HashSet<String>();
+    imports.add("org.openbravo.base.structure.BaseOBObject");
+    simpleImports.add("BaseOBObject");
+
+    if (isTraceable()) {
+      imports.add("org.openbravo.base.structure.Traceable");
+      simpleImports.add("Traceable");
+    }
+    if (isClientEnabled()) {
+      imports.add("org.openbravo.base.structure.ClientEnabled");
+      simpleImports.add("ClientEnabled");
+    }
+    if (isOrganizationEnabled()) {
+      imports.add("org.openbravo.base.structure.OrganizationEnabled");
+      simpleImports.add("OrganizationEnabled");
+    }
+    if (isActiveEnabled()) {
+      imports.add("org.openbravo.base.structure.ActiveEnabled");
+      simpleImports.add("ActiveEnabled");
+    }
+
+    // collect types of properties
+    for (Property p : properties) {
+      String fullType, simpleType;
+      if (p.isOneToMany()) {
+        // add list-type here to take precedence over model class named List
+        fullType = "java.util.List";
+        simpleType = "List";
+        if (!simpleImports.contains(simpleType)) {
+          if (!simpleType.equals(getSimpleClassName())) {
+            if (!imports.contains(fullType)) {
+              imports.add(fullType);
+              simpleImports.add(simpleType);
+            }
+          }
+        }
+      }
+      if (p.getTargetEntity() != null) {
+        fullType = p.getTargetEntity().getClassName();
+        simpleType = p.getTargetEntity().getSimpleClassName();
+      } else if (p.isPrimitive() && !p.getPrimitiveType().isArray()) {
+        fullType = p.getPrimitiveType().getName();
+        simpleType = p.getPrimitiveType().getSimpleName();
+      } else {
+        continue;
+      }
+      if (!simpleImports.contains(simpleType)) {
+        if (!simpleType.equals(getSimpleClassName())) {
+          if (!imports.contains(fullType)) {
+            imports.add(fullType);
+            simpleImports.add(simpleType);
+          }
+        }
+      }
+      // for lists with defaults also add list type
+      if (p.hasDefaultValue() && p.isOneToMany()) {
+        fullType = "java.util.ArrayList";
+        simpleType = "ArrayList";
+        if (!simpleImports.contains(simpleType)) {
+          if (!simpleType.equals(getSimpleClassName())) {
+            if (!imports.contains(fullType)) {
+              imports.add(fullType);
+              simpleImports.add(simpleType);
+            }
+          }
+        }
+      }
+    }
+
+    Collections.sort(imports);
+    return imports;
+  }
+
+  private static String getPackageFromClassname(String className) {
+    int i = className.lastIndexOf(".");
+    return className.substring(0, i);
+  }
+
+  private static String getFirstPartOfPackage(String packageName) {
+    int i = packageName.indexOf(".");
+    return packageName.substring(0, i);
+  }
+
+  /**
+   * Used to generate java import statements during generate.entities
+   */
+  public List<String> getJavaImports() {
+    List<String> imports = getJavaImportsInternal();
+    List<String> result = new ArrayList<String>();
+    String lastImport = "";
+    for (String i : imports) {
+      String packageName = getPackageFromClassname(i);
+      if (!packageName.equals("java.lang") && !packageName.equals(getPackageName())) {
+        if (!getFirstPartOfPackage(packageName).equals(lastImport)) {
+          result.add("");
+        }
+        result.add("import " + i + ";");
+
+        lastImport = getFirstPartOfPackage(packageName);
+      }
+    }
+    return result;
+  }
 }
--- a/src/org/openbravo/base/model/Property.java	Mon Apr 18 14:36:42 2011 +0200
+++ b/src/org/openbravo/base/model/Property.java	Mon Apr 18 15:27:23 2011 +0200
@@ -359,11 +359,11 @@
             "Default value is only supported for composite ids, primitive types, and one-to-many properties: property "
                 + this);
     if (isCompositeId()) {
-      return " new Id()";
+      return "new Id()";
     }
 
     if (isOneToMany()) {
-      return " new java.util.ArrayList<Object>()";
+      return "new ArrayList<Object>()";
     }
 
     if (defaultValue == null && isBoolean()) {
@@ -383,7 +383,7 @@
         return null;
       }
       if (defaultValue.toLowerCase().equals("sysdate")) {
-        return " new java.util.Date()";
+        return "new Date()";
       }
 
       // ignore all other Date defaults for now
@@ -392,13 +392,13 @@
       }
 
       if (getPrimitiveType() == BigDecimal.class) {
-        return " new java.math.BigDecimal(" + defaultValue + ")";
+        return "new BigDecimal(" + defaultValue + ")";
       }
       if (getPrimitiveType() == Float.class || getPrimitiveType() == float.class) {
         return defaultValue + "f";
       }
       if (getPrimitiveType() == Long.class || getPrimitiveType() == long.class) {
-        return "(long)" + defaultValue;
+        return "(long) " + defaultValue;
       }
       if (getPrimitiveType() == String.class) {
         if (defaultValue.length() > 1
@@ -592,6 +592,43 @@
   }
 
   /**
+   * Used during generate.entities to generate short java type-names if a corresponding java import
+   * statement is generated for this type.
+   */
+  public String getShorterTypeName() {
+    List<String> imports = entity.getJavaImportsInternal();
+    String typeName = getTypeName();
+    if (typeName.equals(getEntity().getClassName())) {
+      return getSimpleTypeName();
+    }
+    if (imports.contains(typeName)) {
+      return getSimpleTypeName();
+    }
+    // needed to work around isKey columns mapped as TableDir (i.e. ad_clientinformation)
+    if ("java.lang.String".equals(typeName)) {
+      return getSimpleTypeName();
+    }
+    return typeName;
+  }
+
+  /**
+   * Used during generate.entities to generate short java type-names if a corresponding java import
+   * statement is generated for this type.
+   */
+  public String getShorterNameTargetEntity() {
+    List<String> imports = entity.getJavaImportsInternal();
+    String typeName = targetEntity.getClassName();
+    String simpleName = targetEntity.getSimpleClassName();
+    if (typeName.equals(getEntity().getClassName())) {
+      return simpleName;
+    }
+    if (imports.contains(typeName)) {
+      return simpleName;
+    }
+    return typeName;
+  }
+
+  /**
    * The last part of the class name of the type of the property. Used by the entity code
    * generation.
    */