fixes issue 38520: Deprecate OBDal.registerSQLFunction
authorCarlos Aristu <carlos.aristu@openbravo.com>
Fri, 18 May 2018 13:37:54 +0200
changeset 33992 055351d43c80
parent 33977 4d0349cd40a0 (current diff)
parent 33991 b5f8e5dad6fe (diff)
child 33993 0ac5c4647a10
fixes issue 38520: Deprecate OBDal.registerSQLFunction
modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/utility/APRMApplicationInitializer.java
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/utility/APRMApplicationInitializer.java	Fri May 18 13:36:23 2018 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,88 +0,0 @@
-/*
- *************************************************************************
- * 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 SLU
- * All portions are Copyright (C) 2012-2014 Openbravo SLU
- * All Rights Reserved.
- * Contributor(s):  ______________________________________.
- *************************************************************************
- */
-
-package org.openbravo.advpaymentmngt.utility;
-
-import javax.enterprise.context.ApplicationScoped;
-import javax.servlet.ServletException;
-
-import org.hibernate.SQLQuery;
-import org.hibernate.dialect.function.SQLFunctionTemplate;
-import org.hibernate.dialect.function.StandardSQLFunction;
-import org.hibernate.type.StandardBasicTypes;
-import org.openbravo.client.kernel.ApplicationInitializer;
-import org.openbravo.dal.service.OBDal;
-import org.openbravo.erpCommon.utility.SystemInfo;
-import org.openbravo.service.db.DalConnectionProvider;
-
-@ApplicationScoped
-public class APRMApplicationInitializer implements ApplicationInitializer {
-  final static String RDBMS = new DalConnectionProvider(false).getRDBMS();
-
-  @Override
-  public void initialize() {
-    OBDal.getInstance().registerSQLFunction("ad_message_get2",
-        new StandardSQLFunction("ad_message_get2", StandardBasicTypes.STRING));
-    OBDal.getInstance().registerSQLFunction("hqlagg",
-        new SQLFunctionTemplate(StandardBasicTypes.STRING, getAggregationSQL()));
-    OBDal.getInstance().registerSQLFunction("get_uuid",
-        new StandardSQLFunction("get_uuid", StandardBasicTypes.STRING));
-  }
-
-  private String getAggregationSQL() {
-    if ("ORACLE".equals(RDBMS)) {
-      if (is11R2orNewer()) {
-        return "listagg(to_char(?1), ',') WITHIN GROUP (ORDER BY ?1)";
-      } else if (existsStrAgg()) {
-        return "stragg(to_char(?1))";
-      } else {
-        return "wm_concat(to_char(?1))";
-      }
-    } else {
-      return "array_to_string(array_agg(?1), ',')";
-    }
-  }
-
-  private boolean existsStrAgg() {
-    try {
-      SQLQuery qry = OBDal.getInstance().getSession().createSQLQuery("select stragg(1) from dual");
-      qry.list();
-    } catch (Exception e) {
-      return false;
-    }
-    return true;
-  }
-
-  private boolean is11R2orNewer() {
-    String dbVersion = null;
-    try {
-      dbVersion = SystemInfo.getDatabaseVersion(new DalConnectionProvider(false));
-    } catch (ServletException ignore) {
-
-    }
-    if (dbVersion == null) {
-      return false;
-    }
-    int version = Integer.valueOf(dbVersion.replaceAll("\\.", "").substring(0, 3));
-    if (version >= 112) {
-      return true;
-    }
-    return false;
-  }
-}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/utility/APRMSQLFunctionRegister.java	Fri May 18 13:37:54 2018 +0200
@@ -0,0 +1,99 @@
+/*
+ *************************************************************************
+ * 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 SLU
+ * All portions are Copyright (C) 2018 Openbravo SLU
+ * All Rights Reserved.
+ * Contributor(s):  ______________________________________.
+ *************************************************************************
+ */
+
+package org.openbravo.advpaymentmngt.utility;
+
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.enterprise.context.ApplicationScoped;
+
+import org.hibernate.dialect.function.SQLFunction;
+import org.hibernate.dialect.function.SQLFunctionTemplate;
+import org.hibernate.dialect.function.StandardSQLFunction;
+import org.hibernate.type.StandardBasicTypes;
+import org.openbravo.base.session.OBPropertiesProvider;
+import org.openbravo.dal.core.SQLFunctionRegister;
+import org.openbravo.database.ConnectionProviderImpl;
+import org.openbravo.erpCommon.utility.SystemInfo;
+import org.openbravo.service.db.DalConnectionProvider;
+
+/**
+ * A class in charge of registering APRM SQL functions in Hibernate.
+ */
+@ApplicationScoped
+public class APRMSQLFunctionRegister implements SQLFunctionRegister {
+  private static final String RDBMS = new DalConnectionProvider(false).getRDBMS();
+
+  @Override
+  public Map<String, SQLFunction> getSQLFunctions() {
+    Map<String, SQLFunction> sqlFunctions = new HashMap<>();
+    sqlFunctions.put("ad_message_get2", new StandardSQLFunction("ad_message_get2",
+        StandardBasicTypes.STRING));
+    sqlFunctions.put("hqlagg", new SQLFunctionTemplate(StandardBasicTypes.STRING,
+        getAggregationSQL()));
+    return sqlFunctions;
+  }
+
+  private String getAggregationSQL() {
+    if ("ORACLE".equals(RDBMS)) {
+      if (is11R2orNewer()) {
+        return "listagg(to_char(?1), ',') WITHIN GROUP (ORDER BY ?1)";
+      } else if (existsStrAgg()) {
+        return "stragg(to_char(?1))";
+      } else {
+        return "wm_concat(to_char(?1))";
+      }
+    } else {
+      return "array_to_string(array_agg(?1), ',')";
+    }
+  }
+
+  private boolean existsStrAgg() {
+    try {
+      ConnectionProviderImpl connectionProvider = new ConnectionProviderImpl(OBPropertiesProvider
+          .getInstance().getOpenbravoProperties());
+      String sql = "select stragg(1) from dual";
+      try (PreparedStatement st = connectionProvider.getPreparedStatement(sql);
+          Connection connection = st.getConnection();
+          ResultSet result = st.executeQuery()) {
+        return true;
+      }
+    } catch (Exception ignore) {
+    }
+    return false;
+  }
+
+  private boolean is11R2orNewer() {
+    String dbVersion = null;
+    try {
+      dbVersion = SystemInfo.getDatabaseVersion(new ConnectionProviderImpl(OBPropertiesProvider
+          .getInstance().getOpenbravoProperties()));
+    } catch (Exception ignore) {
+    }
+    if (dbVersion == null) {
+      return false;
+    }
+    int version = Integer.parseInt(dbVersion.replaceAll("\\.", "").substring(0, 3));
+    return version >= 112;
+  }
+}
--- a/modules/org.openbravo.base.weld/src/META-INF/beans.xml	Fri May 18 13:36:23 2018 +0200
+++ b/modules/org.openbravo.base.weld/src/META-INF/beans.xml	Fri May 18 13:37:54 2018 +0200
@@ -24,7 +24,9 @@
         <weld:exclude name="org.openbravo.base.structure.**"/>
         <weld:exclude name="org.openbravo.base.util.**"/>
         <weld:exclude name="org.openbravo.base.validation.**"/>
