Commit to solve some of the memory issues when building after installing modules. Also changed the initialization of the dal after installing a module because it needs to take into account the database model changes applied by a module. In addition solved the issue that after installing a module the new classes of the module can not be loaded and therefore the dal mapping generator failed.
authorMartin Taal <martin.taal@openbravo.com>
Wed, 03 Dec 2008 12:52:09 +0000
changeset 2205 f881eca76a88
parent 2204 f24b079ae7e2
child 2206 615cc3261897
Commit to solve some of the memory issues when building after installing modules. Also changed the initialization of the dal after installing a module because it needs to take into account the database model changes applied by a module. In addition solved the issue that after installing a module the new classes of the module can not be loaded and therefore the dal mapping generator failed.
build.xml
src-test/org/openbravo/test/base/BaseTest.java
src/org/openbravo/base/gen/GenerateEntitiesTask.java
src/org/openbravo/base/model/BaseOBObjectDef.java
src/org/openbravo/base/model/Entity.java
src/org/openbravo/base/model/ModelProvider.java
src/org/openbravo/base/provider/OBProvider.java
src/org/openbravo/base/provider/OBProviderConfigReader.java
src/org/openbravo/base/secureApp/HttpSecureAppServlet.java
src/org/openbravo/base/session/SessionFactoryController.java
src/org/openbravo/base/structure/OBDynamicPropertyHandler.java
src/org/openbravo/base/validation/NumericPropertyValidator.java
src/org/openbravo/dal/core/DalContextListener.java
src/org/openbravo/dal/core/DalInitializingTask.java
src/org/openbravo/dal/core/DalLayerInitializer.java
src/org/openbravo/dal/core/DalMappingGenerator.java
src/org/openbravo/dal/core/DalRequestFilter.java
src/org/openbravo/dal/core/OBDynamicTuplizer.java
src/org/openbravo/dal/core/OBTuplizer.java
src/org/openbravo/dal/core/template.hbm.xml
src/org/openbravo/erpCommon/ad_process/ApplyModules.java
--- a/build.xml	Wed Dec 03 08:33:54 2008 +0000
+++ b/build.xml	Wed Dec 03 12:52:09 2008 +0000
@@ -268,7 +268,7 @@
     <ant dir="${base.src}" target="compile.src.gen" inheritAll="true" inheritRefs="true"/>
   </target>
 
-  <target name="generate.entities" depends="compile.src.gen">
+  <target name="generate.entities">
     <ant dir="${base.src}" target="generate.entities" inheritAll="true" inheritRefs="true"/>
   </target>
 
@@ -483,9 +483,9 @@
       <classpath refid="project.class.path"/>
     </taskdef>
     <antcall target="update.database.mod"/>
-    <antcall target="generate.entities"/>
     <applyModule userId="0"
-                 propertiesFile="${base.config}/Openbravo.properties"/>
+                 propertiesFile="${base.config}/Openbravo.properties"
+    			reinitializemodel="true"/>
 		<antcall target="compile.deploy"/>
 		<!--antcall target="deploy.context"/-->
 	</target>
--- a/src-test/org/openbravo/test/base/BaseTest.java	Wed Dec 03 08:33:54 2008 +0000
+++ b/src-test/org/openbravo/test/base/BaseTest.java	Wed Dec 03 12:52:09 2008 +0000
@@ -53,7 +53,7 @@
     protected void initializeDalLayer() throws Exception {
         if (!DalLayerInitializer.getInstance().isInitialized()) {
             setConfigPropertyFiles();
-            DalLayerInitializer.getInstance().initialize();
+            DalLayerInitializer.getInstance().initialize(true);
         }
     }
 
--- a/src/org/openbravo/base/gen/GenerateEntitiesTask.java	Wed Dec 03 08:33:54 2008 +0000
+++ b/src/org/openbravo/base/gen/GenerateEntitiesTask.java	Wed Dec 03 12:52:09 2008 +0000
@@ -66,7 +66,6 @@
                         getProviderConfigDirectory());
             }
 
-            log.info("Initializing in-memory model...");
             try {
                 ModelProvider.getInstance().getModel();
             } catch (final Exception e) {
--- a/src/org/openbravo/base/model/BaseOBObjectDef.java	Wed Dec 03 08:33:54 2008 +0000
+++ b/src/org/openbravo/base/model/BaseOBObjectDef.java	Wed Dec 03 12:52:09 2008 +0000
@@ -37,4 +37,6 @@
     public Entity getEntity();
 
     public Object getId();
+
+    public String getIdentifier();
 }
\ No newline at end of file
--- a/src/org/openbravo/base/model/Entity.java	Wed Dec 03 08:33:54 2008 +0000
+++ b/src/org/openbravo/base/model/Entity.java	Wed Dec 03 12:52:09 2008 +0000
@@ -24,6 +24,7 @@
 import java.util.List;
 import java.util.Map;
 
+import org.apache.log4j.Logger;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.exception.OBSecurityException;
 import org.openbravo.base.util.Check;