-        <weld:exclude name="org.openbravo.dal.**"/>
+        <weld:exclude name="org.openbravo.dal.security.**"/>
+        <weld:exclude name="org.openbravo.dal.service.**"/>
+        <weld:exclude name="org.openbravo.dal.xml.**"/>
         <weld:exclude name="org.openbravo.erpReports.**"/>
         <weld:exclude name="org.openbravo.reference.**"/>
         <weld:exclude name="org.openbravo.scheduling.**"/>
--- a/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/KernelApplicationInitializer.java	Fri May 18 13:36:23 2018 +0200
+++ b/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/KernelApplicationInitializer.java	Fri May 18 13:37:54 2018 +0200
@@ -25,9 +25,6 @@
 import javax.inject.Inject;
 
 import org.apache.log4j.Logger;
-import org.hibernate.dialect.function.StandardSQLFunction;
-import org.hibernate.type.StandardBasicTypes;
-import org.hibernate.type.StringType;
 import org.openbravo.client.application.report.JmxReportCache;
 import org.openbravo.client.application.window.ApplicationDictionaryCachedStructures;
 import org.openbravo.dal.service.OBDal;
@@ -37,9 +34,8 @@
 import org.openbravo.service.db.DalConnectionProvider;
 
 /**
- * An {@link ApplicationInitializer} in charge of doing some initialization tasks like registering
- * core SQL functions, checking if both Tomcat and DB are configured to use the same time and
- * registering standard jmx beans.
+ * An {@link ApplicationInitializer} in charge of doing some initialization tasks like checking if
+ * both Tomcat and DB are configured to use the same time and registering some standard jmx beans.
  * 
  * @author mtaal
  */