@@ -47,6 +48,7 @@
  */
 
 public class Entity {
+    private static final Logger log = Logger.getLogger(Entity.class);
 
     private List<UniqueConstraint> uniqueConstraints = new ArrayList<UniqueConstraint>();
 
@@ -62,6 +64,7 @@
     private String tableName;
     private String tableId;
     private Class<?> mappingClass = null;
+    private boolean mappingClassComputed = false;
     private String className;
     private boolean isTraceable;
     private boolean isActiveEnabled;
@@ -110,7 +113,7 @@
             properties.add(p);
             propertiesByName.put(p.getName(), p);
             if (p.getColumnName() != null) {
-                propertiesByColumnName.put(p.getColumnName(), p);
+                propertiesByColumnName.put(p.getColumnName().toLowerCase(), p);
             }
             if (p.isId()) {
                 idProperties.add(p);
@@ -160,7 +163,8 @@
     public void addProperty(Property property) {
         getProperties().add(property);
         if (property.getColumnName() != null) {
-            propertiesByColumnName.put(property.getColumnName(), property);
+            propertiesByColumnName.put(property.getColumnName().toLowerCase(),
+                    property);
         }
         if (property.isIdentifier()) {
             getIdentifierProperties().add(property);
@@ -217,15 +221,26 @@
         this.className = className;
     }
 
+    /**
+     * Loads the class using the {@link #getClassName()} . If this fails then
+     * the null is returned and the system will use a DynamicOBObject as the
+     * runtime class.
+     * 
+     * @return the java class implementing this Entity, or null if the class is
+     *         not available (not found)
+     */
     public Class<?> getMappingClass() {
-        if (mappingClass == null) {
+        if (mappingClass == null && !mappingClassComputed) {
             try {
                 // the context class loader is the safest one
                 mappingClass = OBClassLoader.getInstance().loadClass(
                         getClassName());
             } catch (final Exception e) {
-                throw new OBException(e);
+                log.warn("No class present for entity " + getName()
+                        + " using dynamic object");
+                mappingClass = null;
             }
+            mappingClassComputed = true;
         }
         return mappingClass;
     }
@@ -362,7 +377,8 @@
      * @throws CheckException
      */
     public Property getPropertyByColumnName(String columnName) {
-        final Property prop = propertiesByColumnName.get(columnName);
+        final Property prop = propertiesByColumnName.get(columnName
+                .toLowerCase());
         Check.isNotNull(prop, "Property with " + columnName
                 + " does not exist for entity " + this);
         return prop;
--- a/src/org/openbravo/base/model/ModelProvider.java	Wed Dec 03 08:33:54 2008 +0000
+++ b/src/org/openbravo/base/model/ModelProvider.java	Wed Dec 03 12:52:09 2008 +0000
@@ -31,6 +31,7 @@
 import org.hibernate.classic.Session;
 import org.hibernate.criterion.Expression;
 import org.hibernate.criterion.Order;
+import org.openbravo.base.exception.OBException;
 import org.openbravo.base.provider.OBProvider;
 import org.openbravo.base.provider.OBSingleton;
 import org.openbravo.base.session.SessionFactoryController;
@@ -98,6 +99,24 @@
     }
 
     /**
+     * Creates a new ModelProvider, initializes it and sets it in the instance
+     * here.
+     */
+    public static void refresh() {
+        try {
+            OBProvider.getInstance().removeInstance(ModelProvider.class);
+            final ModelProvider localProvider = OBProvider.getInstance().get(
+                    ModelProvider.class);
+            setInstance(localProvider);
+            // initialize it
+            localProvider.getModel();
+        } catch (final Exception e) {
+            e.printStackTrace(System.err);
+            throw new OBException(e);
+        }
+    }
+
+    /**
      * @return the list of Tables read from the Application Dictionary.
      */
     public List<Table> getTables() {
@@ -202,12 +221,12 @@
                 session.close();
                 sessionFactoryController.getSessionFactory().close();
             }
-        }
 
-        // now initialize the names of the properties
-        for (final Entity e : model) {
-            for (final Property p : e.getProperties()) {
-                p.initializeName();
+            // now initialize the names of the properties
+            for (final Entity e : model) {
+                for (final Property p : e.getProperties()) {
+                    p.initializeName();
+                }
             }
         }
 
--- a/src/org/openbravo/base/provider/OBProvider.java	Wed Dec 03 08:33:54 2008 +0000
+++ b/src/org/openbravo/base/provider/OBProvider.java	Wed Dec 03 12:52:09 2008 +0000
@@ -129,13 +129,13 @@
         if (currentReg != null) {
             if (!overwrite || !currentReg.isOverwritable()) {
                 log
-                        .warn("A different registration: "
+                        .debug("A different registration: "
                                 + currentReg
                                 + " already exists under this name, NOT overwriting it by "
                                 + reg);
                 return;
             } else {
-                log.warn(currentReg + " will be replaced by " + reg);
+                log.debug(currentReg + " will be replaced by " + reg);
             }
         } else {
             log.debug("Registering " + reg);
@@ -168,6 +168,24 @@
     }
 
     /**
+     * Removes the singleton instance of the clz (if any) from the internal
+     * registry. It will be recreated at next request.
+     * 
+     * @param clz
+     *            the instance of this class is removed.
+     */
+    public void removeInstance(Class<?> clz) {
+        log.debug("Removing instance " + clz.getName());
+        final Registration reg = registrations.get(clz.getName());
+        if (reg == null) {
+            log.debug("Removing instance " + clz.getName()
+                    + " but it was not registered, doing nothing");
+            return;
+        }
+        reg.setInstance(null);
+    }
+
+    /**
      * Returns an instance of the requested service. If no registration is found
      * an OBProviderException is thrown
      * 
--- a/src/org/openbravo/base/provider/OBProviderConfigReader.java	Wed Dec 03 08:33:54 2008 +0000
+++ b/src/org/openbravo/base/provider/OBProviderConfigReader.java	Wed Dec 03 12:52:09 2008 +0000
@@ -22,9 +22,11 @@
 import java.io.FileInputStream;
 import java.io.InputStream;
 
+import org.apache.log4j.Logger;
 import org.dom4j.Document;
 import org.dom4j.Element;
 import org.dom4j.io.SAXReader;
+import org.openbravo.base.exception.OBException;
 import org.openbravo.base.util.Check;
 import org.openbravo.base.util.OBClassLoader;
 
@@ -36,6 +38,8 @@
  * @author mtaal
  */
 class OBProviderConfigReader {
+    private static final Logger log = Logger
+            .getLogger(OBProviderConfigReader.class);
 
     private static final long serialVersionUID = 1L;
 
@@ -67,7 +71,18 @@
             // now check for three children:
             final String name = getValue(elem, "name", true);
             final String clzName = getValue(elem, "class", true);
-            final Class<?> clz = OBClassLoader.getInstance().loadClass(clzName);
+            Class<?> clz = null;
+            try {
+                clz = OBClassLoader.getInstance().loadClass(clzName);
+            } catch (final OBException e) {
+                // catch ClassNotFoundException
+                log.warn("Class " + clzName
+                        + " can not be loaded. This can happen "
+                        + "when rebuilding after installing new modules. "
+                        + "The system needs to be restarted to find "
+                        + "new services");
+                continue;
+            }
             if (OBModulePrefixRequired.class.isAssignableFrom(clz)
                     && prefix != null && prefix.trim().length() > 0) {
                 OBProvider.getInstance().register(prefix + "." + name, clz,
--- a/src/org/openbravo/base/secureApp/HttpSecureAppServlet.java	Wed Dec 03 08:33:54 2008 +0000
+++ b/src/org/openbravo/base/secureApp/HttpSecureAppServlet.java	Wed Dec 03 12:52:09 2008 +0000
@@ -8,7 +8,7 @@
  * 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.base.secureApp;
 
 import java.io.File;
@@ -17,7 +17,6 @@
 import java.io.InputStream;
 import java.io.PrintWriter;
 import java.sql.Connection;
-
 import java.text.DecimalFormat;
 import java.text.DecimalFormatSymbols;
 import java.util.HashMap;
@@ -71,829 +70,1057 @@
 import org.w3c.dom.Node;
 import org.w3c.dom.NodeList;
 
-public class HttpSecureAppServlet extends HttpBaseServlet{
-  private static final long serialVersionUID = 1L;
-  public boolean boolHist = true;
-  String myTheme = "";
-  public ClassInfoData classInfo;
-  protected AuthenticationManager m_AuthManager = null; 
-  
-  String servletClass = this.getClass().getName();
+public class HttpSecureAppServlet extends HttpBaseServlet {
+    private static final long serialVersionUID = 1L;
+    public boolean boolHist = true;
+    String myTheme = "";
+    public ClassInfoData classInfo;
+    protected AuthenticationManager m_AuthManager = null;
 
-  public class Variables extends VariablesHistory {
-    public Variables(HttpServletRequest request) {
-      super(request);
+    String servletClass = this.getClass().getName();
+
+    public class Variables extends VariablesHistory {
+        public Variables(HttpServletRequest request) {
+            super(request);
+        }
+
+        public void updateHistory(HttpServletRequest request) {
+            if (boolHist) {
+                String sufix = getCurrentHistoryIndex();
+                if (!(servletClass.equals(getSessionValue("reqHistory.servlet"
+                        + sufix, "")))) {
+                    upCurrentHistoryIndex();
+                    sufix = getCurrentHistoryIndex();
+                    setSessionValue("reqHistory.servlet" + sufix, servletClass);
+                    setSessionValue("reqHistory.path" + sufix, request
+                            .getServletPath());
+                    setSessionValue("reqHistory.command" + sufix, "DEFAULT");
+                }
+            }
+        }
+
+        public void setHistoryCommand(String strCommand) {
+            final String sufix = getCurrentHistoryIndex();
+            setSessionValue("reqHistory.command" + sufix, strCommand);
+        }
     }
 
-    public void updateHistory(HttpServletRequest request) {
-      if (boolHist) {
-        String sufix = getCurrentHistoryIndex();
-        if (!(servletClass.equals(getSessionValue("reqHistory.servlet" + sufix,"")))) {
-          upCurrentHistoryIndex();
-          sufix = getCurrentHistoryIndex();
-          setSessionValue("reqHistory.servlet" + sufix, servletClass);
-          setSessionValue("reqHistory.path" + sufix, request.getServletPath());
-          setSessionValue("reqHistory.command" + sufix, "DEFAULT");
+    @Override
+    public void init(ServletConfig config) {
+        super.init(config);
+
+        // Authentication manager load
+        // String sAuthManagerClass =
+        // config.getServletContext().getInitParameter("AuthenticationManager");
+        String sAuthManagerClass = globalParameters
+                .getOBProperty("authentication.class");
+        if (sAuthManagerClass == null || sAuthManagerClass.equals("")) {
+            // If not defined, load default
+            sAuthManagerClass = "org.openbravo.authentication.basic.DefaultAuthenticationManager";
         }
-      }
-    }
-    public void setHistoryCommand(String strCommand) {
-      String sufix = getCurrentHistoryIndex();
-      setSessionValue("reqHistory.command" + sufix, strCommand);
-    }
-  }
 
-  public void init (ServletConfig config) {
-    super.init(config);
+        try {
+            m_AuthManager = (AuthenticationManager) Class.forName(
+                    sAuthManagerClass).newInstance();
+        } catch (final Exception e) {
+            log4j.error("Authentication manager not defined", e);
+            m_AuthManager = new DefaultAuthenticationManager();
+        }
 
-    // Authentication manager load
-    // String sAuthManagerClass = config.getServletContext().getInitParameter("AuthenticationManager");
-    String sAuthManagerClass = globalParameters.getOBProperty("authentication.class");
-    if (sAuthManagerClass == null  || sAuthManagerClass.equals("")) {
-        // If not defined, load default
-        sAuthManagerClass = "org.openbravo.authentication.basic.DefaultAuthenticationManager";
+        try {
+            m_AuthManager.init(this);
+        } catch (final AuthenticationException e) {
+            log4j.error("Unable to initialize authentication manager", e);
+        }
+
+        if (log4j.isDebugEnabled())
+            log4j.debug("strdireccion: " + strDireccion);
     }
 
-    try {
-        m_AuthManager = (AuthenticationManager) Class.forName(sAuthManagerClass).newInstance();
-    } catch (Exception e) {
-        log4j.error("Authentication manager not defined", e);
-        m_AuthManager = new DefaultAuthenticationManager();
+    @Override
+    public void service(HttpServletRequest request, HttpServletResponse response)
+            throws IOException, ServletException {
+        final Variables variables = new Variables(request);
+        // VariablesSecureApp vars = new VariablesSecureApp(request);
+
+        try {
+            myTheme = variables.getSessionValue("#Theme");
+        } catch (final Exception ignored) {
+            myTheme = "Default";
+        }
+        try {
+            if (log4j.isDebugEnabled())
+                log4j.debug("Servlet request for class info: "
+                        + request.getServletPath());
+            ClassInfoData[] classInfoAux = ClassInfoData.select(this, variables
+                    .getLanguage(), request.getServletPath());
+            if (classInfoAux != null && classInfoAux.length > 0)
+                classInfo = classInfoAux[0];
+            else {
+                classInfoAux = ClassInfoData.set();
+                classInfo = classInfoAux[0];
+            }
+        } catch (final Exception ex) {
+            ex.printStackTrace();
+            final ClassInfoData[] classInfoAux = ClassInfoData.set();
+            classInfo = classInfoAux[0];
+        }
+
+        // bdErrorGeneral(response, "Error", "No access");
+
+        if (log4j.isDebugEnabled())
+            log4j.debug("class info type: " + classInfo.type + " - ID: "
+                    + classInfo.id + " - NAME: " + classInfo.name);
+        String strAjax = "";
+        String strHidden = "";
+        String strPopUp = "";
+        try {
+            strAjax = request.getParameter("IsAjaxCall");
+        } catch (final Exception ignored) {
+        }
+        try {
+            strHidden = request.getParameter("IsHiddenCall");
+        } catch (final Exception ignored) {
+        }
+        try {
+            strPopUp = request.getParameter("IsPopUpCall");
+        } catch (final Exception ignored) {
+        }
+
+        try {
+            final String strUserAuth = m_AuthManager.authenticate(request,
+                    response);
+            if (strUserAuth != null) {
+                if (variables.getRole().equals("")
+                        || !SeguridadData.loggedOK(this, variables
+                                .getDBSession())) {
+                    String strLanguage = "";
+                    String strIsRTL = "";
+                    String strRole = "";
+                    String strClient = "";
+                    String strOrg = "";
+                    String strWarehouse = "";
+
+                    strRole = DefaultOptionsData.defaultRole(this, strUserAuth);
+                    if (strRole == null)
+                        strRole = DefaultOptionsData.getDefaultRole(this,
+                                strUserAuth);
+                    validateDefault(strRole, strUserAuth, "Role");
+
+                    strOrg = DefaultOptionsData.defaultOrg(this, strUserAuth);
+                    if (strOrg == null)
+                        strOrg = DefaultOptionsData
+                                .getDefaultOrg(this, strRole);
+                    validateDefault(strOrg, strRole, "Org");
+
+                    strClient = DefaultOptionsData.defaultClient(this,
+                            strUserAuth);
+                    if (strClient == null)
+                        strClient = DefaultOptionsData.getDefaultClient(this,
+                                strRole);
+                    validateDefault(strClient, strRole, "Client");
+
+                    strWarehouse = DefaultOptionsData.defaultWarehouse(this,
+                            strUserAuth);
+                    if (strWarehouse == null) {
+                        if (!strRole.equals("0")) {
+                            strWarehouse = DefaultOptionsData
+                                    .getDefaultWarehouse(this, strClient,
+                                            new OrgTree(this, strClient)
+                                                    .getAccessibleTree(this,
+                                                            strRole).toString());
+                        } else
+                            strWarehouse = "";
+                    }
+
+                    DefaultOptionsData dataLanguage[] = DefaultOptionsData
+                            .defaultLanguage(this, strUserAuth);
+                    if (dataLanguage != null && dataLanguage.length > 0) {
+                        strLanguage = dataLanguage[0]
+                                .getField("DEFAULT_AD_LANGUAGE");
+                        strIsRTL = dataLanguage[0].getField("ISRTL");
+                    }
+                    if (strLanguage == null || strLanguage.equals("")) {
+                        dataLanguage = DefaultOptionsData
+                                .getDefaultLanguage(this);
+                        if (dataLanguage != null && dataLanguage.length > 0) {
+                            strLanguage = dataLanguage[0]
+                                    .getField("AD_LANGUAGE");
+                            strIsRTL = dataLanguage[0].getField("ISRTL");
+                        }
+                    }
+
+                    final VariablesSecureApp vars = new VariablesSecureApp(
+                            request);
+                    if (LoginUtils.fillSessionArguments(this, vars,
+                            strUserAuth, strLanguage, strIsRTL, strRole,
+                            strClient, strOrg, strWarehouse)) {
+                        readProperties(vars, globalParameters
+                                .getOpenbravoPropertiesPath());
+                        readNumberFormat(vars, globalParameters.getFormatPath());
+                        saveLoginBD(request, vars, strClient, strOrg);
+                    } else {
+                        // Re-login
+                        log4j.error("Unable to fill session Arguments for: "
+                                + strUserAuth);
+                        logout(request, response);
+                        return;
+                    }
+                } else
+                    variables.updateHistory(request);
+            }
+            log4j.info("Call to HttpBaseServlet.service");
+        } catch (final DefaultValidationException d) {
+            // Added DefaultValidationException class to catch user login
+            // without a valid role
+            final OBError roleError = new OBError();
+            roleError.setTitle("Invalid " + d.getDefaultField());
+            roleError.setType("Error");
+            roleError
+                    .setMessage("No valid "
+                            + d.getDefaultField()
+                            + " identified. Please contact your system administrator for access.");
+            invalidLogin(request, response, roleError);
+
+            return;
+        } catch (final Exception e) {
+            // Re-login
+            if (log4j.isDebugEnabled())
+                log4j
+                        .debug("HTTPSecureAppServlet.service() - exception caught: "
+                                + e.getMessage());
+            log4j.error(e);
+            logout(request, response);
+            return;
+        }
+
+        try {
+
+            super.initialize(request, response);
+            final VariablesSecureApp vars1 = new VariablesSecureApp(request,
+                    false);
+            if (vars1.getRole().equals("") || hasAccess(vars1)) {
+
+                final Boolean saveRequest = (Boolean) request
+                        .getAttribute("autosave");
+                final String strTabId = vars1.getStringParameter("inpTabId");
+
+                if (saveRequest == null && strTabId != null) {
+
+                    final String autoSave = request.getParameter("autosave");
+                    Boolean failedAutosave = (Boolean) vars1
+                            .getSessionObject(strTabId + "|failedAutosave");
+
+                    if (failedAutosave == null) {
+                        failedAutosave = false;
+                    }
+
+                    if (autoSave != null && autoSave.equalsIgnoreCase("Y")
+                            && !failedAutosave) {
+
+                        if (log4j.isDebugEnabled()) {
+                            log4j.debug("service: saveRequest - "
+                                    + this.getClass().getCanonicalName()
+                                    + " - autosave: " + autoSave);
+                        }
+
+                        if (log4j.isDebugEnabled()) {
+                            log4j.debug(this.getClass().getCanonicalName()
+                                    + " - hash: " + vars1.getPostDataHash());
+                        }
+
+                        final String servletMappingName = request
+                                .getParameter("mappingName");
+
+                        if (servletMappingName != null
+                                && !Utility.isExcludedFromAutoSave(this
+                                        .getClass().getCanonicalName())) {
+
+                            final String hash = vars1
+                                    .getSessionValue(servletMappingName
+                                            + "|hash");
+
+                            if (log4j.isDebugEnabled()) {
+                                log4j.debug("hash in session: " + hash);
+                            }
+                            // Check if the form was previously saved
+                            if (!hash.equals(vars1.getPostDataHash())) {
+                                // forward request
+                                request.setAttribute("autosave", true);
+                                if (vars1.getCommand().indexOf("BUTTON") != -1)
+                                    request.setAttribute("popupWindow", true);
+                                if (!forwardRequest(request, response)) {
+                                    return;
+                                }
+                            }
+                        }
+                    }
+                }
+                super.serviceInitialized(request, response);
+            } else {
+                if ((strPopUp != null && !strPopUp.equals(""))
+                        || (classInfo.type.equals("S")))
+                    bdErrorGeneralPopUp(response, Utility.messageBD(this,
+                            "Error", variables.getLanguage()), Utility
+                            .messageBD(this, "AccessTableNoView", variables
+                                    .getLanguage()));
+                else
+                    bdError(response, "AccessTableNoView", vars1.getLanguage());
+            }
+        } catch (final ServletException ex) {
+            log4j.error("Error captured: " + ex);
+            ex.printStackTrace();
+            final OBError myError = Utility.translateError(this, null,
+                    variables.getLanguage(), ex.getMessage());
+            if (strAjax != null && !strAjax.equals(""))
+                bdErrorAjax(response, myError.getType(), myError.getTitle(),
+                        myError.getMessage());
+            else if (strHidden != null && !strHidden.equals(""))
+                bdErrorHidden(response, myError.getType(), myError.getTitle(),
+                        myError.getMessage());
+            else if (!myError.isConnectionAvailable())
+                bdErrorConnection(response);
+            else if (strPopUp != null && !strPopUp.equals(""))
+                bdErrorGeneralPopUp(response, myError.getTitle(), myError
+                        .getMessage());
+            else
+                bdErrorGeneral(response, myError.getTitle(), myError
+                        .getMessage());
+        } catch (final OBException e) {
+            e.printStackTrace(System.err);
+            final Boolean isAutosaving = (Boolean) request
+                    .getAttribute("autosave");
+            if (isAutosaving) {
+                request.removeAttribute("autosave");
+                request.removeAttribute("popupWindow");
+                throw e;
+            } else {
+                log4j.error("Error captured: " + e);
+                e.printStackTrace();
+                if (strPopUp != null && !strPopUp.equals(""))
+                    bdErrorGeneralPopUp(response, "Error", e.toString());
+                else
+                    bdErrorGeneral(response, "Error", e.toString());
+            }
+        } catch (final Exception e) {
+            log4j.error("Error captured: " + e);
+            e.printStackTrace(System.err);
+            if (strPopUp != null && !strPopUp.equals(""))
+                bdErrorGeneralPopUp(response, "Error", e.toString());
+            else
+                bdErrorGeneral(response, "Error", e.toString());
+        }
     }
 
-    try {
-        m_AuthManager.init(this);
-    } catch (AuthenticationException e) {
-        log4j.error("Unable to initialize authentication manager", e);
-    }
-    
-    if (log4j.isDebugEnabled()) log4j.debug("strdireccion: " + strDireccion);
-  }
+    /**
+     * Cheks access passing all the parameters
+     * 
+     * @param vars
+     * @param type
+     *            type of element
+     * @param id
+     *            id for the element
+     * @return true in case it has access false if not
+     */
+    protected boolean hasGeneralAccess(VariablesSecureApp vars, String type,
+            String id) {
+        try {
+            final String accessLevel = AccessData.selectAccessLevel(this, type,
+                    id);
+            vars.setSessionValue("#CurrentAccessLevel", accessLevel);
+            if (type.equals("W")) {
+                return hasLevelAccess(vars, accessLevel)
+                        && AccessData.selectAccess(this, vars.getRole(),
+                                "TABLE", id).equals("0")
+                        && !AccessData.selectAccess(this, vars.getRole(), type,
+                                id).equals("0");
+            } else if (type.equals("S")) {
+                return !AccessData.selectAccessSearch(this, vars.getRole(), id)
+                        .equals("0");
+            } else if (type.equals("C"))
+                return true;
+            else
+                return hasLevelAccess(vars, accessLevel)
+                        && !AccessData.selectAccess(this, vars.getRole(), type,
+                                id).equals("0");
+        } catch (final Exception e) {
+            log4j.error("Error checking access: " + e.toString());
+            return false;
+        }
 
-  public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
-    Variables variables = new Variables(request);
-  //  VariablesSecureApp vars = new VariablesSecureApp(request);
-
-    try {
-      myTheme = variables.getSessionValue("#Theme");
-    } catch (Exception ignored) {
-      myTheme = "Default";
-    }
-    try {
-      if (log4j.isDebugEnabled()) log4j.debug("Servlet request for class info: " + request.getServletPath());
-      ClassInfoData[] classInfoAux = ClassInfoData.select(this, variables.getLanguage(), request.getServletPath());
-      if (classInfoAux!=null && classInfoAux.length>0) classInfo = classInfoAux[0];
-      else {
-        classInfoAux = ClassInfoData.set();
-        classInfo = classInfoAux[0];
-      }
-    } catch (Exception ex) {
-      ex.printStackTrace();
-      ClassInfoData[] classInfoAux = ClassInfoData.set();
-      classInfo = classInfoAux[0];
     }
 
-  //  bdErrorGeneral(response, "Error", "No access");
+    /**
+     * Checks if the user has access to the window
+     * */
+    private boolean hasAccess(VariablesSecureApp vars) {
+        try {
+            if (classInfo == null || classInfo.id.equals("")
+                    || classInfo.type.equals(""))
+                return true;
+            return hasGeneralAccess(vars, classInfo.type, classInfo.id);
 
-    if (log4j.isDebugEnabled()) log4j.debug("class info type: " + classInfo.type + " - ID: " + classInfo.id + " - NAME: " + classInfo.name);
-    String strAjax = "";
-    String strHidden = "";
-    String strPopUp = "";
-    try {
-      strAjax = request.getParameter("IsAjaxCall");
-    } catch (Exception ignored) {}
-    try {
-      strHidden = request.getParameter("IsHiddenCall");
-    } catch (Exception ignored) {}
-    try {
-      strPopUp = request.getParameter("IsPopUpCall");
-    } catch (Exception ignored) {}
-
-    try {
-      String strUserAuth = m_AuthManager.authenticate(request, response);
-      if (strUserAuth != null) {
-        if (variables.getRole().equals("") || !SeguridadData.loggedOK(this, variables.getDBSession())) {
-          String strLanguage = "";
-          String strIsRTL = "";
-          String strRole = "";
-          String strClient = "";
-          String strOrg = "";
-          String strWarehouse = "";
-
-          strRole = DefaultOptionsData.defaultRole(this, strUserAuth);
-          if(strRole == null)
-        	  strRole = DefaultOptionsData.getDefaultRole(this, strUserAuth);
-          validateDefault(strRole, strUserAuth, "Role");
-          
-          strOrg = DefaultOptionsData.defaultOrg(this, strUserAuth);
-          if(strOrg == null )
-        	  strOrg = DefaultOptionsData.getDefaultOrg(this, strRole);
-          validateDefault(strOrg, strRole, "Org");
-
-          strClient = DefaultOptionsData.defaultClient(this, strUserAuth);
-          if(strClient == null)
-        	  strClient = DefaultOptionsData.getDefaultClient(this, strRole);
-          validateDefault(strClient, strRole, "Client");
-
-          strWarehouse = DefaultOptionsData.defaultWarehouse(this, strUserAuth);
-          if(strWarehouse == null) {
-        	  if(!strRole.equals("0")) {
-        		  strWarehouse = DefaultOptionsData.getDefaultWarehouse(this, strClient, new OrgTree(this, strClient).getAccessibleTree(this, strRole).toString());
-        	  }
-        	  else
-        		  strWarehouse = "";
-          }
-
-          DefaultOptionsData dataLanguage [] = DefaultOptionsData.defaultLanguage(this, strUserAuth);
-          if (dataLanguage != null && dataLanguage.length > 0) {
-            strLanguage = dataLanguage[0].getField("DEFAULT_AD_LANGUAGE");
-            strIsRTL = dataLanguage[0].getField("ISRTL");
-          }
-          if(strLanguage == null || strLanguage.equals("")) {
-            dataLanguage = DefaultOptionsData.getDefaultLanguage(this);
-            if (dataLanguage != null && dataLanguage.length > 0) {
-              strLanguage = dataLanguage[0].getField("AD_LANGUAGE");
-              strIsRTL = dataLanguage[0].getField("ISRTL");
-            }
-          }
-
-          VariablesSecureApp vars = new VariablesSecureApp(request);
-          if (LoginUtils.fillSessionArguments(this, vars, strUserAuth, strLanguage, strIsRTL, strRole, strClient, strOrg, strWarehouse)) {
-            readProperties(vars, globalParameters.getOpenbravoPropertiesPath());
-            readNumberFormat(vars, globalParameters.getFormatPath());
-            saveLoginBD(request, vars, strClient, strOrg);
-          } else {
-            // Re-login
-            log4j.error("Unable to fill session Arguments for: " +  strUserAuth);
-            logout(request, response);
-            return;
-          }
-        } else variables.updateHistory(request);
-      }
-      log4j.info("Call to HttpBaseServlet.service");
-    } catch (DefaultValidationException d) {
-      // Added DefaultValidationException class to catch user login without a valid role
-      OBError roleError = new OBError();
-      roleError.setTitle("Invalid " + d.getDefaultField());
-      roleError.setType("Error");
-      roleError.setMessage("No valid " + d.getDefaultField() + " identified. Please contact your system administrator for access.");
-      invalidLogin(request, response, roleError);
-      
-      return;
-    } catch (Exception e) {
-      // Re-login
-      if (log4j.isDebugEnabled()) log4j.debug("HTTPSecureAppServlet.service() - exception caught: " + e.getMessage());
-      log4j.error(e);
-      logout(request, response);
-      return;
+        } catch (final Exception e) {
+            log4j.error("Error checking access: " + e.toString());
+            return false;
+        }
     }
 
-    try {
+    /**
+     * Checks if the level access is correct.
+     * 
+     */
+    private boolean hasLevelAccess(VariablesSecureApp vars, String accessLevel) {
+        final String userLevel = vars.getSessionValue("#User_Level");
 
-      super.initialize(request,response);
-      VariablesSecureApp vars1 = new VariablesSecureApp(request, false);
-      if (vars1.getRole().equals("") || hasAccess(vars1)) {
+        boolean retValue = true;
 
-          final Boolean saveRequest = (Boolean) request.getAttribute("autosave");
-          final String strTabId = vars1.getStringParameter("inpTabId");
-            
-          if(saveRequest == null && strTabId != null) {    	
-        	
-        	  String autoSave = request.getParameter("autosave");
-        	  Boolean failedAutosave = (Boolean) vars1.getSessionObject(strTabId + "|failedAutosave");
-        	  
-        	  if(failedAutosave == null) {
-        		failedAutosave = false;  
-        	  }
-        	  
-        	  if(autoSave != null && autoSave.equalsIgnoreCase("Y") && !failedAutosave) {    			
-    			
-    			if(log4j.isDebugEnabled()){
-	    			log4j.debug("service: saveRequest - "
-	    					+ this.getClass().getCanonicalName() + " - autosave: " 
-	    					+ autoSave);
-    			}
-    			
-    			if(log4j.isDebugEnabled()) { 
-    				log4j.debug(this.getClass().getCanonicalName() + " - hash: " 
-    						+ vars1.getPostDataHash());
-    			}
-    			
-    			String servletMappingName = request.getParameter("mappingName");
-    			
-    			if(servletMappingName != null && 
-    					!Utility.isExcludedFromAutoSave(this.getClass().getCanonicalName()) ) {
-    				
-	    			String hash = vars1.getSessionValue(servletMappingName + "|hash");
-	    			
-	    			if(log4j.isDebugEnabled()) {
-	    				log4j.debug("hash in session: " + hash);
-	    			}
-	    				// Check if the form was previously saved
-	    			if(!hash.equals(vars1.getPostDataHash())) {
-	    				// forward request
-	    				request.setAttribute("autosave", true);
-	    				if(vars1.getCommand().indexOf("BUTTON") != -1)
-	    					request.setAttribute("popupWindow", true);
-	    				if(!forwardRequest(request, response)) {
-	    					   return;
-	    				}
-	    			}
-    			}
-    		}
-          }
-        super.serviceInitialized(request,response);
-      }
-      else  {
-       if ((strPopUp!=null && !strPopUp.equals(""))||(classInfo.type.equals("S")))  
-         bdErrorGeneralPopUp(response, Utility.messageBD(this, "Error", variables.getLanguage()), Utility.messageBD(this, "AccessTableNoView", variables.getLanguage()));
-       else bdError(response, "AccessTableNoView", vars1.getLanguage());
-      }
-    } catch (ServletException ex) {
-      log4j.error("Error captured: " + ex);
-      ex.printStackTrace();
-      OBError myError = Utility.translateError(this, null, variables.getLanguage(), ex.getMessage());
-      if (strAjax!=null && !strAjax.equals("")) bdErrorAjax(response, myError.getType(), myError.getTitle(), myError.getMessage());
-      else if (strHidden!=null && !strHidden.equals("")) bdErrorHidden(response, myError.getType(), myError.getTitle(), myError.getMessage());
-      else if (!myError.isConnectionAvailable()) bdErrorConnection(response);
-      else if (strPopUp!=null && !strPopUp.equals("")) bdErrorGeneralPopUp(response, myError.getTitle(), myError.getMessage());
-      else bdErrorGeneral(response, myError.getTitle(), myError.getMessage());
-    } catch(OBException e) {
-    	Boolean isAutosaving = (Boolean) request.getAttribute("autosave");
-    	if(isAutosaving) {    		
-    		request.removeAttribute("autosave");
-    		request.removeAttribute("popupWindow");
-    		throw e;
-    	}
-    	else {
-    		log4j.error("Error captured: " + e);
-    		e.printStackTrace();
-        if (strPopUp!=null && !strPopUp.equals("")) bdErrorGeneralPopUp(response, "Error", e.toString());
-        else bdErrorGeneral(response, "Error", e.toString());
-    	}
-    } catch (Exception e) {
-      log4j.error("Error captured: " + e);
-      e.printStackTrace();
-      if (strPopUp!=null && !strPopUp.equals("")) bdErrorGeneralPopUp(response, "Error", e.toString());
-      else bdErrorGeneral(response, "Error", e.toString());
-    }
-  }
+        if (accessLevel.equals("4") && userLevel.indexOf("S") == -1)
+            retValue = false;
+        else if (accessLevel.equals("1") && userLevel.indexOf("O") == -1)
+            retValue = false;
+        else if (accessLevel.equals("3")
+                && (!(userLevel.indexOf("C") != -1 || userLevel.indexOf("O") != -1)))
+            retValue = false;
+        else if (accessLevel.equals("6")
+                && (!(userLevel.indexOf("S") != -1 || userLevel.indexOf("C") != -1)))
+            retValue = false;
 
-
-  /**
-   * Cheks access passing all the parameters
-   * @param vars
-   * @param type type of element
-   * @param id id for the element
-   * @return true in case it has access false if not
-   */
-  protected boolean hasGeneralAccess(VariablesSecureApp vars, String type, String id){
-    try {
-      String accessLevel = AccessData.selectAccessLevel(this, type, id);
-      vars.setSessionValue("#CurrentAccessLevel", accessLevel);
-      if (type.equals("W")) {
-        return hasLevelAccess(vars, accessLevel)
-            && AccessData.selectAccess(this, vars.getRole(), "TABLE", id).equals("0")
-            && !AccessData.selectAccess(this, vars.getRole(), type, id).equals("0");
-      } else if (type.equals("S")) {
-        return !AccessData.selectAccessSearch(this, vars.getRole(), id).equals("0");
-      } else if (type.equals("C"))
-        return true;
-      else
-        return hasLevelAccess(vars, accessLevel)
-            && !AccessData.selectAccess(this, vars.getRole(), type, id).equals("0");
-    } catch (Exception e) {
-      log4j.error("Error checking access: " + e.toString());
-      return false;
+        return retValue;
     }
 
-  }
-  /**
-   * Checks if the user has access to the window
-   * */
-  private boolean hasAccess(VariablesSecureApp vars) {
-    try {
-      if (classInfo==null || classInfo.id.equals("") || classInfo.type.equals(""))
+    /**
+     * Validates if a selected default value is null or empty String
+     * 
+     * @param strValue
+     * @param strKey
+     * @param strError
+     * @throws Exeption
+     * */
+    private void validateDefault(String strValue, String strKey, String strError)
+            throws Exception {
+        if (strValue == null || strValue.equals(""))
+            throw new DefaultValidationException("Unable to read default "
+                    + strError + " for:" + strKey, strError);
+    }
+
+    public void logout(HttpServletRequest request, HttpServletResponse response)
+            throws IOException, ServletException {
+        final VariablesSecureApp vars = new VariablesSecureApp(request);
+
+        final String user = vars.getUser();
+        final String dbSession = vars.getDBSession();
+
+        vars.clearSession(true);
+        if (log4j.isDebugEnabled())
+            log4j.debug("Clearing session");
+        if (!dbSession.equals(""))
+            SessionLoginData.saveProcessed(this, user, dbSession);
+
+        m_AuthManager.logout(request, response);
+    }
+
+    /**
+     * Logs the user out of the application, clears the session and returns the
+     * HTMLErrorLogin page with the relevant error message passed into the
+     * method.
+     * 
+     * @param request
+     * @param response
+     * @param error
+     * @throws IOException
+     * @throws ServletException
+     */
+    public void invalidLogin(HttpServletRequest request,
+            HttpServletResponse response, OBError error) throws IOException,
+            ServletException {
+        final VariablesSecureApp vars = new VariablesSecureApp(request);
+
+        vars.clearSession(true);
+        final XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
+                "org/openbravo/base/secureApp/HtmlErrorLogin")
+                .createXmlDocument();
+
+        xmlDocument.setParameter("messageType", error.getType());
+        xmlDocument.setParameter("messageTitle", error.getTitle());
+        xmlDocument.setParameter("messageMessage", error.getMessage());
+
+        response.setContentType("text/html");
+        final PrintWriter out = response.getWriter();
+        out.println(xmlDocument.print());
+        out.close();
+
+    }
+
+    public void setHistoryCommand(HttpServletRequest request, String strCommand) {
+        final Variables vars = new Variables(request);
+        vars.setHistoryCommand(strCommand);
+    }
+
+    public void advise(HttpServletResponse response, String strTitulo,
+            String strTexto) throws IOException {
+        advise(response, "INFO", strTitulo, strTexto);
+    }
+
+    public void advise(HttpServletResponse response, String strTipo,
+            String strTitulo, String strTexto) throws IOException {
+        final XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
+                "org/openbravo/base/secureApp/Advise").createXmlDocument();
+
+        xmlDocument.setParameter("theme", myTheme);
+        xmlDocument.setParameter("ParamTipo", strTipo.toUpperCase());
+        xmlDocument.setParameter("ParamTitulo", strTitulo);
+        xmlDocument.setParameter("ParamTexto", strTexto);
+        response.setContentType("text/html; charset=UTF-8");
+        final PrintWriter out = response.getWriter();
+        out.println(xmlDocument.print());
+        out.close();
+    }
+
+    public void advisePopUp(HttpServletResponse response, String strTitulo,
+            String strTexto) throws IOException {
+        advisePopUp(response, "Error", strTitulo, strTexto);
+    }
+
+    public void advisePopUp(HttpServletResponse response, String strTipo,
+            String strTitulo, String strTexto) throws IOException {
+        final XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
+                "org/openbravo/base/secureApp/AdvisePopUp").createXmlDocument();
+
+        xmlDocument.setParameter("theme", myTheme);
+        xmlDocument.setParameter("ParamTipo", strTipo.toUpperCase());
+        xmlDocument.setParameter("ParamTitulo", strTitulo);
+        xmlDocument.setParameter("ParamTexto", strTexto);
+        response.setContentType("text/html; charset=UTF-8");
+        final PrintWriter out = response.getWriter();
+        out.println(xmlDocument.print());
+        out.close();
+    }
+
+    public void bdError(HttpServletResponse response, String strCode,
+            String strLanguage) throws IOException {
+        final XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
+                "org/openbravo/base/secureApp/Error").createXmlDocument();
+
+        xmlDocument.setParameter("theme", myTheme);
+        xmlDocument.setParameter("ParamTitulo", strCode);
+        xmlDocument.setParameter("ParamTexto", Utility.messageBD(this, strCode,
+                strLanguage));
+        response.setContentType("text/html; charset=UTF-8");
+        final PrintWriter out = response.getWriter();
+        out.println(xmlDocument.print());
+        out.close();
+    }
+
+    public void bdErrorGeneralPopUp(HttpServletResponse response,
+            String strTitle, String strText) throws IOException {
+        final XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
+                "org/openbravo/base/secureApp/ErrorPopUp").createXmlDocument();
+
+        xmlDocument.setParameter("theme", myTheme);
+        xmlDocument.setParameter("ParamTipo", "ERROR");
+        xmlDocument.setParameter("ParamTitulo", strTitle);
+        xmlDocument.setParameter("ParamTexto", strText);
+        response.setContentType("text/html; charset=UTF-8");
+        final PrintWriter out = response.getWriter();
+        out.println(xmlDocument.print());
+        out.close();
+    }
+
+    public void bdErrorGeneral(HttpServletResponse response, String strTitle,
+            String strText) throws IOException {
+        final XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
+                "org/openbravo/base/secureApp/Error").createXmlDocument();
+
+        xmlDocument.setParameter("theme", myTheme);
+        xmlDocument.setParameter("ParamTitulo", strTitle);
+        xmlDocument.setParameter("ParamTexto", strText);
+
+        response.setContentType("text/html; charset=UTF-8");
+        final PrintWriter out = response.getWriter();
+        out.println(xmlDocument.print());
+        out.close();
+    }
+
+    public void bdErrorConnection(HttpServletResponse response)
+            throws IOException {
+        if (log4j.isDebugEnabled())
+            log4j.debug("Output: Error connection");
+        final XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
+                "org/openbravo/base/secureApp/ErrorConnection")
+                .createXmlDocument();
+
+        response.setContentType("text/html; charset=UTF-8");
+        final PrintWriter out = response.getWriter();
+        out.println(xmlDocument.print());
+        out.close();
+    }
+
+    public void bdErrorAjax(HttpServletResponse response, String strType,
+            String strTitle, String strText) throws IOException {
+        response.setContentType("text/xml; charset=UTF-8");
+        final PrintWriter out = response.getWriter();
+        out.println("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
+        out.println("<xml-structure>\n");
+        out.println("  <status>\n");
+        out.println("    <type>" + strType + "</type>\n");
+        out.println("    <title>" + strTitle + "</title>\n");
+        out.println("    <description><![CDATA[" + strText
+                + "]]></description>\n");
+        out.println("  </status>\n");
+        out.println("</xml-structure>\n");
+        out.close();
+    }
+
+    public void bdErrorHidden(HttpServletResponse response, String strType,
+            String strTitle, String strText) throws IOException {
+        final XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
+                "org/openbravo/erpCommon/ad_callouts/CallOut")
+                .createXmlDocument();
+
+        final StringBuffer resultado = new StringBuffer();
+        resultado.append("var calloutName='';\n\n");
+        resultado.append("var respuesta = new Array(\n");
+
+        resultado.append("new Array(\"MESSAGE\", \"");
+        resultado.append(strText);
+        resultado.append("\")");
+        resultado.append("\n);");
+
+        xmlDocument.setParameter("array", resultado.toString());
+        response.setContentType("text/html; charset=UTF-8");
+        final PrintWriter out = response.getWriter();
+        out.println(xmlDocument.print());
+        out.close();
+    }
+
+    public void pageError(HttpServletResponse response) throws IOException {
+        final XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
+                "org/openbravo/base/secureApp/HtmlError").createXmlDocument();
+
+        response.setContentType("text/html; charset=UTF-8");
+        final PrintWriter out = response.getWriter();
+        out.println(xmlDocument.print());
+        out.close();
+    }
+
+    public void pageErrorPopUp(HttpServletResponse response) throws IOException {
+        final XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
+                "org/openbravo/base/secureApp/HtmlErrorPopUp")
+                .createXmlDocument();
+
+        response.setContentType("text/html; charset=UTF-8");
+        final PrintWriter out = response.getWriter();
+        out.println(xmlDocument.print());
+        out.close();
+    }
+
+    public void whitePage(HttpServletResponse response) throws IOException {
+        whitePage(response, "");
+    }
+
+    public void whitePage(HttpServletResponse response, String strAlert)
+            throws IOException {
+        final XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
+                "org/openbravo/base/secureApp/HtmlWhitePage")
+                .createXmlDocument();
+        if (strAlert == null)
+            strAlert = "";
+        xmlDocument.setParameter("body", strAlert);
+
+        response.setContentType("text/html; charset=UTF-8");
+        final PrintWriter out = response.getWriter();
+        out.println(xmlDocument.print());
+        out.close();
+    }
+
+    public void printPageClosePopUp(HttpServletResponse response,
+            VariablesSecureApp vars, String path) throws IOException,
+            ServletException {
+        if (log4j.isDebugEnabled())
+            log4j.debug("Output: PopUp Response");
+        final XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
+                "org/openbravo/base/secureApp/PopUp_Response")
+                .createXmlDocument();
+        xmlDocument.setParameter("language", "defaultLang=\""
+                + vars.getLanguage() + "\";");
+        xmlDocument.setParameter("href", path.equals("") ? "null" : "'" + path
+                + "'");
+        response.setContentType("text/html; charset=UTF-8");
+        final PrintWriter out = response.getWriter();
+        out.println(xmlDocument.print());
+        out.close();
+    }
+
+    public void printPageClosePopUp(HttpServletResponse response,
+            VariablesSecureApp vars) throws IOException, ServletException {
+        printPageClosePopUp(response, vars, "");
+    }
+
+    public void printPageClosePopUpWindow(HttpServletResponse response,
+            VariablesSecureApp vars) throws IOException, ServletException {
+        if (log4j.isDebugEnabled())
+            log4j.debug("Output: PopUp Response");
+        final XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
+                "org/openbravo/base/secureApp/PopUp_Close").createXmlDocument();
+        xmlDocument.setParameter("language", "defaultLang=\""
+                + vars.getLanguage() + "\";");
+        response.setContentType("text/html; charset=UTF-8");
+        final PrintWriter out = response.getWriter();
+        out.println(xmlDocument.print());
+        out.close();
+    }
+
+    public void printPageClosePopUpAndRefresh(HttpServletResponse response,
+            VariablesSecureApp vars) throws IOException, ServletException {
+        if (log4j.isDebugEnabled())
+            log4j.debug("Output: PopUp Response");
+        final XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
+                "org/openbravo/base/secureApp/PopUp_Close_Refresh")
+                .createXmlDocument();
+        xmlDocument.setParameter("language", "defaultLang=\""
+                + vars.getLanguage() + "\";");
+        response.setContentType("text/html; charset=UTF-8");
+        final PrintWriter out = response.getWriter();
+        out.println(xmlDocument.print());
+        out.close();
+    }
+
+    public void pageErrorCallOut(HttpServletResponse response)
+            throws IOException {
+        final XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
+                "org/openbravo/base/secureApp/HtmlErrorCallOut")
+                .createXmlDocument();
+
+        response.setContentType("text/html; charset=UTF-8");
+        final PrintWriter out = response.getWriter();
+        out.println(xmlDocument.print());
+        out.close();
+    }
+
+    public void readProperties(VariablesSecureApp vars, String strFileProperties) {
+        // Read properties file.
+        final Properties properties = new Properties();
+        try {
+            log4j.info("strFileProperties: " + strFileProperties);
+            properties.load(new FileInputStream(strFileProperties));
+            final String javaDateFormat = properties
+                    .getProperty("dateFormat.java");
+            log4j.info("javaDateFormat: " + javaDateFormat);
+            vars.setSessionValue("#AD_JavaDateFormat", javaDateFormat);
+            final String javaDateTimeFormat = properties
+                    .getProperty("dateTimeFormat.java");
+            log4j.info("javaDateTimeFormat: " + javaDateTimeFormat);
+            vars.setSessionValue("#AD_JavaDateTimeFormat", javaDateTimeFormat);
+            final String jsDateFormat = properties.getProperty("dateFormat.js");
+            log4j.info("jsDateFormat: " + jsDateFormat);
+            vars.setSessionValue("#AD_JsDateFormat", jsDateFormat);
+            final String sqlDateFormat = properties
+                    .getProperty("dateFormat.sql");
+            log4j.info("sqlDateFormat: " + sqlDateFormat);
+            vars.setSessionValue("#AD_SqlDateFormat", sqlDateFormat);
+            final String pentahoServer = properties
+                    .getProperty("pentahoServer");
+            log4j.info("pentahoServer: " + pentahoServer);
+            vars.setSessionValue("#pentahoServer", pentahoServer);
+            final String sourcePath = properties.getProperty("source.path");
+            log4j.info("sourcePath: " + sourcePath);
+            vars.setSessionValue("#sourcePath", sourcePath);
+        } catch (final IOException e) {
+            // catch possible io errors from readLine()
+            e.printStackTrace();
+        }
+    }
+
+    public void readNumberFormat(VariablesSecureApp vars, String strFormatFile) {
+        final String strNumberFormat = "###,##0.00"; // Default number format
+        String strGroupingSeparator = ","; // Default grouping separator
+        String strDecimalSeparator = "."; // Default decimal separator
+        final String strName = "euroInform"; // Name of the format to use
+        try {
+            // Reading number format configuration
+            final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory
+                    .newInstance();
+            final DocumentBuilder docBuilder = docBuilderFactory
+                    .newDocumentBuilder();
+            final Document doc = docBuilder.parse(new File(strFormatFile));
+            doc.getDocumentElement().normalize();
+            final NodeList listOfNumbers = doc.getElementsByTagName("Number");
+            final int totalNumbers = listOfNumbers.getLength();
+            for (int s = 0; s < totalNumbers; s++) {
+                final Node NumberNode = listOfNumbers.item(s);
+                if (NumberNode.getNodeType() == Node.ELEMENT_NODE) {
+                    final Element NumberElement = (Element) NumberNode;
+                    final String strNumberName = NumberElement.getAttributes()
+                            .getNamedItem("name").getNodeValue();
+                    // store in session all the formats
+                    vars.setSessionValue("#FormatOutput|" + strNumberName,
+                            NumberElement.getAttributes().getNamedItem(
+                                    "formatOutput").getNodeValue());
+                    vars.setSessionValue("#DecimalSeparator|" + strNumberName,
+                            NumberElement.getAttributes().getNamedItem(
+                                    "decimal").getNodeValue());
+                    vars.setSessionValue("#GroupSeparator|" + strNumberName,
+                            NumberElement.getAttributes().getNamedItem(
+                                    "grouping").getNodeValue());
+                    if (strNumberName.equals(strName)) {
+                        strDecimalSeparator = NumberElement.getAttributes()
+                                .getNamedItem("decimal").getNodeValue();
+                        strGroupingSeparator = NumberElement.getAttributes()
+                                .getNamedItem("grouping").getNodeValue();
+                    }
+                }
+            }
+        } catch (final Exception e) {
+            log4j.error(e.getMessage());
+        }
+        vars.setSessionValue("#AD_ReportNumberFormat", strNumberFormat);
+        vars.setSessionValue("#AD_ReportGroupingSeparator",
+                strGroupingSeparator);
+        vars.setSessionValue("#AD_ReportDecimalSeparator", strDecimalSeparator);
+    }
+
+    private void saveLoginBD(HttpServletRequest request,
+            VariablesSecureApp vars, String strCliente, String strOrganizacion)
+            throws ServletException {
+        final SessionLogin sl = new SessionLogin(request, strCliente,
+                strOrganizacion, vars.getSessionValue("#AD_User_ID"));
+        sl.save(this);
+        vars.setSessionValue("#AD_Session_ID", sl.getSessionID());
+    }
+
+    public void renderJR(VariablesSecureApp variables,
+            HttpServletResponse response, String strReportName,
+            String strOutputType, HashMap<String, Object> designParameters,
+            FieldProvider[] data, Map<Object, Object> exportParameters)
+            throws ServletException {
+
+        if (strReportName == null || strReportName.equals(""))
+            strReportName = PrintJRData.getReportName(this, classInfo.id);
+
+        final String strAttach = globalParameters.strFTPDirectory + "/284-"
+                + classInfo.id;
+
+        final String strLanguage = variables.getLanguage();
+        final Locale locLocale = new Locale(strLanguage.substring(0, 2),
+                strLanguage.substring(3, 5));
+
+        final String strBaseDesign = getBaseDesignPath(strLanguage);
+
+        strReportName = Replace.replace(Replace.replace(strReportName,
+                "@basedesign@", strBaseDesign), "@attach@", strAttach);
+        final String strFileName = strReportName.substring(strReportName
+                .lastIndexOf("/") + 1);
+
+        final File reportFile = new File(strReportName);
+        log4j.debug("renderJR() - strReportName: " + strReportName);
+
+        InputStream reportInputStream = null;
+        if (reportFile.exists()) {
+            final TranslationHandler handler = new TranslationHandler(this);
+            handler.prepareFile(strReportName, strLanguage, reportFile);
+            reportInputStream = handler.getInputStream();
+        }
+        ServletOutputStream os = null;
+        try {
+            JasperDesign jasperDesign;
+            if (reportInputStream != null) {
+                log4j.debug("Jasper report being created with inputStream.");
+                jasperDesign = JRXmlLoader.load(reportInputStream);
+            } else {
+                log4j.debug("Jasper report being created with strReportName.");
+                jasperDesign = JRXmlLoader.load(strReportName);
+            }
+
+            final JasperReport jasperReport = JasperCompileManager
+                    .compileReport(jasperDesign);
+            if (designParameters == null)
+                designParameters = new HashMap<String, Object>();
+
+            Boolean pagination = true;
+            if (strOutputType.equals("pdf"))
+                pagination = false;
+
+            designParameters.put("IS_IGNORE_PAGINATION", pagination);
+            designParameters.put("BASE_WEB", strReplaceWithFull);
+            designParameters.put("BASE_DESIGN", strBaseDesign);
+            designParameters.put("ATTACH", strAttach);
+            designParameters.put("USER_CLIENT", Utility.getContext(this,
+                    variables, "#User_Client", ""));
+            designParameters.put("USER_ORG", Utility.getContext(this,
+                    variables, "#User_Org", ""));
+            designParameters.put("LANGUAGE", strLanguage);
+            designParameters.put("LOCALE", locLocale);
+
+            final DecimalFormatSymbols dfs = new DecimalFormatSymbols();
+            dfs.setDecimalSeparator(variables.getSessionValue(
+                    "#AD_ReportDecimalSeparator").charAt(0));
+            dfs.setGroupingSeparator(variables.getSessionValue(
+                    "#AD_ReportGroupingSeparator").charAt(0));
+            final DecimalFormat numberFormat = new DecimalFormat(variables
+                    .getSessionValue("#AD_ReportNumberFormat"), dfs);
+            designParameters.put("NUMBERFORMAT", numberFormat);
+
+            if (log4j.isDebugEnabled())
+                log4j.debug("creating the format factory: "
+                        + variables.getJavaDateFormat());
+            final JRFormatFactory jrFormatFactory = new JRFormatFactory();
+            jrFormatFactory.setDatePattern(variables.getJavaDateFormat());
+            designParameters.put(JRParameter.REPORT_FORMAT_FACTORY,
+                    jrFormatFactory);
+
+            JasperPrint jasperPrint;
+            Connection con = null;
+            try {
+                con = getTransactionConnection();
+                if (data != null) {
+                    designParameters.put("REPORT_CONNECTION", con);
+                    jasperPrint = JasperFillManager.fillReport(jasperReport,
+                            designParameters, new JRFieldProviderDataSource(
+                                    data, variables.getJavaDateFormat()));
+                } else {
+                    jasperPrint = JasperFillManager.fillReport(jasperReport,
+                            designParameters, con);
+                }
+            } catch (final Exception e) {
+                throw new ServletException(e.getMessage());
+            } finally {
+                releaseRollbackConnection(con);
+            }
+
+            os = response.getOutputStream();
+            if (exportParameters == null)
+                exportParameters = new HashMap<Object, Object>();
+            if (strOutputType == null || strOutputType.equals(""))
+                strOutputType = "html";
+            if (strOutputType.equals("html")) {
+                if (log4j.isDebugEnabled())
+                    log4j.debug("JR: Print HTML");
+                response.setHeader("Content-disposition", "inline"
+                        + "; filename=" + strFileName + "." + strOutputType);
+                final JRHtmlExporter exporter = new JRHtmlExporter();
+                exportParameters.put(JRHtmlExporterParameter.JASPER_PRINT,
+                        jasperPrint);
+                exportParameters.put(
+                        JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN,
+                        Boolean.FALSE);
+                exportParameters.put(JRHtmlExporterParameter.SIZE_UNIT,
+                        JRHtmlExporterParameter.SIZE_UNIT_POINT);
+                exportParameters.put(JRHtmlExporterParameter.OUTPUT_STREAM, os);
+                exporter.setParameters(exportParameters);
+                exporter.exportReport();
+            } else if (strOutputType.equals("pdf")) {
+                response.setContentType("application/pdf");
+                response.setHeader("Content-disposition", "attachment"
+                        + "; filename=" + strFileName + "." + strOutputType);
+                JasperExportManager.exportReportToPdfStream(jasperPrint, os);
+            } else if (strOutputType.equals("xls")) {
+                response.setContentType("application/vnd.ms-excel");
+                response.setHeader("Content-disposition", "attachment"
+                        + "; filename=" + strFileName + "." + strOutputType);
+                final JExcelApiExporter exporter = new JExcelApiExporter();
+                exportParameters.put(JRExporterParameter.JASPER_PRINT,
+                        jasperPrint);
+                exportParameters.put(JRExporterParameter.OUTPUT_STREAM, os);
+                exportParameters.put(
+                        JExcelApiExporterParameter.IS_ONE_PAGE_PER_SHEET,
+                        Boolean.FALSE);
+                exportParameters
+                        .put(
+                                JExcelApiExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS,
+                                Boolean.TRUE);
+
+                exporter.setParameters(exportParameters);
+                exporter.exportReport();
+
+            } else {
+                throw new ServletException("Output format no supported");
+            }
+        } catch (final JRException e) {
+            if (log4j.isDebugEnabled())
+                log4j.debug("JR: Error: " + e);
+            e.printStackTrace();
+            throw new ServletException(e.getMessage());
+        } catch (final Exception e) {
+            throw new ServletException(e.getMessage());
+        } finally {
+            try {
+                os.close();
+            } catch (final Exception e) {
+            }
+        }
+    }
+
+    /**
+     * Forwards request to the referrer servlet to perform operations like
+     * "auto-save" Note: The referrer servlet should have a hidden input field
+     * with mappingName (e.g. /PurchaOrder/Header_Edition.html) to be able to
+     * get a RequestDispatcher
+     * 
+     * @param request
+     * @param response
+     * @throws IOException
+     * @throws ServletException
+     */
+    public boolean forwardRequest(HttpServletRequest request,
+            HttpServletResponse response) throws IOException, ServletException {
+        final String forwardTo = request.getParameter("mappingName");
+        final String autoSave = request.getParameter("autosave");
+        final String commandType = request.getParameter("inpCommandType");
+        final Boolean popupWindow = request.getAttribute("popupWindow") != null ? (Boolean) request
+                .getAttribute("popupWindow")
+                : false;
+
+        // Forwarding request to save the modified record
+        if (autoSave != null && autoSave.equalsIgnoreCase("Y")) {
+            if (forwardTo != null && !forwardTo.equals("")) {
+                final RequestDispatcher rd = getServletContext()
+                        .getRequestDispatcher(forwardTo);
+                if (rd != null) {
+                    final long time = System.currentTimeMillis();
+                    try {
+                        if (log4j.isDebugEnabled())
+                            log4j.debug("forward request to: " + forwardTo);
+                        rd.include(request, response);
+                        if (log4j.isDebugEnabled())
+                            log4j.debug("Request forward took: "
+                                    + String.valueOf(System.currentTimeMillis()
+                                            - time) + " ms");
+                    } catch (final OBException e) {
+
+                        request.removeAttribute("autosave");
+                        request.removeAttribute("popupWindow");
+
+                        final VariablesSecureApp vars = new VariablesSecureApp(
+                                request);
+                        final String strTabId = vars
+                                .getStringParameter("inpTabId");
+                        vars.setSessionObject(strTabId + "|failedAutosave",
+                                true);
+
+                        if (!popupWindow) {
+                            vars.setSessionValue(strTabId + "|requestURL",
+                                    request.getRequestURL().toString());
+                            response.sendRedirect(strDireccion
+                                    + forwardTo
+                                    + "?Command="
+                                    + (commandType != null ? commandType
+                                            : "NEW"));
+                        } else { // close pop-up
+                            printPageClosePopUpAndRefresh(response, vars);
+                        }
+                        return false;
+                    }
+                }
+            }
+        }
+        request.removeAttribute("autosave");
+        request.removeAttribute("popupWindow");
         return true;
-     return hasGeneralAccess(vars, classInfo.type, classInfo.id);
+    }
 
-    } catch(Exception e) {
-      log4j.error("Error checking access: " + e.toString());
-      return false;
+    @Override
+    public String getServletInfo() {
+        return "This servlet add some functions (autentication, privileges, application menu, ...) over HttpBaseServlet";
     }
-  }
-
-  /**
-   * Checks if the level access is correct.
-   *
-   */
-  private boolean hasLevelAccess(VariablesSecureApp vars, String accessLevel) {
-    String userLevel = vars.getSessionValue("#User_Level");
-
-    boolean retValue = true;
-
-    if (accessLevel.equals("4") && userLevel.indexOf("S") == -1) retValue = false;
-    else if (accessLevel.equals("1") && userLevel.indexOf("O") == -1) retValue = false;
-    else if (accessLevel.equals("3") && (!(userLevel.indexOf("C")!=-1 || userLevel.indexOf("O")!=-1)) ) retValue = false;
-    else if (accessLevel.equals("6") && (!(userLevel.indexOf("S")!=-1 || userLevel.indexOf("C")!=-1)) ) retValue = false;
-
-    return retValue;
-  }
-
-  /**
-   * Validates if a selected default value is null or empty String
-   * @param strValue
-   * @param strKey
-   * @param strError
-   * @throws Exeption
-   * */
-  private void validateDefault(String strValue, String strKey, String strError) throws Exception {
-	  if(strValue == null || strValue.equals(""))
-		  throw new DefaultValidationException("Unable to read default "+ strError +" for:" + strKey, strError);
-  }
-
-  public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
-    VariablesSecureApp vars = new VariablesSecureApp(request);
-
-    String user = vars.getUser();
-    String dbSession = vars.getDBSession();
-    
-    vars.clearSession(true);
-    if (log4j.isDebugEnabled()) log4j.debug("Clearing session");
-    if (!dbSession.equals("")) SessionLoginData.saveProcessed(this, user, dbSession);
-
-    m_AuthManager.logout(request, response);
-  }
-  
-  /**
-   * Logs the user out of the application, clears the session and returns the HTMLErrorLogin page with the relevant 
-   * error message passed into the method.
-   * @param request
-   * @param response
-   * @param error
-   * @throws IOException
-   * @throws ServletException
-   */
-  public void invalidLogin(HttpServletRequest request, HttpServletResponse response, OBError error) throws IOException, ServletException {
-    VariablesSecureApp vars = new VariablesSecureApp(request);
-
-    vars.clearSession(true);
-    XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/base/secureApp/HtmlErrorLogin").createXmlDocument();
-
-    xmlDocument.setParameter("messageType", error.getType());
-    xmlDocument.setParameter("messageTitle", error.getTitle());
-    xmlDocument.setParameter("messageMessage", error.getMessage());
-    
-    response.setContentType("text/html");
-    PrintWriter out = response.getWriter();
-    out.println(xmlDocument.print());
-    out.close();
-    
-  }
-
-  public void setHistoryCommand(HttpServletRequest request, String strCommand) {
-    Variables vars = new Variables(request);
-    vars.setHistoryCommand(strCommand);
-  }
-
-  public void advise(HttpServletResponse response, String strTitulo, String strTexto) throws IOException {
-    advise(response, "INFO", strTitulo, strTexto);
-  }
-
-  public void advise(HttpServletResponse response, String strTipo, String strTitulo, String strTexto) throws IOException {
-    XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/base/secureApp/Advise").createXmlDocument();
-
-    xmlDocument.setParameter("theme", myTheme);
-    xmlDocument.setParameter("ParamTipo", strTipo.toUpperCase());
-    xmlDocument.setParameter("ParamTitulo", strTitulo);
-    xmlDocument.setParameter("ParamTexto", strTexto);
-    response.setContentType("text/html; charset=UTF-8");
-    PrintWriter out = response.getWriter();
-    out.println(xmlDocument.print());
-    out.close();
-  }
-
- public void advisePopUp(HttpServletResponse response, String strTitulo, String strTexto) throws IOException {
-    advisePopUp(response, "Error", strTitulo, strTexto);
-  }
-
-  public void advisePopUp(HttpServletResponse response, String strTipo, String strTitulo, String strTexto) throws IOException {
-    XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/base/secureApp/AdvisePopUp").createXmlDocument();
-
-    xmlDocument.setParameter("theme", myTheme);
-    xmlDocument.setParameter("ParamTipo", strTipo.toUpperCase());
-    xmlDocument.setParameter("ParamTitulo", strTitulo);
-    xmlDocument.setParameter("ParamTexto", strTexto);
-    response.setContentType("text/html; charset=UTF-8");
-    PrintWriter out = response.getWriter();
-    out.println(xmlDocument.print());
-    out.close();
-  }
-
-  public void bdError(HttpServletResponse response, String strCode, String strLanguage) throws IOException {
-    XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/base/secureApp/Error").createXmlDocument();
-
-    xmlDocument.setParameter("theme", myTheme);
-    xmlDocument.setParameter("ParamTitulo", strCode);
-    xmlDocument.setParameter("ParamTexto", Utility.messageBD(this, strCode, strLanguage));
-    response.setContentType("text/html; charset=UTF-8");
-    PrintWriter out = response.getWriter();
-    out.println(xmlDocument.print());
-    out.close();
-  }
-
-  public void bdErrorGeneralPopUp(HttpServletResponse response, String strTitle, String strText) throws IOException {
-    XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/base/secureApp/ErrorPopUp").createXmlDocument();
-
-    xmlDocument.setParameter("theme", myTheme);
-    xmlDocument.setParameter("ParamTipo", "ERROR");
-    xmlDocument.setParameter("ParamTitulo", strTitle);
-    xmlDocument.setParameter("ParamTexto", strText);
-    response.setContentType("text/html; charset=UTF-8");
-    PrintWriter out = response.getWriter();
-    out.println(xmlDocument.print());
-    out.close();
-  }
-
-  public void bdErrorGeneral(HttpServletResponse response, String strTitle, String strText) throws IOException {
-    XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/base/secureApp/Error").createXmlDocument();
-
-    xmlDocument.setParameter("theme", myTheme);
-    xmlDocument.setParameter("ParamTitulo", strTitle);
-    xmlDocument.setParameter("ParamTexto", strText);
-
-    response.setContentType("text/html; charset=UTF-8");
-    PrintWriter out = response.getWriter();
-    out.println(xmlDocument.print());
-    out.close();
-  }
-
-  public void bdErrorConnection(HttpServletResponse response) throws IOException {
-    if (log4j.isDebugEnabled()) log4j.debug("Output: Error connection");
-    XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/base/secureApp/ErrorConnection").createXmlDocument();
-
-    response.setContentType("text/html; charset=UTF-8");
-    PrintWriter out = response.getWriter();
-    out.println(xmlDocument.print());
-    out.close();
-  }
-
-  public void bdErrorAjax(HttpServletResponse response, String strType, String strTitle, String strText) throws IOException {
-    response.setContentType("text/xml; charset=UTF-8");
-    PrintWriter out = response.getWriter();
-    out.println("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
-    out.println("<xml-structure>\n");
-    out.println("  <status>\n");
-    out.println("    <type>" + strType + "</type>\n");
-    out.println("    <title>" + strTitle + "</title>\n");
-    out.println("    <description><![CDATA[" + strText + "]]></description>\n");
-    out.println("  </status>\n");
-    out.println("</xml-structure>\n");
-    out.close();
-  }
-
-  public void bdErrorHidden(HttpServletResponse response, String strType, String strTitle, String strText) throws IOException {
-    XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/erpCommon/ad_callouts/CallOut").createXmlDocument();
-
-    StringBuffer resultado = new StringBuffer();
-    resultado.append("var calloutName='';\n\n");
-    resultado.append("var respuesta = new Array(\n");
-
-    resultado.append("new Array(\"MESSAGE\", \"");
-    resultado.append(strText);
-    resultado.append("\")");
-    resultado.append("\n);");
-
-    xmlDocument.setParameter("array", resultado.toString());
-    response.setContentType("text/html; charset=UTF-8");
-    PrintWriter out = response.getWriter();
-    out.println(xmlDocument.print());
-    out.close();
-  }
-
-  public void pageError(HttpServletResponse response) throws IOException {
-    XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/base/secureApp/HtmlError").createXmlDocument();
-
-    response.setContentType("text/html; charset=UTF-8");
-    PrintWriter out = response.getWriter();
-    out.println(xmlDocument.print());
-    out.close();
-  }
-
-  public void pageErrorPopUp(HttpServletResponse response) throws IOException {
-    XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/base/secureApp/HtmlErrorPopUp").createXmlDocument();
-
-    response.setContentType("text/html; charset=UTF-8");
-    PrintWriter out = response.getWriter();
-    out.println(xmlDocument.print());
-    out.close();
-  }
-
-  public void whitePage(HttpServletResponse response) throws IOException {
-    whitePage(response, "");
-  }
-
-  public void whitePage(HttpServletResponse response, String strAlert) throws IOException {
-    XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/base/secureApp/HtmlWhitePage").createXmlDocument();
-    if (strAlert==null) strAlert="";
-    xmlDocument.setParameter("body", strAlert);
-
-    response.setContentType("text/html; charset=UTF-8");
-    PrintWriter out = response.getWriter();
-    out.println(xmlDocument.print());
-    out.close();
-  }
-
-  public void printPageClosePopUp(HttpServletResponse response, VariablesSecureApp vars, String path) throws IOException, ServletException {
-    if (log4j.isDebugEnabled()) log4j.debug("Output: PopUp Response");
-    XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/base/secureApp/PopUp_Response").createXmlDocument();
-    xmlDocument.setParameter("language", "defaultLang=\"" + vars.getLanguage() + "\";");
-    xmlDocument.setParameter("href", path.equals("")?"null":"'" + path + "'");
-    response.setContentType("text/html; charset=UTF-8");
-    PrintWriter out = response.getWriter();
-    out.println(xmlDocument.print());
-    out.close();
-  }
-
-  public void printPageClosePopUp(HttpServletResponse response, VariablesSecureApp vars) throws IOException, ServletException {
-    printPageClosePopUp(response, vars, "");
-  }
-
-  public void printPageClosePopUpWindow(HttpServletResponse response, VariablesSecureApp vars) throws IOException, ServletException {
-    if (log4j.isDebugEnabled()) log4j.debug("Output: PopUp Response");
-    XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/base/secureApp/PopUp_Close").createXmlDocument();
-    xmlDocument.setParameter("language", "defaultLang=\"" + vars.getLanguage() + "\";");
-    response.setContentType("text/html; charset=UTF-8");
-    PrintWriter out = response.getWriter();
-    out.println(xmlDocument.print());
-    out.close();
-  }
-  
-  public void printPageClosePopUpAndRefresh(HttpServletResponse response, VariablesSecureApp vars) throws IOException, ServletException {
-	if (log4j.isDebugEnabled()) log4j.debug("Output: PopUp Response");
-    XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/base/secureApp/PopUp_Close_Refresh").createXmlDocument();
-    xmlDocument.setParameter("language", "defaultLang=\"" + vars.getLanguage() + "\";");
-    response.setContentType("text/html; charset=UTF-8");
-    PrintWriter out = response.getWriter();
-    out.println(xmlDocument.print());
-    out.close(); 
-  }
-
-  public void pageErrorCallOut(HttpServletResponse response) throws IOException {
-    XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/base/secureApp/HtmlErrorCallOut").createXmlDocument();
-
-    response.setContentType("text/html; charset=UTF-8");
-    PrintWriter out = response.getWriter();
-    out.println(xmlDocument.print());
-    out.close();
-  }
-
-  public void readProperties(VariablesSecureApp vars, String strFileProperties) {
-    //  Read properties file.
-    Properties properties = new Properties();
-    try {
-      log4j.info("strFileProperties: " + strFileProperties);
-      properties.load(new FileInputStream(strFileProperties));
-      String javaDateFormat = properties.getProperty("dateFormat.java");
-      log4j.info("javaDateFormat: " + javaDateFormat);
-      vars.setSessionValue("#AD_JavaDateFormat", javaDateFormat);
-      String javaDateTimeFormat = properties.getProperty("dateTimeFormat.java");
-      log4j.info("javaDateTimeFormat: " + javaDateTimeFormat);
-      vars.setSessionValue("#AD_JavaDateTimeFormat", javaDateTimeFormat);
-      String jsDateFormat = properties.getProperty("dateFormat.js");
-      log4j.info("jsDateFormat: " + jsDateFormat);
-      vars.setSessionValue("#AD_JsDateFormat", jsDateFormat);
-      String sqlDateFormat = properties.getProperty("dateFormat.sql");
-      log4j.info("sqlDateFormat: " + sqlDateFormat);
-      vars.setSessionValue("#AD_SqlDateFormat", sqlDateFormat);
-      String pentahoServer = properties.getProperty("pentahoServer");
-      log4j.info("pentahoServer: " + pentahoServer);
-      vars.setSessionValue("#pentahoServer", pentahoServer);
-      String sourcePath = properties.getProperty("source.path");
-      log4j.info("sourcePath: " + sourcePath);
-      vars.setSessionValue("#sourcePath", sourcePath);
-    } catch (IOException e) {
-     // catch possible io errors from readLine()
-     e.printStackTrace();
-    }
- }
-
- public void readNumberFormat(VariablesSecureApp vars, String strFormatFile) {
-    String strNumberFormat = "###,##0.00"; // Default number format
-    String strGroupingSeparator = ","; // Default grouping separator
-    String strDecimalSeparator = "."; // Default decimal separator
-    String strName = "euroInform"; // Name of the format to use
-    try{
-      // Reading number format configuration
-      DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
-      DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
-      Document doc = docBuilder.parse (new File(strFormatFile));
-      doc.getDocumentElement().normalize();
-      NodeList listOfNumbers = doc.getElementsByTagName("Number");
-      int totalNumbers = listOfNumbers.getLength();
-      for(int s=0; s<totalNumbers; s++) {
-        Node NumberNode = listOfNumbers.item(s);
-        if(NumberNode.getNodeType() == Node.ELEMENT_NODE){
-          Element NumberElement = (Element)NumberNode;
-          String strNumberName = NumberElement.getAttributes().getNamedItem("name").getNodeValue();
-          //store in session all the formats
-          vars.setSessionValue("#FormatOutput|"+strNumberName, NumberElement.getAttributes().getNamedItem("formatOutput").getNodeValue()); 
-          vars.setSessionValue("#DecimalSeparator|"+strNumberName, NumberElement.getAttributes().getNamedItem("decimal").getNodeValue()); 
-          vars.setSessionValue("#GroupSeparator|"+strNumberName, NumberElement.getAttributes().getNamedItem("grouping").getNodeValue());
-          if(strNumberName.equals(strName)) {
-            strDecimalSeparator = NumberElement.getAttributes().getNamedItem("decimal").getNodeValue();
-            strGroupingSeparator = NumberElement.getAttributes().getNamedItem("grouping").getNodeValue();
-          }
-        }
-      }
-    } catch(Exception e) {
-      log4j.error(e.getMessage());
-    }
-    vars.setSessionValue("#AD_ReportNumberFormat", strNumberFormat);
-    vars.setSessionValue("#AD_ReportGroupingSeparator", strGroupingSeparator);
-    vars.setSessionValue("#AD_ReportDecimalSeparator", strDecimalSeparator);
- }
-
-  private void saveLoginBD(HttpServletRequest request, VariablesSecureApp vars, String strCliente, String strOrganizacion) throws ServletException {
-    SessionLogin sl = new SessionLogin(request, strCliente, strOrganizacion, vars.getSessionValue("#AD_User_ID"));
-    sl.save(this);
-    vars.setSessionValue("#AD_Session_ID", sl.getSessionID());
-  }
-
-  public void renderJR(VariablesSecureApp variables, HttpServletResponse response, String strReportName, String strOutputType, HashMap<String, Object> designParameters, FieldProvider[] data, Map<Object, Object> exportParameters) throws ServletException{
-
-    if (strReportName == null || strReportName.equals("")) strReportName = PrintJRData.getReportName(this, classInfo.id);
-
-    String strAttach = globalParameters.strFTPDirectory + "/284-" +classInfo.id;
-
-    String strLanguage = variables.getLanguage();
-    Locale locLocale = new Locale(strLanguage.substring(0,2),strLanguage.substring(3,5));
-
-    String strBaseDesign = getBaseDesignPath(strLanguage);
-
-    strReportName = Replace.replace(Replace.replace(strReportName,"@basedesign@",strBaseDesign),"@attach@",strAttach);
-    String strFileName = strReportName.substring(strReportName.lastIndexOf("/")+1);
-
-    File reportFile = new File(strReportName);
-    log4j.debug("renderJR() - strReportName: " + strReportName);
-
-    InputStream reportInputStream = null;
-    if (reportFile.exists()) {
-      TranslationHandler handler = new TranslationHandler(this);
-      handler.prepareFile(strReportName, strLanguage, reportFile);
-      reportInputStream = handler.getInputStream();
-    }
-    ServletOutputStream os = null;
-    try {
-      JasperDesign jasperDesign;
-      if (reportInputStream != null) {
-        log4j.debug("Jasper report being created with inputStream.");
-        jasperDesign= JRXmlLoader.load(reportInputStream);
-      } else {
-        log4j.debug("Jasper report being created with strReportName.");
-        jasperDesign= JRXmlLoader.load(strReportName);
-      }
-      
-      JasperReport jasperReport= JasperCompileManager.compileReport(jasperDesign);
-      if (designParameters == null) designParameters = new HashMap<String, Object>();
-
-      Boolean pagination = true;
-      if (strOutputType.equals("pdf")) pagination = false;
-
-      designParameters.put("IS_IGNORE_PAGINATION",  pagination );
-      designParameters.put("BASE_WEB", strReplaceWithFull );
-      designParameters.put("BASE_DESIGN", strBaseDesign);
-      designParameters.put("ATTACH", strAttach);
-      designParameters.put("USER_CLIENT", Utility.getContext(this, variables, "#User_Client", ""));
-      designParameters.put("USER_ORG", Utility.getContext(this, variables, "#User_Org", ""));
-      designParameters.put("LANGUAGE", strLanguage);
-      designParameters.put("LOCALE", locLocale);
-
-      DecimalFormatSymbols dfs = new DecimalFormatSymbols();
-      dfs.setDecimalSeparator(variables.getSessionValue("#AD_ReportDecimalSeparator").charAt(0));
-      dfs.setGroupingSeparator(variables.getSessionValue("#AD_ReportGroupingSeparator").charAt(0));
-      DecimalFormat numberFormat = new DecimalFormat(variables.getSessionValue("#AD_ReportNumberFormat"), dfs);
-      designParameters.put("NUMBERFORMAT", numberFormat);
-
-      if (log4j.isDebugEnabled()) log4j.debug("creating the format factory: " + variables.getJavaDateFormat());
-      JRFormatFactory jrFormatFactory = new JRFormatFactory();
-      jrFormatFactory.setDatePattern(variables.getJavaDateFormat());
-      designParameters.put(JRParameter.REPORT_FORMAT_FACTORY, jrFormatFactory);
-
-      JasperPrint jasperPrint;
-      Connection con = null;
-      try {
-        con = getTransactionConnection();
-        if (data != null) {
-          designParameters.put("REPORT_CONNECTION", con);
-          jasperPrint = JasperFillManager.fillReport(jasperReport, designParameters, new JRFieldProviderDataSource(data, variables.getJavaDateFormat()));
-        } else {
-          jasperPrint = JasperFillManager.fillReport(jasperReport, designParameters, con);
-        }
-      } catch (Exception e){
-        throw new ServletException(e.getMessage());
-      } finally {
-        releaseRollbackConnection(con);
-      }
-
-      os = response.getOutputStream();
-      if (exportParameters == null) exportParameters = new HashMap<Object, Object>();
-      if (strOutputType == null || strOutputType.equals("")) strOutputType = "html";
-      if (strOutputType.equals("html")){
-        if (log4j.isDebugEnabled()) log4j.debug("JR: Print HTML");
-        response.setHeader( "Content-disposition", "inline" + "; filename=" + strFileName + "." +strOutputType);
-        JRHtmlExporter exporter = new JRHtmlExporter();
-        exportParameters.put(JRHtmlExporterParameter.JASPER_PRINT, jasperPrint);
-        exportParameters.put(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE);
-        exportParameters.put(JRHtmlExporterParameter.SIZE_UNIT, JRHtmlExporterParameter.SIZE_UNIT_POINT);
-        exportParameters.put(JRHtmlExporterParameter.OUTPUT_STREAM, os);
-        exporter.setParameters(exportParameters);
-        exporter.exportReport();
-      } else if (strOutputType.equals("pdf")){
-        response.setContentType("application/pdf");
-        response.setHeader( "Content-disposition", "attachment" + "; filename=" + strFileName + "." +strOutputType);
-        JasperExportManager.exportReportToPdfStream(jasperPrint, os);
-      } else if (strOutputType.equals("xls")){
-        response.setContentType("application/vnd.ms-excel");
-        response.setHeader( "Content-disposition", "attachment" + "; filename=" + strFileName + "." +strOutputType);
-        JExcelApiExporter exporter = new JExcelApiExporter();
-        exportParameters.put(JRExporterParameter.JASPER_PRINT, jasperPrint);
-        exportParameters.put(JRExporterParameter.OUTPUT_STREAM, os);
-        exportParameters.put(JExcelApiExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);
-        exportParameters.put(JExcelApiExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
-
-        exporter.setParameters(exportParameters);
-        exporter.exportReport();
-
-      } else {
-        throw new ServletException("Output format no supported");
-      }
-    } catch (JRException e) {
-      if (log4j.isDebugEnabled()) log4j.debug("JR: Error: " + e);
-      e.printStackTrace();
-      throw new ServletException(e.getMessage());
-    } catch (Exception e) {
-      throw new ServletException(e.getMessage());
-    } finally {
-      try {
-        os.close();
-      } catch (Exception e) { }
-    }
-  }
-
-  /**
-   * Forwards request to the referrer servlet to perform operations like "auto-save"
-   * Note: The referrer servlet should have a hidden input field with mappingName (e.g. /PurchaOrder/Header_Edition.html)
-   * to be able to get a RequestDispatcher
-   * @param request
-   * @param response
-   * @throws IOException
-   * @throws ServletException
-   */
-  public boolean forwardRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
-	  String forwardTo = request.getParameter("mappingName");
-	  String autoSave = request.getParameter("autosave");
-	  String commandType = request.getParameter("inpCommandType");
-	  Boolean popupWindow = request.getAttribute("popupWindow") != null ? (Boolean) request.getAttribute("popupWindow") : false;
-	  
-	  // Forwarding request to save the modified record
-	  if(autoSave != null && autoSave.equalsIgnoreCase("Y")) {
-		  if(forwardTo != null && !forwardTo.equals("")) {
-			  RequestDispatcher rd = getServletContext().getRequestDispatcher(forwardTo);
-			  if (rd != null) {
-				  long time = System.currentTimeMillis();
-				  try {
-					  if(log4j.isDebugEnabled()) log4j.debug("forward request to: " + forwardTo);
-					  rd.include(request, response);
-					  if(log4j.isDebugEnabled()) log4j.debug("Request forward took: " + String.valueOf(System.currentTimeMillis() - time) + " ms");
-				  }
-				  catch(OBException e) {
-					  
-					  request.removeAttribute("autosave");
-					  request.removeAttribute("popupWindow");
-					  
-					  VariablesSecureApp vars = new VariablesSecureApp(request);
-					  final String strTabId = vars.getStringParameter("inpTabId");
-					  vars.setSessionObject(strTabId + "|failedAutosave", true);
-					  
-					  if(!popupWindow) {
-						  vars.setSessionValue(strTabId +"|requestURL", request.getRequestURL().toString());
-						  response.sendRedirect(strDireccion + forwardTo + "?Command=" + (commandType != null ? commandType : "NEW"));
-					  }
-					  else { // close pop-up						  
-						  printPageClosePopUpAndRefresh(response, vars);
-					  }					  
-					  return false;
-				  }
-			  }
-		  }
-	  }
-	  request.removeAttribute("autosave");
-	  request.removeAttribute("popupWindow");
-	  return true;
-  }
-
-  public String getServletInfo() {
-    return "This servlet add some functions (autentication, privileges, application menu, ...) over HttpBaseServlet";
-  }
 }
--- a/src/org/openbravo/base/session/SessionFactoryController.java	Wed Dec 03 08:33:54 2008 +0000
+++ b/src/org/openbravo/base/session/SessionFactoryController.java	Wed Dec 03 12:52:09 2008 +0000
@@ -78,6 +78,10 @@
     public static void setInstance(SessionFactoryController sfc) {
         log.debug("Setting instance of " + sfc.getClass().getName()
                 + " as session factory controller");
+        if (instance != null) {
+            // TODO: we should ensure that there are no open sessions....
+            instance.getSessionFactory().close();
+        }
         instance = sfc;
     }
 
--- a/src/org/openbravo/base/structure/OBDynamicPropertyHandler.java	Wed Dec 03 08:33:54 2008 +0000
+++ b/src/org/openbravo/base/structure/OBDynamicPropertyHandler.java	Wed Dec 03 12:52:09 2008 +0000
@@ -49,10 +49,14 @@
 
     private String getStaticPropertyName(Class<?> clz, String propName) {
         try {
+            if (clz == null) {
+                return propName;
+            }
             final Field fld = clz
                     .getField("PROPERTY_" + propName.toUpperCase());
             return (String) fld.get(null);
         } catch (final Exception e) {
+            e.printStackTrace(System.err);
             throw new OBException(
                     "Exception when getting static property name "
                             + clz.getName() + "." + "PROPERTY_"
--- a/src/org/openbravo/base/validation/NumericPropertyValidator.java	Wed Dec 03 08:33:54 2008 +0000
+++ b/src/org/openbravo/base/validation/NumericPropertyValidator.java	Wed Dec 03 12:52:09 2008 +0000
@@ -64,21 +64,28 @@
             // mandatory is checked in Hibernate and in the property itself
             return null;
         }
-        Check.isInstanceOf(value, Number.class);
-        final Number num = (Number) value;
-        final double thatValue = num.doubleValue();
+        final BigDecimal localValue;
+        if (float.class.isAssignableFrom(value.getClass())
+                || Float.class.isAssignableFrom(value.getClass())) {
+            localValue = new BigDecimal((Float) value);
+        } else if (int.class.isAssignableFrom(value.getClass())
+                || Integer.class.isAssignableFrom(value.getClass())) {
+            localValue = new BigDecimal((Integer) value);
+        } else {
+            Check.isInstanceOf(value, BigDecimal.class);
+            localValue = (BigDecimal) value;
+        }
+
         if (minValue != null) {
-            if (minValue.doubleValue() > thatValue) {
-                return "Value (" + thatValue
-                        + ") is smaller than the min value: "
-                        + minValue.doubleValue();
+            if (minValue.compareTo(localValue) > 0) {
+                return "Value (" + value + ") is smaller than the min value: "
+                        + minValue;
             }
         }
         if (maxValue != null) {
-            if (maxValue.doubleValue() < thatValue) {
-                return "Value (" + thatValue
-                        + ") is larger than the max value: "
-                        + maxValue.doubleValue();
+            if (maxValue.compareTo(localValue) < 0) {
+                return "Value (" + localValue
+                        + ") is larger than the max value: " + maxValue;
             }
         }
         return null;
--- a/src/org/openbravo/dal/core/DalContextListener.java	Wed Dec 03 08:33:54 2008 +0000
+++ b/src/org/openbravo/dal/core/DalContextListener.java	Wed Dec 03 12:52:09 2008 +0000
@@ -77,7 +77,7 @@
         OBConfigFileProvider.getInstance().setClassPathLocation("/WEB-INF");
 
         // initialize the dal layer
-        DalLayerInitializer.getInstance().initialize();
+        DalLayerInitializer.getInstance().initialize(true);
     }
 
     public void contextDestroyed(ServletContextEvent event) {
--- a/src/org/openbravo/dal/core/DalInitializingTask.java	Wed Dec 03 08:33:54 2008 +0000
+++ b/src/org/openbravo/dal/core/DalInitializingTask.java	Wed Dec 03 12:52:09 2008 +0000
@@ -42,6 +42,7 @@
     protected String propertiesFile;
     protected String userId;
     private String providerConfigDirectory;
+    private boolean reInitializeModel;
 
     public String getPropertiesFile() {
         return propertiesFile;
@@ -84,6 +85,14 @@
         OBProvider.getInstance().register(OBClassLoader.class,
                 OBClassLoader.ClassOBClassLoader.class, false);
 
+        final boolean rereadConfigs = !DalLayerInitializer.getInstance()
+                .isInitialized();
+
+        // after install modules the model should be forcefully reinitialized
+        if (reInitializeModel) {
+            DalLayerInitializer.getInstance().setInitialized(false);
+        }
+
         if (!DalLayerInitializer.getInstance().isInitialized()) {
             log.debug("initializating dal layer, getting properties from "
                     + getPropertiesFile());
@@ -95,7 +104,7 @@
                         getProviderConfigDirectory());
             }
 
-            DalLayerInitializer.getInstance().initialize();
+            DalLayerInitializer.getInstance().initialize(rereadConfigs);
         } else {
             log.debug("Dal Layer already initialized");
         }
@@ -125,4 +134,12 @@
     public void setProviderConfigDirectory(String providerConfigDirectory) {
         this.providerConfigDirectory = providerConfigDirectory;
     }
+
+    public boolean isReInitializeModel() {
+        return reInitializeModel;
+    }
+
+    public void setReInitializeModel(boolean reInitializeModel) {
+        this.reInitializeModel = reInitializeModel;
+    }
 }
--- a/src/org/openbravo/dal/core/DalLayerInitializer.java	Wed Dec 03 08:33:54 2008 +0000
+++ b/src/org/openbravo/dal/core/DalLayerInitializer.java	Wed Dec 03 12:52:09 2008 +0000
@@ -20,7 +20,6 @@
 package org.openbravo.dal.core;
 
 import org.apache.log4j.Logger;
-import org.openbravo.base.exception.OBException;
 import org.openbravo.base.model.Entity;
 import org.openbravo.base.model.ModelProvider;
 import org.openbravo.base.provider.OBConfigFileProvider;
@@ -55,25 +54,27 @@
      * Initializes the in-memory model, registers the entity classes with the
      * {@link OBProvider OBProvider}, initializes the SessionFactory and reads
      * the service config files.
+     * 
+     * @param rereadConfigFiles
+     *            there are cases where it does not make sense to reread the
+     *            config files with services, for example after installing a
+     *            module. The system needs to be restarted for those cases.
      */
-    public void initialize() {
+    public void initialize(boolean rereadConfigFiles) {
         if (initialized) {
             return;
         }
         log.info("Initializing in-memory model...");
-        try {
-            ModelProvider.getInstance().getModel();
-        } catch (final Exception e) {
-            e.printStackTrace(System.err);
-            throw new OBException(e);
-        }
+        ModelProvider.refresh();
 
         log.debug("Registering entity classes in the OBFactory");
         for (final Entity e : ModelProvider.getInstance().getModel()) {
-            OBProvider.getInstance().register(e.getMappingClass(),
-                    e.getMappingClass(), false);
-            OBProvider.getInstance().register(e.getName(), e.getMappingClass(),
-                    false);
+            if (e.getMappingClass() != null) {
+                OBProvider.getInstance().register(e.getMappingClass(),
+                        e.getMappingClass(), false);
+                OBProvider.getInstance().register(e.getName(),
+                        e.getMappingClass(), false);
+            }
         }
 
         log.info("Model read in-memory, generating mapping...");
@@ -85,7 +86,9 @@
         SessionHandler.deleteSessionHandler();
 
         // set the configs
-        OBConfigFileProvider.getInstance().setConfigInProvider();
+        if (rereadConfigFiles) {
+            OBConfigFileProvider.getInstance().setConfigInProvider();
+        }
 
         log.info("Dal layer initialized");
         initialized = true;
--- a/src/org/openbravo/dal/core/DalMappingGenerator.java	Wed Dec 03 08:33:54 2008 +0000
+++ b/src/org/openbravo/dal/core/DalMappingGenerator.java	Wed Dec 03 12:52:09 2008 +0000
@@ -113,11 +113,25 @@
         String hbm = getClassTemplateContents();
         hbm = hbm.replaceAll("mappingName", entity.getName());
         hbm = hbm.replaceAll("tableName", entity.getTableName());
-        hbm = hbm.replaceAll("className", entity.getClassName());
         hbm = hbm.replaceAll("ismutable", entity.isMutable() + "");
 
+        if (entity.getMappingClass() != null) {
+            hbm = hbm.replaceAll("<class", "<class name=\""
+                    + entity.getClassName() + "\" ");
+        }
+
         // create the content by first getting the id
-        final StringBuffer content = new StringBuffer();
+        final StringBuilder content = new StringBuilder();
+
+        if (entity.getMappingClass() == null) {
+            content
+                    .append("<tuplizer entity-mode=\"dynamic-map\" "
+                            + "class=\"org.openbravo.dal.core.OBDynamicTuplizer\"/>\n\n");
+        } else {
+            content.append("<tuplizer entity-mode=\"pojo\" "
+                    + "class=\"org.openbravo.dal.core.OBTuplizer\"/>\n\n");
+        }
+
         if (entity.hasCompositeId()) {
             content.append(generateCompositeID(entity));
         } else {
--- a/src/org/openbravo/dal/core/DalRequestFilter.java	Wed Dec 03 08:33:54 2008 +0000
+++ b/src/org/openbravo/dal/core/DalRequestFilter.java	Wed Dec 03 12:52:09 2008 +0000
@@ -62,7 +62,7 @@
 public class DalRequestFilter implements Filter {
 
     public void init(FilterConfig fConfig) throws ServletException {
-        DalLayerInitializer.getInstance().initialize();
+        DalLayerInitializer.getInstance().initialize(true);
     }
 
     public void destroy() {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/org/openbravo/dal/core/OBDynamicTuplizer.java	Wed Dec 03 12:52:09 2008 +0000
@@ -0,0 +1,122 @@
+/*
+ *************************************************************************
+ * The contents of this file are subject to the Openbravo  Public  License
+ * Version  1.0  (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 SL 
+ * All portions are Copyright (C) 2008 Openbravo SL 
+ * All Rights Reserved. 
+ * Contributor(s):  ______________________________________.
+ ************************************************************************
+ */
+
+package org.openbravo.dal.core;
+
+import org.apache.log4j.Logger;
+import org.hibernate.EntityMode;
+import org.hibernate.HibernateException;
+import org.hibernate.mapping.PersistentClass;
+import org.hibernate.mapping.Property;
+import org.hibernate.property.Getter;
+import org.hibernate.property.Setter;
+import org.hibernate.proxy.ProxyFactory;
+import org.hibernate.proxy.map.MapProxyFactory;
+import org.hibernate.tuple.Instantiator;
+import org.hibernate.tuple.entity.AbstractEntityTuplizer;
+import org.hibernate.tuple.entity.EntityMetamodel;
+import org.openbravo.base.structure.DynamicOBObject;
+
+/**
+ * The tuplizer for {@link DynamicOBObject} objects. This is class used by
+ * Hibernate. It sets the object instantiator (the factory) used by Hibernate.
+ * 
+ * @see OBInstantiator
+ * @author mtaal
+ */
+@SuppressWarnings("unchecked")
+public class OBDynamicTuplizer extends AbstractEntityTuplizer {
+    private static final Logger log = Logger.getLogger(OBDynamicTuplizer.class);
+
+    private final PersistentClass persistentClass;
+
+    public OBDynamicTuplizer(EntityMetamodel entityMetamodel,
+            PersistentClass mappedEntity) {
+        super(entityMetamodel, mappedEntity);
+        log.debug("Created tuplizer for "
+                + (mappedEntity.getMappedClass() != null ? mappedEntity
+                        .getMappedClass().getName() : mappedEntity
+                        .getEntityName()));
+        persistentClass = mappedEntity;
+    }
+
+    // this is done in the generated mapping
+    // @Override
+    // protected Getter buildPropertyGetter(Property mappedProperty,
+    // PersistentClass mappedEntity) {
+    // return new OBDynamicPropertyHandler.Getter(mappedProperty.getName());
+    // }
+    //  
+    // @Override
+    // protected Setter buildPropertySetter(Property mappedProperty,
+    // PersistentClass mappedEntity) {
+    // return new OBDynamicPropertyHandler.Setter(mappedProperty.getName());
+    // }
+
+    @Override
+    protected Instantiator buildInstantiator(PersistentClass mappingInfo) {
+        return new OBInstantiator(mappingInfo);
+    }
+
+    @Override
+    protected ProxyFactory buildProxyFactory(
+            PersistentClass thePersistentClass, Getter idGetter, Setter idSetter) {
+        ProxyFactory pf = new MapProxyFactory();
+        try {
+            pf.postInstantiate(getEntityName(), null, null, null, null, null);
+        } catch (final HibernateException he) {
+            log.warn("could not create proxy factory for:" + getEntityName(),
+                    he);
+            pf = null;
+        }
+        return pf;
+    }
+
+    @Override
+    public Class getMappedClass() {
+        return persistentClass.getMappedClass();
+    }
+
+    @Override
+    public Class getConcreteProxyClass() {
+        return persistentClass.getMappedClass();
+    }
+
+    @Override
+    public EntityMode getEntityMode() {
+        return EntityMode.POJO;
+    }
+
+    @Override
+    protected Getter buildPropertyGetter(Property mappedProperty,
+            PersistentClass mappedEntity) {
+        return mappedProperty.getGetter(mappedEntity.getMappedClass());
+    }
+
+    @Override
+    protected Setter buildPropertySetter(Property mappedProperty,
+            PersistentClass mappedEntity) {
+        return mappedProperty.getSetter(mappedEntity.getMappedClass());
+    }
+
+    public boolean isInstrumented() {
+        return false;
+    }
+
+}
\ No newline at end of file
--- a/src/org/openbravo/dal/core/OBTuplizer.java	Wed Dec 03 08:33:54 2008 +0000
+++ b/src/org/openbravo/dal/core/OBTuplizer.java	Wed Dec 03 12:52:09 2008 +0000
@@ -37,6 +37,7 @@
 import org.hibernate.tuple.entity.PojoEntityTuplizer;
 import org.hibernate.type.AbstractComponentType;
 import org.hibernate.util.ReflectHelper;
+import org.openbravo.base.util.Check;
 
 /**
  * The tuplizer for OBObjects objects. This is class used by Hibernate. It sets
@@ -82,6 +83,10 @@
     @Override
     protected ProxyFactory buildProxyFactory(
             PersistentClass thePersistentClass, Getter idGetter, Setter idSetter) {
+        final Class mappedClass = thePersistentClass.getMappedClass();
+        Check.isNotNull(mappedClass, "Mapped class of entity "
+                + thePersistentClass.getEntityName() + " is null");
+
         // determine the id getter and setter methods from the proxy interface
         // (if
         // any)
@@ -89,7 +94,6 @@
         final HashSet proxyInterfaces = new HashSet();
         proxyInterfaces.add(HibernateProxy.class);
 
-        final Class mappedClass = thePersistentClass.getMappedClass();
         final Class proxyInterface = thePersistentClass.getProxyInterface();
 
         if (proxyInterface != null && !mappedClass.equals(proxyInterface)) {
--- a/src/org/openbravo/dal/core/template.hbm.xml	Wed Dec 03 08:33:54 2008 +0000
+++ b/src/org/openbravo/dal/core/template.hbm.xml	Wed Dec 03 12:52:09 2008 +0000
@@ -1,7 +1,4 @@
-	<class name="className" entity-name="mappingName" lazy="true" table="tableName" mutable="ismutable">
+	<class entity-name="mappingName" lazy="true" table="tableName" mutable="ismutable">
 		<cache usage="read-write"/>
-		<tuplizer entity-mode="dynamic-map" class="org.openbravo.dal.core.OBTuplizer"/>
-		<tuplizer entity-mode="pojo" class="org.openbravo.dal.core.OBTuplizer"/>
-		
 content	
 	</class>
--- a/src/org/openbravo/erpCommon/ad_process/ApplyModules.java	Wed Dec 03 08:33:54 2008 +0000
+++ b/src/org/openbravo/erpCommon/ad_process/ApplyModules.java	Wed Dec 03 12:52:09 2008 +0000
@@ -15,7 +15,7 @@
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
-*/
+ */
 package org.openbravo.erpCommon.ad_process;
 
 import java.io.File;
@@ -39,204 +39,249 @@
 
 /**
  * Servlet for the Apply Modules method.
- *
+ * 
  */
 public class ApplyModules extends HttpSecureAppServlet {
-  private static final long serialVersionUID = 1L;
+    private static final long serialVersionUID = 1L;
 
-  /**
+    /**
    * 
    */
-  @Override
-public void doPost (HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException {
-    final VariablesSecureApp vars = new VariablesSecureApp(request);
+    @Override
+    public void doPost(HttpServletRequest request, HttpServletResponse response)
+            throws IOException, ServletException {
+        final VariablesSecureApp vars = new VariablesSecureApp(request);
 
-    if (vars.commandIn("DEFAULT")) {
-      printPage(response, vars);
-    } if (vars.commandIn("STARTAPPLY")){
-      startApply(response,vars);
-    } if (vars.commandIn("UPDATELOG")){
-      updateLog(response,vars);
-    } if (vars.commandIn("GETERR")){
-      getError(response,vars);
-    } else pageError(response);
-  }
+        if (vars.commandIn("DEFAULT")) {
+            printPage(response, vars);
+        }
+        if (vars.commandIn("STARTAPPLY")) {
+            startApply(response, vars);
+        }
+        if (vars.commandIn("UPDATELOG")) {
+            updateLog(response, vars);
+        }
+        if (vars.commandIn("GETERR")) {
+            getError(response, vars);
+        } else {
+            System.err.println(vars.getCommand());
+            pageError(response);
+        }
+    }
 
-  /**
-   * Prints the default page for the process, showing the process description and a OK and Cancel buttons.
-   * First it checks whether the server has write permissions to be able to execute the process.
-   * 
-   * @param response
-   * @param vars
-   * @throws IOException
-   * @throws ServletException
-   */
-  private void printPage(HttpServletResponse response, VariablesSecureApp vars) throws IOException, ServletException {
-    //Check for permissions to apply modules from application server.
-    final File f = new File(vars.getSessionValue("#sourcePath"));
-    if (!f.canWrite()) {
-      bdErrorGeneralPopUp(response, Utility.messageBD(this, "Error", vars.getLanguage()), 
-                                    Utility.messageBD(this, "NoApplicableModules", vars.getLanguage()));
-      return;
+    /**
+     * Prints the default page for the process, showing the process description
+     * and a OK and Cancel buttons. First it checks whether the server has write
+     * permissions to be able to execute the process.
+     * 
+     * @param response
+     * @param vars
+     * @throws IOException
+     * @throws ServletException
+     */
+    private void printPage(HttpServletResponse response, VariablesSecureApp vars)
+            throws IOException, ServletException {
+        // Check for permissions to apply modules from application server.
+        final File f = new File(vars.getSessionValue("#sourcePath"));
+        if (!f.canWrite()) {
+            bdErrorGeneralPopUp(response, Utility.messageBD(this, "Error", vars
+                    .getLanguage()), Utility.messageBD(this,
+                    "NoApplicableModules", vars.getLanguage()));
+            return;
+        }
+
+        final XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
+                "org/openbravo/erpCommon/ad_process/ApplyModules")
+                .createXmlDocument();
+        xmlDocument.setParameter("language", "defaultLang=\""
+                + vars.getLanguage() + "\";");
+        xmlDocument.setParameter("directory", "var baseDirectory = \""
+                + strReplaceWith + "/\";\r\n");
+        xmlDocument.setParameter("theme", vars.getTheme());
+        xmlDocument.setParameter("help", ApplyModulesData.getHelp(this, vars
+                .getLanguage()));
+        {
+            final OBError myMessage = vars.getMessage("ApplyModules");
+            vars.removeMessage("ApplyModules");
+            if (myMessage != null) {
+                xmlDocument.setParameter("messageType", myMessage.getType());
+                xmlDocument.setParameter("messageTitle", myMessage.getTitle());
+                xmlDocument.setParameter("messageMessage", myMessage
+                        .getMessage());
+            }
+        }
+        final PrintWriter out = response.getWriter();
+        response.setContentType("text/html; charset=UTF-8");
+        out.println(xmlDocument.print());
+        out.close();
     }
-    
-    final XmlDocument xmlDocument=xmlEngine.readXmlTemplate("org/openbravo/erpCommon/ad_process/ApplyModules").createXmlDocument();
-    xmlDocument.setParameter("language", "defaultLang=\"" + vars.getLanguage() + "\";");
-    xmlDocument.setParameter("directory", "var baseDirectory = \"" + strReplaceWith + "/\";\r\n");
-    xmlDocument.setParameter("theme", vars.getTheme());
-    xmlDocument.setParameter("help", ApplyModulesData.getHelp(this, vars.getLanguage()));
-    {
-      final OBError myMessage = vars.getMessage("ApplyModules");
-      vars.removeMessage("ApplyModules");
-      if (myMessage!=null) {
-        xmlDocument.setParameter("messageType", myMessage.getType());
-        xmlDocument.setParameter("messageTitle", myMessage.getTitle());
-        xmlDocument.setParameter("messageMessage", myMessage.getMessage());
-      }
+
+    /**
+     * Method to be called via AJAX. Creates a new AntExecutor object, saves it
+     * in session and executes the apply modules task on it.
+     * 
+     * @param response
+     * @param vars
+     * @throws IOException
+     * @throws ServletException
+     */
+    private void startApply(HttpServletResponse response,
+            VariablesSecureApp vars) throws IOException, ServletException {
+        // final PrintStream oldOut=System.out;
+        try {
+            final AntExecutor ant = new AntExecutor(vars
+                    .getSessionValue("#sourcePath"));
+            String fileName = new SimpleDateFormat("yyyyMMddHHmmss")
+                    .format(new Date())
+                    + "-apply.log";
+            // final OBPrintStream obps=new OBPrintStream(new
+            // PrintStream(response.getOutputStream()));
+            // System.setOut(obps);
+
+            // ant.setOBPrintStreamLog(response.getWriter());
+            final PrintStream out = new PrintStream(response.getOutputStream());
+            ant.setOBPrintStreamLog(new PrintStream(out));
+
+            fileName = ant.setLogFile(fileName);
+            // obps.setLogFile(new File(fileName+".db"));
+            ant.setLogFileInOBPrintStream(new File(fileName));
+            vars.setSessionObject("ApplyModules|Log", ant);
+
+            final Vector<String> tasks = new Vector<String>();
+
+            final String unnappliedModules = getUnnapliedModules();
+
+            if (ApplyModulesData.isUpdatingCore(this)) {
+                tasks.add("update.database");
+                tasks.add("core.lib");
+                tasks.add("wad.lib");
+                tasks.add("trl.lib");
+                tasks.add("compile.complete.deploy");
+                ant.setProperty("apply.on.create", "true");
+            } else if (ApplyModulesData.selectUninstalledModules(this)) { // there're
+                // uninstalled
+                // modules
+                tasks.add("update.database");
+                tasks.add("compile.deploy");
+                if (!unnappliedModules.equals("")) { // There are also installed
+                    // modules, let's compile
+                    // them
+                    ant.setProperty("module", unnappliedModules);
+                } else {
+                    ant.setProperty("tab", "xx"); // Only uninstall, compile no
+                    // window to re-generate
+                    // web.xml
+                }
+                ant.setProperty("apply.on.create", "true");
+            } else {
+                tasks.add("apply.modules");
+                ant.setProperty("module", unnappliedModules);
+            }
+
+            ant.runTask(tasks);
+
+            ant.setFinished(true);
+
+            response.setContentType("text/plain; charset=UTF-8");
+            out.println("finished");
+            out.close();
+        } catch (final Exception e) {
+            e.printStackTrace();
+        } finally {
+            // System.setOut(oldOut);
+        }
     }
-    final PrintWriter out = response.getWriter();
-    response.setContentType("text/html; charset=UTF-8");
-    out.println(xmlDocument.print());
-    out.close();
-  }
-  
-  /**
-   * Method to be called via AJAX. Creates a new AntExecutor object, saves it in session and executes the apply modules task on it.
-   * @param response
-   * @param vars
-   * @throws IOException
-   * @throws ServletException
-   */
-  private void startApply(HttpServletResponse response, VariablesSecureApp vars) throws IOException, ServletException {
-    //final PrintStream oldOut=System.out;
-    try {
-      final AntExecutor ant=new AntExecutor(vars.getSessionValue("#sourcePath"));
-      String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+"-apply.log";
-      //final OBPrintStream obps=new OBPrintStream(new PrintStream(response.getOutputStream()));
-      //System.setOut(obps);
-      
-      //ant.setOBPrintStreamLog(response.getWriter());
-      final PrintStream out = new PrintStream(response.getOutputStream());
-      ant.setOBPrintStreamLog(new PrintStream(out));
-      fileName = ant.setLogFile(fileName);
-      //obps.setLogFile(new File(fileName+".db"));
-      ant.setLogFileInOBPrintStream(new File(fileName));
-      vars.setSessionObject("ApplyModules|Log", ant);
-      
-      final Vector<String> tasks = new Vector<String>();
-      
-      final String unnappliedModules = getUnnapliedModules();
-      
-      if (ApplyModulesData.isUpdatingCore(this)) {
-          tasks.add("update.database");
-          tasks.add("core.lib");
-          tasks.add("wad.lib");
-          tasks.add("trl.lib");
-          tasks.add("compile.complete.deploy");
-          ant.setProperty("apply.on.create", "true");
-      } else if (ApplyModulesData.selectUninstalledModules(this)) { //there're uninstalled modules
-        tasks.add("update.database");
-        tasks.add("generate.entities");
-        tasks.add("compile.deploy");
-        if (!unnappliedModules.equals("")) { //There are also installed modules, let's compile them
-            ant.setProperty("module", unnappliedModules);
-        } else {
-            ant.setProperty("tab", "xx"); //Only uninstall, compile no window to re-generate web.xml
+
+    /**
+     * Method to be called via AJAX. It is intended to be called periodically to
+     * show the log generated after the las call
+     * 
+     * @param response
+     * @param vars
+     * @throws IOException
+     * @throws ServletException
+     */
+    private void updateLog(HttpServletResponse response, VariablesSecureApp vars)
+            throws IOException, ServletException {
+        try {
+            final AntExecutor ant = (AntExecutor) vars
+                    .getSessionObject("ApplyModules|Log");
+            if (ant != null)
+                ant.setPrintWriter(response.getWriter());
+        } catch (final Exception e) {
+            e.printStackTrace();
         }
-        ant.setProperty("apply.on.create", "true");
-      } else {
-        tasks.add("apply.modules");
-        ant.setProperty("module", unnappliedModules);
-      }
-      
-      ant.runTask(tasks);
-     
-      ant.setFinished(true);
-      
-      
-      response.setContentType("text/plain; charset=UTF-8");
-      out.println("finished");
-      out.close();
-    } catch (final Exception e) {e.printStackTrace();}  
-    finally{
-     // System.setOut(oldOut);
     }
-  }
-  
-  /**
-   * Method to be called via AJAX. It is intended to be called periodically to show the log generated after the las call
-   *  
-   * @param response
-   * @param vars
-   * @throws IOException
-   * @throws ServletException
-   */
-  private void updateLog(HttpServletResponse response, VariablesSecureApp vars) throws IOException, ServletException {
-    try {
-      final AntExecutor ant = (AntExecutor) vars.getSessionObject("ApplyModules|Log");
-      if (ant!=null) ant.setPrintWriter(response.getWriter());
-    } catch (final Exception e) {
-      e.printStackTrace();
+
+    /**
+     * Method to be called via AJAX. It returns a XML structure with the error
+     * messages (if any) or a Success one
+     * 
+     * @param response
+     * @param vars
+     * @throws IOException
+     * @throws ServletException
+     */
+    private void getError(HttpServletResponse response, VariablesSecureApp vars)
+            throws IOException, ServletException {
+        if (log4j.isDebugEnabled())
+            log4j.debug("Output: print page errors");
+        final XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
+                "org/openbravo/erpCommon/businessUtility/MessageJS")
+                .createXmlDocument();
+        String type = "Hidden";
+        String title = "";
+        String description = "";
+        final String strLanguage = vars.getLanguage();
+
+        try {
+            final AntExecutor ant = (AntExecutor) vars
+                    .getSessionObject("ApplyModules|Log");
+            if (ant != null)
+                description = ant.getErr();
+            if (description.startsWith("SuccessRebuild")) {
+                type = "Success";
+                title = Utility.messageBD(this, type, strLanguage);
+                description = "<![CDATA["
+                        + Utility.messageBD(this, description, strLanguage)
+                        + "]]>";
+            } else {
+                type = "Error";
+                title = Utility.messageBD(this, type, strLanguage);
+                description = "<![CDATA[" + description + "]]>";
+            }
+            xmlDocument.setParameter("type", type);
+            xmlDocument.setParameter("title", title);
+            xmlDocument.setParameter("description", description);
+            response.setContentType("text/xml; charset=UTF-8");
+            response.setHeader("Cache-Control", "no-cache");
+            final PrintWriter out = response.getWriter();
+            out.println(xmlDocument.print());
+            out.close();
+        } catch (final Exception e) {
+            description = "";
+        }
     }
-  }
 
-  /**
-   * Method to be called via AJAX. It returns a XML structure with the error messages (if any) or a Success one 
-   * 
-   * @param response
-   * @param vars
-   * @throws IOException
-   * @throws ServletException
-   */
-  private void getError(HttpServletResponse response, VariablesSecureApp vars) throws IOException, ServletException {
-    if (log4j.isDebugEnabled()) log4j.debug("Output: print page errors");
-    final XmlDocument xmlDocument = xmlEngine.readXmlTemplate("org/openbravo/erpCommon/businessUtility/MessageJS").createXmlDocument();
-    String type = "Hidden";
-    String title = "";
-    String description = "";
-    final String strLanguage = vars.getLanguage();
-    
-    try {
-      final AntExecutor ant = (AntExecutor) vars.getSessionObject("ApplyModules|Log");
-      if (ant!=null) description = ant.getErr();
-      if (description.startsWith("SuccessRebuild")) {
-        type="Success";
-        title= Utility.messageBD(this, type, strLanguage);
-        description =  "<![CDATA[" +Utility.messageBD(this, description, strLanguage)+ "]]>";
-      } else {
-        type="Error";
-        title= Utility.messageBD(this, type, strLanguage);
-        description= "<![CDATA[" +description+"]]>";
-      }
-      xmlDocument.setParameter("type", type);
-      xmlDocument.setParameter("title", title);
-      xmlDocument.setParameter("description", description);
-      response.setContentType("text/xml; charset=UTF-8");
-      response.setHeader("Cache-Control", "no-cache");
-      final PrintWriter out = response.getWriter();
-      out.println(xmlDocument.print());
-      out.close();
-    } catch (final Exception e) {
-      description = "";
+    /**
+     * Returns a String of comma separated values for all the modules that are
+     * installed but not applied
+     * 
+     * @return
+     * @throws IOException
+     * @throws ServletException
+     */
+    private String getUnnapliedModules() throws IOException, ServletException {
+        String rt = "";
+        final ApplyModulesData[] data = ApplyModulesData
+                .selectUnappliedModules(this);
+        if (data != null) {
+            for (int i = 0; i < data.length; i++) {
+                if (!rt.equals(""))
+                    rt += ", ";
+                rt += data[i].name;
+            }
+        }
+        return rt;
     }
-  }
-  
-  /**
-   * Returns a String of comma separated values for all the modules that are installed but not applied
-   * 
-   * @return
-   * @throws IOException
-   * @throws ServletException
-   */
-  private String getUnnapliedModules() throws IOException, ServletException{
-    String rt = "";
-    final ApplyModulesData[] data=ApplyModulesData.selectUnappliedModules(this);
-    if (data!=null) {
-      for (int i=0; i<data.length; i++) {
-        if (!rt.equals("")) rt += ", ";
-        rt += data[i].name;
-      }
-    }
-    return rt;
-  }
 }