@@ -61,23 +57,11 @@
   private ApplicationDictionaryCachedStructures adCachedStructures;
 
   public void initialize() {
-    registerSQLFunctions();
     checkDatabaseAndTomcatDateTime();
     registerMBeans();
     setModulesAsNotInDevelopment();
   }
 
-  private void registerSQLFunctions() {
-    OBDal.getInstance().registerSQLFunction("ad_org_getcalendarowner",
-        new StandardSQLFunction("ad_org_getcalendarowner", new StringType()));
-    OBDal.getInstance().registerSQLFunction("ad_org_getperiodcontrolallow",
-        new StandardSQLFunction("ad_org_getperiodcontrolallow", new StringType()));
-    OBDal.getInstance().registerSQLFunction("m_isparent_ch_value",
-        new StandardSQLFunction("m_isparent_ch_value", new StringType()));
-    OBDal.getInstance().registerSQLFunction("m_getjsondescription",
-        new StandardSQLFunction("m_getjsondescription", StandardBasicTypes.STRING));
-  }
-
   private void checkDatabaseAndTomcatDateTime() {
     // This method checks if both Tomcat and DB are configured to use the same time. If there
     // is a difference bigger than a few seconds, it logs a warning.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/KernelSQLFunctionRegister.java	Fri May 18 13:37:54 2018 +0200
@@ -0,0 +1,52 @@
+/*
+ *************************************************************************
+ * The contents of this file are subject to the Openbravo  Public  License
+ * Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
+ * Version 1.1  with a permitted attribution clause; you may not  use this
+ * file except in compliance with the License. You  may  obtain  a copy of
+ * the License at http://www.openbravo.com/legal/license.html 
+ * Software distributed under the License  is  distributed  on  an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+ * License for the specific  language  governing  rights  and  limitations
+ * under the License. 
+ * The Original Code is Openbravo ERP. 
+ * The Initial Developer of the Original Code is Openbravo SLU 
+ * All portions are Copyright (C) 2018 Openbravo SLU 
+ * All Rights Reserved. 
+ * Contributor(s):  ______________________________________.
+ ************************************************************************
+ */
+package org.openbravo.client.kernel;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.enterprise.context.ApplicationScoped;
+
+import org.hibernate.dialect.function.SQLFunction;
+import org.hibernate.dialect.function.StandardSQLFunction;
+import org.hibernate.type.StandardBasicTypes;
+import org.openbravo.dal.core.SQLFunctionRegister;
+
+/**
+ * A class in charge of registering core SQL functions in Hibernate.
+ */
+@ApplicationScoped
+public class KernelSQLFunctionRegister implements SQLFunctionRegister {
+
+  @Override
+  public Map<String, SQLFunction> getSQLFunctions() {
+    Map<String, SQLFunction> sqlFunctions = new HashMap<>();
+    sqlFunctions.put("ad_org_getcalendarowner", new StandardSQLFunction("ad_org_getcalendarowner",
+        StandardBasicTypes.STRING));
+    sqlFunctions.put("ad_org_getperiodcontrolallow", new StandardSQLFunction(
+        "ad_org_getperiodcontrolallow", StandardBasicTypes.STRING));
+    sqlFunctions.put("get_uuid", new StandardSQLFunction("get_uuid", StandardBasicTypes.STRING));
+    sqlFunctions.put("m_isparent_ch_value", new StandardSQLFunction("m_isparent_ch_value",
+        StandardBasicTypes.STRING));
+    sqlFunctions.put("m_getjsondescription", new StandardSQLFunction("m_getjsondescription",
+        StandardBasicTypes.STRING));
+    sqlFunctions.put("now", new StandardSQLFunction("now", StandardBasicTypes.DATE));
+    return sqlFunctions;
+  }
+}
--- a/src-test/src/org/openbravo/test/base/OBBaseTest.java	Fri May 18 13:36:23 2018 +0200
+++ b/src-test/src/org/openbravo/test/base/OBBaseTest.java	Fri May 18 13:37:54 2018 +0200
@@ -38,6 +38,7 @@
 import org.apache.log4j.Logger;
 import org.apache.log4j.PropertyConfigurator;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.dialect.function.SQLFunction;
 import org.jboss.arquillian.container.weld.ee.embedded_1_1.mock.MockServletContext;
 import org.junit.After;
 import org.junit.Before;
@@ -376,15 +377,27 @@
   /**
    * Initializes the DALLayer, can be overridden to add specific initialization behavior.
    * 
+   * @param sqlFunctions
+   *          a Map with SQL functions to be registered in Hibernate during the DAL layer
+   *          initialization. It can be null if not needed.
    * @throws Exception
    */
-  protected void initializeDalLayer() throws Exception {
-    staticInitializeDalLayer();
+  protected void initializeDalLayer(Map<String, SQLFunction> sqlFunctions) throws Exception {
+    DalLayerInitializer.getInstance().setInitialized(false);
+    log.info("Creating custom DAL layer initialization...");
+    staticInitializeDalLayer(sqlFunctions);
   }
 
   private static void staticInitializeDalLayer() throws Exception {
-    if (!DalLayerInitializer.getInstance().isInitialized()) {
-      DalLayerInitializer.getInstance().initialize(true);
+    staticInitializeDalLayer(null);
+  }
+
+  private static void staticInitializeDalLayer(Map<String, SQLFunction> sqlFunctions)
+      throws Exception {
+    DalLayerInitializer initializer = DalLayerInitializer.getInstance();
+    if (!initializer.isInitialized()) {
+      initializer.setSQLFunctions(sqlFunctions);
+      initializer.initialize(true);
     }
   }
 
--- a/src-test/src/org/openbravo/test/dal/IssuesTest.java	Fri May 18 13:36:23 2018 +0200
+++ b/src-test/src/org/openbravo/test/dal/IssuesTest.java	Fri May 18 13:37:54 2018 +0200
@@ -47,6 +47,7 @@
 import org.hibernate.ScrollableResults;
 import org.hibernate.Session;
 import org.hibernate.criterion.Restrictions;
+import org.hibernate.dialect.function.SQLFunction;
 import org.hibernate.dialect.function.StandardSQLFunction;
 import org.hibernate.type.StandardBasicTypes;
 import org.junit.Assert;
@@ -181,12 +182,18 @@
 
   /**
    * https://issues.openbravo.com/view.php?id=18688
+   * 
+   * @throws Exception
    */
   @Test
-  public void test18688() {
+  public void test18688() throws Exception {
+    // define the map containing the SQL function to be registered in Hibernate
+    Map<String, SQLFunction> sqlFunctions = new HashMap<>();
+    sqlFunctions.put("ad_column_identifier_std", new StandardSQLFunction(
+        "ad_column_identifier_std", StandardBasicTypes.STRING));
+    initializeDalLayer(sqlFunctions);
+
     final Session session = OBDal.getInstance().getSession();
-    OBDal.getInstance().registerSQLFunction("ad_column_identifier_std",
-        new StandardSQLFunction("ad_column_identifier_std", StandardBasicTypes.STRING));
     final String qryStr = "select bc.id, ad_column_identifier_std('C_BP_Group', bc.id) from "
         + Category.ENTITY_NAME + " bc";
     final Query qry = session.createQuery(qryStr);
@@ -393,7 +400,7 @@
 
   private Language getNonInstalledLanguage() {
     return (Language) OBDal.getInstance().createCriteria(Language.class)
-      .add(Restrictions.eq(Language.PROPERTY_SYSTEMLANGUAGE, false)).list().get(0);
+        .add(Restrictions.eq(Language.PROPERTY_SYSTEMLANGUAGE, false)).list().get(0);
   }
 
   /**
--- a/src-test/src/org/openbravo/test/inventoryStatus/InventoryStatusTest.java	Fri May 18 13:36:23 2018 +0200
+++ b/src-test/src/org/openbravo/test/inventoryStatus/InventoryStatusTest.java	Fri May 18 13:37:54 2018 +0200
@@ -11,7 +11,7 @@
  * under the License. 
  * The Original Code is Openbravo ERP. 
  * The Initial Developer of the Original Code is Openbravo SLU 
- * All portions are Copyright (C) 2017 Openbravo SLU 
+ * All portions are Copyright (C) 2017-2018 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -28,8 +28,6 @@
 import java.util.Date;
 import java.util.List;
 
-import javax.inject.Inject;
-
 import org.apache.commons.lang.StringUtils;
 import org.hibernate.criterion.Restrictions;
 import org.junit.Before;
@@ -38,7 +36,6 @@
 import org.junit.Test;
 import org.junit.rules.ExpectedException;
 import org.junit.runners.MethodSorters;
-import org.openbravo.advpaymentmngt.utility.APRMApplicationInitializer;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.provider.OBProvider;
 import org.openbravo.base.weld.test.WeldBaseTest;
@@ -127,15 +124,11 @@
   @Rule
   public ExpectedException thrown = ExpectedException.none();
 
-  @Inject
-  public APRMApplicationInitializer initializer;
-
   @Before
   public void initialize() {
     log.info("Initializing Inventory Status Test ...");
     OBContext.setOBContext(USER_ID, ROLE_ID, CLIENT_ID, ORG_ID, LANGUAGE_CODE);
     initializeReservationsPreference();
-    initializer.initialize();
   }
 
   private void initializeReservationsPreference() {
--- a/src/build.xml	Fri May 18 13:36:23 2018 +0200
+++ b/src/build.xml	Fri May 18 13:37:54 2018 +0200
@@ -165,6 +165,7 @@
       <src path="${base.src}"/>
       <src path="../build/javasqlc/src"/>
       <src path="../src-gen"/>
+      <src path="../modules/org.openbravo.base.weld/src/"/>
       <classpath refid="apply.module.compile.classpath" />
     </javac>
   </target>
@@ -224,7 +225,7 @@
         <classpath refid="project.class.path" />      
       </javac>
       -->
-      <javac srcdir="${base.src}:${base.src.gen}" includes="org/openbravo/model/**,org/openbravo/base/structure/**,org/openbravo/dal/**,org/openbravo/service/dataset/**" destdir="${build}" encoding="UTF-8" fork="true" memorymaximumsize="${build.maxmemory}" debug="true" debuglevel="lines,vars,source" deprecation="on" includeantruntime="false">
+      <javac srcdir="${base.src}:${base.src.gen}:${base.modules}" includes="org/openbravo/model/**,org/openbravo/base/structure/**,org/openbravo/dal/**,org/openbravo/service/dataset/**,*/src/**/base/weld/**" destdir="${build}" encoding="UTF-8" fork="true" memorymaximumsize="${build.maxmemory}" debug="true" debuglevel="lines,vars,source" deprecation="on" includeantruntime="false">
         <classpath refid="project.class.path" />      
       </javac>
       <javac srcdir="${base.src.gen}" excludes="org/openbravo/model/**,org/openbravo/base/structure/**,org/openbravo/dal/**,org/openbravo/service/dataset/**" destdir="${build}" encoding="UTF-8" fork="true" memorymaximumsize="${build.maxmemory}" debug="true" debuglevel="lines,vars,source" deprecation="on" includeantruntime="false">
--- a/src/org/openbravo/base/session/SessionFactoryController.java	Fri May 18 13:36:23 2018 +0200
+++ b/src/org/openbravo/base/session/SessionFactoryController.java	Fri May 18 13:37:54 2018 +0200
@@ -19,7 +19,10 @@
 
 package org.openbravo.base.session;
 
+import java.util.Collections;
 import java.util.Enumeration;
+import java.util.Map;
+import java.util.Map.Entry;
 import java.util.Properties;
 
 import org.apache.log4j.Logger;
@@ -29,6 +32,7 @@
 import org.hibernate.connection.ConnectionProvider;
 import org.hibernate.connection.DriverManagerConnectionProvider;
 import org.hibernate.dialect.PostgreSQLDialect;
+import org.hibernate.dialect.function.SQLFunction;
 import org.hibernate.impl.SessionFactoryImpl;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.provider.OBProvider;
@@ -173,9 +177,10 @@
       // configuration.getProperties().setProperty(Environment.ISOLATION,
       // "" + Connection.TRANSACTION_READ_COMMITTED);
 
+      registerSqlFunctions();
+
       final DalSessionFactory dalSessionFactory = OBProvider.getInstance().get(
           DalSessionFactory.class);
-
       SessionFactory delegateSessionFactory = configuration.buildSessionFactory();
       dalSessionFactory.setDelegateSessionFactory(delegateSessionFactory);
 
@@ -196,6 +201,20 @@
     }
   }
 
+  private void registerSqlFunctions() {
+    Map<String, SQLFunction> sqlFunctions = getSQLFunctions();
+    if (sqlFunctions == null || sqlFunctions.isEmpty()) {
+      return;
+    }
+    for (Entry<String, SQLFunction> entry : sqlFunctions.entrySet()) {
+      configuration.addSqlFunction(entry.getKey(), entry.getValue());
+    }
+  }
+
+  protected Map<String, SQLFunction> getSQLFunctions() {
+    return Collections.emptyMap();
+  }
+
   protected abstract void mapModel(Configuration theConfiguration);
 
   protected Properties getOpenbravoProperties() {
--- a/src/org/openbravo/costing/CostingMigrationProcess.java	Fri May 18 13:36:23 2018 +0200
+++ b/src/org/openbravo/costing/CostingMigrationProcess.java	Fri May 18 13:37:54 2018 +0200
@@ -11,7 +11,7 @@
  * under the License.
  * The Original Code is Openbravo ERP.
  * The Initial Developer of the Original Code is Openbravo SLU
- * All portions are Copyright (C) 2012-2017 Openbravo SLU
+ * All portions are Copyright (C) 2012-2018 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  *************************************************************************
@@ -36,7 +36,6 @@
 import org.hibernate.ScrollMode;
 import org.hibernate.ScrollableResults;
 import org.hibernate.criterion.Restrictions;
-import org.hibernate.dialect.function.StandardSQLFunction;
 import org.hibernate.type.DateType;
 import org.hibernate.type.StringType;
 import org.openbravo.base.exception.OBException;
@@ -115,12 +114,6 @@
         throw new OBException("@CostMigratedInstance@");
       }
 
-      // FIXME: Remove when HQL based inserts are removed.
-      OBDal.getInstance().registerSQLFunction("get_uuid",
-          new StandardSQLFunction("get_uuid", new StringType()));
-      OBDal.getInstance()
-          .registerSQLFunction("now", new StandardSQLFunction("now", new DateType()));
-
       if (!isMigrationFirstPhaseCompleted()) {
         long t1 = System.currentTimeMillis();
         log4j.debug("Starting CostingMigrationProcess first phase at: " + new Date());
--- a/src/org/openbravo/dal/core/DalLayerInitializer.java	Fri May 18 13:36:23 2018 +0200
+++ b/src/org/openbravo/dal/core/DalLayerInitializer.java	Fri May 18 13:37:54 2018 +0200
@@ -11,7 +11,7 @@
  * under the License. 
  * The Original Code is Openbravo ERP. 
  * The Initial Developer of the Original Code is Openbravo SLU 
- * All portions are Copyright (C) 2008-2010 Openbravo SLU 
+ * All portions are Copyright (C) 2008-2018 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -19,16 +19,20 @@
 
 package org.openbravo.dal.core;
 
+import java.util.Map;
+
 import org.apache.log4j.Logger;
+import org.hibernate.dialect.function.SQLFunction;
 import org.openbravo.base.model.Entity;
 import org.openbravo.base.model.ModelProvider;
 import org.openbravo.base.provider.OBConfigFileProvider;
 import org.openbravo.base.provider.OBProvider;
 import org.openbravo.base.provider.OBSingleton;
 import org.openbravo.base.session.SessionFactoryController;
+import org.openbravo.base.weld.WeldUtils;
 
 /**
- * This class is responsible for initializing the dal layer. It ensures that the model is read in
+ * This class is responsible for initializing the DAL layer. It ensures that the model is read in
  * memory and that the mapping is generated in a two stage process.
  * 
  * @author mtaal
@@ -39,6 +43,8 @@
 
   private static DalLayerInitializer instance;
 
+  private Map<String, SQLFunction> sqlFunctions;
+
   public static DalLayerInitializer getInstance() {
     if (instance == null) {
       instance = OBProvider.getInstance().get(DalLayerInitializer.class);
@@ -73,8 +79,7 @@
     }
 
     log.info("Model read in-memory, generating mapping...");
-    SessionFactoryController.setInstance(OBProvider.getInstance().get(
-        DalSessionFactoryController.class));
+    SessionFactoryController.setInstance(getDalSessionFactoryController());
     SessionFactoryController.getInstance().initialize();
 
     // reset the session
@@ -89,13 +94,38 @@
     initialized = true;
   }
 
+  private DalSessionFactoryController getDalSessionFactoryController() {
+    DalSessionFactoryController dsfc;
+    try {
+      dsfc = WeldUtils.getInstanceFromStaticBeanManager(DalSessionFactoryController.class);
+    } catch (Exception ex) {
+      log.debug("Could not instantiate DalSessionFactoryController using weld", ex);
+      dsfc = OBProvider.getInstance().get(DalSessionFactoryController.class);
+    }
+    if (sqlFunctions != null && !sqlFunctions.isEmpty()) {
+      dsfc.setSQLFunctions(sqlFunctions);
+    }
+    return dsfc;
+  }
+
+  /**
+   * Can be used to manually provide to the {@link DalSessionFactoryController} the SQL functions to
+   * be registered in Hibernate.
+   * 
+   * @param sqlFunctions
+   *          a Map with the SQL functions to be registered in Hibernate.
+   */
+  public void setSQLFunctions(Map<String, SQLFunction> sqlFunctions) {
+    this.sqlFunctions = sqlFunctions;
+  }
+
   public boolean isInitialized() {
     return initialized;
   }
 
   /**
    * Can be used to set the internal initialized member to false and then call initialize again to
-   * re-initialize the Dal layer.
+   * re-initialize the DAL layer.
    * 
    * @param initialized
    *          the value of the initialized member
--- a/src/org/openbravo/dal/core/DalSessionFactoryController.java	Fri May 18 13:36:23 2018 +0200
+++ b/src/org/openbravo/dal/core/DalSessionFactoryController.java	Fri May 18 13:37:54 2018 +0200
@@ -11,7 +11,7 @@
  * under the License. 
  * The Original Code is Openbravo ERP. 
  * The Initial Developer of the Original Code is Openbravo SLU 
- * All portions are Copyright (C) 2008-2010 Openbravo SLU 
+ * All portions are Copyright (C) 2008-2018 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -19,8 +19,16 @@
 
 package org.openbravo.dal.core;
 
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.enterprise.inject.Any;
+import javax.enterprise.inject.Instance;
+import javax.inject.Inject;
+
 import org.apache.log4j.Logger;
 import org.hibernate.cfg.Configuration;
+import org.hibernate.dialect.function.SQLFunction;
 import org.openbravo.base.model.ModelProvider;
 import org.openbravo.base.session.SessionFactoryController;
 
@@ -36,6 +44,12 @@
 public class DalSessionFactoryController extends SessionFactoryController {
   private static final Logger log = Logger.getLogger(DalSessionFactoryController.class);
 
+  @Inject
+  @Any
+  private Instance<SQLFunctionRegister> sqlFunctionRegisters;
+
+  private Map<String, SQLFunction> sqlFunctions;
+
   @Override
   protected void mapModel(Configuration configuration) {
     final String mapping = DalMappingGenerator.getInstance().generateMapping();
@@ -48,4 +62,27 @@
   protected void setInterceptor(Configuration configuration) {
     configuration.setInterceptor(new OBInterceptor());
   }
+
+  @Override
+  protected Map<String, SQLFunction> getSQLFunctions() {
+    if (sqlFunctions != null) {
+      return sqlFunctions;
+    }
+    sqlFunctions = new HashMap<>();
+    if (sqlFunctionRegisters == null) {
+      return sqlFunctions;
+    }
+    for (SQLFunctionRegister register : sqlFunctionRegisters) {
+      Map<String, SQLFunction> registeredSqlFunctions = register.getSQLFunctions();
+      if (registeredSqlFunctions == null) {
+        continue;
+      }
+      sqlFunctions.putAll(registeredSqlFunctions);
+    }
+    return sqlFunctions;
+  }
+
+  void setSQLFunctions(Map<String, SQLFunction> sqlFunctions) {
+    this.sqlFunctions = sqlFunctions;
+  }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/org/openbravo/dal/core/SQLFunctionRegister.java	Fri May 18 13:37:54 2018 +0200
@@ -0,0 +1,39 @@
+/*
+ *************************************************************************
+ * The contents of this file are subject to the Openbravo  Public  License
+ * Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
+ * Version 1.1  with a permitted attribution clause; you may not  use this
+ * file except in compliance with the License. You  may  obtain  a copy of
+ * the License at http://www.openbravo.com/legal/license.html 
+ * Software distributed under the License  is  distributed  on  an "AS IS"
+ * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
+ * License for the specific  language  governing  rights  and  limitations
+ * under the License. 
+ * The Original Code is Openbravo ERP. 
+ * The Initial Developer of the Original Code is Openbravo SLU 
+ * All portions are Copyright (C) 2018 Openbravo SLU 
+ * All Rights Reserved. 
+ * Contributor(s):  ______________________________________.
+ ************************************************************************
+ */
+package org.openbravo.dal.core;
+
+import java.util.Map;
+
+import org.hibernate.dialect.function.SQLFunction;
+
+/**
+ * An interface that must be implemented by those classes intended to register SQL functions which
+ * are pretended to be used in HQL.
+ */
+public interface SQLFunctionRegister {
+
+  /**
+   * This method is executed by the {@link DalSessionFactoryController} to retrieve SQL functions
+   * that should be registered in Hibernate.
+   * 
+   * @return A Map with SQL functions to be registered in Hibernate.
+   */
+  public Map<String, SQLFunction> getSQLFunctions();
+
+}
--- a/src/org/openbravo/dal/service/OBDal.java	Fri May 18 13:36:23 2018 +0200
+++ b/src/org/openbravo/dal/service/OBDal.java	Fri May 18 13:37:54 2018 +0200
@@ -50,6 +50,7 @@
 import org.openbravo.dal.core.DalSessionFactory;
 import org.openbravo.dal.core.DalUtil;
 import org.openbravo.dal.core.OBContext;
+import org.openbravo.dal.core.SQLFunctionRegister;
 import org.openbravo.dal.core.SessionHandler;
 import org.openbravo.dal.security.SecurityChecker;
 import org.openbravo.database.ExternalConnectionPool;
@@ -129,8 +130,14 @@
 
   /**
    * Register a sql function in the session factory, after this call it can be used by queries.
+   * 
+   * @deprecated Use a {@link SQLFunctionRegister} instead. This method is slated for removal in the
+   *             upcoming releases.
    */
+  @Deprecated
   public void registerSQLFunction(String name, SQLFunction function) {
+    log.warn("Using deprecated way of registering SQL functions in Hibernate", new Exception(
+        "Current Stack Trace"));
     final DalSessionFactory dalSessionFactory = (DalSessionFactory) SessionFactoryController
         .getInstance().getSessionFactory();
 
--- a/src/org/openbravo/erpCommon/utility/SystemInfo.java	Fri May 18 13:36:23 2018 +0200
+++ b/src/org/openbravo/erpCommon/utility/SystemInfo.java	Fri May 18 13:37:54 2018 +0200
@@ -131,7 +131,12 @@
   }
 
   private static void load(Item i, ConnectionProvider conn) throws ServletException {
-
+    if (i == Item.DATABASE) {
+      // The database information can be requested without having DAL initialized, so we directly
+      // retrieve it here, avoiding to initialize OBContext
+      systemInfo.put(i, conn.getRDBMS());
+      return;
+    }
     OBContext.setAdminMode();
     try {
 
@@ -147,7 +152,7 @@
         systemInfo.put(i, getDBIdentifier(conn));
         break;
       case DATABASE:
-        systemInfo.put(i, conn.getRDBMS());
+        // already handled
         break;
       case DATABASE_VERSION:
         systemInfo.put(i, getDatabaseVersion(conn));
@@ -839,11 +844,11 @@
         false), WEBSERVER_VERSION("webserverVersion", false), SERVLET_CONTAINER("servletContainer",
         false), SERVLET_CONTAINER_VERSION("servletContainerVersion", false), ANT_VERSION(
         "antVersion", false), OB_VERSION("obVersion", false), OB_INSTALL_MODE("obInstallMode",
-        false), NUM_REGISTERED_USERS("numRegisteredUsers",
-        false), ISHEARTBEATACTIVE("isheartbeatactive", true), ISPROXYREQUIRED("isproxyrequired",
-        false), PROXY_SERVER("proxyServer", false), PROXY_PORT("proxyPort", false), JAVA_VERSION(
-        "javaVersion", false), MODULES("modules", false), OBPS_INSTANCE("obpsId", false), FIRST_LOGIN(
-        "firstLogin", false), LAST_LOGIN("lastLogin", false), TOTAL_LOGINS("totalLogins", false), TOTAL_LOGINS_LAST_MOTH(
+        false), NUM_REGISTERED_USERS("numRegisteredUsers", false), ISHEARTBEATACTIVE(
+        "isheartbeatactive", true), ISPROXYREQUIRED("isproxyrequired", false), PROXY_SERVER(
+        "proxyServer", false), PROXY_PORT("proxyPort", false), JAVA_VERSION("javaVersion", false), MODULES(
+        "modules", false), OBPS_INSTANCE("obpsId", false), FIRST_LOGIN("firstLogin", false), LAST_LOGIN(
+        "lastLogin", false), TOTAL_LOGINS("totalLogins", false), TOTAL_LOGINS_LAST_MOTH(
         "loginsMoth", false), MAX_CONCURRENT_USERS("maxUsers", false), AVG_CONCURRENT_USERS(
         "avgUsers", false), PERC_TIME_USAGE("timeUsage", false), NUMBER_OF_CLIENTS("clientNum",
         false), NUMBER_OF_ORGS("orgNum", false), USAGE_AUDIT("usageAudit", false), INSTANCE_PURPOSE(