Merged from PI
authorUnai Martirena <unai.martirena@openbravo.com>
Fri, 03 Jun 2016 10:22:43 +0200
changeset 29787 f88b03439e7c
parent 29676 e012ee268cf7 (current diff)
parent 29786 4cb4e1989316 (diff)
child 29789 e0eb72165fa8
Merged from PI
modules/org.openbravo.advpaymentmngt/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.advpaymentmngt/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/dao/AdvPaymentMngtDao.java
modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/utility/FIN_Utility.java
modules/org.openbravo.apachejdbcconnectionpool/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.apachejdbcconnectionpool/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.base.weld/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.base.weld/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.client.application/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.client.application/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.client.htmlwidget/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.client.htmlwidget/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.client.kernel/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.client.kernel/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.client.myob/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.client.myob/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.client.querylist/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.client.querylist/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.client.widgets/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.client.widgets/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.financial.paymentreport/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.financial.paymentreport/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.reports.ordersawaitingdelivery/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.reports.ordersawaitingdelivery/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.service.datasource/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.service.datasource/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.service.integration.google/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.service.integration.google/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.service.integration.openid/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.service.integration.openid/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.service.json/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.service.json/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.userinterface.selector/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.userinterface.selector/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.userinterface.skin.250to300Comp/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.userinterface.skin.250to300Comp/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.userinterface.smartclient/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.userinterface.smartclient/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.utility.cleanup.log/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.utility.cleanup.log/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.v3.datasets/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.v3.datasets/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.v3.framework/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.v3.framework/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
modules/org.openbravo.v3/src-db/database/sourcedata/AD_MODULE.xml
modules/org.openbravo.v3/src-db/database/sourcedata/AD_MODULE_DEPENDENCY.xml
src-db/database/model/functions/AD_SHORTNAME.xml
src-db/database/model/functions/C_ORDER_POST1.xml
src-db/database/sourcedata/AD_MODULE.xml
src/org/openbravo/base/model/ModelProvider.java
src/org/openbravo/base/secureApp/LoginHandler.java
--- a/.hgsigs	Wed Jun 01 13:42:08 2016 +0200
+++ b/.hgsigs	Fri Jun 03 10:22:43 2016 +0200
@@ -192,3 +192,4 @@
 bdeb5a373f19eb7a144377621926d877ae2322f1 0 iEYEABECAAYFAlcgSPgACgkQCX/oGf+2qkMPLwCgzV//EHUa2bHmP8FA2IwnrFWB1X4AnjGHHjYKfSwiucQhltXR9POZXGaX
 38ef1dc10aa3d6fb8210b85beab370f62a4545ca 0 iEYEABECAAYFAlbiTM0ACgkQCX/oGf+2qkNBDwCfXmKXkqNGsAsfiofYOBBdvjA/XgkAoIwLK3DkmHeM71JihwfVOWyB4hmj
 265e8eccf704614fe88220026f2e2bafcebaaf00 0 iEYEABECAAYFAlcgZEQACgkQCX/oGf+2qkPuZgCcDPuB9d77M+51AglMvvmtpCDtnvoAnjqst7QgD6IP3Sv21+4vlqEjLVqU
+98bdf9167a3d4ea9cb9b6f5e214a539220a3f3cb 0 iEYEABECAAYFAldD+MEACgkQCX/oGf+2qkPLHwCgngPaeyLsiGk2FhShX4/IzVARWN8AnRSCXIoWp6ruOcbEfIUFQiM9lY7f
--- a/.hgtags	Wed Jun 01 13:42:08 2016 +0200
+++ b/.hgtags	Fri Jun 03 10:22:43 2016 +0200
@@ -203,3 +203,4 @@
 8828e6e8e071247f329320c63da66e30c357da9f 3.0PR15Q4.6
 ee5383e071318afe8eece515b4b264cfb46c1a84 3.0PR16Q1
 d386f41fa755d23e0e23f881aece691009051ebd 3.0PR16Q1.1
+ec73935a2c83b6164a18cb70996226cb15672038 3.0PR16Q1.2
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/actionHandler/AddPaymentActionHandler.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/actionHandler/AddPaymentActionHandler.java	Fri Jun 03 10:22:43 2016 +0200
@@ -21,6 +21,7 @@
 import java.math.BigDecimal;
 import java.sql.SQLException;
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.Date;
 import java.util.HashMap;
 import java.util.List;
@@ -49,6 +50,7 @@
 import org.openbravo.dal.service.OBCriteria;
 import org.openbravo.dal.service.OBDal;
 import org.openbravo.dal.service.OBDao;
+import org.openbravo.dal.service.OBQuery;
 import org.openbravo.database.ConnectionProvider;
 import org.openbravo.erpCommon.utility.OBDateUtils;
 import org.openbravo.erpCommon.utility.OBError;
@@ -291,11 +293,16 @@
       strPaymentDocumentNo = FIN_Utility.getDocumentNo(documentType, "FIN_Payment");
     }
 
-    FIN_Payment payment = (new AdvPaymentMngtDao()).getNewPayment(isReceipt, org, documentType,
-        strPaymentDocumentNo, bPartner, paymentMethod, finAccount, strPaymentAmount, paymentDate,
-        strReferenceNo, currency, conversionRate, convertedAmt);
-    OBDal.getInstance().getConnection(true).commit();
-    return payment;
+    OBContext.setAdminMode(false);
+    try {
+      FIN_Payment payment = (new AdvPaymentMngtDao()).getNewPayment(isReceipt, org, documentType,
+          strPaymentDocumentNo, bPartner, paymentMethod, finAccount, strPaymentAmount, paymentDate,
+          strReferenceNo, currency, conversionRate, convertedAmt);
+      OBDal.getInstance().getConnection(true).commit();
+      return payment;
+    } finally {
+      OBContext.restorePreviousMode();
+    }
   }
 
   private void addSelectedPSDs(FIN_Payment payment, JSONObject jsonparams, List<String> pdToRemove)
@@ -310,7 +317,7 @@
 
       boolean isWriteOff = psdRow.getBoolean("writeoff");
       // psdIds can be grouped
-      String[] psdIds = strPSDIds.replaceAll(" ", "").split(",");
+      List<String> psdIds = Arrays.asList(strPSDIds.replaceAll(" ", "").split(","));
       List<FIN_PaymentScheduleDetail> psds = getOrderedPaymentScheduleDetails(psdIds);
       BigDecimal outstandingAmount = BigDecimal.ZERO;
       BigDecimal remainingAmount = paidAmount;
@@ -332,8 +339,7 @@
         }
         // Manage negative amounts
         if ((remainingAmount.signum() > 0 && remainingAmount.compareTo(outstandingAmount) >= 0)
-            || ((remainingAmount.signum() < 0 && outstandingAmount.signum() < 0) && (remainingAmount
-                .compareTo(outstandingAmount) >= 0))) {
+            || (remainingAmount.signum() < 0 && remainingAmount.compareTo(outstandingAmount) <= 0)) {
           assignAmount = outstandingAmount;
           remainingAmount = remainingAmount.subtract(outstandingAmount);
         } else {
@@ -611,12 +617,15 @@
     return message;
   }
 
-  private List<FIN_PaymentScheduleDetail> getOrderedPaymentScheduleDetails(String[] psdSet) {
-    OBCriteria<FIN_PaymentScheduleDetail> orderedPSDs = OBDal.getInstance().createCriteria(
-        FIN_PaymentScheduleDetail.class);
-    orderedPSDs.add(Restrictions.in(FIN_PaymentScheduleDetail.PROPERTY_ID, psdSet));
-    orderedPSDs.addOrderBy(FIN_PaymentScheduleDetail.PROPERTY_PAYMENTDETAILS, true);
-    orderedPSDs.addOrderBy(FIN_PaymentScheduleDetail.PROPERTY_AMOUNT, true);
+  private List<FIN_PaymentScheduleDetail> getOrderedPaymentScheduleDetails(List<String> psdSet) {
+    StringBuffer where = new StringBuffer();
+    where.append(" as psd");
+    where.append(" where psd." + FIN_PaymentScheduleDetail.PROPERTY_ID + " in (:psdSet)");
+    where.append(" order by psd." + FIN_PaymentScheduleDetail.PROPERTY_PAYMENTDETAILS);
+    where.append(", abs(psd." + FIN_PaymentScheduleDetail.PROPERTY_AMOUNT + ")");
+    OBQuery<FIN_PaymentScheduleDetail> orderedPSDs = OBDal.getInstance().createQuery(
+        FIN_PaymentScheduleDetail.class, where.toString());
+    orderedPSDs.setNamedParameter("psdSet", psdSet);
     return orderedPSDs.list();
   }
 
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/ad_actionbutton/MatchTransaction.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/ad_actionbutton/MatchTransaction.java	Fri Jun 03 10:22:43 2016 +0200
@@ -361,8 +361,7 @@
     return ((FIN_ReconciliationLine_v) obc.uniqueResult()).getTransactionDate();
   }
 
-  @SuppressWarnings("unused")
-  private void printPage(HttpServletResponse response, VariablesSecureApp vars, String strOrgId,
+  private void printPage(HttpServletResponse response, VariablesSecureApp variables, String strOrgId,
       String strWindowId, String strTabId, String strPaymentTypeFilter,
       String strFinancialAccountId, String reconciliationId, String strShowCleared,
       String strHideDate) throws IOException, ServletException {
@@ -373,8 +372,8 @@
         "org/openbravo/advpaymentmngt/ad_actionbutton/MatchTransaction").createXmlDocument();
 
     xmlDocument.setParameter("directory", "var baseDirectory = \"" + strReplaceWith + "/\";\n");
-    xmlDocument.setParameter("language", "defaultLang=\"" + vars.getLanguage() + "\";");
-    xmlDocument.setParameter("theme", vars.getTheme());
+    xmlDocument.setParameter("language", "defaultLang=\"" + variables.getLanguage() + "\";");
+    xmlDocument.setParameter("theme", variables.getTheme());
     final String MATCHED_AGAINST_TRANSACTION = FIN_Utility.messageBD("APRM_Transaction");
     final String CONFIRMATION_MESSAGE = FIN_Utility.messageBD("APRM_AlgorithmConfirm");
 
@@ -404,7 +403,7 @@
     xmlDocument.setParameter("paramPaymentTypeFilter", strPaymentTypeFilter);
     xmlDocument.setParameter("showCleared", strShowCleared);
     xmlDocument.setParameter("hideDate", strHideDate);
-    xmlDocument.setParameter("jsDateFormat", "var sc_JsDateFormat =\"" + vars.getJsDateFormat()
+    xmlDocument.setParameter("jsDateFormat", "var sc_JsDateFormat =\"" + variables.getJsDateFormat()
         + "\";");
     // Check if There is a matching algorithm for the given financial account
     FIN_FinancialAccount financial = OBDal.getInstance().get(FIN_FinancialAccount.class,
@@ -414,20 +413,20 @@
       new FIN_MatchingTransaction(financial.getMatchingAlgorithm().getJavaClassName());
     } catch (Exception ex) {
       OBDal.getInstance().rollbackAndClose();
-      OBError message = Utility.translateError(this, vars, vars.getLanguage(), Utility
-          .parseTranslation(this, vars, vars.getLanguage(), "@APRM_MissingMatchingAlgorithm@"));
-      vars.setMessage(strTabId, message);
-      printPageClosePopUp(response, vars, Utility.getTabURL(strTabId, "R", true));
+      OBError message = Utility.translateError(this, variables, variables.getLanguage(), Utility
+          .parseTranslation(this, variables, variables.getLanguage(), "@APRM_MissingMatchingAlgorithm@"));
+      variables.setMessage(strTabId, message);
+      printPageClosePopUp(response, variables, Utility.getTabURL(strTabId, "R", true));
       return;
     } finally {
       OBContext.restorePreviousMode();
     }
     try {
-      ComboTableData comboTableData = new ComboTableData(vars, this, "LIST", "",
-          "0CC268ED2E8D4B0397A0DCBBFA2237DE", "", Utility.getContext(this, vars,
-              "#AccessibleOrgTree", "MatchTransaction"), Utility.getContext(this, vars,
+      ComboTableData comboTableData = new ComboTableData(variables, this, "LIST", "",
+          "0CC268ED2E8D4B0397A0DCBBFA2237DE", "", Utility.getContext(this, variables,
+              "#AccessibleOrgTree", "MatchTransaction"), Utility.getContext(this, variables,
               "#User_Client", "MatchTransaction"), 0);
-      Utility.fillSQLParameters(this, vars, null, comboTableData, "MatchTransaction", "");
+      Utility.fillSQLParameters(this, variables, null, comboTableData, "MatchTransaction", "");
       xmlDocument.setData("reportPaymentTypeFilter", "liststructure", comboTableData.select(false));
       comboTableData = null;
     } catch (Exception ex) {
@@ -440,7 +439,7 @@
     out.close();
   }
 
-  private void printGrid(HttpServletResponse response, VariablesSecureApp vars,
+  private void printGrid(HttpServletResponse response, VariablesSecureApp variables,
       String strPaymentTypeFilter, String strFinancialAccountId, String strReconciliationId,
       String strShowCleared, String strHideDate, String showJSMessage, boolean executeMatching)
       throws IOException, ServletException {
@@ -453,7 +452,7 @@
     try {
       OBContext.setAdminMode(true);
       // long init = System.currentTimeMillis();
-      data = getMatchedBankStatementLinesData(vars, strFinancialAccountId, strReconciliationId,
+      data = getMatchedBankStatementLinesData(variables, strFinancialAccountId, strReconciliationId,
           strPaymentTypeFilter, strShowCleared, strHideDate, executeMatching);
       // log4j.error("Getting Grid Data: " + (System.currentTimeMillis() - init));
     } catch (Exception e) {
@@ -505,7 +504,7 @@
     }
   }
 
-  private FieldProvider[] getMatchedBankStatementLinesData(VariablesSecureApp vars,
+  private FieldProvider[] getMatchedBankStatementLinesData(VariablesSecureApp variables,
       String strFinancialAccountId, String strReconciliationId, String strPaymentTypeFilter,
       String strShowCleared, String strHideDate, boolean executeMatching) throws ServletException {
     FIN_FinancialAccount financial = new AdvPaymentMngtDao().getObject(FIN_FinancialAccount.class,
@@ -536,7 +535,6 @@
         final String COLOR_STRONG = "#66CC00";
         final String COLOR_WEAK = "#99CC66";
         final String COLOR_WHITE = "white";
-        boolean alreadyMatched = false;
 
         FIN_BankStatementLine line = OBDal.getInstance().get(FIN_BankStatementLine.class,
             FIN_BankStatementLines[i].getId());
@@ -548,7 +546,6 @@
           if (executeMatching) {
             // try to match if exception is thrown continue
             try {
-              long initMatchLine = System.currentTimeMillis();
               matched = matchingTransaction.match(line, excluded);
               // initMatch = initMatch + (System.currentTimeMillis() - initMatchLine);
               OBDal.getInstance().getConnection().commit();
@@ -584,8 +581,6 @@
           }
           matchingType = matched.getMatchLevel();
 
-        } else {
-          alreadyMatched = true;
         }
 
         FieldProviderFactory.setField(data[i], "rownum", Integer.toString(i + 1));
@@ -595,7 +590,7 @@
             data[i],
             "bankLineTransactionDate",
             Utility.formatDate(FIN_BankStatementLines[i].getTransactionDate(),
-                vars.getJavaDateFormat()));
+                variables.getJavaDateFormat()));
         FieldProviderFactory.setField(
             data[i],
             "bankLineBusinessPartner",
@@ -636,7 +631,7 @@
                   "transactionDate",
                   Utility.formatDate(
                       transaction.getTransactionDate().compareTo(reconciliation.getEndingDate()) > 0 ? reconciliation
-                          .getEndingDate() : transaction.getTransactionDate(), vars
+                          .getEndingDate() : transaction.getTransactionDate(), variables
                           .getJavaDateFormat()));
           FieldProviderFactory
               .setField(
@@ -723,7 +718,7 @@
     return result;
   }
 
-  public String checkReconciliationNotProcessed(VariablesSecureApp vars,
+  public String checkReconciliationNotProcessed(VariablesSecureApp variables,
       String strReconciliationId, String strTabId) {
     FIN_Reconciliation reconciliation = MatchTransactionDao.getObject(FIN_Reconciliation.class,
         strReconciliationId);
@@ -731,8 +726,8 @@
     try {
       String text = "Closed or Invalid Reconciliation";
       if (reconciliation != null && !reconciliation.isNewOBObject() && reconciliation.isProcessed()) {
-        OBError menssage = Utility.translateError(this, vars, vars.getLanguage(), text);
-        vars.setMessage(strTabId, menssage);
+        OBError menssage = Utility.translateError(this, variables, variables.getLanguage(), text);
+        variables.setMessage(strTabId, menssage);
         return text;
       }
       return "";
@@ -872,13 +867,14 @@
   }
 
   private void unmatch(FIN_BankStatementLine bsline) {
+    FIN_BankStatementLine localBsline = bsline;
     OBContext.setAdminMode();
     try {
-      bsline = OBDal.getInstance().get(FIN_BankStatementLine.class, bsline.getId());
-      FIN_FinaccTransaction finTrans = bsline.getFinancialAccountTransaction();
+      localBsline = OBDal.getInstance().get(FIN_BankStatementLine.class, localBsline.getId());
+      FIN_FinaccTransaction finTrans = localBsline.getFinancialAccountTransaction();
       if (finTrans == null) {
         String strTransactionId = vars.getStringParameter("inpFinancialTransactionId_"
-            + bsline.getId());
+            + localBsline.getId());
         if (strTransactionId != null && !"".equals(strTransactionId)) {
           finTrans = OBDal.getInstance().get(FIN_FinaccTransaction.class, strTransactionId);
         }
@@ -887,16 +883,16 @@
         finTrans.setReconciliation(null);
         finTrans.setStatus((finTrans.getDepositAmount().subtract(finTrans.getPaymentAmount())
             .signum() == 1) ? "RDNC" : "PWNC");
-        bsline.setFinancialAccountTransaction(null);
+        localBsline.setFinancialAccountTransaction(null);
         OBDal.getInstance().save(finTrans);
         // OBDal.getInstance().flush();
       }
-      bsline.setMatchingtype(null);
-      OBDal.getInstance().save(bsline);
+      localBsline.setMatchingtype(null);
+      OBDal.getInstance().save(localBsline);
       // OBDal.getInstance().flush();
 
       // merge if the bank statement line was split before
-      mergeBankStatementLine(bsline);
+      mergeBankStatementLine(localBsline);
 
       if (finTrans != null) {
         if (finTrans.getFinPayment() != null) {
@@ -915,19 +911,19 @@
         // OBDal.getInstance().flush();
       }
       // Execute un-matching logic defined by algorithm
-      MatchingAlgorithm ma = bsline.getBankStatement().getAccount().getMatchingAlgorithm();
+      MatchingAlgorithm ma = localBsline.getBankStatement().getAccount().getMatchingAlgorithm();
       FIN_MatchingTransaction matchingTransaction = new FIN_MatchingTransaction(
           ma.getJavaClassName());
       matchingTransaction.unmatch(finTrans);
 
       // Do not allow bank statement lines of 0
-      if (bsline.getCramount().compareTo(BigDecimal.ZERO) == 0
-          && bsline.getDramount().compareTo(BigDecimal.ZERO) == 0) {
-        FIN_BankStatement bs = bsline.getBankStatement();
+      if (localBsline.getCramount().compareTo(BigDecimal.ZERO) == 0
+          && localBsline.getDramount().compareTo(BigDecimal.ZERO) == 0) {
+        FIN_BankStatement bs = localBsline.getBankStatement();
         bs.setProcessed(false);
         OBDal.getInstance().save(bs);
         OBDal.getInstance().flush();
-        OBDal.getInstance().remove(bsline);
+        OBDal.getInstance().remove(localBsline);
         OBDal.getInstance().flush();
         bs.setProcessed(true);
         OBDal.getInstance().save(bs);
@@ -1374,6 +1370,7 @@
 
   void matchBankStatementLine(String strFinBankStatementLineId, String strFinancialTransactionId,
       String strReconciliationId, String matchLevel) {
+    String localMatchLevel = matchLevel;
     OBContext.setAdminMode(false);
     try {
       FIN_BankStatementLine bsl = OBDal.getInstance().get(FIN_BankStatementLine.class,
@@ -1388,10 +1385,10 @@
           unmatch(bsl);
         }
         bsl.setFinancialAccountTransaction(transaction);
-        if (matchLevel == null || "".equals(matchLevel)) {
-          matchLevel = FIN_MatchedTransaction.MANUALMATCH;
+        if (localMatchLevel == null || "".equals(localMatchLevel)) {
+          localMatchLevel = FIN_MatchedTransaction.MANUALMATCH;
         }
-        bsl.setMatchingtype(matchLevel);
+        bsl.setMatchingtype(localMatchLevel);
         transaction.setStatus("RPPC");
         transaction.setReconciliation(MatchTransactionDao.getObject(FIN_Reconciliation.class,
             strReconciliationId));
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/dao/AdvPaymentMngtDao.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/dao/AdvPaymentMngtDao.java	Fri Jun 03 10:22:43 2016 +0200
@@ -496,6 +496,8 @@
       FIN_PaymentMethod paymentMethod, FIN_FinancialAccount finAccount, String strPaymentAmount,
       Date paymentDate, String referenceNo, Currency paymentCurrency, BigDecimal finTxnConvertRate,
       BigDecimal finTxnAmount, String paymentId) {
+    BigDecimal localFinTxnConvertRate = finTxnConvertRate;
+    BigDecimal localFinTxnAmount = finTxnAmount;
     final FIN_Payment newPayment = OBProvider.getInstance().get(FIN_Payment.class);
     if (paymentId != null) {
       newPayment.setId(paymentId);
@@ -519,11 +521,11 @@
       newPayment.setCurrency(finAccount.getCurrency());
     }
     newPayment.setReferenceNo(referenceNo);
-    if (finTxnConvertRate == null || finTxnConvertRate.compareTo(BigDecimal.ZERO) <= 0) {
-      finTxnConvertRate = BigDecimal.ONE;
+    if (localFinTxnConvertRate == null || localFinTxnConvertRate.compareTo(BigDecimal.ZERO) <= 0) {
+      localFinTxnConvertRate = BigDecimal.ONE;
     }
-    if (finTxnAmount == null || finTxnAmount.compareTo(BigDecimal.ZERO) == 0) {
-      finTxnAmount = paymentAmount.multiply(finTxnConvertRate);
+    if (localFinTxnAmount == null || localFinTxnAmount.compareTo(BigDecimal.ZERO) == 0) {
+      localFinTxnAmount = paymentAmount.multiply(localFinTxnConvertRate);
     }
     // This code commented due to fix in bug 17829
     // else if (paymentAmount != null && paymentAmount.compareTo(BigDecimal.ZERO) != 0) {
@@ -531,8 +533,8 @@
     // finTxnConvertRate = finTxnAmount.divide(paymentAmount, MathContext.DECIMAL64);
     // }
 
-    newPayment.setFinancialTransactionConvertRate(finTxnConvertRate);
-    newPayment.setFinancialTransactionAmount(finTxnAmount);
+    newPayment.setFinancialTransactionConvertRate(localFinTxnConvertRate);
+    newPayment.setFinancialTransactionAmount(localFinTxnAmount);
 
     OBDal.getInstance().save(newPayment);
 
@@ -578,12 +580,6 @@
       paymentScheduleDetails.add(paymentScheduleDetail);
       newPaymentDetail.setFINPaymentScheduleDetailList(paymentScheduleDetails);
 
-      if (payment.getDocumentType().getDocumentSequence() != null) {
-        FIN_Payment reloadedPayment = OBDal.getInstance().get(FIN_Payment.class, payment.getId());
-        OBContext.getOBContext().addWritableOrganization(
-            reloadedPayment.getDocumentType().getDocumentSequence().getOrganization().getId());
-      }
-
       OBDal.getInstance().save(payment);
       OBDal.getInstance().save(newPaymentDetail);
       OBDal.getInstance().save(paymentScheduleDetail);
@@ -591,11 +587,6 @@
         OBDal.getInstance().flush();
       }
 
-      if (payment.getDocumentType().getDocumentSequence() != null) {
-        OBContext.getOBContext().removeWritableOrganization(
-            payment.getDocumentType().getDocumentSequence().getOrganization().getId());
-      }
-
       return newPaymentDetail;
     } finally {
       OBContext.restorePreviousMode();
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/filterexpression/AddTransactionFilterExpression.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/filterexpression/AddTransactionFilterExpression.java	Fri Jun 03 10:22:43 2016 +0200
@@ -135,9 +135,9 @@
     return getFinancialAccount(_requestMap).getCurrency().getId().toString();
   }
 
-  private FIN_FinancialAccount getFinancialAccount(Map<String, String> requestMap)
+  private FIN_FinancialAccount getFinancialAccount(Map<String, String> reqstMap)
       throws JSONException {
-    JSONObject context = new JSONObject(requestMap.get("context"));
+    JSONObject context = new JSONObject(reqstMap.get("context"));
     if (context.has("inpfinFinancialAccountId") && !context.isNull("inpfinFinancialAccountId")
         && !"".equals(context.getString("inpfinFinancialAccountId"))) {
       return OBDal.getInstance().get(FIN_FinancialAccount.class,
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/filterexpression/TransactionAddPaymentDefaultValues.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/filterexpression/TransactionAddPaymentDefaultValues.java	Fri Jun 03 10:22:43 2016 +0200
@@ -69,12 +69,13 @@
   }
 
   private String convertToSafeDecimalString(String bigdecimalString) {
-    bigdecimalString = bigdecimalString.replaceAll("[^\\d,\\.]++", "");
-    if (bigdecimalString.matches(".+\\.\\d+,\\d+$"))
-      return bigdecimalString.replaceAll("\\.", "").replaceAll(",", ".");
-    if (bigdecimalString.matches(".+,\\d+\\.\\d+$"))
-      return bigdecimalString.replaceAll(",", "");
-    return bigdecimalString.replaceAll(",", ".");
+    String localBigdecimalString = bigdecimalString;
+    localBigdecimalString = localBigdecimalString.replaceAll("[^\\d,\\.]++", "");
+    if (localBigdecimalString.matches(".+\\.\\d+,\\d+$"))
+      return localBigdecimalString.replaceAll("\\.", "").replaceAll(",", ".");
+    if (localBigdecimalString.matches(".+,\\d+\\.\\d+$"))
+      return localBigdecimalString.replaceAll(",", "");
+    return localBigdecimalString.replaceAll(",", ".");
   }
 
   @Override
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/filterexpression/TransactionAddPaymentDisplayLogics.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/filterexpression/TransactionAddPaymentDisplayLogics.java	Fri Jun 03 10:22:43 2016 +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) 2014-2015 Openbravo SLU
+ * All portions are Copyright (C) 2014-2016 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -30,7 +30,6 @@
 import org.openbravo.model.common.businesspartner.BusinessPartner;
 import org.openbravo.model.common.currency.Currency;
 import org.openbravo.model.common.enterprise.Organization;
-import org.openbravo.model.financialmgmt.payment.FIN_FinaccTransaction;
 
 @ComponentProvider.Qualifier(APRMConstants.TRANSACTION_WINDOW_ID)
 public class TransactionAddPaymentDisplayLogics extends AddPaymentDisplayLogicsHandler {
@@ -80,21 +79,6 @@
     }
   }
 
-  private FIN_FinaccTransaction getTransaction(Map<String, String> requestMap) throws JSONException {
-    // Current Payment
-    JSONObject context = new JSONObject(requestMap.get("context"));
-    String strFinFinaccTransactionIdd = "";
-    if (context.has("inpfinFinaccTransactionId") && !context.isNull("inpfinFinaccTransactionId")) {
-      strFinFinaccTransactionIdd = context.getString("inpfinFinaccTransactionId");
-    }
-    if (context.has("Fin_Finacc_Transaction_ID") && !context.isNull("Fin_Finacc_Transaction_ID")) {
-      strFinFinaccTransactionIdd = context.getString("Fin_Finacc_Transaction_ID");
-    }
-    FIN_FinaccTransaction transaction = OBDal.getInstance().get(FIN_FinaccTransaction.class,
-        strFinFinaccTransactionIdd);
-    return transaction;
-  }
-
   BigDecimal getDefaultGeneratedCredit(Map<String, String> requestMap) throws JSONException {
     return BigDecimal.ZERO;
   }
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/utility/FIN_BankStatementImport.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/utility/FIN_BankStatementImport.java	Fri Jun 03 10:22:43 2016 +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) 2010-2015 Openbravo SLU
+ * All portions are Copyright (C) 2010-2016 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  *************************************************************************
@@ -502,10 +502,8 @@
       return targetBusinessPartnerId;
     } catch (Exception e) {
       log4j.error(e.getStackTrace());
-    } finally {
       return targetBusinessPartnerId;
     }
-
   }
 
   private BankFileFormat getBankFileFormat() {
--- a/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/utility/FIN_Utility.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.advpaymentmngt/src/org/openbravo/advpaymentmngt/utility/FIN_Utility.java	Fri Jun 03 10:22:43 2016 +0200
@@ -1585,12 +1585,6 @@
    * any FinAccPaymentMethod related to paymentMethodId FIN_PaymentMethod ordered by default field.
    * FinAccPaymentMethod must have pay in/out active and must be compatible with currencyId Currency
    * if currencyId is not null.
-   * 
-   * @param paymentMethodId
-   * @param financialAccountId
-   * @param issotrx
-   * @param currencyId
-   * @return
    */
   public static FinAccPaymentMethod getFinancialAccountPaymentMethod(String paymentMethodId,
       String financialAccountId, boolean issotrx, String currencyId) {
@@ -1638,10 +1632,6 @@
   /**
    * Appends existing Financial Account Transaction description with either GL Item Description or
    * Payment description in a new line
-   * 
-   * @param description
-   * @param descriptionToAppend
-   * @return returnDescription
    */
 
   public static String getFinAccTransactionDescription(String description,
--- a/modules/org.openbravo.base.weld/src-test/org/openbravo/base/weld/test/WeldBaseTest.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.base.weld/src-test/org/openbravo/base/weld/test/WeldBaseTest.java	Fri Jun 03 10:22:43 2016 +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) 2010-2015 Openbravo SLU
+ * All portions are Copyright (C) 2010-2016 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -57,6 +57,12 @@
   @Deployment
   public static JavaArchive createTestArchive() {
     if (archive == null) {
+
+      // Setting this property to "true" is avoided throwing an error when this class is used with
+      // analytics module. It is a workaround for Weld proxy bug. See issue:
+      // https://issues.openbravo.com/view.php?id=32704
+      System.setProperty("com.sun.jersey.server.impl.cdi.lookupExtensionInBeanManager", "true");
+
       log.info("Creating cdi archive...");
       final String sourcePath = OBPropertiesProvider.getInstance().getOpenbravoProperties()
           .getProperty("source.path");
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/DynamicExpressionParser.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/DynamicExpressionParser.java	Fri Jun 03 10:22:43 2016 +0200
@@ -357,11 +357,11 @@
     List<Field> fields;
     List<AuxiliaryInput> auxIns;
     if (parameterDisplayLogic) {
-      for (Parameter parameter : parameters) {
-        if (token.equalsIgnoreCase(parameter.getDBColumnName())) {
-          parametersInExpression.add(parameter);
+      for (Parameter param : parameters) {
+        if (token.equalsIgnoreCase(param.getDBColumnName())) {
+          parametersInExpression.add(param);
           UIDefinition uiDef = UIDefinitionController.getInstance().getUIDefinition(
-              parameter.getReference());
+              param.getReference());
           if (uiDef.getDomainType() instanceof DateDomainType) {
             return new DisplayLogicElement(
                 "OB.Utilities.Date.JSToOB(OB.Utilities.getValue(currentValues,'" + token
@@ -383,17 +383,17 @@
         fields = tab.getADFieldList();
         auxIns = tab.getADAuxiliaryInputList();
       }
-      for (Field field : fields) {
-        if (field.getColumn() == null) {
+      for (Field tabField : fields) {
+        if (tabField.getColumn() == null) {
           continue;
         }
-        if (token.equalsIgnoreCase(field.getColumn().getDBColumnName()) && !tabLevelDisplayLogic) {
-          fieldsInExpression.add(field);
+        if (token.equalsIgnoreCase(tabField.getColumn().getDBColumnName()) && !tabLevelDisplayLogic) {
+          fieldsInExpression.add(tabField);
           final String fieldName = KernelUtils.getInstance()
-              .getPropertyFromColumn(field.getColumn()).getName();
+              .getPropertyFromColumn(tabField.getColumn()).getName();
 
           UIDefinition uiDef = UIDefinitionController.getInstance().getUIDefinition(
-              field.getColumn().getId());
+              tabField.getColumn().getId());
           if (uiDef.getDomainType() instanceof DateDomainType) {
             return new DisplayLogicElement(
                 "OB.Utilities.Date.JSToOB(OB.Utilities.getValue(currentValues,'" + fieldName
@@ -450,8 +450,8 @@
     return aField;
   }
 
-  private Field searchForFieldInTab(Tab tab, String fieldName) {
-    List<Field> fields = tab.getADFieldList();
+  private Field searchForFieldInTab(Tab targetTab, String fieldName) {
+    List<Field> fields = targetTab.getADFieldList();
     for (Field aField : fields) {
       if (aField.getColumn() == null) {
         continue;
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/ParameterUtils.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/ParameterUtils.java	Fri Jun 03 10:22:43 2016 +0200
@@ -188,7 +188,7 @@
    *          the parameter to get the Default Value from
    * @param session
    *          the HttpSession of the request
-   * @param context
+   * @param _context
    *          the JSONObject with the context information of the request.
    * @return the DefaultValue of the Parameter.
    * @throws ScriptException
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/attachment/AttachImplementationManager.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/attachment/AttachImplementationManager.java	Fri Jun 03 10:22:43 2016 +0200
@@ -96,14 +96,10 @@
   /**
    * Method to upload files. This method calls needed handler class
    * 
-   * @param requestParams
-   * 
    * @param strTab
    *          the tab Id where the attachment is done
    * @param strKey
    *          the recordId where the attachment is done
-   * @param strDataType
-   *          the datatype of the document that is attached
    * @param strDocumentOrganization
    *          the organization ID of the record where the attachment is done
    * @param file
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/attachment/AttachmentWindowComponent.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/attachment/AttachmentWindowComponent.java	Fri Jun 03 10:22:43 2016 +0200
@@ -111,9 +111,9 @@
    * Sets the Attachment Method and Tab. Actualizes metadata depending on this tab an attachment
    * method
    * 
-   * @param tab
+   * @param _tab
    *          Tab to set.
-   * @param attMethod
+   * @param _attMethod
    *          Method to set.
    */
   public void initialize(Tab _tab, AttachmentMethod _attMethod) {
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/event/ElementValueEventHandler.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/event/ElementValueEventHandler.java	Fri Jun 03 10:22:43 2016 +0200
@@ -54,7 +54,6 @@
     return entities;
   }
 
-  @SuppressWarnings("unused")
   public void onSave(@Observes EntityNewEvent event) {
     if (!isValidEvent(event)) {
       return;
@@ -96,7 +95,6 @@
     doIt(account);
   }
 
-  @SuppressWarnings("unused")
   private void doIt(ElementValue account) {
     boolean isNumber = true;
     try {
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/event/LocationSettingsHandler.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/event/LocationSettingsHandler.java	Fri Jun 03 10:22:43 2016 +0200
@@ -73,7 +73,6 @@
     }
   }
 
-  @SuppressWarnings("unused")
   private void checkCorrectValues(String numericmask, String datetimeformat, String dateformat) {
     if (numericmask != null) {
       if (checkNumericMask(numericmask)) {
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/window/ApplicationDictionaryCachedStructures.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/window/ApplicationDictionaryCachedStructures.java	Fri Jun 03 10:22:43 2016 +0200
@@ -290,10 +290,10 @@
    * Gets the list of parameters associated to an Attachment Method and a Tab. The list is sorted so
    * the fixed parameters are returned first.
    * 
-   * @param attachMethod
-   *          active attachment method
-   * @param tab
-   *          tab to take metadata
+   * @param strAttMethodId
+   *          active attachment method id
+   * @param strTabId
+   *          tab id to take metadata
    * @return List of parameters by attachment method and tab sorted by Fixed and Sequence Number
    *         where fixed parameters are first.
    */
--- a/modules/org.openbravo.client.application/src/org/openbravo/client/application/window/OBViewFieldHandler.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.client.application/src/org/openbravo/client/application/window/OBViewFieldHandler.java	Fri Jun 03 10:22:43 2016 +0200
@@ -74,7 +74,6 @@
   private Tab tab;
   private List<String> statusBarFields;
 
-  private List<String> windowEntities = null;
   private List<OBViewFieldDefinition> fields;
   private List<String> propertiesInButtonFieldDisplayLogic = new ArrayList<String>();
   private List<String> hiddenPropertiesInDisplayLogic = new ArrayList<String>();
@@ -2254,16 +2253,6 @@
     }
   }
 
-  private List<String> getWindowEntities() {
-    if (windowEntities == null) {
-      windowEntities = new ArrayList<String>();
-      for (Tab localTab : tab.getWindow().getADTabList()) {
-        windowEntities.add(localTab.getTable().getName());
-      }
-    }
-    return windowEntities;
-  }
-
   public List<Field> getIgnoredFields() {
     getFields(); // initializes stuff
     return ignoredFields;
--- a/modules/org.openbravo.client.application/web/org.openbravo.client.application/js/alert-management/ob-alert-manager.js	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.client.application/web/org.openbravo.client.application/js/alert-management/ob-alert-manager.js	Fri Jun 03 10:22:43 2016 +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) 2010-2013 Openbravo SLU
+ * All portions are Copyright (C) 2010-2016 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -80,10 +80,20 @@
       for (i = 0; i < length; i++) {
         OB.AlertManager.listeners[i](rpcResponse, data, rpcRequest);
       }
+      OB.AlertManager.schedule();
+    },
+
+    schedule: function () {
       isc.Timer.setTimeout(OB.AlertManager.call, OB.AlertManager.delay);
     },
 
     call: function () {
+      if (OB.User && OB.User.loggingIn) {
+        // do not perform requests while logging in
+        OB.AlertManager.schedule();
+        return;
+      }
+
       OB.RemoteCallManager.call('org.openbravo.client.application.AlertActionHandler', {}, {
         IsAjaxCall: '1',
         ignoreForSessionTimeout: '1'
--- a/modules/org.openbravo.client.application/web/org.openbravo.client.application/js/navbar/ob-user-profile-widget.js	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.client.application/web/org.openbravo.client.application/js/navbar/ob-user-profile-widget.js	Fri Jun 03 10:22:43 2016 +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) 2010-2015 Openbravo SLU
+ * All portions are Copyright (C) 2010-2016 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -327,6 +327,7 @@
 
       // call the server to save the information
       doSave: function () {
+        OB.User.loggingIn = true;
         OB.RemoteCallManager.call(this.widgetInstance.formActionHandler, this.getValues(), {
           'command': 'save'
         }, this.doSaveCallback);
@@ -334,6 +335,7 @@
 
       // and reload
       doSaveCallback: function (rpcResponse, data, rpcRequest) {
+        delete OB.User.loggingIn;
         // if not success then an error, can not really occur
         // is handled as an exception is returned anyway
         if (data.result === OB.Constants.SUCCESS) {
--- a/modules/org.openbravo.client.htmlwidget/src-db/database/sourcedata/OBKMO_WIDGET_CLASS.xml	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.client.htmlwidget/src-db/database/sourcedata/OBKMO_WIDGET_CLASS.xml	Fri Jun 03 10:22:43 2016 +0200
@@ -13,6 +13,7 @@
 <!--10DE6579FF7A4864AEB31FE957849461-->  <ISSUPERCLASS><![CDATA[Y]]></ISSUPERCLASS>
 <!--10DE6579FF7A4864AEB31FE957849461-->  <CAN_MAXIMIZE><![CDATA[N]]></CAN_MAXIMIZE>
 <!--10DE6579FF7A4864AEB31FE957849461-->  <ACCESSLEVEL><![CDATA[4]]></ACCESSLEVEL>
+<!--10DE6579FF7A4864AEB31FE957849461-->  <AVAILABLE_IN_WORKSPACE><![CDATA[Y]]></AVAILABLE_IN_WORKSPACE>
 <!--10DE6579FF7A4864AEB31FE957849461--></OBKMO_WIDGET_CLASS>
 
 <!--E4C82D04605C4256A74258B770AA8867--><OBKMO_WIDGET_CLASS>
@@ -28,6 +29,7 @@
 <!--E4C82D04605C4256A74258B770AA8867-->  <WIDGET_SUPERCLASS_ID><![CDATA[10DE6579FF7A4864AEB31FE957849461]]></WIDGET_SUPERCLASS_ID>
 <!--E4C82D04605C4256A74258B770AA8867-->  <CAN_MAXIMIZE><![CDATA[N]]></CAN_MAXIMIZE>
 <!--E4C82D04605C4256A74258B770AA8867-->  <ACCESSLEVEL><![CDATA[7]]></ACCESSLEVEL>
+<!--E4C82D04605C4256A74258B770AA8867-->  <AVAILABLE_IN_WORKSPACE><![CDATA[Y]]></AVAILABLE_IN_WORKSPACE>
 <!--E4C82D04605C4256A74258B770AA8867--></OBKMO_WIDGET_CLASS>
 
 </data>
--- a/modules/org.openbravo.client.kernel/jsbeautify/jsbeautify	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.client.kernel/jsbeautify/jsbeautify	Fri Jun 03 10:22:43 2016 +0200
@@ -1,3 +1,4 @@
+#!/bin/bash
 # *************************************************************************
 # * The contents of this file are subject to the Openbravo  Public  License
 # * Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
@@ -14,14 +15,14 @@
 # * All Rights Reserved.
 # * Contributor(s):  ______________________________________.
 # ************************************************************************
-#!/bin/bash
+
 set -e
 # Mercurial pre-commit hook for jsbeautify
 
 changedfile=$1
 replaceparam=$2
-./modules/org.openbravo.client.kernel/jsbeautify/jsbeautifier.py --indent-size=2 --jslint-happy "$changedfile" > "$changedfile.beautified"
-if ! diff -Z "$changedfile" "$changedfile.beautified" >/dev/null ; then
+./modules/org.openbravo.client.kernel/jsbeautify/jsbeautifier.py --indent-size=2 --jslint-happy "$changedfile" | perl -pe 'chop if eof' > "$changedfile.beautified"
+if ! diff "$changedfile" "$changedfile.beautified" >/dev/null ; then
   if [ "$replaceparam" != "replace" ] ; then
     echo "Beautify Error --> Please, beautify $changedfile";
     rm -rf "$changedfile.beautified"
--- a/modules/org.openbravo.client.kernel/jsbeautify/jsbeautify-module	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.client.kernel/jsbeautify/jsbeautify-module	Fri Jun 03 10:22:43 2016 +0200
@@ -1,3 +1,4 @@
+#!/bin/bash
 # *************************************************************************
 # * The contents of this file are subject to the Openbravo  Public  License
 # * Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
@@ -14,14 +15,14 @@
 # * All Rights Reserved.
 # * Contributor(s):  ______________________________________.
 # ************************************************************************
-#!/bin/bash
+
 set -e
 # Mercurial pre-commit hook for jsbeautify
 
 changedfile=$1
 replaceparam=$2
-../org.openbravo.client.kernel/jsbeautify/jsbeautifier.py --indent-size=2 --jslint-happy "$changedfile" > "$changedfile.beautified"
-if ! diff -Z "$changedfile" "$changedfile.beautified" >/dev/null ; then
+../org.openbravo.client.kernel/jsbeautify/jsbeautifier.py --indent-size=2 --jslint-happy "$changedfile" | perl -pe 'chop if eof' > "$changedfile.beautified"
+if ! diff "$changedfile" "$changedfile.beautified" >/dev/null ; then
   if [ "$replaceparam" != "replace" ] ; then
     echo "Beautify Error --> Please, beautify $changedfile";
     rm -rf "$changedfile.beautified"
--- a/modules/org.openbravo.client.kernel/jsbeautify/jscheck-btfy	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.client.kernel/jsbeautify/jscheck-btfy	Fri Jun 03 10:22:43 2016 +0200
@@ -1,3 +1,4 @@
+#!/bin/bash
 # *************************************************************************
 # * The contents of this file are subject to the Openbravo  Public  License
 # * Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
@@ -14,7 +15,7 @@
 # * All Rights Reserved.
 # * Contributor(s):  ______________________________________.
 # ************************************************************************
-#!/bin/bash
+
 set -e
 replaceparam=$1
 if [ "$replaceparam" != "replace" ] ; then
--- a/modules/org.openbravo.client.kernel/jsbeautify/jscheck-btfy-hg	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.client.kernel/jsbeautify/jscheck-btfy-hg	Fri Jun 03 10:22:43 2016 +0200
@@ -1,3 +1,4 @@
+#!/bin/bash
 # *************************************************************************
 # * The contents of this file are subject to the Openbravo  Public  License
 # * Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
@@ -14,7 +15,7 @@
 # * All Rights Reserved.
 # * Contributor(s):  ______________________________________.
 # ************************************************************************
-#!/bin/bash
+
 set -e
 # Mercurial pre-commit hook for jsbeautify
 
--- a/modules/org.openbravo.client.kernel/jsbeautify/jscheck-btfy-module	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.client.kernel/jsbeautify/jscheck-btfy-module	Fri Jun 03 10:22:43 2016 +0200
@@ -1,3 +1,4 @@
+#!/bin/bash
 # *************************************************************************
 # * The contents of this file are subject to the Openbravo  Public  License
 # * Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
@@ -14,7 +15,7 @@
 # * All Rights Reserved.
 # * Contributor(s):  ______________________________________.
 # ************************************************************************
-#!/bin/bash
+
 set -e
 replaceparam=$1
 if [ "$replaceparam" != "replace" ] ; then
@@ -25,7 +26,7 @@
 
 files=$(../org.openbravo.client.kernel/jscheck/jsfiles ./)
 
-for changedfile in echo $(hg st -ma)
+for changedfile in echo $files;
 do
   if [ -f "$changedfile" -a -n "$(echo $changedfile | awk '/.js$/')" ]; then
   source ../org.openbravo.client.kernel/jsbeautify/jsbeautify-module $changedfile $replaceparam
--- a/modules/org.openbravo.client.kernel/jsbeautify/jscheck-btfy-module-hg	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.client.kernel/jsbeautify/jscheck-btfy-module-hg	Fri Jun 03 10:22:43 2016 +0200
@@ -1,3 +1,4 @@
+#!/bin/bash
 # *************************************************************************
 # * The contents of this file are subject to the Openbravo  Public  License
 # * Version  1.1  (the  "License"),  being   the  Mozilla   Public  License
@@ -14,7 +15,7 @@
 # * All Rights Reserved.
 # * Contributor(s):  ______________________________________.
 # ************************************************************************
-#!/bin/bash
+
 set -e
 # Mercurial pre-commit hook for jsbeautify
 replaceparam=$1
--- a/modules/org.openbravo.client.kernel/jscheck/jsfiles	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.client.kernel/jscheck/jsfiles	Fri Jun 03 10:22:43 2016 +0200
@@ -31,4 +31,5 @@
 -and ! -path '*enyo*' \
 -and ! -path '*smartclient*' \
 -and ! -path '*scopeleaks*' \
--and ! -path '*BigDecimal*'
\ No newline at end of file
+-and ! -path '*BigDecimal*' \
+-and ! -path '*AppDynamics*'
--- a/modules/org.openbravo.client.kernel/src-test/org/openbravo/client/kernel/freemarker/test/FreemarkerTemplateProcessorTest.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.client.kernel/src-test/org/openbravo/client/kernel/freemarker/test/FreemarkerTemplateProcessorTest.java	Fri Jun 03 10:22:43 2016 +0200
@@ -23,7 +23,6 @@
 import static org.junit.Assert.fail;
 
 import java.io.File;
-import java.io.FileInputStream;
 import java.net.URL;
 import java.util.Arrays;
 import java.util.Collections;
@@ -33,6 +32,7 @@
 
 import javax.inject.Inject;
 
+import org.apache.commons.io.FileUtils;
 import org.junit.Before;
 import org.junit.Test;
 import org.openbravo.base.model.Entity;
@@ -153,8 +153,8 @@
     template.setModule(getModule());
 
     for (Template dependency : dependencies) {
-      final TemplateDependency templateDependency = OBProvider.getInstance()
-          .get(TemplateDependency.class);
+      final TemplateDependency templateDependency = OBProvider.getInstance().get(
+          TemplateDependency.class);
       templateDependency.setObclkerTemplate(template);
       templateDependency.setDependsOnTemplate(dependency);
       template.getOBCLKERTemplateDependencyList().add(templateDependency);
@@ -166,14 +166,7 @@
   private String readTemplateSource(String fileName) throws Exception {
     final URL url = this.getClass().getResource(fileName + ".ftl");
     final File file = new File(url.toURI());
-    return readFileAsString(file);
-  }
-
-  private static String readFileAsString(File file) throws java.io.IOException {
-    byte[] buffer = new byte[(int) file.length()];
-    FileInputStream f = new FileInputStream(file);
-    f.read(buffer);
-    return new String(buffer);
+    return FileUtils.readFileToString(file);
   }
 
   private Module getModule() {
--- a/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/BaseKernelServlet.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/BaseKernelServlet.java	Fri Jun 03 10:22:43 2016 +0200
@@ -34,7 +34,6 @@
  * 
  * @author mtaal
  */
-@SuppressWarnings("deprecation")
 public abstract class BaseKernelServlet extends HttpSecureAppServlet {
   protected static final String RESPONSE_HEADER_ETAG = "ETag";
   protected static final String RESPONSE_HEADER_LASTMODIFIED = "Last-Modified";
--- a/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/CSSMinimizer.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/CSSMinimizer.java	Fri Jun 03 10:22:43 2016 +0200
@@ -293,8 +293,8 @@
    * @param properties1
    *          The array to be sorted.
    */
-  private void sortProperties(Property[] properties) {
-    Arrays.sort(properties);
+  private void sortProperties(Property[] props) {
+    Arrays.sort(props);
   }
 }
 
@@ -316,7 +316,7 @@
   public Property(String property) throws Exception {
     try {
       // Parse the property.
-      ArrayList<String> parts = new ArrayList<String>();
+      ArrayList<String> partList = new ArrayList<String>();
       boolean bCanSplit = true;
       int j = 0;
       String substr;
@@ -331,19 +331,19 @@
         } else if (property.charAt(i) == ':') {
           substr = property.substring(j, i);
           if (!(substr.trim().equals("") || (substr == null)))
-            parts.add(substr);
+            partList.add(substr);
           j = i + 1;
         }
       }
       substr = property.substring(j, property.length());
       if (!(substr.trim().equals("") || (substr == null)))
-        parts.add(substr);
-      if (parts.size() < 2) {
+        partList.add(substr);
+      if (partList.size() < 2) {
         throw new Exception("\t\tWarning: Incomplete property: " + property);
       }
-      this.property = parts.get(0).trim().toLowerCase();
+      this.property = partList.get(0).trim().toLowerCase();
 
-      this.parts = parseValues(simplifyColours(parts.get(1).trim().replaceAll(", ", ",")));
+      this.parts = parseValues(simplifyColours(partList.get(1).trim().replaceAll(", ", ",")));
 
     } catch (PatternSyntaxException e) {
       // Invalid regular expression used.
@@ -377,7 +377,6 @@
     // prefixes last -- eg, *display should come after display.
     String thisProp = this.property;
     String thatProp = other.property;
-    String[] parts;
 
     if (thisProp.charAt(0) == '-') {
       thisProp = thisProp.substring(1);
@@ -404,12 +403,12 @@
    * @returns An array of Parts
    */
   private Part[] parseValues(String contents) {
-    String[] parts = contents.split(",");
-    Part[] results = new Part[parts.length];
+    String[] propertyParts = contents.split(",");
+    Part[] results = new Part[propertyParts.length];
 
-    for (int i = 0; i < parts.length; i++) {
+    for (int i = 0; i < propertyParts.length; i++) {
       try {
-        results[i] = new Part(parts[i], property);
+        results[i] = new Part(propertyParts[i], property);
       } catch (Exception e) {
         log.error(e.getMessage(), e);
         results[i] = null;
@@ -626,12 +625,15 @@
   }
 }
 
+@SuppressWarnings("serial")
 class UnterminatedCommentException extends Exception {
 }
 
+@SuppressWarnings("serial")
 class UnbalancedBracesException extends Exception {
 }
 
+@SuppressWarnings("serial")
 class IncompletePropertyException extends Exception {
   String message = null;
 
@@ -644,6 +646,7 @@
   }
 }
 
+@SuppressWarnings("serial")
 class EmptySelectorBodyException extends Exception {
   String message = null;
 
@@ -656,6 +659,7 @@
   }
 }
 
+@SuppressWarnings("serial")
 class UnterminatedSelectorException extends Exception {
   String message = null;
 
@@ -668,6 +672,7 @@
   }
 }
 
+@SuppressWarnings("serial")
 class IncompleteSelectorException extends Exception {
   String message = null;
 
--- a/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/KernelServlet.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/KernelServlet.java	Fri Jun 03 10:22:43 2016 +0200
@@ -66,7 +66,7 @@
   private static String servletPathPart = "org.openbravo.client.kernel";
 
   // are used to compute the relative path
-  private static ConfigParameters globalParameters;
+  private static ConfigParameters kernelServletglobalParameters;
 
   private static ServletContext servletContext;
 
@@ -74,7 +74,7 @@
    * @return the parameters as they are defined in the servlet context.
    */
   public static ConfigParameters getGlobalParameters() {
-    return globalParameters;
+    return kernelServletglobalParameters;
   }
 
   public static String getServletPathPart() {
@@ -146,7 +146,7 @@
 
   public void init(ServletConfig config) {
     super.init(config);
-    globalParameters = ConfigParameters.retrieveFrom(config.getServletContext());
+    kernelServletglobalParameters = ConfigParameters.retrieveFrom(config.getServletContext());
     servletContext = config.getServletContext();
   }
 
--- a/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/RequestContext.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/RequestContext.java	Fri Jun 03 10:22:43 2016 +0200
@@ -49,7 +49,6 @@
  * 
  * @author mtaal
  */
-@SuppressWarnings("deprecation")
 public class RequestContext {
   private static ServletContext servletContext = null;
 
--- a/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/freemarker/FreemarkerTemplateProcessor.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/freemarker/FreemarkerTemplateProcessor.java	Fri Jun 03 10:22:43 2016 +0200
@@ -93,7 +93,6 @@
    * @see
    * org.openbravo.client.kernel.TemplateProcessor#validate(org.openbravo.client.kernel.Template)
    */
-  @SuppressWarnings("unused")
   public void validate(Template template) throws ValidationException {
     try {
       final String source = createTemplateSource(template);
--- a/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/templates/application-js.ftl	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.client.kernel/src/org/openbravo/client/kernel/templates/application-js.ftl	Fri Jun 03 10:22:43 2016 +0200
@@ -68,12 +68,14 @@
         FILTER_PARAMETER : '_filter',
         SQL_FILTER_PARAMETER : '_sqlFilter',
         SORTBY_PARAMETER : '_sortBy',
-        OR_EXPRESSION: '_OrExpression',
-        TEXT_MATCH_PARAMETER_OVERRIDE: '_textMatchStyleOverride',
+        OR_EXPRESSION : '_OrExpression',
+        TEXT_MATCH_PARAMETER_OVERRIDE : '_textMatchStyleOverride',
         SUCCESS : 'success',
-        DBL_CLICK_DELAY: 300,
+        DBL_CLICK_DELAY : 300,
         ERROR : 'error',
-        IS_PICK_AND_EDIT : '_isPickAndEdit'
+        IS_PICK_AND_EDIT : '_isPickAndEdit',
+        SELECTED_PROPERTIES : '_selectedProperties',
+        EXTRA_PROPERTIES : '_extraProperties'
     },
 
     Styles : {
--- a/modules/org.openbravo.client.myob/src-db/database/model/tables/OBKMO_WIDGET_CLASS.xml	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.client.myob/src-db/database/model/tables/OBKMO_WIDGET_CLASS.xml	Fri Jun 03 10:22:43 2016 +0200
@@ -81,6 +81,10 @@
         <default/>
         <onCreateDefault/>
       </column>
+      <column name="AVAILABLE_IN_WORKSPACE" primaryKey="false" required="true" type="CHAR" size="1" autoIncrement="false">
+        <default><![CDATA[Y]]></default>
+        <onCreateDefault><![CDATA['Y']]></onCreateDefault>
+      </column>
       <foreign-key foreignTable="AD_CLIENT" name="OBKMO_WIDGET_CLIENT">
         <reference local="AD_CLIENT_ID" foreign="AD_CLIENT_ID"/>
       </foreign-key>
--- a/modules/org.openbravo.client.myob/src-db/database/sourcedata/AD_COLUMN.xml	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.client.myob/src-db/database/sourcedata/AD_COLUMN.xml	Fri Jun 03 10:22:43 2016 +0200
@@ -621,6 +621,43 @@
 <!--75B803688DF94160B79E92FABFD7033B-->  <ALLOWED_CROSS_ORG_LINK><![CDATA[N]]></ALLOWED_CROSS_ORG_LINK>
 <!--75B803688DF94160B79E92FABFD7033B--></AD_COLUMN>
 
+<!--7D1559318B3140508C83E893EF404710--><AD_COLUMN>
+<!--7D1559318B3140508C83E893EF404710-->  <AD_COLUMN_ID><![CDATA[7D1559318B3140508C83E893EF404710]]></AD_COLUMN_ID>
+<!--7D1559318B3140508C83E893EF404710-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
+<!--7D1559318B3140508C83E893EF404710-->  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
+<!--7D1559318B3140508C83E893EF404710-->  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+<!--7D1559318B3140508C83E893EF404710-->  <NAME><![CDATA[Available_In_Workspace]]></NAME>
+<!--7D1559318B3140508C83E893EF404710-->  <COLUMNNAME><![CDATA[Available_In_Workspace]]></COLUMNNAME>
+<!--7D1559318B3140508C83E893EF404710-->  <AD_TABLE_ID><![CDATA[5F20F3D554CA408891C1BA6545114D4D]]></AD_TABLE_ID>
+<!--7D1559318B3140508C83E893EF404710-->  <AD_REFERENCE_ID><![CDATA[20]]></AD_REFERENCE_ID>
+<!--7D1559318B3140508C83E893EF404710-->  <FIELDLENGTH><![CDATA[1]]></FIELDLENGTH>
+<!--7D1559318B3140508C83E893EF404710-->  <DEFAULTVALUE><![CDATA[Y]]></DEFAULTVALUE>
+<!--7D1559318B3140508C83E893EF404710-->  <ISKEY><![CDATA[N]]></ISKEY>
+<!--7D1559318B3140508C83E893EF404710-->  <ISPARENT><![CDATA[N]]></ISPARENT>
+<!--7D1559318B3140508C83E893EF404710-->  <ISMANDATORY><![CDATA[Y]]></ISMANDATORY>
+<!--7D1559318B3140508C83E893EF404710-->  <ISUPDATEABLE><![CDATA[Y]]></ISUPDATEABLE>
+<!--7D1559318B3140508C83E893EF404710-->  <ISIDENTIFIER><![CDATA[N]]></ISIDENTIFIER>
+<!--7D1559318B3140508C83E893EF404710-->  <SEQNO><![CDATA[220]]></SEQNO>
+<!--7D1559318B3140508C83E893EF404710-->  <ISTRANSLATED><![CDATA[N]]></ISTRANSLATED>
+<!--7D1559318B3140508C83E893EF404710-->  <ISENCRYPTED><![CDATA[N]]></ISENCRYPTED>
+<!--7D1559318B3140508C83E893EF404710-->  <ISSELECTIONCOLUMN><![CDATA[N]]></ISSELECTIONCOLUMN>
+<!--7D1559318B3140508C83E893EF404710-->  <AD_ELEMENT_ID><![CDATA[8E2D37834C60447698936C888B390F9E]]></AD_ELEMENT_ID>
+<!--7D1559318B3140508C83E893EF404710-->  <ISSESSIONATTR><![CDATA[N]]></ISSESSIONATTR>
+<!--7D1559318B3140508C83E893EF404710-->  <ISSECONDARYKEY><![CDATA[N]]></ISSECONDARYKEY>
+<!--7D1559318B3140508C83E893EF404710-->  <ISDESENCRYPTABLE><![CDATA[N]]></ISDESENCRYPTABLE>
+<!--7D1559318B3140508C83E893EF404710-->  <DEVELOPMENTSTATUS><![CDATA[RE]]></DEVELOPMENTSTATUS>
+<!--7D1559318B3140508C83E893EF404710-->  <AD_MODULE_ID><![CDATA[2758CD25B2704AF6BBAD10365FC82C06]]></AD_MODULE_ID>
+<!--7D1559318B3140508C83E893EF404710-->  <POSITION><![CDATA[23]]></POSITION>
+<!--7D1559318B3140508C83E893EF404710-->  <ISTRANSIENT><![CDATA[N]]></ISTRANSIENT>
+<!--7D1559318B3140508C83E893EF404710-->  <ISAUTOSAVE><![CDATA[Y]]></ISAUTOSAVE>
+<!--7D1559318B3140508C83E893EF404710-->  <VALIDATEONNEW><![CDATA[Y]]></VALIDATEONNEW>
+<!--7D1559318B3140508C83E893EF404710-->  <IMAGESIZEVALUESACTION><![CDATA[N]]></IMAGESIZEVALUESACTION>
+<!--7D1559318B3140508C83E893EF404710-->  <ISUSEDSEQUENCE><![CDATA[N]]></ISUSEDSEQUENCE>
+<!--7D1559318B3140508C83E893EF404710-->  <ALLOWSORTING><![CDATA[Y]]></ALLOWSORTING>
+<!--7D1559318B3140508C83E893EF404710-->  <ALLOWFILTERING><![CDATA[Y]]></ALLOWFILTERING>
+<!--7D1559318B3140508C83E893EF404710-->  <ALLOWED_CROSS_ORG_LINK><![CDATA[N]]></ALLOWED_CROSS_ORG_LINK>
+<!--7D1559318B3140508C83E893EF404710--></AD_COLUMN>
+
 <!--7E8BDEF054974AB6BD23A8865636DAB4--><AD_COLUMN>
 <!--7E8BDEF054974AB6BD23A8865636DAB4-->  <AD_COLUMN_ID><![CDATA[7E8BDEF054974AB6BD23A8865636DAB4]]></AD_COLUMN_ID>
 <!--7E8BDEF054974AB6BD23A8865636DAB4-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
--- a/modules/org.openbravo.client.myob/src-db/database/sourcedata/AD_ELEMENT.xml	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.client.myob/src-db/database/sourcedata/AD_ELEMENT.xml	Fri Jun 03 10:22:43 2016 +0200
@@ -82,6 +82,18 @@
 <!--57DD9A05462444B1A7977E7F9A94DF8A-->  <ISGLOSSARY><![CDATA[N]]></ISGLOSSARY>
 <!--57DD9A05462444B1A7977E7F9A94DF8A--></AD_ELEMENT>
 
+<!--8E2D37834C60447698936C888B390F9E--><AD_ELEMENT>
+<!--8E2D37834C60447698936C888B390F9E-->  <AD_ELEMENT_ID><![CDATA[8E2D37834C60447698936C888B390F9E]]></AD_ELEMENT_ID>
+<!--8E2D37834C60447698936C888B390F9E-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
+<!--8E2D37834C60447698936C888B390F9E-->  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
+<!--8E2D37834C60447698936C888B390F9E-->  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+<!--8E2D37834C60447698936C888B390F9E-->  <COLUMNNAME><![CDATA[Available_In_Workspace]]></COLUMNNAME>
+<!--8E2D37834C60447698936C888B390F9E-->  <NAME><![CDATA[Available_In_Workspace]]></NAME>
+<!--8E2D37834C60447698936C888B390F9E-->  <PRINTNAME><![CDATA[Available_In_Workspace]]></PRINTNAME>
+<!--8E2D37834C60447698936C888B390F9E-->  <AD_MODULE_ID><![CDATA[2758CD25B2704AF6BBAD10365FC82C06]]></AD_MODULE_ID>
+<!--8E2D37834C60447698936C888B390F9E-->  <ISGLOSSARY><![CDATA[N]]></ISGLOSSARY>
+<!--8E2D37834C60447698936C888B390F9E--></AD_ELEMENT>
+
 <!--927D0D118B8EEF36E040A8C0CF071CF5--><AD_ELEMENT>
 <!--927D0D118B8EEF36E040A8C0CF071CF5-->  <AD_ELEMENT_ID><![CDATA[927D0D118B8EEF36E040A8C0CF071CF5]]></AD_ELEMENT_ID>
 <!--927D0D118B8EEF36E040A8C0CF071CF5-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
--- a/modules/org.openbravo.client.myob/src-db/database/sourcedata/AD_FIELD.xml	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.client.myob/src-db/database/sourcedata/AD_FIELD.xml	Fri Jun 03 10:22:43 2016 +0200
@@ -144,6 +144,32 @@
 <!--31363A02FD05444DA8D0493110566806-->  <EM_OBUIAPP_SHOWSUMMARY><![CDATA[N]]></EM_OBUIAPP_SHOWSUMMARY>
 <!--31363A02FD05444DA8D0493110566806--></AD_FIELD>
 
+<!--5E2FBB96AE394B12938889ACBF585D89--><AD_FIELD>
+<!--5E2FBB96AE394B12938889ACBF585D89-->  <AD_FIELD_ID><![CDATA[5E2FBB96AE394B12938889ACBF585D89]]></AD_FIELD_ID>
+<!--5E2FBB96AE394B12938889ACBF585D89-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
+<!--5E2FBB96AE394B12938889ACBF585D89-->  <AD_ORG_ID><![CDATA[0]]></AD_ORG_ID>
+<!--5E2FBB96AE394B12938889ACBF585D89-->  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
+<!--5E2FBB96AE394B12938889ACBF585D89-->  <NAME><![CDATA[Available_In_Workspace]]></NAME>
+<!--5E2FBB96AE394B12938889ACBF585D89-->  <ISCENTRALLYMAINTAINED><![CDATA[Y]]></ISCENTRALLYMAINTAINED>
+<!--5E2FBB96AE394B12938889ACBF585D89-->  <AD_TAB_ID><![CDATA[EA867498578C4E98A4935A53A3A5F6AE]]></AD_TAB_ID>
+<!--5E2FBB96AE394B12938889ACBF585D89-->  <AD_COLUMN_ID><![CDATA[7D1559318B3140508C83E893EF404710]]></AD_COLUMN_ID>
+<!--5E2FBB96AE394B12938889ACBF585D89-->  <IGNOREINWAD><![CDATA[N]]></IGNOREINWAD>
+<!--5E2FBB96AE394B12938889ACBF585D89-->  <ISDISPLAYED><![CDATA[Y]]></ISDISPLAYED>
+<!--5E2FBB96AE394B12938889ACBF585D89-->  <DISPLAYLENGTH><![CDATA[1]]></DISPLAYLENGTH>
+<!--5E2FBB96AE394B12938889ACBF585D89-->  <ISREADONLY><![CDATA[N]]></ISREADONLY>
+<!--5E2FBB96AE394B12938889ACBF585D89-->  <SEQNO><![CDATA[140]]></SEQNO>
+<!--5E2FBB96AE394B12938889ACBF585D89-->  <ISSAMELINE><![CDATA[N]]></ISSAMELINE>
+<!--5E2FBB96AE394B12938889ACBF585D89-->  <ISFIELDONLY><![CDATA[N]]></ISFIELDONLY>
+<!--5E2FBB96AE394B12938889ACBF585D89-->  <ISENCRYPTED><![CDATA[N]]></ISENCRYPTED>
+<!--5E2FBB96AE394B12938889ACBF585D89-->  <SHOWINRELATION><![CDATA[N]]></SHOWINRELATION>
+<!--5E2FBB96AE394B12938889ACBF585D89-->  <ISFIRSTFOCUSEDFIELD><![CDATA[N]]></ISFIRSTFOCUSEDFIELD>
+<!--5E2FBB96AE394B12938889ACBF585D89-->  <AD_MODULE_ID><![CDATA[2758CD25B2704AF6BBAD10365FC82C06]]></AD_MODULE_ID>
+<!--5E2FBB96AE394B12938889ACBF585D89-->  <STARTINODDCOLUMN><![CDATA[N]]></STARTINODDCOLUMN>
+<!--5E2FBB96AE394B12938889ACBF585D89-->  <STARTNEWLINE><![CDATA[N]]></STARTNEWLINE>
+<!--5E2FBB96AE394B12938889ACBF585D89-->  <ISSHOWNINSTATUSBAR><![CDATA[N]]></ISSHOWNINSTATUSBAR>
+<!--5E2FBB96AE394B12938889ACBF585D89-->  <EM_OBUIAPP_SHOWSUMMARY><![CDATA[N]]></EM_OBUIAPP_SHOWSUMMARY>
+<!--5E2FBB96AE394B12938889ACBF585D89--></AD_FIELD>
+
 <!--6878AFF0F77A47F8B9702E6F1EF95FE3--><AD_FIELD>
 <!--6878AFF0F77A47F8B9702E6F1EF95FE3-->  <AD_FIELD_ID><![CDATA[6878AFF0F77A47F8B9702E6F1EF95FE3]]></AD_FIELD_ID>
 <!--6878AFF0F77A47F8B9702E6F1EF95FE3-->  <AD_CLIENT_ID><![CDATA[0]]></AD_CLIENT_ID>
--- a/modules/org.openbravo.client.myob/src-db/database/sourcedata/OBKMO_WIDGET_CLASS.xml	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.client.myob/src-db/database/sourcedata/OBKMO_WIDGET_CLASS.xml	Fri Jun 03 10:22:43 2016 +0200
@@ -14,6 +14,7 @@
 <!--479BC7D918D84F948F4C2BDA402D0AA3-->  <WIDGET_SUPERCLASS_ID><![CDATA[C26A68FD8CF347EC9D1FB7E274622450]]></WIDGET_SUPERCLASS_ID>
 <!--479BC7D918D84F948F4C2BDA402D0AA3-->  <CAN_MAXIMIZE><![CDATA[Y]]></CAN_MAXIMIZE>
 <!--479BC7D918D84F948F4C2BDA402D0AA3-->  <ACCESSLEVEL><![CDATA[3]]></ACCESSLEVEL>
+<!--479BC7D918D84F948F4C2BDA402D0AA3-->  <AVAILABLE_IN_WORKSPACE><![CDATA[Y]]></AVAILABLE_IN_WORKSPACE>
 <!--479BC7D918D84F948F4C2BDA402D0AA3--></OBKMO_WIDGET_CLASS>
 
 <!--50F3F7AED43A4B31AF176F1AF0714284--><OBKMO_WIDGET_CLASS>
@@ -30,6 +31,7 @@
 <!--50F3F7AED43A4B31AF176F1AF0714284-->  <ISSUPERCLASS><![CDATA[N]]></ISSUPERCLASS>
 <!--50F3F7AED43A4B31AF176F1AF0714284-->  <CAN_MAXIMIZE><![CDATA[N]]></CAN_MAXIMIZE>
 <!--50F3F7AED43A4B31AF176F1AF0714284-->  <ACCESSLEVEL><![CDATA[3]]></ACCESSLEVEL>
+<!--50F3F7AED43A4B31AF176F1AF0714284-->  <AVAILABLE_IN_WORKSPACE><![CDATA[Y]]></AVAILABLE_IN_WORKSPACE>
 <!--50F3F7AED43A4B31AF176F1AF0714284--></OBKMO_WIDGET_CLASS>
 
 <!--C26A68FD8CF347EC9D1FB7E274622450--><OBKMO_WIDGET_CLASS>
@@ -45,6 +47,7 @@
 <!--C26A68FD8CF347EC9D1FB7E274622450-->  <ISSUPERCLASS><![CDATA[Y]]></ISSUPERCLASS>
 <!--C26A68FD8CF347EC9D1FB7E274622450-->  <CAN_MAXIMIZE><![CDATA[N]]></CAN_MAXIMIZE>
 <!--C26A68FD8CF347EC9D1FB7E274622450-->  <ACCESSLEVEL><![CDATA[4]]></ACCESSLEVEL>
+<!--C26A68FD8CF347EC9D1FB7E274622450-->  <AVAILABLE_IN_WORKSPACE><![CDATA[Y]]></AVAILABLE_IN_WORKSPACE>
 <!--C26A68FD8CF347EC9D1FB7E274622450--></OBKMO_WIDGET_CLASS>
 
 <!--E9DA175470B747268E09DEF5174FDD3A--><OBKMO_WIDGET_CLASS>
@@ -61,6 +64,7 @@
 <!--E9DA175470B747268E09DEF5174FDD3A-->  <WIDGET_SUPERCLASS_ID><![CDATA[C26A68FD8CF347EC9D1FB7E274622450]]></WIDGET_SUPERCLASS_ID>
 <!--E9DA175470B747268E09DEF5174FDD3A-->  <CAN_MAXIMIZE><![CDATA[N]]></CAN_MAXIMIZE>
 <!--E9DA175470B747268E09DEF5174FDD3A-->  <ACCESSLEVEL><![CDATA[3]]></ACCESSLEVEL>
+<!--E9DA175470B747268E09DEF5174FDD3A-->  <AVAILABLE_IN_WORKSPACE><![CDATA[Y]]></AVAILABLE_IN_WORKSPACE>
 <!--E9DA175470B747268E09DEF5174FDD3A--></OBKMO_WIDGET_CLASS>
 
 <!--F41E327965084556BCF7EC7B271603AA--><OBKMO_WIDGET_CLASS>
@@ -77,6 +81,7 @@
 <!--F41E327965084556BCF7EC7B271603AA-->  <ISSUPERCLASS><![CDATA[Y]]></ISSUPERCLASS>
 <!--F41E327965084556BCF7EC7B271603AA-->  <CAN_MAXIMIZE><![CDATA[Y]]></CAN_MAXIMIZE>
 <!--F41E327965084556BCF7EC7B271603AA-->  <ACCESSLEVEL><![CDATA[3]]></ACCESSLEVEL>
+<!--F41E327965084556BCF7EC7B271603AA-->  <AVAILABLE_IN_WORKSPACE><![CDATA[Y]]></AVAILABLE_IN_WORKSPACE>
 <!--F41E327965084556BCF7EC7B271603AA--></OBKMO_WIDGET_CLASS>
 
 <!--FF8080812E144FAE012E1455F6020009--><OBKMO_WIDGET_CLASS>
@@ -92,6 +97,7 @@
 <!--FF8080812E144FAE012E1455F6020009-->  <ISSUPERCLASS><![CDATA[N]]></ISSUPERCLASS>
 <!--FF8080812E144FAE012E1455F6020009-->  <CAN_MAXIMIZE><![CDATA[N]]></CAN_MAXIMIZE>
 <!--FF8080812E144FAE012E1455F6020009-->  <ACCESSLEVEL><![CDATA[3]]></ACCESSLEVEL>
+<!--FF8080812E144FAE012E1455F6020009-->  <AVAILABLE_IN_WORKSPACE><![CDATA[Y]]></AVAILABLE_IN_WORKSPACE>
 <!--FF8080812E144FAE012E1455F6020009--></OBKMO_WIDGET_CLASS>
 
 </data>
--- a/modules/org.openbravo.client.myob/src/org/openbravo/client/myob/MyOpenbravoActionHandler.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.client.myob/src/org/openbravo/client/myob/MyOpenbravoActionHandler.java	Fri Jun 03 10:22:43 2016 +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) 2010-2015 Openbravo SLU
+ * All portions are Copyright (C) 2010-2016 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -182,8 +182,14 @@
 
   private void addAvailableWidgetClasses(JSONObject o, String roleId, boolean isAdminMode) {
     MyOpenbravoComponent component = weldUtils.getInstance(MyOpenbravoComponent.class);
+    List<String> availableClasses = null;
     try {
-      List<String> availableClasses = component.getAvailableWidgetClasses(roleId, isAdminMode);
+      final String strEventType = o.getString("eventType");
+      if (GET_AVAILABLE_WIDGET_CLASSES.equals(strEventType)) {
+        availableClasses = component.getAvailableWidgetClasses(roleId, isAdminMode, true);
+      } else {
+        availableClasses = component.getAvailableWidgetClasses(roleId, isAdminMode);
+      }
       o.put("availableWidgetClasses", availableClasses);
     } catch (Exception e) {
       log.error("Error retreiving widget classes", e);
--- a/modules/org.openbravo.client.myob/src/org/openbravo/client/myob/MyOpenbravoComponent.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.client.myob/src/org/openbravo/client/myob/MyOpenbravoComponent.java	Fri Jun 03 10:22:43 2016 +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) 2010-2014 Openbravo SLU
+ * All portions are Copyright (C) 2010-2016 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -96,6 +96,12 @@
 
   public List<String> getAvailableWidgetClasses(String roleId, boolean isAdminMode)
       throws Exception {
+    boolean shouldBeDisplayedInWorkspace = false;
+    return getAvailableWidgetClasses(roleId, isAdminMode, shouldBeDisplayedInWorkspace);
+  }
+
+  public List<String> getAvailableWidgetClasses(String roleId, boolean isAdminMode,
+      boolean shouldBeDisplayed) throws Exception {
     OBContext.setAdminMode();
     try {
       if (widgetClassDefinitions != null) {
@@ -105,8 +111,13 @@
       final List<JSONObject> definitions = new ArrayList<JSONObject>();
       final List<String> tmp = new ArrayList<String>();
       String classDef = "";
+      String strConditionQuery = WidgetClass.PROPERTY_SUPERCLASS + " is false";
+      if (shouldBeDisplayed) {
+        strConditionQuery += " and " + WidgetClass.PROPERTY_AVAILABLEINWORKSPACE + " is true";
+      }
+
       final OBQuery<WidgetClass> widgetClassesQry = OBDal.getInstance().createQuery(
-          WidgetClass.class, WidgetClass.PROPERTY_SUPERCLASS + " is false");
+          WidgetClass.class, strConditionQuery);
       for (WidgetClass widgetClass : widgetClassesQry.list()) {
         if (isAccessible(widgetClass, roleId)) {
           final WidgetProvider widgetProvider = myOBUtils.getWidgetProvider(widgetClass);
--- a/modules/org.openbravo.client.querylist/src-db/database/sourcedata/OBKMO_WIDGET_CLASS.xml	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.client.querylist/src-db/database/sourcedata/OBKMO_WIDGET_CLASS.xml	Fri Jun 03 10:22:43 2016 +0200
@@ -14,6 +14,7 @@
 <!--147D825456D54D0486C3D7072531C5C9-->  <WIDGET_SUPERCLASS_ID><![CDATA[2A32CF26F3F64FE39C7F94E9D82497D1]]></WIDGET_SUPERCLASS_ID>
 <!--147D825456D54D0486C3D7072531C5C9-->  <CAN_MAXIMIZE><![CDATA[N]]></CAN_MAXIMIZE>
 <!--147D825456D54D0486C3D7072531C5C9-->  <ACCESSLEVEL><![CDATA[3]]></ACCESSLEVEL>
+<!--147D825456D54D0486C3D7072531C5C9-->  <AVAILABLE_IN_WORKSPACE><![CDATA[Y]]></AVAILABLE_IN_WORKSPACE>
 <!--147D825456D54D0486C3D7072531C5C9--></OBKMO_WIDGET_CLASS>
 
 <!--2662490B7D3B4F80AF308C88F6DB68C0--><OBKMO_WIDGET_CLASS>
@@ -30,6 +31,7 @@
 <!--2662490B7D3B4F80AF308C88F6DB68C0-->  <WIDGET_SUPERCLASS_ID><![CDATA[2A32CF26F3F64FE39C7F94E9D82497D1]]></WIDGET_SUPERCLASS_ID>
 <!--2662490B7D3B4F80AF308C88F6DB68C0-->  <CAN_MAXIMIZE><![CDATA[N]]></CAN_MAXIMIZE>
 <!--2662490B7D3B4F80AF308C88F6DB68C0-->  <ACCESSLEVEL><![CDATA[3]]></ACCESSLEVEL>
+<!--2662490B7D3B4F80AF308C88F6DB68C0-->  <AVAILABLE_IN_WORKSPACE><![CDATA[Y]]></AVAILABLE_IN_WORKSPACE>
 <!--2662490B7D3B4F80AF308C88F6DB68C0--></OBKMO_WIDGET_CLASS>
 
 <!--2A32CF26F3F64FE39C7F94E9D82497D1--><OBKMO_WIDGET_CLASS>
@@ -45,6 +47,7 @@
 <!--2A32CF26F3F64FE39C7F94E9D82497D1-->  <ISSUPERCLASS><![CDATA[Y]]></ISSUPERCLASS>
 <!--2A32CF26F3F64FE39C7F94E9D82497D1-->  <CAN_MAXIMIZE><![CDATA[Y]]></CAN_MAXIMIZE>
 <!--2A32CF26F3F64FE39C7F94E9D82497D1-->  <ACCESSLEVEL><![CDATA[4]]></ACCESSLEVEL>
+<!--2A32CF26F3F64FE39C7F94E9D82497D1-->  <AVAILABLE_IN_WORKSPACE><![CDATA[Y]]></AVAILABLE_IN_WORKSPACE>
 <!--2A32CF26F3F64FE39C7F94E9D82497D1--></OBKMO_WIDGET_CLASS>
 
 <!--34F279BBB85945519DC38F21573106C0--><OBKMO_WIDGET_CLASS>
@@ -61,6 +64,7 @@
 <!--34F279BBB85945519DC38F21573106C0-->  <WIDGET_SUPERCLASS_ID><![CDATA[2A32CF26F3F64FE39C7F94E9D82497D1]]></WIDGET_SUPERCLASS_ID>
 <!--34F279BBB85945519DC38F21573106C0-->  <CAN_MAXIMIZE><![CDATA[N]]></CAN_MAXIMIZE>
 <!--34F279BBB85945519DC38F21573106C0-->  <ACCESSLEVEL><![CDATA[3]]></ACCESSLEVEL>
+<!--34F279BBB85945519DC38F21573106C0-->  <AVAILABLE_IN_WORKSPACE><![CDATA[Y]]></AVAILABLE_IN_WORKSPACE>
 <!--34F279BBB85945519DC38F21573106C0--></OBKMO_WIDGET_CLASS>
 
 <!--8267FB3F59D7401980DDDEFF51FE55C3--><OBKMO_WIDGET_CLASS>
@@ -77,6 +81,7 @@
 <!--8267FB3F59D7401980DDDEFF51FE55C3-->  <WIDGET_SUPERCLASS_ID><![CDATA[2A32CF26F3F64FE39C7F94E9D82497D1]]></WIDGET_SUPERCLASS_ID>
 <!--8267FB3F59D7401980DDDEFF51FE55C3-->  <CAN_MAXIMIZE><![CDATA[N]]></CAN_MAXIMIZE>
 <!--8267FB3F59D7401980DDDEFF51FE55C3-->  <ACCESSLEVEL><![CDATA[3]]></ACCESSLEVEL>
+<!--8267FB3F59D7401980DDDEFF51FE55C3-->  <AVAILABLE_IN_WORKSPACE><![CDATA[Y]]></AVAILABLE_IN_WORKSPACE>
 <!--8267FB3F59D7401980DDDEFF51FE55C3--></OBKMO_WIDGET_CLASS>
 
 <!--F8E4F382BCFB441CADBB4AC693C41C93--><OBKMO_WIDGET_CLASS>
@@ -93,6 +98,7 @@
 <!--F8E4F382BCFB441CADBB4AC693C41C93-->  <WIDGET_SUPERCLASS_ID><![CDATA[2A32CF26F3F64FE39C7F94E9D82497D1]]></WIDGET_SUPERCLASS_ID>
 <!--F8E4F382BCFB441CADBB4AC693C41C93-->  <CAN_MAXIMIZE><![CDATA[N]]></CAN_MAXIMIZE>
 <!--F8E4F382BCFB441CADBB4AC693C41C93-->  <ACCESSLEVEL><![CDATA[3]]></ACCESSLEVEL>
+<!--F8E4F382BCFB441CADBB4AC693C41C93-->  <AVAILABLE_IN_WORKSPACE><![CDATA[Y]]></AVAILABLE_IN_WORKSPACE>
 <!--F8E4F382BCFB441CADBB4AC693C41C93--></OBKMO_WIDGET_CLASS>
 
 </data>
--- a/modules/org.openbravo.client.widgets/src-db/database/sourcedata/OBKMO_WIDGET_CLASS.xml	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.client.widgets/src-db/database/sourcedata/OBKMO_WIDGET_CLASS.xml	Fri Jun 03 10:22:43 2016 +0200
@@ -14,6 +14,7 @@
 <!--0B90015CD9C84792A98F1E9357C262E2-->  <WIDGET_SUPERCLASS_ID><![CDATA[C26A68FD8CF347EC9D1FB7E274622450]]></WIDGET_SUPERCLASS_ID>
 <!--0B90015CD9C84792A98F1E9357C262E2-->  <CAN_MAXIMIZE><![CDATA[N]]></CAN_MAXIMIZE>
 <!--0B90015CD9C84792A98F1E9357C262E2-->  <ACCESSLEVEL><![CDATA[3]]></ACCESSLEVEL>
+<!--0B90015CD9C84792A98F1E9357C262E2-->  <AVAILABLE_IN_WORKSPACE><![CDATA[Y]]></AVAILABLE_IN_WORKSPACE>
 <!--0B90015CD9C84792A98F1E9357C262E2--></OBKMO_WIDGET_CLASS>
 
 <!--267D9C95EE4E4E59BC0627658D0B9B37--><OBKMO_WIDGET_CLASS>
@@ -30,6 +31,7 @@
 <!--267D9C95EE4E4E59BC0627658D0B9B37-->  <WIDGET_SUPERCLASS_ID><![CDATA[C26A68FD8CF347EC9D1FB7E274622450]]></WIDGET_SUPERCLASS_ID>
 <!--267D9C95EE4E4E59BC0627658D0B9B37-->  <CAN_MAXIMIZE><![CDATA[N]]></CAN_MAXIMIZE>
 <!--267D9C95EE4E4E59BC0627658D0B9B37-->  <ACCESSLEVEL><![CDATA[3]]></ACCESSLEVEL>
+<!--267D9C95EE4E4E59BC0627658D0B9B37-->  <AVAILABLE_IN_WORKSPACE><![CDATA[Y]]></AVAILABLE_IN_WORKSPACE>
 <!--267D9C95EE4E4E59BC0627658D0B9B37--></OBKMO_WIDGET_CLASS>
 
 <!--35002C82027448708D173B75FB27D037--><OBKMO_WIDGET_CLASS>
@@ -45,6 +47,7 @@
 <!--35002C82027448708D173B75FB27D037-->  <WIDGET_SUPERCLASS_ID><![CDATA[C26A68FD8CF347EC9D1FB7E274622450]]></WIDGET_SUPERCLASS_ID>
 <!--35002C82027448708D173B75FB27D037-->  <CAN_MAXIMIZE><![CDATA[N]]></CAN_MAXIMIZE>
 <!--35002C82027448708D173B75FB27D037-->  <ACCESSLEVEL><![CDATA[3]]></ACCESSLEVEL>
+<!--35002C82027448708D173B75FB27D037-->  <AVAILABLE_IN_WORKSPACE><![CDATA[Y]]></AVAILABLE_IN_WORKSPACE>
 <!--35002C82027448708D173B75FB27D037--></OBKMO_WIDGET_CLASS>
 
 <!--5B41A19E11494C519BE33BBED6012DAE--><OBKMO_WIDGET_CLASS>
@@ -61,6 +64,7 @@
 <!--5B41A19E11494C519BE33BBED6012DAE-->  <WIDGET_SUPERCLASS_ID><![CDATA[2A32CF26F3F64FE39C7F94E9D82497D1]]></WIDGET_SUPERCLASS_ID>
 <!--5B41A19E11494C519BE33BBED6012DAE-->  <CAN_MAXIMIZE><![CDATA[N]]></CAN_MAXIMIZE>
 <!--5B41A19E11494C519BE33BBED6012DAE-->  <ACCESSLEVEL><![CDATA[3]]></ACCESSLEVEL>
+<!--5B41A19E11494C519BE33BBED6012DAE-->  <AVAILABLE_IN_WORKSPACE><![CDATA[Y]]></AVAILABLE_IN_WORKSPACE>
 <!--5B41A19E11494C519BE33BBED6012DAE--></OBKMO_WIDGET_CLASS>
 
 <!--5EA740A9473048CFA6B6F1FB6F5576AC--><OBKMO_WIDGET_CLASS>
@@ -76,6 +80,7 @@
 <!--5EA740A9473048CFA6B6F1FB6F5576AC-->  <WIDGET_SUPERCLASS_ID><![CDATA[C26A68FD8CF347EC9D1FB7E274622450]]></WIDGET_SUPERCLASS_ID>
 <!--5EA740A9473048CFA6B6F1FB6F5576AC-->  <CAN_MAXIMIZE><![CDATA[N]]></CAN_MAXIMIZE>
 <!--5EA740A9473048CFA6B6F1FB6F5576AC-->  <ACCESSLEVEL><![CDATA[3]]></ACCESSLEVEL>
+<!--5EA740A9473048CFA6B6F1FB6F5576AC-->  <AVAILABLE_IN_WORKSPACE><![CDATA[Y]]></AVAILABLE_IN_WORKSPACE>
 <!--5EA740A9473048CFA6B6F1FB6F5576AC--></OBKMO_WIDGET_CLASS>
 
 <!--6C1D7EC862F249B2AD1CD73A4F16A87F--><OBKMO_WIDGET_CLASS>
@@ -92,6 +97,7 @@
 <!--6C1D7EC862F249B2AD1CD73A4F16A87F-->  <WIDGET_SUPERCLASS_ID><![CDATA[C26A68FD8CF347EC9D1FB7E274622450]]></WIDGET_SUPERCLASS_ID>
 <!--6C1D7EC862F249B2AD1CD73A4F16A87F-->  <CAN_MAXIMIZE><![CDATA[N]]></CAN_MAXIMIZE>
 <!--6C1D7EC862F249B2AD1CD73A4F16A87F-->  <ACCESSLEVEL><![CDATA[3]]></ACCESSLEVEL>
+<!--6C1D7EC862F249B2AD1CD73A4F16A87F-->  <AVAILABLE_IN_WORKSPACE><![CDATA[Y]]></AVAILABLE_IN_WORKSPACE>
 <!--6C1D7EC862F249B2AD1CD73A4F16A87F--></OBKMO_WIDGET_CLASS>
 
 <!--6E3AC867DCB34C068DEED85B40611FD8--><OBKMO_WIDGET_CLASS>
@@ -108,6 +114,7 @@
 <!--6E3AC867DCB34C068DEED85B40611FD8-->  <ISSUPERCLASS><![CDATA[N]]></ISSUPERCLASS>
 <!--6E3AC867DCB34C068DEED85B40611FD8-->  <CAN_MAXIMIZE><![CDATA[N]]></CAN_MAXIMIZE>
 <!--6E3AC867DCB34C068DEED85B40611FD8-->  <ACCESSLEVEL><![CDATA[3]]></ACCESSLEVEL>
+<!--6E3AC867DCB34C068DEED85B40611FD8-->  <AVAILABLE_IN_WORKSPACE><![CDATA[Y]]></AVAILABLE_IN_WORKSPACE>
 <!--6E3AC867DCB34C068DEED85B40611FD8--></OBKMO_WIDGET_CLASS>
 
 <!--6FB59F927ADE4DD0B997BDDF615D3159--><OBKMO_WIDGET_CLASS>
@@ -124,6 +131,7 @@
 <!--6FB59F927ADE4DD0B997BDDF615D3159-->  <WIDGET_SUPERCLASS_ID><![CDATA[C26A68FD8CF347EC9D1FB7E274622450]]></WIDGET_SUPERCLASS_ID>
 <!--6FB59F927ADE4DD0B997BDDF615D3159-->  <CAN_MAXIMIZE><![CDATA[N]]></CAN_MAXIMIZE>
 <!--6FB59F927ADE4DD0B997BDDF615D3159-->  <ACCESSLEVEL><![CDATA[3]]></ACCESSLEVEL>
+<!--6FB59F927ADE4DD0B997BDDF615D3159-->  <AVAILABLE_IN_WORKSPACE><![CDATA[Y]]></AVAILABLE_IN_WORKSPACE>
 <!--6FB59F927ADE4DD0B997BDDF615D3159--></OBKMO_WIDGET_CLASS>
 
 <!--862EEC18D6FC4FA68E7867E3CF337CC7--><OBKMO_WIDGET_CLASS>
@@ -142,6 +150,7 @@
 <!--862EEC18D6FC4FA68E7867E3CF337CC7-->  <ACCESSLEVEL><![CDATA[3]]></ACCESSLEVEL>
 <!--862EEC18D6FC4FA68E7867E3CF337CC7-->  <AUTHOR_MSG><![CDATA[Requires Project Management module, which is part of Basic or Professional Edition]]></AUTHOR_MSG>
 <!--862EEC18D6FC4FA68E7867E3CF337CC7-->  <AUTHOR_URL><![CDATA[http://www.openbravo.com/product/erp/]]></AUTHOR_URL>
+<!--862EEC18D6FC4FA68E7867E3CF337CC7-->  <AVAILABLE_IN_WORKSPACE><![CDATA[Y]]></AVAILABLE_IN_WORKSPACE>
 <!--862EEC18D6FC4FA68E7867E3CF337CC7--></OBKMO_WIDGET_CLASS>
 
 <!--8A6B99392E2B4192012E2B53EDF3003D--><OBKMO_WIDGET_CLASS>
@@ -160,6 +169,7 @@
 <!--8A6B99392E2B4192012E2B53EDF3003D-->  <ACCESSLEVEL><![CDATA[3]]></ACCESSLEVEL>
 <!--8A6B99392E2B4192012E2B53EDF3003D-->  <AUTHOR_MSG><![CDATA[ What keeps us busy]]></AUTHOR_MSG>
 <!--8A6B99392E2B4192012E2B53EDF3003D-->  <AUTHOR_URL><![CDATA[http://planet.openbravo.com]]></AUTHOR_URL>
+<!--8A6B99392E2B4192012E2B53EDF3003D-->  <AVAILABLE_IN_WORKSPACE><![CDATA[Y]]></AVAILABLE_IN_WORKSPACE>
 <!--8A6B99392E2B4192012E2B53EDF3003D--></OBKMO_WIDGET_CLASS>
 
 <!--8A6B99392E2B4192012E2B55D957004C--><OBKMO_WIDGET_CLASS>
@@ -178,6 +188,7 @@
 <!--8A6B99392E2B4192012E2B55D957004C-->  <ACCESSLEVEL><![CDATA[3]]></ACCESSLEVEL>
 <!--8A6B99392E2B4192012E2B55D957004C-->  <AUTHOR_MSG><![CDATA[What goes up, must come down!]]></AUTHOR_MSG>
 <!--8A6B99392E2B4192012E2B55D957004C-->  <AUTHOR_URL><![CDATA[http://www.google.com/finance]]></AUTHOR_URL>
+<!--8A6B99392E2B4192012E2B55D957004C-->  <AVAILABLE_IN_WORKSPACE><![CDATA[Y]]></AVAILABLE_IN_WORKSPACE>
 <!--8A6B99392E2B4192012E2B55D957004C--></OBKMO_WIDGET_CLASS>
 
 <!--8A6B99392E2B4192012E2B58F5790056--><OBKMO_WIDGET_CLASS>
@@ -196,6 +207,7 @@
 <!--8A6B99392E2B4192012E2B58F5790056-->  <ACCESSLEVEL><![CDATA[3]]></ACCESSLEVEL>
 <!--8A6B99392E2B4192012E2B58F5790056-->  <AUTHOR_MSG><![CDATA[Want to share a customer story? Contact Openbravo!]]></AUTHOR_MSG>
 <!--8A6B99392E2B4192012E2B58F5790056-->  <AUTHOR_URL><![CDATA[http://www.openbravo.com/about-us/contact-us/]]></AUTHOR_URL>
+<!--8A6B99392E2B4192012E2B58F5790056-->  <AVAILABLE_IN_WORKSPACE><![CDATA[Y]]></AVAILABLE_IN_WORKSPACE>
 <!--8A6B99392E2B4192012E2B58F5790056--></OBKMO_WIDGET_CLASS>
 
 <!--8A6B99392E2D9088012E2DC2C5520031--><OBKMO_WIDGET_CLASS>
@@ -214,6 +226,7 @@
 <!--8A6B99392E2D9088012E2DC2C5520031-->  <ACCESSLEVEL><![CDATA[3]]></ACCESSLEVEL>
 <!--8A6B99392E2D9088012E2DC2C5520031-->  <AUTHOR_MSG><![CDATA[Just an example that points to an external Google spreadsheet]]></AUTHOR_MSG>
 <!--8A6B99392E2D9088012E2DC2C5520031-->  <AUTHOR_URL><![CDATA[https://spreadsheets.google.com/ccc?key=0AnhNC__gfTgAcmE2czJ1WlkwR2x1aTZnTHNlR0dsNHc&hl=en_GB]]></AUTHOR_URL>
+<!--8A6B99392E2D9088012E2DC2C5520031-->  <AVAILABLE_IN_WORKSPACE><![CDATA[Y]]></AVAILABLE_IN_WORKSPACE>
 <!--8A6B99392E2D9088012E2DC2C5520031--></OBKMO_WIDGET_CLASS>
 
 <!--8A6B99392E2D9088012E2DCFC39B005F--><OBKMO_WIDGET_CLASS>
@@ -232,6 +245,7 @@
 <!--8A6B99392E2D9088012E2DCFC39B005F-->  <ACCESSLEVEL><![CDATA[3]]></ACCESSLEVEL>
 <!--8A6B99392E2D9088012E2DCFC39B005F-->  <AUTHOR_MSG><![CDATA[This one is slightly outdated as it still uses RC3 design. Check back at the UX Lab on the Forge (link below) for more information & discussions on widgets.]]></AUTHOR_MSG>
 <!--8A6B99392E2D9088012E2DCFC39B005F-->  <AUTHOR_URL><![CDATA[http://forge.openbravo.com/plugins/espforum/browse.php?group_id=100&forumid=886353]]></AUTHOR_URL>
+<!--8A6B99392E2D9088012E2DCFC39B005F-->  <AVAILABLE_IN_WORKSPACE><![CDATA[Y]]></AVAILABLE_IN_WORKSPACE>
 <!--8A6B99392E2D9088012E2DCFC39B005F--></OBKMO_WIDGET_CLASS>
 
 <!--8A6B99392E2D9088012E2DE2AD61008C--><OBKMO_WIDGET_CLASS>
@@ -250,6 +264,7 @@
 <!--8A6B99392E2D9088012E2DE2AD61008C-->  <ACCESSLEVEL><![CDATA[3]]></ACCESSLEVEL>
 <!--8A6B99392E2D9088012E2DE2AD61008C-->  <AUTHOR_MSG><![CDATA[Check out the UX Lab blog or forum for more info on widgets]]></AUTHOR_MSG>
 <!--8A6B99392E2D9088012E2DE2AD61008C-->  <AUTHOR_URL><![CDATA[http://openbravouxlab.blogspot.com/]]></AUTHOR_URL>
+<!--8A6B99392E2D9088012E2DE2AD61008C-->  <AVAILABLE_IN_WORKSPACE><![CDATA[Y]]></AVAILABLE_IN_WORKSPACE>
 <!--8A6B99392E2D9088012E2DE2AD61008C--></OBKMO_WIDGET_CLASS>
 
 <!--8A6B99392E2D9088012E2DFD131900BD--><OBKMO_WIDGET_CLASS>
@@ -268,6 +283,7 @@
 <!--8A6B99392E2D9088012E2DFD131900BD-->  <ACCESSLEVEL><![CDATA[3]]></ACCESSLEVEL>
 <!--8A6B99392E2D9088012E2DFD131900BD-->  <AUTHOR_MSG><![CDATA[What´s hot and what´s not]]></AUTHOR_MSG>
 <!--8A6B99392E2D9088012E2DFD131900BD-->  <AUTHOR_URL><![CDATA[http://www.google.com/insights/search/#]]></AUTHOR_URL>
+<!--8A6B99392E2D9088012E2DFD131900BD-->  <AVAILABLE_IN_WORKSPACE><![CDATA[Y]]></AVAILABLE_IN_WORKSPACE>
 <!--8A6B99392E2D9088012E2DFD131900BD--></OBKMO_WIDGET_CLASS>
 
 <!--CD1B06C4ED974B5F905A5A01B097DF4E--><OBKMO_WIDGET_CLASS>
@@ -285,6 +301,7 @@
 <!--CD1B06C4ED974B5F905A5A01B097DF4E-->  <CAN_MAXIMIZE><![CDATA[N]]></CAN_MAXIMIZE>
 <!--CD1B06C4ED974B5F905A5A01B097DF4E-->  <ACCESSLEVEL><![CDATA[3]]></ACCESSLEVEL>
 <!--CD1B06C4ED974B5F905A5A01B097DF4E-->  <AUTHOR_MSG><![CDATA[A simple and useful sample widget]]></AUTHOR_MSG>
+<!--CD1B06C4ED974B5F905A5A01B097DF4E-->  <AVAILABLE_IN_WORKSPACE><![CDATA[Y]]></AVAILABLE_IN_WORKSPACE>
 <!--CD1B06C4ED974B5F905A5A01B097DF4E--></OBKMO_WIDGET_CLASS>
 
 <!--DEEFF28410DD488E9EF2EB28DCD6ADA1--><OBKMO_WIDGET_CLASS>
@@ -300,6 +317,7 @@
 <!--DEEFF28410DD488E9EF2EB28DCD6ADA1-->  <WIDGET_SUPERCLASS_ID><![CDATA[C26A68FD8CF347EC9D1FB7E274622450]]></WIDGET_SUPERCLASS_ID>
 <!--DEEFF28410DD488E9EF2EB28DCD6ADA1-->  <CAN_MAXIMIZE><![CDATA[N]]></CAN_MAXIMIZE>
 <!--DEEFF28410DD488E9EF2EB28DCD6ADA1-->  <ACCESSLEVEL><![CDATA[3]]></ACCESSLEVEL>
+<!--DEEFF28410DD488E9EF2EB28DCD6ADA1-->  <AVAILABLE_IN_WORKSPACE><![CDATA[Y]]></AVAILABLE_IN_WORKSPACE>
 <!--DEEFF28410DD488E9EF2EB28DCD6ADA1--></OBKMO_WIDGET_CLASS>
 
 </data>
--- a/modules/org.openbravo.financial.paymentreport/src/org/openbravo/financial/paymentreport/erpCommon/ad_reports/PaymentReportDao.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.financial.paymentreport/src/org/openbravo/financial/paymentreport/erpCommon/ad_reports/PaymentReportDao.java	Fri Jun 03 10:22:43 2016 +0200
@@ -1702,6 +1702,7 @@
       String strcProjectIdIN, String strfinPaymSt, String strcCurrency, String strPaymType,
       String strGroupCrit, String strOrdCrit, String strcNoBusinessPartner, String strDueDateFrom,
       String strDueDateTo, String strExpectedDateFrom, String strExpectedDateTo) {
+    String localStrfinPaymSt = strfinPaymSt;
     Organization[] organizations;
     if (strInclSubOrg.equalsIgnoreCase("include")) {
       Set<String> orgChildTree = OBContext.getOBContext().getOrganizationStructureProvider()
@@ -1828,12 +1829,12 @@
       }
 
       // Status
-      if (!strfinPaymSt.isEmpty() && !strfinPaymSt.equalsIgnoreCase("('')")) {
-        strfinPaymSt = strfinPaymSt.replace("(", "");
-        strfinPaymSt = strfinPaymSt.replace(")", "");
-        strfinPaymSt = strfinPaymSt.replace("'", "");
-        strfinPaymSt = strfinPaymSt.replace(" ", "");
-        String[] status = strfinPaymSt.split(",");
+      if (!localStrfinPaymSt.isEmpty() && !localStrfinPaymSt.equalsIgnoreCase("('')")) {
+        localStrfinPaymSt = localStrfinPaymSt.replace("(", "");
+        localStrfinPaymSt = localStrfinPaymSt.replace(")", "");
+        localStrfinPaymSt = localStrfinPaymSt.replace("'", "");
+        localStrfinPaymSt = localStrfinPaymSt.replace(" ", "");
+        String[] status = localStrfinPaymSt.split(",");
         obCriteriaTrans.add(Restrictions.in(FIN_FinaccTransaction.PROPERTY_STATUS, status));
       }
 
--- a/modules/org.openbravo.financial.paymentreport/src/org/openbravo/financial/paymentreport/erpCommon/ad_reports/PaymentReportExcel.jrxml	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.financial.paymentreport/src/org/openbravo/financial/paymentreport/erpCommon/ad_reports/PaymentReportExcel.jrxml	Fri Jun 03 10:22:43 2016 +0200
@@ -16,6 +16,7 @@
 	<property name="com.jaspersoft.studio.unit.rightMargin" value="pixel"/>
 	<property name="com.jaspersoft.studio.unit.columnWidth" value="pixel"/>
 	<property name="com.jaspersoft.studio.unit.columnSpacing" value="pixel"/>
+	<property name="net.sf.jasperreports.export.xls.detect.cell.type" value="true"/>
 	<import value="net.sf.jasperreports.engine.*"/>
 	<import value="java.util.*"/>
 	<import value="net.sf.jasperreports.engine.data.*"/>
@@ -65,6 +66,9 @@
 	<parameter name="TWO_ASTERISK_SHOW" class="java.lang.Boolean" isForPrompting="false">
 		<defaultValueExpression><![CDATA[new Boolean(false)]]></defaultValueExpression>
 	</parameter>
+	<parameter name="NUMBERFORMAT" class="java.text.DecimalFormat" isForPrompting="false">
+		<defaultValueExpression><![CDATA[new DecimalFormat("###,##0.00", new DecimalFormatSymbols())]]></defaultValueExpression>
+	</parameter>
 	<queryString>
 		<![CDATA[SELECT 'hello' AS BP_GROUP, 'hello' AS BPARTNER, 'hello' AS PROJECT, 'hello' AS PAYMENT, 'hello' AS SALES_PERSON, 1234 AS INVOICE_NUMBER, to_Date('01/01/2010') AS INVOICE_DATE,
        to_Date('01/03/2010') AS DUE_DATE, 1234 AS PLANNED_DSO, 1234 AS CURRENT_DSO, 1234 AS OVERDUE, 1234 AS DAYS_OVERDUE, 1234 AS AMOUNT,
@@ -384,6 +388,7 @@
 					<font size="8"/>
 				</textElement>
 				<textFieldExpression><![CDATA[$F{BASE_AMOUNT}]]></textFieldExpression>
+				<patternExpression><![CDATA[$P{NUMBERFORMAT}.toPattern()]]></patternExpression>
 			</textField>
 			<textField isStretchWithOverflow="true" isBlankWhenNull="true">
 				<reportElement key="textField-14" style="Report_Footer" x="1597" y="0" width="46" height="25" uuid="5048cde4-f51d-4ce0-8a89-adc9406901c8"/>
@@ -399,6 +404,7 @@
 					<font size="8"/>
 				</textElement>
 				<textFieldExpression><![CDATA[$F{TRANS_AMOUNT}]]></textFieldExpression>
+				<patternExpression><![CDATA[$P{NUMBERFORMAT}.toPattern()]]></patternExpression>
 			</textField>
 			<textField isStretchWithOverflow="true" isBlankWhenNull="true">
 				<reportElement key="textField-16" style="Report_Footer" x="1457" y="0" width="60" height="25" uuid="ff340e8e-63c1-4df9-af58-75c6c7bbabee"/>
--- a/modules/org.openbravo.service.datasource/src/org/openbravo/service/datasource/DataSourceServlet.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.service.datasource/src/org/openbravo/service/datasource/DataSourceServlet.java	Fri Jun 03 10:22:43 2016 +0200
@@ -816,16 +816,16 @@
     setSessionInfo();
 
     try {
-      if (!hasAccess(request, parameters.get(JsonConstants.TAB_PARAMETER))) {
-        throw new OBUserException("AccessTableNoView");
-      }
-
       if (DataSourceConstants.FETCH_OPERATION.equals(parameters
           .get(DataSourceConstants.OPERATION_TYPE_PARAM))) {
         doFetch(request, response, parameters);
         return;
       }
 
+      if (!hasAccess(request, parameters.get(JsonConstants.TAB_PARAMETER))) {
+        throw new OBUserException("AccessTableNoView");
+      }
+
       // note if clause updates parameter map
       if (checkSetIDDataSourceName(request, response, parameters)) {
         String content = getRequestContent(request);
--- a/modules/org.openbravo.service.datasource/src/org/openbravo/service/datasource/DefaultDataSourceService.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.service.datasource/src/org/openbravo/service/datasource/DefaultDataSourceService.java	Fri Jun 03 10:22:43 2016 +0200
@@ -357,12 +357,7 @@
     if (entity == null) {
       dsProperties = super.getDataSourceProperties(parameters);
     } else {
-      if (false) {
-        dsProperties = getInitialProperties(entity,
-            parameters.containsKey(DataSourceConstants.MINIMAL_PROPERTY_OUTPUT));
-      } else {
-        dsProperties = getInitialProperties(entity, false);
-      }
+      dsProperties = getInitialProperties(entity, false);
     }
 
     // now see if there are additional properties, these are often property paths
--- a/modules/org.openbravo.service.datasource/web/org.openbravo.service.datasource/js/ob-datasource-utilities.js	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.service.datasource/web/org.openbravo.service.datasource/js/ob-datasource-utilities.js	Fri Jun 03 10:22:43 2016 +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) 2009-2013 Openbravo SLU
+ * All portions are Copyright (C) 2009-2016 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -185,8 +185,12 @@
 isc.OBRestDataSource.addProperties({
   sendDSRequest: function (dsRequest) {
     //TODO: Report an issue to SmartClient - This part is a work around
+    var extraProperties = {};
     if (dsRequest.params && this.requestProperties && this.requestProperties.params) {
-      isc.addProperties(dsRequest.params, this.requestProperties.params);
+      if (dsRequest.params._extraProperties) {
+        extraProperties[OB.Constants.EXTRA_PROPERTIES] = dsRequest.params._extraProperties;
+      }
+      isc.addProperties(dsRequest.params, this.requestProperties.params, extraProperties);
     }
     // if the datasource is not paginated, paginate them in case of selectors working in 2.50 UI.
     // in other cases error is thrown from server side.
--- a/modules/org.openbravo.service.json/src/org/openbravo/service/json/AdvancedQueryBuilder.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.service.json/src/org/openbravo/service/json/AdvancedQueryBuilder.java	Fri Jun 03 10:22:43 2016 +0200
@@ -160,10 +160,12 @@
   private String distinctPropertyPath;
   private DataEntityQueryService subDataEntityQueryService;
 
-  // map that indicates, for a property, if its join definition is used only in joins used for
-  // filtering the grid
-  // see issue https://issues.openbravo.com/view.php?id=26279
-  private Map<String, Boolean> gridFilterExclusiveJoinMap = new HashMap<String, Boolean>();
+  // map that indicates, for a property, if it should be joined using an inner join or a left join.
+  // An inner join will be used if one of the following cases is fulfilled:
+  // 1- the join definition of the property is used only in joins used for filtering the grid.
+  // 2- the join definition is included for sorting, and the property used to make the join is
+  // mandatory, i.e., the inner join can be used safely.
+  private Map<String, Boolean> useInnerJoinMap = new HashMap<String, Boolean>();
 
   private int aliasOffset = 0;
 
@@ -1335,23 +1337,6 @@
       }
     }
 
-    for (String additionalProperty : additionalProperties) {
-      List<Property> properties = JsonUtils.getPropertiesOnPath(getEntity(), additionalProperty);
-      if (properties.isEmpty()) {
-        continue;
-      }
-      properties = getPropertyForTableReference(properties);
-      final Property lastProperty = properties.get(properties.size() - 1);
-      if (lastProperty.isPrimitive()) {
-        properties.remove(lastProperty);
-      }
-      if (properties.isEmpty() || lastProperty.isOneToMany()) {
-        continue;
-      }
-      boolean fromCriteria = false;
-      resolveJoins(properties, getMainAlias(), fromCriteria);
-    }
-
     // make sure that the join clauses are computed
     getOrderByClause();
     getWhereClause();
@@ -1547,9 +1532,9 @@
         path = orderByExpression[0];
         direction = " " + orderByExpression[1] + " ";
       }
-      boolean fromCriteria = false;
-      final String resolvedPath = resolveJoins(JsonUtils.getPropertiesOnPath(getEntity(), path),
-          path, fromCriteria);
+      List<Property> properties = JsonUtils.getPropertiesOnPath(getEntity(), path);
+      // decide whether the entity joined for sorting have to use a left join or an inner join
+      final String resolvedPath = resolveJoins(properties, path, canUseInnerJoin(properties));
       sb.append(resolvedPath);
       sb.append(direction);
     }
@@ -1564,6 +1549,17 @@
     return orderByClausePart;
   }
 
+  // When joining DB tables, this method can be used to check if the joining property of the
+  // leftmost table is mandatory. In that case, an inner join would not discard any record of that
+  // table. This means that the left join can be safely replaced with inner join.
+  private boolean canUseInnerJoin(List<Property> properties) {
+    if (properties.size() == 0) {
+      return false;
+    }
+    Property firstProperty = properties.get(0);
+    return !firstProperty.isPrimitive() && firstProperty.isMandatory();
+  }
+
   // Creates a Hibernate concatenation if there are multiple identifierproperties
   // note prefix includes the dot at the end
   private String createIdentifierLeftClause(List<Property> identifierProperties, String prefix) {
@@ -1758,7 +1754,7 @@
       for (JoinDefinition joinDefinition : joinDefinitions) {
         if (joinDefinition.appliesTo(alias, prop)) {
           if (!fromCriteria) {
-            gridFilterExclusiveJoinMap.put(prop.getName(), Boolean.FALSE);
+            useInnerJoinMap.put(prop.getName(), Boolean.FALSE);
           }
           alias = joinDefinition.getJoinAlias();
           joinedPropertyIndex = index;
@@ -1783,9 +1779,9 @@
       joinDefinition.setOwnerAlias(alias);
       joinDefinition.setProperty(prop);
       if (fromCriteria) {
-        gridFilterExclusiveJoinMap.put(prop.getName(), Boolean.TRUE);
+        useInnerJoinMap.put(prop.getName(), Boolean.TRUE);
       } else {
-        gridFilterExclusiveJoinMap.put(prop.getName(), Boolean.FALSE);
+        useInnerJoinMap.put(prop.getName(), Boolean.FALSE);
       }
       joinDefinitions.add(joinDefinition);
 
@@ -1840,7 +1836,7 @@
         // entity is used only in where clauses resulting from filtering the grid, an inner join can
         // be used
         if (KernelUtils.hasNullableIdentifierProperties(property.getTargetEntity())
-            || !(Boolean.TRUE.equals(gridFilterExclusiveJoinMap.get(property.getName())))) {
+            || !(Boolean.TRUE.equals(useInnerJoinMap.get(property.getName())))) {
           joinType = " left join ";
         } else {
           joinType = " inner join ";
--- a/modules/org.openbravo.service.json/src/org/openbravo/service/json/DefaultJsonDataService.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.service.json/src/org/openbravo/service/json/DefaultJsonDataService.java	Fri Jun 03 10:22:43 2016 +0200
@@ -35,6 +35,7 @@
 import org.codehaus.jettison.json.JSONObject;
 import org.hibernate.ScrollableResults;
 import org.openbravo.base.exception.OBException;
+import org.openbravo.base.model.Column;
 import org.openbravo.base.model.Entity;
 import org.openbravo.base.model.ModelProvider;
 import org.openbravo.base.model.Property;
@@ -51,6 +52,7 @@
 import org.openbravo.erpCommon.utility.OBMessageUtils;
 import org.openbravo.service.db.DbUtility;
 import org.openbravo.service.json.JsonToDataConverter.JsonConversionError;
+import org.openbravo.userinterface.selector.Selector;
 import org.openbravo.userinterface.selector.SelectorConstants;
 
 /**
@@ -73,6 +75,7 @@
   private static final Logger log = Logger.getLogger(DefaultJsonDataService.class);
 
   private static final String ADD_FLAG = "_doingAdd";
+  private static final int DEFAULT_ID_LENGTH = 32;
 
   @Inject
   private CachedPreference cachedPreference;
@@ -549,9 +552,16 @@
       if (parameters.get(JsonConstants.SUMMARY_PARAMETER) != null
           && parameters.get(JsonConstants.SUMMARY_PARAMETER).trim().length() > 0) {
         queryService.setSummarySettings(parameters.get(JsonConstants.SUMMARY_PARAMETER));
+      } else if (parameters.containsKey(SelectorConstants.DS_REQUEST_SELECTOR_ID_PARAMETER)
+          && entityIsViewWithConcatenatedPK(entityName)) {
+        // To avoid performance problems, views whose primary key is built with the concatenation of
+        // several columns must not use that key for predictable sorting
+        String idProperty = getSelectorValueFieldProperty(entityName,
+            parameters.get(SelectorConstants.DS_REQUEST_SELECTOR_ID_PARAMETER));
+        orderBy += (orderBy.isEmpty() ? "" : ",") + idProperty;
       } else {
         // Always append id to the orderby to make a predictable sorting
-        orderBy += (orderBy.isEmpty() ? "" : ",") + "id";
+        orderBy += (orderBy.isEmpty() ? "" : ",") + JsonConstants.ID;
       }
     } else {
       orderBy = JsonConstants.IDENTIFIER;
@@ -564,7 +574,9 @@
     if (!forCountOperation && !directNavigation
         && parameters.containsKey(JsonConstants.TARGETRECORDID_PARAMETER)) {
       final String targetRecordId = parameters.get(JsonConstants.TARGETRECORDID_PARAMETER);
-      targetRowNumber = queryService.getRowNumber(targetRecordId);
+      if (StringUtils.isNotBlank(targetRecordId) && !"null".equals(targetRecordId)) {
+        targetRowNumber = queryService.getRowNumber(targetRecordId);
+      }
       if (targetRowNumber != -1) {
         startRow = targetRowNumber;
         // if the startrow is really low, then just read from 0
@@ -602,6 +614,32 @@
     return paramMsg;
   }
 
+  private boolean entityIsViewWithConcatenatedPK(String entityName) {
+    Entity entity = ModelProvider.getInstance().getEntity(entityName);
+    if (entity.isView()) {
+      // If a view has a concatenation of several column values as its primary key value, the length
+      // of the primary key will be higher than 32, the default size for a UUID.
+      List<Column> primaryKeys = ModelProvider.getInstance().getTable(entity.getTableName())
+          .getPrimaryKeyColumns();
+      return primaryKeys.size() > 0 && primaryKeys.get(0).getFieldLength() > DEFAULT_ID_LENGTH;
+    }
+    return false;
+  }
+
+  private String getSelectorValueFieldProperty(String entityName, String selectorId) {
+    try {
+      OBContext.setAdminMode(false); // Need access to Application Dictionary information
+      Selector selector = OBDal.getInstance().get(Selector.class, selectorId);
+      if (selector != null && selector.getValuefield() != null
+          && selector.getValuefield().getProperty() != null) {
+        return selector.getValuefield().getProperty();
+      }
+      return JsonConstants.ID;
+    } finally {
+      OBContext.restorePreviousMode();
+    }
+  }
+
   private void addWritableAttribute(List<JSONObject> jsonObjects) throws JSONException {
     for (JSONObject jsonObject : jsonObjects) {
       if (!jsonObject.has("client") || !jsonObject.has("organization")) {
--- a/modules/org.openbravo.service.json/src/org/openbravo/service/json/JsonRestServlet.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.service.json/src/org/openbravo/service/json/JsonRestServlet.java	Fri Jun 03 10:22:43 2016 +0200
@@ -157,6 +157,8 @@
         JSONStreamWriter writer = new JSONStreamWriter(response, parameters);
         parameters.put(JsonConstants.USE_ALIAS, "true");
         parameters.put(JsonConstants.IS_WS_CALL, "true");
+        parameters.put(JsonConstants.WHERE_AND_FILTER_CLAUSE,
+            parameters.get(JsonConstants.WHERE_PARAMETER));
         DefaultJsonDataService.getInstance().fetch(parameters, writer);
         writer.close();
       }
--- a/modules/org.openbravo.service.json/src/org/openbravo/service/json/JsonToDataConverter.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.service.json/src/org/openbravo/service/json/JsonToDataConverter.java	Fri Jun 03 10:22:43 2016 +0200
@@ -127,7 +127,6 @@
 
   private final static SimpleDateFormat xmlDateFormat = JsonUtils.createDateFormat();
   private final static SimpleDateFormat xmlDateTimeFormat = JsonUtils.createDateTimeFormat();
-  private final static SimpleDateFormat xmlTimeFormat = JsonUtils.createTimeFormat();
   private final static SimpleDateFormat jsTimeFormat = JsonUtils.createJSTimeFormat();
 
   private final List<JsonConversionError> errors = new ArrayList<JsonConversionError>();
--- a/modules/org.openbravo.userinterface.selector/src/org/openbravo/userinterface/selector/SelectorConstants.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.userinterface.selector/src/org/openbravo/userinterface/selector/SelectorConstants.java	Fri Jun 03 10:22:43 2016 +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) 2009-2013 Openbravo SLU 
+ * All portions are Copyright (C) 2009-2016 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -25,8 +25,12 @@
  */
 public class SelectorConstants {
   public static final String SELECTOR_COMPONENT_TYPE = "OBUISEL_Selector";
+  public static final String JS = "js";
 
   // parameters used by the SelectorComponent
+  public static final String PARAM_ID = "id";
+  public static final String PARAM_IDENTIFIER = "_identifier";
+  public static final String PARAM_FIELD_NAME = "fieldName";
   public static final String PARAM_COLUMN_NAME = "columnName";
   public static final String PARAM_DISABLED = "disabled";
   public static final String PARAM_REQUIRED = "required";
@@ -34,6 +38,8 @@
   public static final String PARAM_TAB_ID = "adTabId";
   public static final String PARAM_COMBO_RELOAD = "comboReload";
   public static final String PARAM_TARGET_PROPERTY_NAME = "targetProperty";
+  public static final String PARAM_ID_FILTERS = "idFilters";
+  public static final String PARAM_FILTER_EXPRESSION = "filterExpression";
 
   // Reference definition IDs
   public static final String SELECTOR_REFERENCE_ID = "95E2A8B50A254B2AAE6774B8C2F28120";
@@ -44,4 +50,5 @@
   public static final String DS_REQUEST_TYPE_PARAMETER = "_requestType";
   public static final String DS_REQUEST_PROCESS_DEFINITION_ID = "_processDefinitionId";
   public static final String DS_REQUEST_SELECTOR_FIELD_ID = "_selectorFieldId";
+  public static final String DS_REQUEST_IS_FILTER_BY_ID_SUPPORTED = "_isFilterByIdSupported";
 }
--- a/modules/org.openbravo.userinterface.selector/src/org/openbravo/userinterface/selector/SelectorDefaultFilterActionHandler.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.userinterface.selector/src/org/openbravo/userinterface/selector/SelectorDefaultFilterActionHandler.java	Fri Jun 03 10:22:43 2016 +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) 2010-2012 Openbravo SLU
+ * All portions are Copyright (C) 2010-2016 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -27,6 +27,8 @@
 import javax.servlet.http.HttpSession;
 
 import org.apache.log4j.Logger;
+import org.codehaus.jettison.json.JSONArray;
+import org.codehaus.jettison.json.JSONException;
 import org.codehaus.jettison.json.JSONObject;
 import org.hibernate.criterion.Restrictions;
 import org.openbravo.base.model.Entity;
@@ -60,11 +62,11 @@
     OBContext.setAdminMode();
 
     try {
-      if (!params.containsKey("_selectorDefinitionId")) {
+      if (!params.containsKey(SelectorConstants.DS_REQUEST_SELECTOR_ID_PARAMETER)) {
         return result;
       }
 
-      String selectorId = params.get("_selectorDefinitionId");
+      String selectorId = params.get(SelectorConstants.DS_REQUEST_SELECTOR_ID_PARAMETER);
 
       Selector sel = OBDal.getInstance().get(Selector.class, selectorId);
       final Table table;
@@ -90,16 +92,21 @@
       }
 
       final ScriptEngineManager manager = new ScriptEngineManager();
-      final ScriptEngine engine = manager.getEngineByName("js");
+      final ScriptEngine engine = manager.getEngineByName(SelectorConstants.JS);
       engine.put(
           "OB",
           new OBBindings(OBContext.getOBContext(), params, (HttpSession) parameters
               .get(KernelConstants.HTTP_SESSION)));
 
+      boolean isFilterByIdSupported = params
+          .containsKey(SelectorConstants.DS_REQUEST_IS_FILTER_BY_ID_SUPPORTED)
+          && "true".equals(params.get(SelectorConstants.DS_REQUEST_IS_FILTER_BY_ID_SUPPORTED));
       Object exprResult = null;
+      JSONArray idFilters = new JSONArray();
       for (SelectorField f : obc.list()) {
         try {
           exprResult = engine.eval(f.getDefaultExpression());
+          Object bobId = null;
 
           if (exprResult != null && !exprResult.equals("") && !exprResult.equals("''")) {
             Property property = null;
@@ -111,6 +118,7 @@
             if (property != null && property.getTargetEntity() != null && !property.isOneToMany()) {
               final BaseOBObject bob = OBDal.getInstance().get(
                   property.getTargetEntity().getName(), exprResult);
+              bobId = exprResult;
               exprResult = bob.getIdentifier();
             }
           }
@@ -119,8 +127,12 @@
             result.put(f.getDisplayColumnAlias().replace(DalUtil.DOT, DalUtil.FIELDSEPARATOR),
                 exprResult);
           } else if (exprResult != null && !exprResult.equals("") && !exprResult.equals("''")) {
-            String fieldName = f.getProperty();
-            result.put(fieldName.replace(DalUtil.DOT, DalUtil.FIELDSEPARATOR), exprResult);
+            String fieldName = f.getProperty().replace(DalUtil.DOT, DalUtil.FIELDSEPARATOR);
+            if (bobId != null && isFilterByIdSupported) {
+              idFilters.put(createJSONObjectFilter(fieldName, (String) bobId, (String) exprResult));
+            } else {
+              result.put(fieldName, exprResult);
+            }
           }
         } catch (Exception e) {
           log.error(
@@ -129,12 +141,16 @@
         }
       }
 
+      if (idFilters.length() > 0) {
+        result.put(SelectorConstants.PARAM_ID_FILTERS, idFilters);
+      }
+
       // Obtaining the filter Expression from Selector. Refer issue
       // https://issues.openbravo.com/view.php?id=21541
       Object dynamicFilterExpression = null;
       if (sel.getFilterExpression() != null) {
         dynamicFilterExpression = engine.eval(sel.getFilterExpression());
-        result.put("filterExpression", dynamicFilterExpression.toString());
+        result.put(SelectorConstants.PARAM_FILTER_EXPRESSION, dynamicFilterExpression.toString());
       }
 
     } catch (Exception e) {
@@ -146,6 +162,15 @@
     return result;
   }
 
+  private JSONObject createJSONObjectFilter(String fieldName, String id, String identifier)
+      throws JSONException {
+    JSONObject jsonResult = new JSONObject();
+    jsonResult.put(SelectorConstants.PARAM_FIELD_NAME, fieldName);
+    jsonResult.put(SelectorConstants.PARAM_ID, id);
+    jsonResult.put(SelectorConstants.PARAM_IDENTIFIER, identifier);
+    return jsonResult;
+  }
+
   private Map<String, String> getParameterMap(Map<String, Object> parameters) {
     Map<String, String> params = new HashMap<String, String>();
     for (String key : parameters.keySet()) {
--- a/modules/org.openbravo.userinterface.selector/src/org/openbravo/userinterface/selector/SelectorFieldPropertyCallout.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.userinterface.selector/src/org/openbravo/userinterface/selector/SelectorFieldPropertyCallout.java	Fri Jun 03 10:22:43 2016 +0200
@@ -92,7 +92,7 @@
     } else {
       final String[] parts = property.split("\\.");
       Entity currentEntity = entity;
-      Property currentProperty;
+      Property currentProperty = null;
       for (String part : parts) {
         if (part.length() == 0) {
           writeEmptyResult(response);
@@ -110,7 +110,13 @@
         if (currentProperty.isPrimitive()) {
           break;
         }
-        currentEntity = foundProperty.getTargetEntity();
+
+        if (Entity.COMPUTED_COLUMNS_PROXY_PROPERTY.equals(currentProperty.getName())) {
+          currentEntity = ModelProvider.getInstance().getEntity(
+              currentEntity.getName() + Entity.COMPUTED_COLUMNS_CLASS_APPENDIX);
+        } else {
+          currentEntity = foundProperty.getTargetEntity();
+        }
       }
     }
 
@@ -119,11 +125,18 @@
     try {
       // get the table
       final Entity propertyEntity = foundProperty.getEntity();
-      final Table propertyTable = OBDal
-          .getInstance()
-          .createQuery(Table.class,
-              Table.PROPERTY_DBTABLENAME + "='" + propertyEntity.getTableName() + "'").list()
-          .get(0);
+
+      String tableId = propertyEntity.getTableId();
+
+      if (propertyEntity.isVirtualEntity()) {
+        // If it is a virtual entity, that means that the variable tableId will be
+        // the id of the table concatenated to the "_CC" substring, this is why the
+        // tableId variable is get by removing the last three characters.
+        tableId = tableId.substring(0, tableId.length() - 3);
+      }
+
+      final Table propertyTable = OBDal.getInstance()
+          .createQuery(Table.class, Table.PROPERTY_ID + "='" + tableId + "'").list().get(0);
 
       final OBCriteria<Column> columnCriteria = OBDal.getInstance().createCriteria(Column.class);
       columnCriteria.add(Restrictions.and(Restrictions.eq(Column.PROPERTY_TABLE, propertyTable),
--- a/modules/org.openbravo.userinterface.selector/web/org.openbravo.userinterface.selector/js/ob-selector-item.js	Wed Jun 01 13:42:08 2016 +0200
+++ b/modules/org.openbravo.userinterface.selector/web/org.openbravo.userinterface.selector/js/ob-selector-item.js	Fri Jun 03 10:22:43 2016 +0200
@@ -143,12 +143,13 @@
       },
 
       getFetchRequestParams: function (params) {
+        var requestType = 'Window';
         params = params || {};
         if (this.selector) {
-          isc.OBSelectorItem.prepareDSRequest(params, this.selector);
+          isc.OBSelectorItem.prepareDSRequest(params, this.selector, requestType);
         }
 
-        params._requestType = 'Window';
+        params._requestType = requestType;
 
         if (this.getSelectedRecord()) {
           params._targetRecordId = this.targetRecordId;
@@ -357,6 +358,7 @@
     // first time    
     var ret = this.Super('show', arguments);
     if (applyDefaultFilter) {
+      this.setFilterByIdEditorCriteria(this.defaultFilter);
       this.selectorGrid.setFilterEditorCriteria(this.defaultFilter);
       this.selectorGrid.filterByEditor();
     }
@@ -380,7 +382,8 @@
         callback, data;
 
     data = {
-      '_selectorDefinitionId': this.selectorDefinitionId || this.selector.selectorDefinitionId
+      '_selectorDefinitionId': this.selectorDefinitionId || this.selector.selectorDefinitionId,
+      '_isFilterByIdSupported': true
     };
 
     // on purpose not passing the third boolean param
@@ -412,6 +415,33 @@
     this.show(true);
   },
 
+  setFilterByIdEditorCriteria: function (defaultFilter) {
+    var editForm = this.getFilterEditorForm(),
+        filterField, idFilter, i;
+    if (!defaultFilter.idFilters || !editForm) {
+      return;
+    }
+    for (i = 0; i < defaultFilter.idFilters.length; i++) {
+      idFilter = defaultFilter.idFilters[i];
+      filterField = editForm.getField(idFilter.fieldName);
+      if (filterField) {
+        // Force filter by id
+        filterField.filterType = 'id';
+        filterField.filterAuxCache = [idFilter];
+        defaultFilter[idFilter.fieldName] = idFilter._identifier;
+      }
+    }
+    // idFilters is no longer needed. Its information is already included into the grid filters.
+    delete this.defaultFilter.idFilters;
+  },
+
+  getFilterEditorForm: function () {
+    if (!this.selectorGrid || !this.selectorGrid.filterEditor || !this.selectorGrid.filterEditor.getEditForm) {
+      return null;
+    }
+    return this.selectorGrid.filterEditor.getEditForm();
+  },
+
   setValueInField: function () {
     if (this.multiselect) {
       this.selector.setSelectedRecords(this.selectorGrid.getSelectedRecords());
@@ -917,10 +947,20 @@
   },
 
   openSelectorWindow: function () {
+    var selectorGrid = this.selectorWindow.selectorGrid;
     // always refresh the content of the grid to force a reload
     // if the organization has changed
-    if (this.selectorWindow.selectorGrid) {
-      this.selectorWindow.selectorGrid.invalidateCache();
+    if (selectorGrid && selectorGrid.data) {
+      delete selectorGrid.data;
+      // Ensure that the scroll is on the top after reopening the selector pop-up
+      selectorGrid.scrollToRow(0);
+      if (selectorGrid.body) {
+        selectorGrid.body.markForRedraw();
+      }
+      if (selectorGrid.getSelectedRecord()) {
+        // Clean selection information, it will be recalculated on dataArrived
+        selectorGrid.deselectAllRecords();
+      }
     }
     this.selectorWindow.open();
   },
@@ -977,7 +1017,7 @@
     requestProperties = requestProperties || {};
     requestProperties.params = requestProperties.params || {};
 
-    isc.OBSelectorItem.prepareDSRequest(requestProperties.params, this);
+    isc.OBSelectorItem.prepareDSRequest(requestProperties.params, this, 'PickList');
 
     // sometimes the value is passed as a filter criteria remove it
     if (this.getValueFieldName() && requestProperties.params[this.getValueFieldName()]) {
@@ -1061,6 +1101,36 @@
     return criteria;
   },
 
+  getSelectedPropertiesString: function () {
+    var i, fieldName, selectedProperties = OB.Constants.ID;
+    for (i = 0; i < this.pickListFields.length; i++) {
+      fieldName = this.pickListFields[i].name;
+      if (fieldName === OB.Constants.ID || fieldName === OB.Constants.IDENTIFIER) {
+        continue;
+      }
+      selectedProperties += ',' + fieldName;
+    }
+    return selectedProperties;
+  },
+
+  getExtraPropertiesString: function () {
+    var i, outFieldName, outFieldsNames, extraProperties = this.valueField || '';
+    if (this.displayField && this.displayField !== OB.Constants.IDENTIFIER) {
+      extraProperties += ',' + this.displayField;
+    }
+    if (this.outFields) {
+      outFieldsNames = isc.getKeys(this.outFields);
+      for (i = 0; i < outFieldsNames.length; i++) {
+        outFieldName = outFieldsNames[i];
+        if (outFieldName === this.valueField || outFieldName === this.displayField) {
+          continue;
+        }
+        extraProperties += ',' + outFieldName;
+      }
+    }
+    return extraProperties;
+  },
+
   mapValueToDisplay: function (value) {
     var ret = this.Super('mapValueToDisplay', arguments);
     if (ret === value && this.isDisabled()) {
@@ -1111,7 +1181,7 @@
 isc.OBSelectorItem.addClassMethods({
   // Prepares requestProperties adding contextInfo, this is later used in backed
   // to prepare filters 
-  prepareDSRequest: function (params, selector) {
+  prepareDSRequest: function (params, selector, requestType) {
     function setOrgIdParam(params) {
       if (!params.inpadOrgId) {
         // look for an ad_org_id parameter. If there is no such parameter or its value is empty, use the current user organization
@@ -1179,6 +1249,13 @@
     // initially
     params[OB.Constants.SORTBY_PARAMETER] = selector.displayField;
 
+    if (requestType === 'PickList') {
+      // Add the fields to be displayed in the picklist as selected properties
+      params[OB.Constants.SELECTED_PROPERTIES] = selector.getSelectedPropertiesString();
+      // Include value field, display field and out fields into additional properties
+      params[OB.Constants.EXTRA_PROPERTIES] = selector.getExtraPropertiesString();
+    }
+
     // Parameter windows
     if (selector.form.paramWindow) {
       params._processDefinitionId = selector.form.paramWindow.processId;
--- a/src-core/src/org/openbravo/data/Sqlc.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src-core/src/org/openbravo/data/Sqlc.java	Fri Jun 03 10:22:43 2016 +0200
@@ -94,6 +94,7 @@
   private static boolean includeQueryTimeOut;
 
   private List<String> scrollableFunctionNames = new ArrayList<String>();
+  private boolean hasCountField;
 
   private Sqlc() {
     init();
@@ -107,6 +108,7 @@
     strComments = null;
     sqlcAccessModifier = "";
     scrollableFunctionNames = new ArrayList<String>();
+    hasCountField = false;
   }
 
   public static void main(String argv[]) throws Exception {
@@ -887,6 +889,11 @@
       // add needed instance variables & functions
       String toInsert = "\n";
       toInsert += "  private String scrollableGetter;\n";
+
+      if (!hasCountField) {
+        toInsert += "  @SuppressWarnings(\"unused\")\n";
+      }
+
       toInsert += "  private long countRecord;\n";
       toInsert += "  private ResultSet result;\n";
       toInsert += "  private boolean hasData;\n";
@@ -1589,10 +1596,11 @@
     }
     for (final Enumeration<Object> e = sql.vecFieldAdded.elements(); e.hasMoreElements();) {
       final FieldAdded fieldAdded = (FieldAdded) e.nextElement();
-      if (fieldAdded.strValue.equals("count"))
+      if (fieldAdded.strValue.equals("count")) {
         out2.append("        object" + sqlcName + "." + fieldAdded.strName
             + " = Long.toString(countRecord);\n");
-      else if (fieldAdded.strValue.equals("void"))
+        hasCountField = true;
+      } else if (fieldAdded.strValue.equals("void"))
         out2.append("        object" + sqlcName + "." + fieldAdded.strName + " = \"\";\n");
     }
     if (sql.sqlReturn.equalsIgnoreCase("MULTIPLE"))
--- a/src-core/src/org/openbravo/utils/FileUtility.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src-core/src/org/openbravo/utils/FileUtility.java	Fri Jun 03 10:22:43 2016 +0200
@@ -20,9 +20,8 @@
 import java.io.IOException;
 import java.io.OutputStream;
 import java.io.PrintWriter;
-import java.nio.MappedByteBuffer;
-import java.nio.channels.FileChannel;
 
+import org.apache.commons.io.FileUtils;
 import org.apache.log4j.Logger;
 
 /**
@@ -139,31 +138,12 @@
   }
 
   public static void copyFile(File in, File out) throws Exception {
-    FileChannel src = null, cp = null;
-    try {
-      src = new FileInputStream(in).getChannel();
-      cp = new FileOutputStream(out).getChannel();
-      long size = src.size();
-      MappedByteBuffer buf = src.map(FileChannel.MapMode.READ_ONLY, 0, size);
-      cp.write(buf);
-    } finally {
-      if (src != null)
-        src.close();
-      if (cp != null)
-        cp.close();
-    }
+    // TODO: check preserveFileDate how we want it
+    // kept false as that probably matches the old openCoded behavior
+    // only single user (MigrateAttachments script) anyway
+    FileUtils.copyFile(in, out, false);
   }
 
-  /*
-   * public void copyFile(File in, File out) throws Exception { //FileInputStream fis = new
-   * FileInputStream(in); BufferedReader fileBuffer = new BufferedReader(new FileReader(in));
-   * FileOutputStream fos = new FileOutputStream(out); OutputStreamWriter printWriterData = new
-   * OutputStreamWriter(fos, "UTF-8"); String nextLine = fileBuffer.readLine(); while (nextLine !=
-   * null) { printWriterData.write(nextLine); printWriterData.write("\n"); nextLine =
-   * fileBuffer.readLine(); } printWriterData.flush(); fos.close(); fileBuffer.close();
-   * /while((i=fis.read(buf))!=-1) { fos.write(buf, 0, i); } fis.close(); fos.close(); }
-   */
-
   public static void delete(File source) throws Exception {
     File[] list = source.listFiles();
     for (int i = 0; i < list.length; i++) {
--- a/src-db/database/model/functions/AD_SHORTNAME.xml	Wed Jun 01 13:42:08 2016 +0200
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,42 +0,0 @@
-<?xml version="1.0"?>
-  <database name="FUNCTION AD_SHORTNAME">
-    <function name="AD_SHORTNAME" type="NVARCHAR">
-      <parameter name="p_name" type="NVARCHAR" mode="in">
-        <default/>
-      </parameter>
-      <body><![CDATA[/*************************************************************************
-* 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) 2001-2006 Openbravo SLU
-* All Rights Reserved.
-* Contributor(s):  ______________________________________.
-************************************************************************/
-/*************************************************************************
-* Title: AD_ShortName
-************************************************************************/
-  v_RetValue NVARCHAR2(2000) ;
-  v_pos NUMBER:=1;
-BEGIN
-  v_RetValue:=SUBSTR(p_Name, 1, 1) ;
-  WHILE(INSTR(REPLACE(p_Name, '.', ' '), ' ', v_pos+1) > 0)
-  LOOP
-    v_pos:=INSTR(REPLACE(p_Name, '.', ' '), ' ', v_pos+1) ;
-    v_RetValue:=v_RetValue || SUBSTR(p_Name, v_pos+1, 1) ;
-  END LOOP;
-  RETURN v_RetValue;
-EXCEPTION
-WHEN OTHERS THEN
-  RETURN TO_CHAR(v_pos) ;
-END AD_SHORTNAME
-]]></body>
-    </function>
-  </database>
--- a/src-db/database/model/functions/C_INVOICE_CREATE.xml	Wed Jun 01 13:42:08 2016 +0200
+++ b/src-db/database/model/functions/C_INVOICE_CREATE.xml	Fri Jun 03 10:22:43 2016 +0200
@@ -585,18 +585,21 @@
                   END IF;
                   IF(NOT Next_O_Line) THEN
                     v_InOutLine_ID:=NULL;
-                    -- In case of POS Order get M_InOutLine_ID for OrderLine
+                    -- In any case get M_InOutLine_ID for OrderLine
                     -- Making sure exactly one record is retreived using Max
                     -- Qty compared to get full shipped line reference only
+                    -- from a processed shipment
                     -- There could a case where Order Line is split into two
                     -- based on available stock in different storage bins
                     -- in that no reference would be set in Invoice Line
-                    IF(v_DocSubTypeSO = 'WR') THEN
-                      SELECT MAX(sl.M_INOUTLINE_ID) INTO v_InOutLine_ID
-                        FROM M_INOUTLINE sl
-                        WHERE sl.C_ORDERLINE_ID = ptr_ol.C_OrderLine_ID
-                          AND ptr_ol.QtyOrdered = sl.MovementQty;
-                    END IF;
+                    SELECT MAX(sl.M_INOUTLINE_ID)
+                    INTO v_InOutLine_ID
+                    FROM M_INOUT s
+                    JOIN M_INOUTLINE sl
+                    ON s.M_INOUT_ID = sl.M_INOUT_ID
+                    WHERE sl.C_ORDERLINE_ID = ptr_ol.C_OrderLine_ID
+                    AND sl.MovementQty = ptr_ol.QtyOrdered
+                    AND s.processed='Y';
                     --
                     Ad_Sequence_Next('C_InvoiceLine', Cur_Order.C_Order_ID, v_NextNo) ;
                     v_LineNo:=v_LineNo + 10;
--- a/src-db/database/model/functions/C_ORDER_POST1.xml	Wed Jun 01 13:42:08 2016 +0200
+++ b/src-db/database/model/functions/C_ORDER_POST1.xml	Fri Jun 03 10:22:43 2016 +0200
@@ -571,6 +571,7 @@
           v_QtyOrderSO NUMBER;
           v_QtyPO NUMBER; -- Ordered
           v_QtyOrderPO NUMBER;
+          v_UOM_ID VARCHAR2(32);
         BEGIN
           v_ResultStr:='ReserveInventory';
           -- For all lines needing reservation
@@ -594,14 +595,22 @@
               IF (Cur_ResLine.QtyDelivered=0) THEN
                 v_QtyOrderPO := -Cur_ResLine.QuantityOrder;
               ELSIF Cur_ResLine.M_Product_UOM_ID IS NOT NULL THEN
-                v_QtyOrderPO := -C_Uom_Convert(v_QtyPO, Cur_ResLine.C_UOM_ID, Cur_ResLine.M_Product_UOM_ID, 'Y');
+                SELECT c_uom_id
+                INTO v_UOM_ID
+                FROM m_product_uom
+                WHERE m_product_uom_id = Cur_ResLine.M_Product_UOM_ID;
+                v_QtyOrderPO := -C_Uom_Convert(v_QtyPO, Cur_ResLine.C_UOM_ID, v_UOM_ID, 'Y');
               END IF;
             ELSE
               v_QtySO:=-Cur_ResLine.QtyReserved;
               IF (Cur_ResLine.QtyReserved=Cur_ResLine.Qty) THEN
                 v_QtyOrderSO := -Cur_ResLine.QuantityOrder;
               ELSIF Cur_ResLine.M_Product_UOM_ID IS NOT NULL THEN
-                v_QtyOrderSO := -C_Uom_Convert(v_QtySO, Cur_ResLine.C_UOM_ID, Cur_ResLine.M_Product_UOM_ID, 'Y');
+                SELECT c_uom_id
+                INTO v_UOM_ID
+                FROM m_product_uom
+                WHERE m_product_uom_id = Cur_ResLine.M_Product_UOM_ID;
+                v_QtyOrderSO := -C_Uom_Convert(v_QtySO, Cur_ResLine.C_UOM_ID, v_UOM_ID, 'Y');
               END IF;
               v_QtyPO:=0;
               v_QtyOrderPO:=NULL;
@@ -1166,6 +1175,7 @@
           v_QtyOrderSO  NUMBER;
           v_QtyPO       NUMBER; -- Ordered
           v_QtyOrderPO  NUMBER;
+          v_UOM_ID      VARCHAR2(32);
         BEGIN
           v_ResultStr := 'ReserveInventory';
           -- For all lines needing reservation
@@ -1192,7 +1202,11 @@
               IF (Cur_ResLine.QtyReserved = 0 AND Cur_ResLine.QtyDelivered = 0) THEN
                 v_QtyOrderSO := Cur_ResLine.QuantityOrder;
               ELSIF (Cur_ResLine.M_Product_UOM_ID IS NOT NULL) THEN
-                v_QtyOrderSO := C_Uom_Convert(v_QtySO, Cur_ResLine.C_UOM_ID, Cur_ResLine.M_Product_UOM_ID, 'Y');
+                SELECT c_uom_id
+                INTO v_UOM_ID
+                FROM m_product_uom
+                WHERE m_product_uom_id = Cur_ResLine.M_Product_UOM_ID;
+                v_QtyOrderSO := C_Uom_Convert(v_QtySO, Cur_ResLine.C_UOM_ID, v_UOM_ID, 'Y');
               END IF;
               v_QtyPO   := 0;
               v_QtyOrderPO := NULL;
@@ -1204,7 +1218,11 @@
               IF (Cur_ResLine.QtyReserved = 0 AND Cur_ResLine.QtyDelivered = 0) THEN
                 v_QtyOrderPO := Cur_ResLine.QuantityOrder;
               ELSIF (Cur_ResLine.M_Product_UOM_ID IS NOT NULL) THEN
-                v_QtyOrderPO := C_Uom_Convert(v_QtyPO, Cur_ResLine.C_UOM_ID, Cur_ResLine.M_Product_UOM_ID, 'Y');
+                SELECT c_uom_id
+                INTO v_UOM_ID
+                FROM m_product_uom
+                WHERE m_product_uom_id = Cur_ResLine.M_Product_UOM_ID;
+                v_QtyOrderPO := C_Uom_Convert(v_QtyPO, Cur_ResLine.C_UOM_ID, v_UOM_ID, 'Y');
               END IF;
             END IF;
             IF ((v_DocStatus<>'IP' OR v_DocAction<>'CO') AND COALESCE(v_DocSubTypeSO, '')<>'OB') THEN
--- a/src-db/database/model/functions/M_INOUT_CREATE.xml	Wed Jun 01 13:42:08 2016 +0200
+++ b/src-db/database/model/functions/M_INOUT_CREATE.xml	Fri Jun 03 10:22:43 2016 +0200
@@ -34,7 +34,7 @@
   * parts created by ComPiere are Copyright (C) ComPiere, Inc.;
   * All Rights Reserved.
   * Contributor(s): Openbravo SLU
-  * Contributions are Copyright (C) 2001-2015 Openbravo, S.L.U.
+  * Contributions are Copyright (C) 2001-2016 Openbravo, S.L.U.
   *
   * Specifically, this derivative work is based upon the following Compiere
   * file and version.
@@ -445,7 +445,6 @@
                 v_QtyOrder:=ol.QuantityOrder;
               ELSIF (v_ProductUOM IS NOT NULL) THEN
                 v_QtyOrder:=ROUND(ol.QuantityOrder*v_Qty/ol.QtyOrdered,v_stdPrecision);
-                --v_QtyOrder:=C_Uom_Convert(v_Qty, ol.C_UOM_ID, v_ProductUOM, 'Y') ;
               ELSE
                 v_QtyOrder:=NULL;
               END IF;
@@ -594,7 +593,6 @@
                   Ad_Sequence_Next('M_InOutLine', Cur_Order.C_Order_ID, v_NextNo) ;
                   IF (v_ProductUOM IS NOT NULL) THEN
                     v_ActualQty:=ol.QuantityOrder*v_Qty/ol.QtyOrdered;
-                    --v_ActualQty:=C_Uom_Convert(v_Qty, ol.C_UOM_ID, v_ProductUOM, 'Y') ;
                   ELSE
                     v_ActualQty:=NULL;
                   END IF;
--- a/src-db/database/model/functions/M_RESERVATION_REALLOCATE.xml	Wed Jun 01 13:42:08 2016 +0200
+++ b/src-db/database/model/functions/M_RESERVATION_REALLOCATE.xml	Fri Jun 03 10:22:43 2016 +0200
@@ -34,7 +34,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) 2013-2015 Openbravo SLU
+* All portions are Copyright (C) 2013-2016 Openbravo SLU
 * All Rights Reserved.
 * Contributor(s):  ______________________________________.
 ************************************************************************/
--- a/src-db/database/model/postscript-DB2.sql	Wed Jun 01 13:42:08 2016 +0200
+++ b/src-db/database/model/postscript-DB2.sql	Fri Jun 03 10:22:43 2016 +0200
@@ -23,31 +23,6 @@
 END NOW;
 /-- END NOW
 
-CREATE OR REPLACE FUNCTION hex_to_int (hexn VARCHAR)
-  RETURN number
-AS
-/*************************************************************************
-* 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) 2001-2008 Openbravo SLU
-* All Rights Reserved.
-* Contributor(s):  ______________________________________.
-************************************************************************/
-BEGIN
-    return to_number(hexn,'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
-END hex_to_int;
-/-- END hex_to_int
-
-
 CREATE OR REPLACE FUNCTION ad_script_execute (param_Message VARCHAR2)
   RETURN VARCHAR2
 AS
--- a/src-db/database/model/postscript-Oracle.sql	Wed Jun 01 13:42:08 2016 +0200
+++ b/src-db/database/model/postscript-Oracle.sql	Fri Jun 03 10:22:43 2016 +0200
@@ -22,30 +22,6 @@
 END NOW;
 /-- END NOW
 
-CREATE OR REPLACE FUNCTION hex_to_int (hexn VARCHAR)
-  RETURN number
-AS
-/*************************************************************************
-* 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) 2001-2008 Openbravo SLU
-* All Rights Reserved.
-* Contributor(s):  ______________________________________.
-************************************************************************/
-BEGIN
-    return to_number(hexn,'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx');
-END hex_to_int;
-/-- END hex_to_int
-
 CREATE OR REPLACE FUNCTION ad_script_execute (param_Message VARCHAR2)
   RETURN VARCHAR2
 AS
--- a/src-db/database/model/prescript-PostgreSql.sql	Wed Jun 01 13:42:08 2016 +0200
+++ b/src-db/database/model/prescript-PostgreSql.sql	Fri Jun 03 10:22:43 2016 +0200
@@ -165,22 +165,8 @@
 text
 )
 RETURNS NUMERIC AS '
-DECLARE
-  v_Pos INTEGER;
-  v_Mant NUMERIC;
-  v_Exp NUMERIC;
-  v_Res NUMERIC;
 BEGIN
-  v_Pos := position(''E'' in upper($1));
-  IF v_Pos = 0 THEN
-    -- this is the old behaviour
-    RETURN to_number($1, ''S99999999999999D999999'');
-  ELSE
-    v_Mant := substring($1 from 1 for v_Pos - 1); -- Mantissa, implicit cast to data type NUMERIC
-    v_Exp := substring($1 from v_Pos + 1); -- Exponent, implicit cast to data type NUMERIC
-    v_Res := v_Mant * power(10, v_Exp);
-    RETURN v_Res;
-  END IF;
+  RETURN cast($1 as numeric);
 EXCEPTION
   WHEN OTHERS THEN
     RETURN NULL;
@@ -263,11 +249,11 @@
 
 CREATE OR REPLACE FUNCTION to_date
 (
-timestamp, varchar
+ timestamp, varchar
 )
-RETURNS timestamp AS '
+  RETURNS timestamp AS '
 BEGIN
-RETURN to_timestamp($1, $2);
+  RETURN to_timestamp(to_char($1), $2);
 END;
 ' LANGUAGE 'plpgsql' IMMUTABLE
 /-- END
@@ -429,79 +415,6 @@
 ' language 'plpgsql' IMMUTABLE
 /-- END
 
-CREATE OR REPLACE FUNCTION hex_to_int("varchar")
-  RETURNS "numeric" AS
-$BODY$
-DECLARE
-h alias for $1;
-exec varchar;
-curs refcursor;
-res numeric;
-res1 numeric;
-res2 numeric;
-res3 numeric;
-res4 numeric;
-hi varchar;
-h1 varchar;
-h2 varchar;
-h3 varchar;
-h4 varchar;
-exp1 numeric(50);
-exp2 numeric(50);
-exp3 numeric(50);
-BEGIN
-if length(h) < 32 then
-	hi:=repeat('0',32-length(h)) || h;
-else
-	hi:=h;
-end if;
-h1:=substr(hi,25,8);
-h2:=substr(hi,17,8);
-h3:=substr(hi,9,8);
-h4:=substr(hi,1,8);
-exec := 'SELECT x''' || h1 || '''::bigint';
-OPEN curs FOR EXECUTE exec;
-FETCH curs INTO res1;
-CLOSE curs;
-exec := 'SELECT x''' || h2 || '''::bigint';
-OPEN curs FOR EXECUTE exec;
-FETCH curs INTO res2;
-CLOSE curs;
-exec := 'SELECT x''' || h3 || '''::bigint';
-OPEN curs FOR EXECUTE exec;
-FETCH curs INTO res3;
-CLOSE curs;
-exec := 'SELECT x''' || h4 || '''::bigint';
-OPEN curs FOR EXECUTE exec;
-FETCH curs INTO res4;
-CLOSE curs;
-exp1=pow(16::numeric,8::numeric);
-exp2=pow(16::numeric,16::numeric);
-exp3=pow(16::numeric,24::numeric);
-res:=res1;
-res:=res+res2*exp1;
-res:=res+res3*exp2;
-res:=res+res4*exp3;
-return to_number(res);
-END;$BODY$
-  LANGUAGE 'plpgsql' IMMUTABLE STRICT;
-/-- END
-
-CREATE OR REPLACE FUNCTION hex_to_int(numeric) RETURNS numeric AS '
-DECLARE
-h alias for $1;
-exec varchar;
-curs refcursor;
-res int;
-BEGIN
-return h;
-END;'
-LANGUAGE 'plpgsql'
-IMMUTABLE
-STRICT;
-/-- END
-
-
 CREATE OR REPLACE FUNCTION add_months
 (
 date,
@@ -1051,23 +964,6 @@
   RIGHTARG = numeric)
 /-- END
 
--- Auxiliar function for compatibility between 8.2 and 8.3 Postgres version.
-CREATE OR REPLACE FUNCTION is_Trigger_Enabled(tg_name "text")
-  RETURNS boolean AS
-$BODY$ 
-DECLARE
-  v_isEnabled boolean := false;
-BEGIN
-  SELECT tgenabled INTO v_isEnabled FROM pg_trigger WHERE UPPER(tgname) = UPPER(tg_name);
-  RETURN v_isEnabled;
-EXCEPTION
-WHEN OTHERS THEN
-  SELECT (UPPER(tgenabled)<>'D') INTO v_isEnabled FROM pg_trigger WHERE tgname = tg_name;
-  RETURN v_isEnabled;
-END;   $BODY$
-  LANGUAGE 'plpgsql' STABLE;
-/-- END
-
 -- Creating auxiliar functions for view dropping
 CREATE or REPLACE function drop_view (view_name IN varchar) returns varchar as '
 DECLARE
--- a/src-db/database/model/triggers/C_ORDERLINE2_TRG.xml	Wed Jun 01 13:42:08 2016 +0200
+++ b/src-db/database/model/triggers/C_ORDERLINE2_TRG.xml	Fri Jun 03 10:22:43 2016 +0200
@@ -18,11 +18,11 @@
 * under the License.
 * The Original Code is Openbravo ERP.
 * The Initial Developer of the Original Code is Openbravo SLU
-* All portions are Copyright (C) 2001-2015 Openbravo SLU
+* All portions are Copyright (C) 2001-2016 Openbravo SLU
 * All Rights Reserved.
 * Contributor(s):  ______________________________________.
 ************************************************************************/
-  v_ID VARCHAR2(32);   
+  v_ID                 VARCHAR2(32);
   v_QtyReserved        NUMBER;
   v_QtyOrderReserved   NUMBER;
   V_STOCKED            NUMBER;
@@ -32,6 +32,7 @@
   v_QtyReservedPO      NUMBER;
   v_QtyOrderReservedPO NUMBER;
   v_count              NUMBER;
+  v_UOM_ID             VARCHAR2(32);
 
 BEGIN
     
@@ -54,7 +55,11 @@
           IF :old.qtydelivered=0 AND :new.qtydelivered=:new.qtyordered THEN
             v_QtyOrderReserved:=-:new.QuantityOrder;
           ELSIF :new.M_Product_UOM_ID IS NOT NULL THEN
-            v_QtyOrderReserved:=C_Uom_Convert(v_QtyReserved, :new.C_UOM_ID, :new.m_product_uom_id, 'Y') ;
+            SELECT c_uom_id
+            INTO v_UOM_ID
+            FROM m_product_uom
+            WHERE m_product_uom_id = :new.m_product_uom_id;
+            v_QtyOrderReserved:=C_Uom_Convert(v_QtyReserved, :new.C_UOM_ID, v_UOM_ID, 'Y') ;
           END IF;
           SELECT COUNT(*)
           INTO V_STOCKED
--- a/src-db/database/model/views/M_PRODUCT_PRICE_WAREHOUSE_V.xml	Wed Jun 01 13:42:08 2016 +0200
+++ b/src-db/database/model/views/M_PRODUCT_PRICE_WAREHOUSE_V.xml	Fri Jun 03 10:22:43 2016 +0200
@@ -1,4 +1,4 @@
 <?xml version="1.0"?>
   <database name="VIEW M_PRODUCT_PRICE_WAREHOUSE_V">
-    <view name="M_PRODUCT_PRICE_WAREHOUSE_V"><![CDATA[SELECT COALESCE(w.m_warehouse_id, '-') || pp.m_productprice_id AS m_product_price_warehouse_v_id, p.ad_client_id, p.ad_org_id, p.isactive, p.updated, p.updatedby, p.created, p.createdby, p.m_product_id, w.m_warehouse_id, pp.m_productprice_id, CASE WHEN p.producttype <> 'I' OR p.isstocked = 'N' THEN 99999 ELSE COALESCE(pwq.qtyonhand - pwq.qtyreserved, 0) END AS qty_available, CASE WHEN p.producttype <> 'I' OR p.isstocked = 'N' THEN 99999 ELSE COALESCE(pwq.qtyonhand, 0) END AS qty_onhand, CASE WHEN p.producttype <> 'I' OR p.isstocked = 'N' THEN 0 ELSE COALESCE(pwq.qtyreserved, 0) END AS qty_reserved, CASE WHEN p.producttype <> 'I' OR p.isstocked = 'N' THEN 0 ELSE COALESCE(pwq.qtyordered, 0) END AS qty_ordered, pp.pricelist, pp.pricestd, pp.pricelimit, COALESCE(w.ad_org_id, '0') AS orgwarehouse FROM m_productprice pp LEFT JOIN m_warehouse w ON pp.ad_client_id = w.ad_client_id LEFT JOIN m_product p ON p.m_product_id = pp.m_product_id LEFT JOIN m_product_warehouse_qtys_v pwq ON pwq.m_product_id = pp.m_product_id AND pwq.m_warehouse_id = w.m_warehouse_id WHERE p.isgeneric = 'N' AND pp.isactive = 'Y' AND w.isactive = 'Y' AND p.isactive = 'Y']]></view>
+    <view name="M_PRODUCT_PRICE_WAREHOUSE_V"><![CDATA[SELECT COALESCE(w.m_warehouse_id, '-') || pp.m_productprice_id AS m_product_price_warehouse_v_id, p.ad_client_id, p.ad_org_id, p.isactive, p.updated, p.updatedby, p.created, p.createdby, p.m_product_id, w.m_warehouse_id, pp.m_productprice_id, CASE WHEN p.producttype <> 'I' OR p.isstocked = 'N' THEN 99999 ELSE COALESCE((SELECT sum(sdd.qtyonhand) AS sum FROM m_storage_detail sdd JOIN m_locator l ON sdd.m_locator_id = l.m_locator_id WHERE sdd.m_product_id = p.m_product_id AND l.m_warehouse_id = w.m_warehouse_id), 0) - COALESCE((SELECT sum(sp.qtyreserved) AS sum FROM m_storage_pending sp WHERE sp.m_product_id = p.m_product_id AND sp.m_warehouse_id = w.m_warehouse_id), 0) END AS qty_available, CASE WHEN p.producttype <> 'I' OR p.isstocked = 'N' THEN 99999 ELSE COALESCE((SELECT sum(sdd.qtyonhand) AS sum FROM m_storage_detail sdd JOIN m_locator l ON sdd.m_locator_id = l.m_locator_id WHERE sdd.m_product_id = p.m_product_id AND l.m_warehouse_id = w.m_warehouse_id), 0) END AS qty_onhand, CASE WHEN p.producttype <> 'I' OR p.isstocked = 'N' THEN 0 ELSE COALESCE((SELECT sum(sp.qtyreserved) AS sum FROM m_storage_pending sp WHERE sp.m_product_id = p.m_product_id AND sp.m_warehouse_id = w.m_warehouse_id), 0) END AS qty_reserved, CASE WHEN p.producttype <> 'I' OR p.isstocked = 'N' THEN 0 ELSE COALESCE((SELECT sum(sp.qtyordered) AS sum FROM m_storage_pending sp WHERE sp.m_product_id = p.m_product_id AND sp.m_warehouse_id = w.m_warehouse_id), 0) END AS qty_ordered, pp.pricelist, pp.pricestd, pp.pricelimit, COALESCE(w.ad_org_id, '0') AS orgwarehouse FROM m_productprice pp LEFT JOIN m_warehouse w ON pp.ad_client_id = w.ad_client_id LEFT JOIN m_product p ON p.m_product_id = pp.m_product_id WHERE p.isgeneric = 'N' AND pp.isactive = 'Y' AND w.isactive = 'Y' AND p.isactive = 'Y']]></view>
   </database>
--- a/src-db/database/sourcedata/OBKMO_WIDGET_CLASS.xml	Wed Jun 01 13:42:08 2016 +0200
+++ b/src-db/database/sourcedata/OBKMO_WIDGET_CLASS.xml	Fri Jun 03 10:22:43 2016 +0200
@@ -13,6 +13,7 @@
 <!--7EE694CFF8B94B4C9B9CE69C9D292CC4-->  <WIDGET_SUPERCLASS_ID><![CDATA[2A32CF26F3F64FE39C7F94E9D82497D1]]></WIDGET_SUPERCLASS_ID>
 <!--7EE694CFF8B94B4C9B9CE69C9D292CC4-->  <CAN_MAXIMIZE><![CDATA[N]]></CAN_MAXIMIZE>
 <!--7EE694CFF8B94B4C9B9CE69C9D292CC4-->  <ACCESSLEVEL><![CDATA[3]]></ACCESSLEVEL>
+<!--7EE694CFF8B94B4C9B9CE69C9D292CC4-->  <AVAILABLE_IN_WORKSPACE><![CDATA[Y]]></AVAILABLE_IN_WORKSPACE>
 <!--7EE694CFF8B94B4C9B9CE69C9D292CC4--></OBKMO_WIDGET_CLASS>
 
 </data>
--- a/src-db/database/sourcedata/OBUISEL_SELECTOR.xml	Wed Jun 01 13:42:08 2016 +0200
+++ b/src-db/database/sourcedata/OBUISEL_SELECTOR.xml	Fri Jun 03 10:22:43 2016 +0200
@@ -1071,7 +1071,7 @@
 <!--F3CDEE79343F4746A2FEE8C60EBEC0BF-->  <NAME><![CDATA[Receipts]]></NAME>
 <!--F3CDEE79343F4746A2FEE8C60EBEC0BF-->  <AD_REFERENCE_ID><![CDATA[E68CCF4495A34ED7902293A930386B93]]></AD_REFERENCE_ID>
 <!--F3CDEE79343F4746A2FEE8C60EBEC0BF-->  <AD_TABLE_ID><![CDATA[319]]></AD_TABLE_ID>
-<!--F3CDEE79343F4746A2FEE8C60EBEC0BF-->  <WHERECLAUSE><![CDATA[e.salesTransaction = false AND e.documentStatus = 'CO' AND exists ( select 1 from MaterialMgmtShipmentInOutLine m where m.shipmentReceipt.id=e.id and m.movementQuantity >= 0 ) AND exists (select 1 from MaterialMgmtMaterialTransaction t, CostingRule r where t.goodsShipmentLine.shipmentReceipt.id=e.id and r.validated = 'Y' and ad_org_isinnaturaltree(r.organization.id, t.organization.id, t.client.id) = 'Y' and r.startingDate <= t.transactionProcessDate and r.endingDate is null ) ]]></WHERECLAUSE>
+<!--F3CDEE79343F4746A2FEE8C60EBEC0BF-->  <WHERECLAUSE><![CDATA[e.salesTransaction = false and e.documentStatus = 'CO' and exists (select 1 from MaterialMgmtShipmentInOutLine m where m.shipmentReceipt.id=e.id and m.movementQuantity >= 0) and exists (select 1 from MaterialMgmtMaterialTransaction t, CostingRule r where t.goodsShipmentLine.shipmentReceipt.id=e.id and r.validated = 'Y' and ad_org_isinnaturaltree(r.organization.id, t.organization.id, t.client.id) = 'Y' and r.endingDate is null and (r.startingDate is null or r.startingDate <= t.transactionProcessDate)) ]]></WHERECLAUSE>
 <!--F3CDEE79343F4746A2FEE8C60EBEC0BF-->  <OBCLKER_TEMPLATE_ID><![CDATA[9314DE8599AD44E7BFC4CC50699042AB]]></OBCLKER_TEMPLATE_ID>
 <!--F3CDEE79343F4746A2FEE8C60EBEC0BF-->  <ISACTIVE><![CDATA[Y]]></ISACTIVE>
 <!--F3CDEE79343F4746A2FEE8C60EBEC0BF-->  <SUGGESTIONTEXTMATCHSTYLE><![CDATA[startsWith]]></SUGGESTIONTEXTMATCHSTYLE>
--- a/src-test/src/org/openbravo/test/AllWebserviceTests.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src-test/src/org/openbravo/test/AllWebserviceTests.java	Fri Jun 03 10:22:43 2016 +0200
@@ -43,6 +43,7 @@
 import org.openbravo.test.webservice.WSUpdateTest;
 import org.openbravo.test.webservice.WSWithNoActiveDalObjects;
 import org.openbravo.test.webservice.WebServicesWithNoActiveFilterTest;
+import org.openbravo.test.webservice.JSONWebServicesWhereParameter;
 
 /**
  * This test suite should only contain test cases which are to run the webservices included in core.
@@ -74,6 +75,7 @@
     FetchDSNoActiveEntityObjects.class, //
     ExplicitCrossOrganizationReference.class, //
     DataSourceSecurity.class, //
-    EmptyStringWhereAndFilterClauseParameter.class })
+    EmptyStringWhereAndFilterClauseParameter.class, //
+    JSONWebServicesWhereParameter.class })
 public class AllWebserviceTests {
 }
--- a/src-test/src/org/openbravo/test/accounting/PostDocumentTest.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src-test/src/org/openbravo/test/accounting/PostDocumentTest.java	Fri Jun 03 10:22:43 2016 +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) 2015 Openbravo SLU 
+ * All portions are Copyright (C) 2015-2016 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -66,8 +66,6 @@
   private static final String ORGANIZATION_SPAIN_ID = "357947E87C284935AD1D783CF6F099A1";
   // Organization USA
   private static final String ORGANIZATION_USA_ID = "5EFF95EB540740A3B10510D9814EFAD5";
-  // Role QA Testing Admin
-  private final String ROLE_ID = "4028E6C72959682B01295A071429011E";
   // Table INVOICE
   private static final String TABLE_INVOICE = "318";
   // Table GL_JOURNAL
@@ -91,8 +89,6 @@
   private static final String GLJOURNAL_TEST7 = "F284DBAF46F244EB8CCA145A0CC47ACD";
   // G/L Journal Test with documentNo: 1003
   private static final String GLJOURNAL_TEST8 = "12857A9C03AD49D795F05A889CBEC0F2";
-  // G/L Journal Test with documentNo: 1004
-  private static final String GLJOURNAL_TEST9 = "8F27C4F6393A4457AA07E8D7754CEDF9";
   // ACCOUNTS USED FOR TEST RESULTS
   private static String TAX_RECEIVABLES = "FABD8D6CF3F04EE7A0389C2BAA1D620E";
   private static String SERVICE_COST = "F7B96292FB5842FBB51143BA659008B0";
@@ -109,8 +105,10 @@
   private static String PRETTY_CASH = "627A1291274F4BCF838588BB2F2102AD";
   private static String BANK_ACCOUNT = "58D66F384F7549D995523BF116F29BA0";
 
-  private String testNumber;
-  private String testDescription;
+  @SuppressWarnings("unused")
+  private String testNumber; // It is used to show the test number when the test is run.
+  @SuppressWarnings("unused")
+  private String testDescription; // It is used to show the test description when the test is run.
   private String keyId;
   private String tableId;
   private String orgId;
@@ -177,11 +175,6 @@
         { USA_DOLLAR_LEGDER, PRETTY_CASH, "03-06-2015", "100", "100.00", "0.00", "100.00", "0.00" },
         { MAIN_EURO_LEGDER, FONDO_SOCIAL, "03-06-2015", "100", "0.00", "100.00", "0.00", "200.00" },
         { MAIN_EURO_LEGDER, CAPITAL_SOCIAL, "03-06-2015", "100", "100.00", "0.00", "200.00", "0.00" } };
-    String[][] resultTest9 = {
-        { USA_DOLLAR_LEGDER, BANK_ACCOUNT, "03-06-2015", "100", "0.00", "100.00", "0.00", "100.00" },
-        { USA_DOLLAR_LEGDER, PRETTY_CASH, "03-06-2015", "100", "100.00", "0.00", "100.00", "0.00" },
-        { MAIN_EURO_LEGDER, FONDO_SOCIAL, "03-06-2015", "100", "0.00", "100.00", "0.00", "200.00" },
-        { MAIN_EURO_LEGDER, CAPITAL_SOCIAL, "03-06-2015", "100", "100.00", "0.00", "200.00", "0.00" } };
 
     return Arrays.asList(new Object[][] {
         { "1", "Sales invoice I/29", INVOICE_TEST1, TABLE_INVOICE, ORGANIZATION_SPAIN_ID,
--- a/src-test/src/org/openbravo/test/dal/IssuesTest.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src-test/src/org/openbravo/test/dal/IssuesTest.java	Fri Jun 03 10:22:43 2016 +0200
@@ -708,10 +708,7 @@
             + "WHERE AD_REF_LIST.AD_REFERENCE_ID = ?");
     query.setString(0, "en_US");
     query.setString(1, "800025");
-
-    @SuppressWarnings("unchecked")
-    java.util.List<Object[]> l = query.list();
-
+    query.list();
   }
 
   /**
@@ -894,9 +891,5 @@
     public boolean isErrorOccured() {
       return errorOccured;
     }
-
-    public void setErrorOccured(boolean errorOccured) {
-      this.errorOccured = errorOccured;
-    }
   }
 }
--- a/src-test/src/org/openbravo/test/db/model/functions/Ad_isorgincludedTest.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src-test/src/org/openbravo/test/db/model/functions/Ad_isorgincludedTest.java	Fri Jun 03 10:22:43 2016 +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) 2015 Openbravo SLU
+ * All portions are Copyright (C) 2015-2016 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -53,11 +53,6 @@
   private static final String ORG_A1 = "357947E87C284935AD1D783CF6F099A1";
 
   /**
-   * USA Organization
-   */
-  private static final String ORG_A2 = "5EFF95EB540740A3B10510D9814EFAD5";
-
-  /**
    * F&B International Group Client
    */
   private static final String CLIENT_B = "23C59575B9CF467C9620760EB255B389";
--- a/src-test/src/org/openbravo/test/security/AllowedOrganizationsTest.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src-test/src/org/openbravo/test/security/AllowedOrganizationsTest.java	Fri Jun 03 10:22:43 2016 +0200
@@ -25,6 +25,7 @@
 
 import java.util.Set;
 
+import org.junit.Ignore;
 import org.junit.Test;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.dal.core.OBContext;
@@ -50,27 +51,24 @@
    * Tests valid organizations trees for different organizations.
    */
   @Test
+  @Ignore("Fix test with new org tree map")
   public void testOrganizationTree() {
     setTestAdminContext();
-    // FIXME: Fix test with new org tree map
 
-    // final OrganizationStructureProvider osp = new OrganizationStructureProvider();
-    // osp.setClientId(TEST_CLIENT_ID);
-    //
-    // checkResult("1000001", osp, new String[] { "1000001" });
-    // checkResult("1000002", osp, new String[] { "1000003", "1000004", "1000000", "0", "1000002"
-    // });
-    // checkResult("1000003", osp, new String[] { "1000003", "1000000", "0", "1000002" });
-    // checkResult("1000004", osp, new String[] { "1000004", "1000000", "0", "1000002" });
-    // checkResult("1000005", osp, new String[] { "1000009", "1000006", "0", "1000000", "1000008",
-    // "1000005", "1000007" });
-    // checkResult("1000006", osp, new String[] { "1000009", "1000006", "0", "1000000", "1000008",
-    // "1000005" });
-    // checkResult("1000007", osp, new String[] { "1000000", "0", "1000005", "1000007" });
-    // checkResult("1000008", osp, new String[] { "1000000", "1000006", "0", "1000008", "1000005"
-    // });
-    // checkResult("1000009", osp, new String[] { "1000009", "1000006", "0", "1000000", "1000005"
-    // });
+    final OrganizationStructureProvider osp = new OrganizationStructureProvider();
+    osp.setClientId(TEST_CLIENT_ID);
+
+    checkResult("1000001", osp, new String[] { "1000001" });
+    checkResult("1000002", osp, new String[] { "1000003", "1000004", "1000000", "0", "1000002" });
+    checkResult("1000003", osp, new String[] { "1000003", "1000000", "0", "1000002" });
+    checkResult("1000004", osp, new String[] { "1000004", "1000000", "0", "1000002" });
+    checkResult("1000005", osp, new String[] { "1000009", "1000006", "0", "1000000", "1000008",
+        "1000005", "1000007" });
+    checkResult("1000006", osp, new String[] { "1000009", "1000006", "0", "1000000", "1000008",
+        "1000005" });
+    checkResult("1000007", osp, new String[] { "1000000", "0", "1000005", "1000007" });
+    checkResult("1000008", osp, new String[] { "1000000", "1000006", "0", "1000008", "1000005" });
+    checkResult("1000009", osp, new String[] { "1000009", "1000006", "0", "1000000", "1000005" });
   }
 
   private void checkResult(String id, OrganizationStructureProvider osp, String[] values) {
--- a/src-test/src/org/openbravo/test/services/ServicesTest.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src-test/src/org/openbravo/test/services/ServicesTest.java	Fri Jun 03 10:22:43 2016 +0200
@@ -92,10 +92,7 @@
       PARAMS);
 
   /** this field will take the values defined by parameterValuesRule field. */
-  private @ParameterCdiTest
-  ServiceTestData parameter;
-
-  private static int counterTest = 0;
+  private @ParameterCdiTest ServiceTestData parameter;
 
   /**
    * Verifies price computation for services. Add a relation line, update it and delete it. Review
@@ -191,7 +188,6 @@
           .getOrderlineServiceRelationCOrderlineRelatedIDList().size()),
           closeTo(BigDecimal.ZERO, BigDecimal.ZERO));
 
-      counterTest++;
     } catch (Exception e) {
       log.error("Error when executing: " + parameter.getTestDescription(), e);
       assertFalse(true);
--- a/src-test/src/org/openbravo/test/services/ServicesTest2.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src-test/src/org/openbravo/test/services/ServicesTest2.java	Fri Jun 03 10:22:43 2016 +0200
@@ -85,10 +85,7 @@
       PARAMS);
 
   /** this field will take the values defined by parameterValuesRule field. */
-  private @ParameterCdiTest
-  ServiceTestData parameter;
-
-  private static int counterTest = 0;
+  private @ParameterCdiTest ServiceTestData parameter;
 
   /**
    * Tests cases to check modifications on quantities of a sales order lines with related service
@@ -164,7 +161,6 @@
         }
       }
 
-      counterTest++;
     } catch (Exception e) {
       log.error("Error when executing: " + parameter.getTestDescription(), e);
       assertFalse(true);
--- a/src-test/src/org/openbravo/test/services/ServicesTest3.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src-test/src/org/openbravo/test/services/ServicesTest3.java	Fri Jun 03 10:22:43 2016 +0200
@@ -90,10 +90,7 @@
       PARAMS);
 
   /** this field will take the values defined by parameterValuesRule field. */
-  private @ParameterCdiTest
-  ServiceTestData parameter;
-
-  private static int counterTest = 0;
+  private @ParameterCdiTest ServiceTestData parameter;
 
   /**
    * Tests cases to check ServicePriceUtils.getServiceAmount method. All possible errors are
@@ -160,7 +157,6 @@
       }
 
       assertTrue("Not properly handled error obtained", error);
-      counterTest++;
     } catch (Exception e) {
       log.error("Error when executing: " + parameter.getTestDescription(), e);
       assertFalse(true);
--- a/src-test/src/org/openbravo/test/system/SystemValidatorTest.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src-test/src/org/openbravo/test/system/SystemValidatorTest.java	Fri Jun 03 10:22:43 2016 +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) 2009-2014 Openbravo SLU 
+ * All portions are Copyright (C) 2009-2016 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -21,22 +21,16 @@
 
 import static org.junit.Assert.fail;
 
-import java.io.File;
+import java.util.ArrayList;
 import java.util.List;
-import java.util.Properties;
 
-import org.apache.commons.dbcp.BasicDataSource;
-import org.apache.ddlutils.Platform;
-import org.apache.ddlutils.PlatformFactory;
-import org.apache.ddlutils.model.Database;
-import org.apache.ddlutils.platform.ExcludeFilter;
 import org.apache.log4j.Logger;
+import org.hibernate.Query;
+import org.hibernate.criterion.Restrictions;
 import org.junit.Test;
-import org.openbravo.base.session.OBPropertiesProvider;
+import org.openbravo.dal.service.OBCriteria;
 import org.openbravo.dal.service.OBDal;
-import org.openbravo.ddlutils.util.DBSMOBUtil;
 import org.openbravo.model.ad.module.Module;
-import org.openbravo.service.system.DatabaseValidator;
 import org.openbravo.service.system.ModuleValidator;
 import org.openbravo.service.system.SystemValidationResult;
 import org.openbravo.service.system.SystemValidationResult.SystemValidationType;
@@ -45,7 +39,6 @@
 /**
  * Tests System Validation.
  * 
- * @see DatabaseValidator
  * @see ModuleValidator
  * 
  * @author mtaal
@@ -56,83 +49,42 @@
   private static final Logger log = Logger.getLogger(SystemValidatorTest.class);
 
   /**
-   * Executes the {@link DatabaseValidator#validate()} method on the current database.
-   */
-  public void noTestSystemValidation() {
-    // disabled as covered by dbconsistency test and quite slow
-    setSystemAdministratorContext();
-    final DatabaseValidator databaseValidator = new DatabaseValidator();
-    databaseValidator.setDatabase(createDatabaseObject(null));
-    final SystemValidationResult result = databaseValidator.validate();
-    printResult(result, true);
-  }
-
-  /**
-   * Executes the {@link DatabaseValidator#validate()} method on the current database for all
-   * modules.
-   */
-  public void noTestSystemValidationModules() {
-    // disabled as covered by dbconsistency test and quite slow
-    setSystemAdministratorContext();
-    for (Module module : OBDal.getInstance().createQuery(Module.class, "").list()) {
-      final DatabaseValidator databaseValidator = new DatabaseValidator();
-      if (module.getModuleDBPrefixList().isEmpty()) {
-        // ignore these ones
-        continue;
-      }
-      databaseValidator.setDatabase(createDatabaseObject(module));
-      databaseValidator.setValidateModule(module);
-      final SystemValidationResult result = databaseValidator.validate();
-      printResult(result, false);
-    }
-  }
-
-  private Database createDatabaseObject(Module module) {
-    final Properties props = OBPropertiesProvider.getInstance().getOpenbravoProperties();
-
-    final BasicDataSource ds = new BasicDataSource();
-    ds.setDriverClassName(props.getProperty("bbdd.driver"));
-    if (props.getProperty("bbdd.rdbms").equals("POSTGRE")) {
-      ds.setUrl(props.getProperty("bbdd.url") + "/" + props.getProperty("bbdd.sid"));
-    } else {
-      ds.setUrl(props.getProperty("bbdd.url"));
-    }
-    ds.setUsername(props.getProperty("bbdd.user"));
-    ds.setPassword(props.getProperty("bbdd.password"));
-    Platform platform = PlatformFactory.createNewPlatformInstance(ds);
-    platform.getModelLoader().setOnlyLoadTableColumns(true);
-
-    if (module != null) {
-      final String dbPrefix = module.getModuleDBPrefixList().get(0).getName();
-      final ExcludeFilter filter = DBSMOBUtil.getInstance().getExcludeFilter(
-          new File(props.getProperty("source.path")));
-      filter.addPrefix(dbPrefix);
-
-      return platform.loadModelFromDatabase(filter, dbPrefix, true, module.getId());
-    }
-
-    return platform.loadModelFromDatabase(null);
-  }
-
-  /**
    * Performs module validation using the {@link ModuleValidator}.
    */
   @Test
   public void testModulesValidation() {
     setSystemAdministratorContext();
-    final ModuleValidator moduleValidator = new ModuleValidator();
-    final SystemValidationResult result = moduleValidator.validate();
-    printResult(result, true);
+    List<String> updatedModules = null;
+    try {
+      updatedModules = setModulesInDev();
+      final ModuleValidator moduleValidator = new ModuleValidator();
+      final SystemValidationResult result = moduleValidator.validate();
+      printResult(result, true);
+    } finally {
+      resetModules(updatedModules);
+    }
+  }
+
+  private List<String> setModulesInDev() {
+    List<String> updatedModules = new ArrayList<String>();
+    OBCriteria<Module> qModules = OBDal.getInstance().createCriteria(Module.class);
+    qModules.add(Restrictions.eq(Module.PROPERTY_INDEVELOPMENT, false));
+    for (Module mod : qModules.list()) {
+      mod.setInDevelopment(true);
+      updatedModules.add(mod.getId());
+    }
+    OBDal.getInstance().flush();
+    return updatedModules;
   }
 
   private void printResult(SystemValidationResult result, boolean allowFail) {
     for (SystemValidationType validationType : result.getWarnings().keySet()) {
-      log.debug("\n+++++++++++++++++++++++++++++++++++++++++++++++++++");
-      log.debug("Warnings for Validation type: " + validationType);
-      log.debug("\n+++++++++++++++++++++++++++++++++++++++++++++++++++");
+      log.warn("\n+++++++++++++++++++++++++++++++++++++++++++++++++++");
+      log.warn("Warnings for Validation type: " + validationType);
+      log.warn("\n+++++++++++++++++++++++++++++++++++++++++++++++++++");
       final List<String> warnings = result.getWarnings().get(validationType);
       for (String warning : warnings) {
-        log.debug(warning);
+        log.warn(warning);
       }
     }
 
@@ -148,11 +100,23 @@
           sb.append("\n");
         }
       }
-      if (allowFail && errors.size() > 0) {
-        fail(sb.toString());
-      }
     }
-    log.debug(sb.toString());
+    log.error(sb.toString());
+    if (allowFail && sb.length() > 0) {
+      fail(sb.toString());
+    }
   }
 
+  private void resetModules(List<String> updatedModules) {
+    if (updatedModules == null || updatedModules.isEmpty()) {
+      return;
+    }
+
+    Query upd = OBDal.getInstance().getSession()
+        .createQuery("update ADModule set inDevelopment = false where id in (:mods)");
+    upd.setParameterList("mods", updatedModules);
+    upd.executeUpdate();
+
+    OBDal.getInstance().flush();
+  }
 }
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src-test/src/org/openbravo/test/webservice/JSONWebServicesWhereParameter.java	Fri Jun 03 10:22:43 2016 +0200
@@ -0,0 +1,47 @@
+/*
+ *************************************************************************
+ * 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)2016 Openbravo SLU 
+ * All Rights Reserved. 
+ * Contributor(s):  ______________________________________.
+ ************************************************************************
+ */
+package org.openbravo.test.webservice;
+
+import static org.hamcrest.Matchers.equalTo;
+import static org.hamcrest.Matchers.is;
+import static org.junit.Assert.assertThat;
+
+import org.codehaus.jettison.json.JSONObject;
+import org.junit.Test;
+
+/**
+ * This test evaluates the correct behavior of a JSON webservice request using the "_where"
+ * parameter.
+ * 
+ * @author Naroa Iriarte
+ * 
+ */
+public class JSONWebServicesWhereParameter extends BaseWSTest {
+
+  @Test
+  public void WebserviceWithWhereParameter() throws Exception {
+    JSONWebServices jws = new JSONWebServices();
+    JSONObject resp = new JSONObject(jws.request("Country", null, "_where=name='Spain'", "GET"))
+        .getJSONObject("response");
+    JSONObject firstRecord = resp.getJSONArray("data").getJSONObject(0);
+    assertThat("Spanish Country", firstRecord.getString("_identifier"), is(equalTo("Spain")));
+    assertThat("Sucess status", resp.getInt("status"), is(0));
+    assertThat("Total Rows", resp.getInt("totalRows"), is(1));
+  }
+}
--- a/src-test/src/org/openbravo/test/xml/ClientExportImportTest.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src-test/src/org/openbravo/test/xml/ClientExportImportTest.java	Fri Jun 03 10:22:43 2016 +0200
@@ -108,6 +108,7 @@
    * 
    * Also tests mantis 9000: https://issues.openbravo.com/view.php?id=9000
    */
+  @SuppressWarnings("deprecation")
   @Ignore("This test has been temporarily disabled until the following issue related to the export client functionality is fixed: https://issues.openbravo.com/view.php?id=14848")
   @Test
   public void testExportImportClient1000000() {
@@ -115,12 +116,11 @@
     // This test has been temporarily disabled until the following issue related to the export
     // client functionality is fixed:
     // https://issues.openbravo.com/view.php?id=14848
-
-    // final String newClientId = exportImport(TEST_CLIENT_ID);
-    // testMantis8509(newClientId);
-    // testAccountingFactMantis9000(newClientId);
-    // testTreeNodesMantis9000(newClientId);
-    // SystemService.getInstance().removeAllClientData(newClientId);
+    final String newClientId = exportImport(TEST_CLIENT_ID);
+    testMantis8509(newClientId);
+    testAccountingFactMantis9000(newClientId);
+    testTreeNodesMantis9000(newClientId);
+    SystemService.getInstance().removeAllClientData(newClientId);
   }
 
   private void testTreeNodesMantis9000(String newClientID) {
--- a/src-test/src/org/openbravo/test/xml/XMLBaseTest.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src-test/src/org/openbravo/test/xml/XMLBaseTest.java	Fri Jun 03 10:22:43 2016 +0200
@@ -23,13 +23,14 @@
 
 import java.io.BufferedReader;
 import java.io.File;
-import java.io.FileReader;
 import java.io.StringReader;
 import java.net.URI;
 import java.net.URL;
 import java.util.ArrayList;
 import java.util.List;
 
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.io.LineIterator;
 import org.hibernate.criterion.Restrictions;
 import org.openbravo.base.exception.OBException;
 import org.openbravo.base.structure.BaseOBObject;
@@ -52,11 +53,12 @@
     try {
       final URL url = this.getClass().getResource("testdata/" + file);
       final File f = new File(new URI(url.toString()));
-      final BufferedReader r1 = new BufferedReader(new FileReader(f));
+      LineIterator li1 = FileUtils.lineIterator(f);
       final BufferedReader r2 = new BufferedReader(new StringReader(result));
       String line = null;
       int lineNo = 1;
-      while ((line = r1.readLine()) != null) {
+      while (li1.hasNext()) {
+        line = li1.nextLine();
         final String otherLine = r2.readLine();
         assertTrue("File: " + file + ": Lines are unequal: \n" + line + "\n" + otherLine
             + "\n Line number is " + lineNo, line.equals(otherLine));
@@ -71,16 +73,7 @@
     try {
       final URL url = this.getClass().getResource("testdata/" + file);
       final File f = new File(new URI(url.toString()));
-      final BufferedReader r1 = new BufferedReader(new FileReader(f));
-      final StringBuilder sb = new StringBuilder();
-      String line;
-      while ((line = r1.readLine()) != null) {
-        if (sb.length() > 0) {
-          sb.append("\n");
-        }
-        sb.append(line);
-      }
-      return sb.toString();
+      return FileUtils.readFileToString(f);
     } catch (final Exception e) {
       throw new OBException(e);
     }
Binary file src-util/buildvalidation/build/classes/org/openbravo/buildvalidation/DatabaseDecimalNumberCheck.class has changed
Binary file src-util/buildvalidation/build/classes/org/openbravo/buildvalidation/DatabaseDecimalNumberCheckData.class has changed
--- a/src-util/buildvalidation/src/org/openbravo/buildvalidation/DatabaseDecimalNumberCheck.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src-util/buildvalidation/src/org/openbravo/buildvalidation/DatabaseDecimalNumberCheck.java	Fri Jun 03 10:22:43 2016 +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) 2015 Openbravo SLU
+ * All portions are Copyright (C) 2015-2016 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -40,7 +40,12 @@
     ArrayList<String> errors = new ArrayList<String>();
     try {
       String numberString = new BigDecimal(ORIGINAL_NUMBER).toString();
-      String returnedNumber = DatabaseDecimalNumberCheckData.checkToNumber(cp, numberString);
+      String returnedNumber;
+      if (cp.getRDBMS().equalsIgnoreCase("POSTGRE")) {
+        returnedNumber = DatabaseDecimalNumberCheckData.checkToNumberPG(cp, numberString);
+      } else {
+        returnedNumber = DatabaseDecimalNumberCheckData.checkToNumberORA(cp, numberString);
+      }
       if (!ORIGINAL_NUMBER.equals(returnedNumber)) {
         errors.add("The decimal numbers are not being retrieved properly from the database. "
             + "This could be caused because the current database locale uses a decimal separator different from a period(.). "
--- a/src-util/buildvalidation/src/org/openbravo/buildvalidation/DatabaseDecimalNumberCheck_data.xsql	Wed Jun 01 13:42:08 2016 +0200
+++ b/src-util/buildvalidation/src/org/openbravo/buildvalidation/DatabaseDecimalNumberCheck_data.xsql	Fri Jun 03 10:22:43 2016 +0200
@@ -12,14 +12,23 @@
  * under the License.
  * The Original Code is Openbravo ERP.
  * The Initial Developer of the Original Code is Openbravo SLU
- * All portions are Copyright (C) 2015 Openbravo SLU
+ * All portions are Copyright (C) 2015-2016 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
 -->
 
 <SqlClass name="DatabaseDecimalNumberCheckData" package="org.openbravo.buildvalidation">
-  <SqlMethod name="checkToNumber" type="preparedStatement" return="String">
+  <SqlMethod name="checkToNumberPG" type="preparedStatement" return="String">
+      <Sql><![CDATA[
+         SELECT TO_NUMBER(?, 'S99D99') as NUM
+         FROM DUAL
+          ]]>
+      </Sql>
+      <Parameter name="number"/>
+  </SqlMethod>
+
+  <SqlMethod name="checkToNumberORA" type="preparedStatement" return="String">
       <Sql><![CDATA[
          SELECT TO_NUMBER(?) as NUM
          FROM DUAL
--- a/src-wad/src/org/openbravo/wad/ActionButtonJava_Responser.javaxml	Wed Jun 01 13:42:08 2016 +0200
+++ b/src-wad/src/org/openbravo/wad/ActionButtonJava_Responser.javaxml	Fri Jun 03 10:22:43 2016 +0200
@@ -42,6 +42,7 @@
 import javax.servlet.http.*;
 import java.util.HashMap;
 
+@SuppressWarnings("unused")
 public class ActionButtonJava_Responser extends HttpSecureAppServlet {
   private static final long serialVersionUID = 1L;
   protected static final String windowId = "ActionButtonResponser";
--- a/src-wad/src/org/openbravo/wad/ActionButton_Responser.javaxml	Wed Jun 01 13:42:08 2016 +0200
+++ b/src-wad/src/org/openbravo/wad/ActionButton_Responser.javaxml	Fri Jun 03 10:22:43 2016 +0200
@@ -41,6 +41,7 @@
 import javax.servlet.*;
 import javax.servlet.http.*;
 
+@SuppressWarnings("unused")
 public class ActionButton_Responser extends HttpSecureAppServlet {
   private static final long serialVersionUID = 1L;
   protected static final String windowId = "ActionButtonResponser";
--- a/src-wad/src/org/openbravo/wad/Tabs_data.xsql	Wed Jun 01 13:42:08 2016 +0200
+++ b/src-wad/src/org/openbravo/wad/Tabs_data.xsql	Fri Jun 03 10:22:43 2016 +0200
@@ -12,7 +12,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) 2001-2015 Openbravo SLU 
+ * All portions are Copyright (C) 2001-2016 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -295,7 +295,7 @@
         WHERE AD_TABLE.ad_table_id = AD_COLUMN.ad_table_id 
         AND iskey='Y' 
         AND AD_TABLE.ad_table_id = a2.ad_table_id) AS KEY, '' AS href, '' AS Td_Height, 
-        COALESCE(a1.ad_tab_id,'-1') AS Parent_Key, a2.isInfoTab, a2.isTranslationTab, AD_ShortName(a2.Name) as NameTab, 
+        COALESCE(a1.ad_tab_id,'-1') AS Parent_Key, a2.isInfoTab, a2.isTranslationTab, 
         a2.EDITREFERENCE, a2.AD_MODULE_ID as tabmodule
         FROM AD_TAB a1, AD_TAB a2
         WHERE a1.ad_tab_id = ?
--- a/src/org/openbravo/base/model/ModelProvider.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/base/model/ModelProvider.java	Fri Jun 03 10:22:43 2016 +0200
@@ -89,7 +89,6 @@
   private List<Module> modules;
   private Session initsession;
 
-  private static final String DATASOURCEBASEDTABLE = "Datasource";
   private static final String TABLEBASEDTABLE = "Table";
 
   /**
--- a/src/org/openbravo/base/secureApp/Attribute_data.xsql	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/base/secureApp/Attribute_data.xsql	Fri Jun 03 10:22:43 2016 +0200
@@ -1,7 +1,7 @@
 <?xml version="1.0" encoding="UTF-8" ?>
 <!--
  ************************************************************************************
- * Copyright (C) 2001-2011 Openbravo S.L.U.
+ * Copyright (C) 2001-2016 Openbravo S.L.U.
  * Licensed under the Apache Software License version 2.0
  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
  * Unless required by applicable law or agreed to  in writing,  software  distributed
@@ -29,6 +29,21 @@
       <Parameter name="clientlist" optional="true" type="replace" after="AND a.AD_CLIENT_ID IN (" text="'1'"/>
       <Parameter name="orglist" optional="true" type="replace" after="AND a.AD_ORG_ID IN (" text="'1'"/>
    </SqlMethod>
+   <SqlMethod name="selectAcctSchema" type="preparedStatement" return="multiple">
+      <SqlMethodComment></SqlMethodComment>
+      <Sql><![CDATA[
+        SELECT a.C_ACCTSCHEMA_ID as VALUE, a.C_CURRENCY_ID as Attribute, a.HASALIAS,
+        ae.ELEMENTTYPE, '' as AD_Window_ID, '' as C_CURRENCY_ID
+        FROM C_AcctSchema a
+        JOIN C_AcctSchema_Element ae
+        ON a.C_AcctSchema_ID=ae.C_ACCTSCHEMA_ID
+        WHERE a.C_AcctSchema_ID = ?
+        AND a.AD_CLIENT_ID IN ('1')
+        AND ae.ISACTIVE = 'Y'
+      ]]></Sql>
+      <Parameter name="acctId"/>
+      <Parameter name="clientlist" optional="true" type="replace" after="AND a.AD_CLIENT_ID IN (" text="'1'"/>
+   </SqlMethod>
    <SqlMethod name="selectIsSOTrx" type="preparedStatement" return="multiple">
       <SqlMethodComment></SqlMethodComment>
       <Sql>
--- a/src/org/openbravo/base/secureApp/HttpSecureAppServlet.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/base/secureApp/HttpSecureAppServlet.java	Fri Jun 03 10:22:43 2016 +0200
@@ -1165,8 +1165,13 @@
       String strReportName, String strFileName, String strOutputType,
       HashMap<String, Object> designParameters, JRDataSource data,
       Map<Object, Object> exportParameters, boolean forceRefresh) throws ServletException {
-    if (strReportName == null || strReportName.equals(""))
-      strReportName = PrintJRData.getReportName(this, classInfo.id);
+    String localStrReportName = strReportName;
+    String localStrOutputType = strOutputType;
+    String localStrFileName = strFileName;
+    Map<Object, Object> localExportParameters = exportParameters;
+    HashMap<String, Object> localDesignParameters = designParameters;
+    if (localStrReportName == null || localStrReportName.equals(""))
+      localStrReportName = PrintJRData.getReportName(this, classInfo.id);
 
     final String strAttach = globalParameters.strFTPDirectory + "/284-" + classInfo.id;
 
@@ -1175,26 +1180,27 @@
 
     final String strBaseDesign = getBaseDesignPath(strLanguage);
 
-    strReportName = Replace.replace(Replace.replace(strReportName, "@basedesign@", strBaseDesign),
-        "@attach@", strAttach);
-    if (strFileName == null) {
-      strFileName = strReportName.substring(strReportName.lastIndexOf("/") + 1);
+    localStrReportName = Replace.replace(
+        Replace.replace(localStrReportName, "@basedesign@", strBaseDesign), "@attach@", strAttach);
+    if (localStrFileName == null) {
+      localStrFileName = localStrReportName.substring(localStrReportName.lastIndexOf("/") + 1);
     }
 
     ServletOutputStream os = null;
     UUID reportId = null;
     try {
-      if (designParameters == null)
-        designParameters = new HashMap<String, Object>();
+      if (localDesignParameters == null)
+        localDesignParameters = new HashMap<String, Object>();
 
-      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);
-      designParameters.put("REPORT_TITLE",
+      localDesignParameters.put("BASE_WEB", strReplaceWithFull);
+      localDesignParameters.put("BASE_DESIGN", strBaseDesign);
+      localDesignParameters.put("ATTACH", strAttach);
+      localDesignParameters.put("USER_CLIENT",
+          Utility.getContext(this, variables, "#User_Client", ""));
+      localDesignParameters.put("USER_ORG", Utility.getContext(this, variables, "#User_Org", ""));
+      localDesignParameters.put("LANGUAGE", strLanguage);
+      localDesignParameters.put("LOCALE", locLocale);
+      localDesignParameters.put("REPORT_TITLE",
           PrintJRData.getReportTitle(this, variables.getLanguage(), classInfo.id));
 
       final DecimalFormatSymbols dfs = new DecimalFormatSymbols();
@@ -1202,53 +1208,55 @@
       dfs.setGroupingSeparator(variables.getSessionValue("#AD_ReportGroupingSeparator").charAt(0));
       final DecimalFormat numberFormat = new DecimalFormat(
           variables.getSessionValue("#AD_ReportNumberFormat"), dfs);
-      designParameters.put("NUMBERFORMAT", numberFormat);
+      localDesignParameters.put("NUMBERFORMAT", numberFormat);
 
       os = response.getOutputStream();
-      if (exportParameters == null)
-        exportParameters = new HashMap<Object, Object>();
-      if (strOutputType == null || strOutputType.equals(""))
-        strOutputType = "html";
-      final ExportType expType = ExportType.getExportType(strOutputType.toUpperCase());
+      if (localExportParameters == null)
+        localExportParameters = new HashMap<Object, Object>();
+      if (localStrOutputType == null || localStrOutputType.equals(""))
+        localStrOutputType = "html";
+      final ExportType expType = ExportType.getExportType(localStrOutputType.toUpperCase());
 
-      if (strOutputType.equals("html")) {
+      if (localStrOutputType.equals("html")) {
         if (log4j.isDebugEnabled())
           log4j.debug("JR: Print HTML");
-        response.setHeader("Content-disposition", "inline" + "; filename=" + strFileName + "."
-            + strOutputType);
+        response.setHeader("Content-disposition", "inline" + "; filename=" + localStrFileName + "."
+            + localStrOutputType);
         HttpServletRequest request = RequestContext.get().getRequest();
         String localAddress = HttpBaseUtils.getLocalAddress(request);
-        exportParameters.put(ReportingUtils.IMAGES_URI, localAddress + "/servlets/image?image={0}");
-        ReportingUtils.exportJR(strReportName, expType, designParameters, os, false, this, data,
-            exportParameters);
-      } else if (strOutputType.equals("pdf") || strOutputType.equalsIgnoreCase("xls")
-          || strOutputType.equalsIgnoreCase("txt") || strOutputType.equalsIgnoreCase("csv")) {
+        localExportParameters.put(ReportingUtils.IMAGES_URI, localAddress
+            + "/servlets/image?image={0}");
+        ReportingUtils.exportJR(localStrReportName, expType, localDesignParameters, os, false,
+            this, data, localExportParameters);
+      } else if (localStrOutputType.equals("pdf") || localStrOutputType.equalsIgnoreCase("xls")
+          || localStrOutputType.equalsIgnoreCase("txt")
+          || localStrOutputType.equalsIgnoreCase("csv")) {
         reportId = UUID.randomUUID();
-        File outputFile = new File(globalParameters.strFTPDirectory + "/" + strFileName + "-"
-            + (reportId) + "." + strOutputType);
-        ReportingUtils.exportJR(strReportName, expType, designParameters, outputFile, false, this,
-            data, exportParameters);
+        File outputFile = new File(globalParameters.strFTPDirectory + "/" + localStrFileName + "-"
+            + (reportId) + "." + localStrOutputType);
+        ReportingUtils.exportJR(localStrReportName, expType, localDesignParameters, outputFile,
+            false, this, data, localExportParameters);
         response.setContentType("text/html;charset=UTF-8");
-        response.setHeader("Content-disposition", "inline" + "; filename=" + strFileName + "-"
+        response.setHeader("Content-disposition", "inline" + "; filename=" + localStrFileName + "-"
             + (reportId) + ".html");
         if (forceRefresh) {
-          printPagePopUpDownloadAndRefresh(response.getOutputStream(), strFileName + "-"
-              + (reportId) + "." + strOutputType);
+          printPagePopUpDownloadAndRefresh(response.getOutputStream(), localStrFileName + "-"
+              + (reportId) + "." + localStrOutputType);
         } else {
-          printPagePopUpDownload(response.getOutputStream(), strFileName + "-" + (reportId) + "."
-              + strOutputType);
+          printPagePopUpDownload(response.getOutputStream(), localStrFileName + "-" + (reportId)
+              + "." + localStrOutputType);
         }
       }
 
     } catch (IOException ioe) {
       try {
-        FileUtility f = new FileUtility(globalParameters.strFTPDirectory, strFileName + "-"
-            + (reportId) + "." + strOutputType, false, true);
+        FileUtility f = new FileUtility(globalParameters.strFTPDirectory, localStrFileName + "-"
+            + (reportId) + "." + localStrOutputType, false, true);
         if (f.exists())
           f.deleteFile();
       } catch (IOException ioex) {
-        log4j.error("Error trying to delete temporary report file " + strFileName + "-"
-            + (reportId) + "." + strOutputType + " : " + ioex.getMessage());
+        log4j.error("Error trying to delete temporary report file " + localStrFileName + "-"
+            + (reportId) + "." + localStrOutputType + " : " + ioex.getMessage());
       }
     } catch (final Exception e) {
       throw new ServletException(e.getMessage(), e);
--- a/src/org/openbravo/base/secureApp/LoginHandler.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/base/secureApp/LoginHandler.java	Fri Jun 03 10:22:43 2016 +0200
@@ -563,8 +563,6 @@
    *          the userId
    * @param unHashedPassword
    *          the password, the unhashed password as it is entered by the user.
-   * @param myPool
-   *          ConnectionProvider used to translate messages.
    * @param language
    *          Default language for the user
    * @throws ServletException
--- a/src/org/openbravo/base/secureApp/LoginUtils.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/base/secureApp/LoginUtils.java	Fri Jun 03 10:22:43 2016 +0200
@@ -21,6 +21,8 @@
 import javax.xml.parsers.DocumentBuilder;
 import javax.xml.parsers.DocumentBuilderFactory;
 
+import org.apache.commons.lang.ArrayUtils;
+import org.apache.commons.lang.StringUtils;
 import org.apache.log4j.Logger;
 import org.openbravo.base.HttpBaseUtils;
 import org.openbravo.base.exception.OBException;
@@ -32,6 +34,7 @@
 import org.openbravo.erpCommon.businessUtility.Preferences;
 import org.openbravo.erpCommon.security.SessionLogin;
 import org.openbravo.erpCommon.utility.DimensionDisplayUtility;
+import org.openbravo.erpCommon.utility.OBLedgerUtils;
 import org.openbravo.erpCommon.utility.PropertyException;
 import org.openbravo.erpCommon.utility.Utility;
 import org.openbravo.model.ad.access.RoleOrganization;
@@ -125,8 +128,9 @@
       throws ServletException {
     boolean valid = SeguridadData.isRoleClient(conn, role, client);
     if (!valid) {
-      log4j
-          .error("Login client is not in role clients list. Role: " + role + ", Client: " + client);
+      log4j.error(
+          "Login client is not in role clients list. Role: " + role + ", Client: " + client,
+          new Exception("stack trace"));
     }
     return valid;
   }
@@ -136,7 +140,7 @@
     boolean valid = SeguridadData.isLoginRoleOrg(conn, role, org);
     if (!valid) {
       log4j.error("Login organization is not in role organizations list. Role: " + role + ", Org: "
-          + org);
+          + org, new Exception("stack trace"));
     }
     return valid;
   }
@@ -272,9 +276,19 @@
       vars.setSessionValue("#Client_SMTP", data[0].smtphost);
       data = null;
 
-      AttributeData[] attr = AttributeData.select(conn,
-          Utility.getContext(conn, vars, "#User_Client", "LoginHandler"),
-          Utility.getContext(conn, vars, "#User_Org", "LoginHandler"));
+      AttributeData[] attr = null;
+      String[] orgList = Utility.getContext(conn, vars, "#User_Org", "LoginHandler").split(",");
+      for (String orgId : orgList) {
+        String acctSchemaId = OBLedgerUtils.getOrgLedger(orgId.replace("'", ""));
+        if (StringUtils.isNotEmpty(acctSchemaId)) {
+          attr = AttributeData.selectAcctSchema(conn, acctSchemaId,
+              Utility.getContext(conn, vars, "#User_Client", "LoginHandler"));
+          if (ArrayUtils.isNotEmpty(attr)) {
+            break;
+          }
+        }
+      }
+
       if (attr != null && attr.length > 0) {
         vars.setSessionValue("$C_AcctSchema_ID", attr[0].value);
         if (orgCurrency.length > 0) {
--- a/src/org/openbravo/base/secureApp/OrgTreeNode.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/base/secureApp/OrgTreeNode.java	Fri Jun 03 10:22:43 2016 +0200
@@ -1,6 +1,6 @@
 /*
  ************************************************************************************
- * Copyright (C) 2008-2010 Openbravo S.L.U.
+ * Copyright (C) 2008-2016 Openbravo S.L.U.
  * Licensed under the Apache Software License version 2.0
  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
  * Unless required by applicable law or agreed to  in writing,  software  distributed
@@ -30,7 +30,6 @@
   private String value;
   private String isReady;
   private OrganizationType orgType;
-  private String serializedOrgTypeId;
 
   /**
    * Creates a node from data related to it
@@ -65,7 +64,6 @@
   // only be deserialized if they are connected to the db because some
   // of the references maybe a cglib proxy
   private void writeObject(ObjectOutputStream out) throws IOException {
-    serializedOrgTypeId = orgType.getId();
     orgType = null;
     out.defaultWriteObject();
   }
--- a/src/org/openbravo/base/secureApp/VariablesSecureApp.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/base/secureApp/VariablesSecureApp.java	Fri Jun 03 10:22:43 2016 +0200
@@ -1,6 +1,6 @@
 /*
  ************************************************************************************
- * Copyright (C) 2001-2012 Openbravo S.L.U.
+ * Copyright (C) 2001-2016 Openbravo S.L.U.
  * Licensed under the Apache Software License version 2.0
  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
  * Unless required by applicable law or agreed to  in writing,  software  distributed
@@ -22,6 +22,7 @@
 import org.openbravo.erpCommon.utility.OBError;
 import org.openbravo.model.ad.system.Client;
 import org.openbravo.scheduling.OBScheduler;
+import org.quartz.SchedulerException;
 
 /**
  * This class is used to provide the coder with friendly methods to retrieve certain environment,
@@ -41,7 +42,6 @@
   private String warehouse;
   private String command;
   private String userClient;
-  private String userOrganization;
   private String dbSessionID;
   private String javaDateFormat;
   private String javaDataTimeFormat;
@@ -70,7 +70,6 @@
     this.client = strClient;
     this.organization = strOrganization;
     this.userClient = "";
-    this.userOrganization = "";
     this.warehouse = "";
     this.dbSessionID = "";
     this.command = "DEFAULT";
@@ -129,7 +128,6 @@
     this.client = strClient;
     this.organization = strOrganization;
     this.userClient = "";
-    this.userOrganization = "";
     this.warehouse = "";
     this.dbSessionID = "";
     this.command = "DEFAULT";
@@ -175,7 +173,6 @@
     this.client = getSessionValue("#AD_Client_ID");
     this.organization = getSessionValue("#AD_Org_ID");
     this.userClient = getSessionValue("#User_Client");
-    this.userOrganization = getSessionValue("#User_Org");
     this.warehouse = getSessionValue("#M_Warehouse_ID");
     this.dbSessionID = getSessionValue("#AD_Session_ID");
     this.command = getStringParameter("Command", "DEFAULT");
@@ -228,7 +225,8 @@
     } else {
       String strTheme = "";
       try {
-        if (OBScheduler.getInstance().getScheduler().isStarted()) {
+        if (OBScheduler.getInstance().getScheduler() != null
+            && OBScheduler.getInstance().getScheduler().isStarted()) {
           Client systemClient = OBDal.getInstance().get(Client.class, "0");
 
           // Get theme (skin)
@@ -248,12 +246,14 @@
             OBContext.restorePreviousMode();
           }
         }
+      } catch (SchedulerException e) {
+        log4j.error("Error while checking if the scheduler is started.", e);
       } finally {
         if (strTheme.isEmpty()) {
           strTheme = "ltr/org.openbravo.userinterface.skin.250to300Comp/250to300Comp";
         }
-        return strTheme;
       }
+      return strTheme;
     }
   }
 
--- a/src/org/openbravo/common/datasource/StockReservationPickAndEditDataSource.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/common/datasource/StockReservationPickAndEditDataSource.java	Fri Jun 03 10:22:43 2016 +0200
@@ -1628,21 +1628,6 @@
     return (BigDecimal) query.uniqueResult();
   }
 
-  private BigDecimal getQtyReserved(Reservation reservation, StorageDetail sd) {
-    final StringBuilder hqlString = new StringBuilder();
-    hqlString
-        .append("select coalesce(sum(rs.quantity - coalesce(rs.released,0)),0) from MaterialMgmtReservationStock rs ");
-    hqlString.append("join rs.reservation as r ");
-    hqlString.append(" where r.rESStatus not in ('CL', 'DR') ");
-    hqlString.append(" and rs.storageDetail = :storageDetail ");
-    hqlString.append(" and r <> :reservation ");
-    final Session session = OBDal.getInstance().getSession();
-    Query query = session.createQuery(hqlString.toString());
-    query.setParameter("storageDetail", sd);
-    query.setParameter("reservation", reservation);
-    return (BigDecimal) query.uniqueResult();
-  }
-
   private BigDecimal getQtyReserved(Reservation reservation, Product product,
       AttributeSetInstance attribute, Locator storageBin) {
     final StringBuilder hqlString = new StringBuilder();
--- a/src/org/openbravo/costing/CostingAlgorithm.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/costing/CostingAlgorithm.java	Fri Jun 03 10:22:43 2016 +0200
@@ -297,7 +297,6 @@
 
     if (ppDate.before(olDate) && stdCostDate.before(olDate)) {
       // purchase order
-      @SuppressWarnings("null")
       BigDecimal cost = transaction.getMovementQuantity().abs().multiply(orderLine.getUnitPrice());
       if (costCurrency.getId().equals(orderLine.getCurrency().getId())) {
         return cost;
--- a/src/org/openbravo/costing/InventoryAmountUpdateProcess.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/costing/InventoryAmountUpdateProcess.java	Fri Jun 03 10:22:43 2016 +0200
@@ -248,6 +248,7 @@
 
   private ScrollableResults getStockLines(Set<String> childOrgs, Date date, Product product,
       Warehouse warehouse, boolean backdatedTransactionsFixed) {
+    Date localDate = date;
     StringBuffer select = new StringBuffer();
     StringBuffer subSelect = new StringBuffer();
 
@@ -261,7 +262,7 @@
     select.append(" from " + MaterialTransaction.ENTITY_NAME + " as trx");
     select.append("    join trx." + MaterialTransaction.PROPERTY_STORAGEBIN + " as loc");
     select.append(" where trx." + MaterialTransaction.PROPERTY_ORGANIZATION + ".id in (:orgs)");
-    if (date != null) {
+    if (localDate != null) {
       if (backdatedTransactionsFixed) {
         select.append("   and trx." + MaterialTransaction.PROPERTY_MOVEMENTDATE + " <= :date");
       } else {
@@ -283,7 +284,7 @@
             + ".id in (:orgs)");
 
         Query trxsubQry = OBDal.getInstance().getSession().createQuery(subSelect.toString());
-        trxsubQry.setParameter("date", date);
+        trxsubQry.setParameter("date", localDate);
         trxsubQry.setParameter("product", product.getId());
         if (warehouse != null) {
           trxsubQry.setParameter("warehouse", warehouse.getId());
@@ -291,7 +292,7 @@
         trxsubQry.setParameterList("orgs", childOrgs);
         Object trxprocessDate = trxsubQry.uniqueResult();
         if (trxprocessDate != null) {
-          date = (Date) trxprocessDate;
+          localDate = (Date) trxprocessDate;
           select.append("   and trx." + MaterialTransaction.PROPERTY_TRANSACTIONPROCESSDATE
               + " < :date");
         } else {
@@ -318,8 +319,8 @@
 
     Query stockLinesQry = OBDal.getInstance().getSession().createQuery(select.toString());
     stockLinesQry.setParameterList("orgs", childOrgs);
-    if (date != null) {
-      stockLinesQry.setTimestamp("date", date);
+    if (localDate != null) {
+      stockLinesQry.setTimestamp("date", localDate);
     }
     if (warehouse != null) {
       stockLinesQry.setParameter("warehouse", warehouse);
--- a/src/org/openbravo/costing/LCCostMatchFromInvoiceHandler.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/costing/LCCostMatchFromInvoiceHandler.java	Fri Jun 03 10:22:43 2016 +0200
@@ -99,6 +99,7 @@
 
   private JSONObject processSelectedLines(InvoiceLine il, JSONArray selectedLines,
       List<String> existingMatchings) throws JSONException {
+    InvoiceLine localIl = il;
     JSONObject message = null;
     for (int i = 0; i < selectedLines.length(); i++) {
       JSONObject line = selectedLines.getJSONObject(i);
@@ -116,7 +117,7 @@
         match = OBProvider.getInstance().get(LCMatched.class);
         match.setOrganization(lcc.getOrganization());
         match.setLandedCostCost(lcc);
-        match.setInvoiceLine(il);
+        match.setInvoiceLine(localIl);
         match.setAmount(BigDecimal.ZERO);
       } else {
         // Update existing record.
@@ -131,8 +132,8 @@
       BigDecimal amount = new BigDecimal(line.getString("matchedAmt"));
       if (amount.compareTo(match.getAmount()) != 0) {
         match.setAmountInInvoiceCurrency(amount);
-        if (lcc.getCurrency() != il.getInvoice().getCurrency()) {
-          amount = FinancialUtils.getConvertedAmount(amount, il.getInvoice().getCurrency(),
+        if (lcc.getCurrency() != localIl.getInvoice().getCurrency()) {
+          amount = FinancialUtils.getConvertedAmount(amount, localIl.getInvoice().getCurrency(),
               lcc.getCurrency(), lcc.getAccountingDate(), lcc.getOrganization(),
               FinancialUtils.PRECISION_STANDARD);
         }
@@ -149,7 +150,8 @@
 
       final OBCriteria<ConversionRateDoc> conversionRateDoc = OBDal.getInstance().createCriteria(
           ConversionRateDoc.class);
-      conversionRateDoc.add(Restrictions.eq(ConversionRateDoc.PROPERTY_INVOICE, il.getInvoice()));
+      conversionRateDoc.add(Restrictions.eq(ConversionRateDoc.PROPERTY_INVOICE,
+          localIl.getInvoice()));
       ConversionRateDoc invoiceconversionrate = (ConversionRateDoc) conversionRateDoc
           .uniqueResult();
 
@@ -169,7 +171,7 @@
         lcmCm.setOrganization(lcc.getOrganization());
         lcmCm.setLandedCostCost(lcc);
         lcmCm.setAmount(amount);
-        lcmCm.setInvoiceLine(il);
+        lcmCm.setInvoiceLine(localIl);
         lcmCm.setConversionmatching(true);
         OBDal.getInstance().save(lcmCm);
 
@@ -185,8 +187,8 @@
     // Delete unselected matches
     if (!existingMatchings.isEmpty()) {
       LandedCostCost lcCost = null;
-      il = OBDal.getInstance().get(InvoiceLine.class, il.getId());
-      OBDal.getInstance().refresh(il);
+      localIl = OBDal.getInstance().get(InvoiceLine.class, localIl.getId());
+      OBDal.getInstance().refresh(localIl);
 
       for (String strLCMatchId : existingMatchings) {
         LCMatched matchToRemove = OBDal.getInstance().get(LCMatched.class, strLCMatchId);
@@ -195,11 +197,11 @@
         lcCost = OBDal.getInstance().get(LandedCostCost.class,
             matchToRemove.getLandedCostCost().getId());
         lcCost.getLandedCostMatchedList().remove(matchToRemove);
-        il.getLandedCostCostList().remove(matchToRemove);
+        localIl.getLandedCostCostList().remove(matchToRemove);
         OBDal.getInstance().save(lcCost);
         OBDal.getInstance().remove(matchToRemove);
       }
-      OBDal.getInstance().save(il);
+      OBDal.getInstance().save(localIl);
     }
     return message;
   }
--- a/src/org/openbravo/costing/LandedCostDistributionByAmount.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/costing/LandedCostDistributionByAmount.java	Fri Jun 03 10:22:43 2016 +0200
@@ -45,19 +45,20 @@
   @Override
   public void distributeAmount(LandedCostCost lcCost, boolean isMatching) {
     // Calculate total amount of all receipt lines assigned to the landed cost.
-    lcCost = (LandedCostCost) OBDal.getInstance().getProxy(LandedCostCost.ENTITY_NAME,
-        lcCost.getId());
-    LandedCost landedCost = lcCost.getLandedCost();
+    LandedCostCost localLcCost = lcCost;
+    localLcCost = (LandedCostCost) OBDal.getInstance().getProxy(LandedCostCost.ENTITY_NAME,
+        localLcCost.getId());
+    LandedCost landedCost = localLcCost.getLandedCost();
     // Get the currency of the Landed Cost Cost
-    String strCurId = lcCost.getCurrency().getId();
+    String strCurId = localLcCost.getCurrency().getId();
     String strOrgId = landedCost.getOrganization().getId();
     Date dateReference = landedCost.getReferenceDate();
-    int precission = lcCost.getCurrency().getCostingPrecision().intValue();
+    int precission = localLcCost.getCurrency().getCostingPrecision().intValue();
     BigDecimal baseAmt;
     if (isMatching) {
-      baseAmt = lcCost.getMatchingAmount().subtract(lcCost.getAmount());
+      baseAmt = localLcCost.getMatchingAmount().subtract(localLcCost.getAmount());
     } else {
-      baseAmt = lcCost.getAmount();
+      baseAmt = localLcCost.getAmount();
     }
 
     BigDecimal totalAmt = BigDecimal.ZERO;
@@ -113,14 +114,14 @@
           receiptCosts.get()[0]);
       LCReceiptLineAmt lcrla = OBProvider.getInstance().get(LCReceiptLineAmt.class);
       lcrla.setLandedCostCost((LandedCostCost) OBDal.getInstance().getProxy(
-          LandedCostCost.ENTITY_NAME, lcCost.getId()));
-      lcCost = (LandedCostCost) OBDal.getInstance().getProxy(LandedCostCost.ENTITY_NAME,
-          lcCost.getId());
+          LandedCostCost.ENTITY_NAME, localLcCost.getId()));
+      localLcCost = (LandedCostCost) OBDal.getInstance().getProxy(LandedCostCost.ENTITY_NAME,
+          localLcCost.getId());
       lcrla.setLandedCostReceipt(lcrl);
       lcrla.setGoodsShipmentLine(receiptline);
       lcrla.setMatchingAdjustment(isMatching);
       lcrla.setAmount(receiptAmt);
-      lcrla.setOrganization(lcCost.getOrganization());
+      lcrla.setOrganization(localLcCost.getOrganization());
       OBDal.getInstance().save(lcrla);
       if (i % 100 == 0) {
         OBDal.getInstance().flush();
--- a/src/org/openbravo/costing/ReactivateLandedCost.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/costing/ReactivateLandedCost.java	Fri Jun 03 10:22:43 2016 +0200
@@ -73,12 +73,13 @@
 
   public static JSONObject doReactivateLandedCost(LandedCost landedCost) throws OBException,
       JSONException {
-    String strLCostId = landedCost.getId();
+    LandedCost localLandedCost = landedCost;
+    String strLCostId = localLandedCost.getId();
     JSONObject message = null;
 
     // Cancel cost adjustment only if exists
-    if (landedCost.getCostAdjustment() != null) {
-      message = CancelCostAdjustment.doCancelCostAdjustment(landedCost.getCostAdjustment());
+    if (localLandedCost.getCostAdjustment() != null) {
+      message = CancelCostAdjustment.doCancelCostAdjustment(localLandedCost.getCostAdjustment());
       if (!"success".equals(message.get("severity"))) {
         return message;
       }
@@ -90,11 +91,11 @@
 
     String strPartialMessage = "";
     // Reload in case the cancel cost adjustment has cleared the session.
-    landedCost = OBDal.getInstance().get(LandedCost.class, strLCostId);
-    landedCost.setProcessed(Boolean.FALSE);
-    OBDal.getInstance().save(landedCost);
+    localLandedCost = OBDal.getInstance().get(LandedCost.class, strLCostId);
+    localLandedCost.setProcessed(Boolean.FALSE);
+    OBDal.getInstance().save(localLandedCost);
     OBDal.getInstance().flush();
-    for (LandedCostCost lcc : landedCost.getLandedCostCostList()) {
+    for (LandedCostCost lcc : localLandedCost.getLandedCostCostList()) {
       if (lcc.isMatched()) {
         message = LCMatchingCancelHandler.doCancelMatchingLandedCost(lcc.getId());
       }
@@ -116,10 +117,10 @@
     }
 
     // Reload in case the cancel cost adjustment has cleared the session.
-    landedCost = OBDal.getInstance().get(LandedCost.class, strLCostId);
-    landedCost.setDocumentStatus("DR");
-    landedCost.setCostAdjustment(null);
-    OBDal.getInstance().save(landedCost);
+    localLandedCost = OBDal.getInstance().get(LandedCost.class, strLCostId);
+    localLandedCost.setDocumentStatus("DR");
+    localLandedCost.setCostAdjustment(null);
+    OBDal.getInstance().save(localLandedCost);
 
     message.put("title", OBMessageUtils.messageBD("Success"));
     message.put("text", strPartialMessage);
--- a/src/org/openbravo/costing/StandardCostAdjustment.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/costing/StandardCostAdjustment.java	Fri Jun 03 10:22:43 2016 +0200
@@ -124,8 +124,6 @@
   /**
    * Returns transactions with movement/process date after trx and before next Inventory Amount
    * Update
-   * 
-   * @return
    */
   private ScrollableResults getLaterTransactions(MaterialTransaction trx) {
 
@@ -231,8 +229,6 @@
   /**
    * Returns opening physical inventory transactions created by a Inventory Amount Update and
    * created after trx
-   * 
-   * @return
    */
   private ScrollableResults getLaterOpeningTransactions(MaterialTransaction trx) {
 
--- a/src/org/openbravo/dal/xml/EntityResolver.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/dal/xml/EntityResolver.java	Fri Jun 03 10:22:43 2016 +0200
@@ -94,7 +94,6 @@
   private Organization organization;
   private String[] orgNaturalTree;
   private ResolvingMode resolvingMode = ResolvingMode.ALLOW_NOT_EXIST;
-  private boolean lookForTranslatedIDs;
 
   private OrganizationStructureProvider organizationStructureProvider;
 
@@ -442,7 +441,7 @@
       boolean filterByClient) {
     PreparedStatement ps = null;
     try {
-      String st = "Select specific_id, generic_id, ad_client_id, ad_org_id from ad_ref_data_loaded where ad_client_id in ('"
+      String st = "Select specific_id, ad_client_id, ad_org_id from ad_ref_data_loaded where ad_client_id in ('"
           + client.getId()
           + "', '0') and generic_id='"
           + id
@@ -455,11 +454,11 @@
       while (rs.next()) {
         RefDataLoaded rfl = new RefDataLoaded();
         rfl.setSpecificId(rs.getString(1));
-        rfl.setGenericId(rs.getString(2));
-        rfl.setClientId(rs.getString(3));
-        rfl.setOrgId(rs.getString(4));
+        rfl.setClientId(rs.getString(2));
+        rfl.setOrgId(rs.getString(3));
         refDataLoadeds.add(rfl);
       }
+
       return refDataLoadeds;
     } catch (Exception e) {
       throw new OBException("Error while accessing the ad_ref_data_loaded table", e);
@@ -474,18 +473,9 @@
 
   private class RefDataLoaded {
     private String specificId;
-    private String genericId;
     private String clientId;
     private String orgId;
 
-    public String getGenericId() {
-      return genericId;
-    }
-
-    public void setGenericId(String genericId) {
-      this.genericId = genericId;
-    }
-
     public String getSpecificId() {
       return specificId;
     }
@@ -746,9 +736,4 @@
     return entityName + id;
   }
 
-  @Deprecated
-  public void setLookForTranslatedIDs(boolean lookForTranslatedIDs) {
-    this.lookForTranslatedIDs = lookForTranslatedIDs;
-  }
-
 }
\ No newline at end of file
--- a/src/org/openbravo/erpCommon/ad_actionButton/CreateFrom.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_actionButton/CreateFrom.java	Fri Jun 03 10:22:43 2016 +0200
@@ -310,8 +310,6 @@
     final String strAmountFrom = vars.getNumericParameter("inpamountFrom");
     final String strAmountTo = vars.getNumericParameter("inpamountTo");
     String strIsReceipt = vars.getStringParameter("inpisreceipt");
-    final String isSOTrx = Utility.getContext(this, vars, "isSOTrx", strWindowId);
-    final String strBankAccount = vars.getStringParameter("inpcBankaccountId");
     final String strOrg = vars.getStringParameter("inpadOrgId");
     final String strCharge = vars.getStringParameter("inpCharge");
     final String strPlannedDate = vars.getStringParameter("inpplanneddate", strStatementDate);
@@ -1528,9 +1526,7 @@
             else
               C_Tax_ID = CreateFromInvoiceData.getTax(this, data[i].cOrderlineId);
 
-            final int stdPrecision;
             final int curPrecision;
-            stdPrecision = Integer.valueOf(data[i].stdprecision).intValue();
             if (strType.equals("SHIPMENT")) {
               curPrecision = Integer.valueOf(dataAux[0].priceprecision).intValue();
             } else {
@@ -1602,7 +1598,6 @@
             BigDecimal taxAmt = ((lineNetAmt.multiply(taxRate)).divide(new BigDecimal("100"), 12,
                 BigDecimal.ROUND_HALF_EVEN)).setScale(curPrecision, BigDecimal.ROUND_HALF_UP);
             try {
-              final String strOrg2 = vars.getGlobalVariable("inpadOrgId", "CreateFrom|adOrgId", "");
               // Calculate Acc and Def Plan from Product
               String isDeferred = "N";
               HashMap<String, String> accDefPlanData = AccDefUtility
@@ -1610,7 +1605,6 @@
               String planType = accDefPlanData.get("planType");
               String periodNumber = accDefPlanData.get("periodNumber");
               String startingPeriodId = accDefPlanData.get("startingPeriodId");
-              boolean isSOTRX = "Y".equals(isSOTrx);
               if (!"".equals(planType) && !"".equals(periodNumber) && !"".equals(startingPeriodId)) {
                 isDeferred = "Y";
               } else {
@@ -2353,12 +2347,13 @@
   }
 
   private String[] restrictParameter(String strIds) {
+    String localStrIds = strIds;
     String[] ids = null;
-    if (strIds == null || ("").equals(strIds)) {
+    if (localStrIds == null || ("").equals(localStrIds)) {
       return new String[0];
     }
-    strIds = strIds.substring(1, strIds.length() - 1);
-    StringTokenizer st = new StringTokenizer(strIds, ",");
+    localStrIds = localStrIds.substring(1, localStrIds.length() - 1);
+    StringTokenizer st = new StringTokenizer(localStrIds, ",");
     int noOfRecords = 1;
     int tokenCount = st.countTokens();
     final double totalRecords = 900.0;
@@ -2367,7 +2362,7 @@
       ids = new String[strArrayCount];
     } else {
       ids = new String[1];
-      ids[0] = "(" + strIds + ")";
+      ids[0] = "(" + localStrIds + ")";
     }
 
     int count = 1;
--- a/src/org/openbravo/erpCommon/ad_actionButton/CreateFromMultiple.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_actionButton/CreateFromMultiple.java	Fri Jun 03 10:22:43 2016 +0200
@@ -132,6 +132,7 @@
   protected void printPageReceipt(HttpServletResponse response, VariablesSecureApp vars,
       String strKey, String strWindowId, String strTabId, String strSOTrx, String strProcessId,
       String strBpartner, String strmWarehouseId) throws IOException, ServletException {
+    String localStrmWarehouseId = strmWarehouseId;
     if (log4j.isDebugEnabled())
       log4j.debug("Output: Receipt");
     ActionButtonDefaultData[] data = null;
@@ -161,7 +162,7 @@
     xmlDocument.setParameter("tabId", strTabId);
     xmlDocument.setParameter("sotrx", strSOTrx);
     xmlDocument.setParameter("bpartner", strBpartner);
-    xmlDocument.setParameter("mWarehouseId", strmWarehouseId);
+    xmlDocument.setParameter("mWarehouseId", localStrmWarehouseId);
 
     try {
       ComboTableData comboTableData = new ComboTableData(this, "TABLEDIR", "C_UOM_ID", "", "",
@@ -178,7 +179,8 @@
       ComboTableData comboTableData = new ComboTableData(this, "TABLEDIR", "M_Warehouse_ID", "",
           "", Utility.getContext(this, vars, "#AccessibleOrgTree", strWindowId),
           Utility.getContext(this, vars, "#User_Client", strWindowId), 0);
-      Utility.fillSQLParameters(this, vars, null, comboTableData, strWindowId, strmWarehouseId);
+      Utility
+          .fillSQLParameters(this, vars, null, comboTableData, strWindowId, localStrmWarehouseId);
       xmlDocument.setData("reportM_WAREHOUSE_ID", "liststructure", comboTableData.select(false));
       comboTableData = null;
     } catch (Exception ex) {
@@ -187,10 +189,10 @@
 
     CreateFromMultipleReceiptData[] dataW = CreateFromMultipleReceiptData
         .selectAccessibleWarehouses(this, vars.getRole(), vars.getClient());
-    if (strmWarehouseId.equals("") && dataW != null && dataW.length > 0)
-      strmWarehouseId = dataW[0].id;
+    if (localStrmWarehouseId.equals("") && dataW != null && dataW.length > 0)
+      localStrmWarehouseId = dataW[0].id;
     xmlDocument.setData("reportM_LOCATOR_X", "liststructure",
-        CreateFromMultipleReceiptData.selectM_Locator_X(this, strmWarehouseId));
+        CreateFromMultipleReceiptData.selectM_Locator_X(this, localStrmWarehouseId));
 
     response.setContentType("text/html; charset=UTF-8");
     PrintWriter out = response.getWriter();
--- a/src/org/openbravo/erpCommon/ad_actionButton/ProjectCopyFrom.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_actionButton/ProjectCopyFrom.java	Fri Jun 03 10:22:43 2016 +0200
@@ -70,6 +70,8 @@
       pageErrorPopUp(response);
   }
 
+  @SuppressWarnings("resource")
+  // con is closed in commit/rollback methods
   private OBError processButton(VariablesSecureApp vars, String strKey, String strProject,
       String windowId) {
     Connection conn = null;
--- a/src/org/openbravo/erpCommon/ad_actionButton/ProjectSetType.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_actionButton/ProjectSetType.java	Fri Jun 03 10:22:43 2016 +0200
@@ -78,6 +78,8 @@
       pageErrorPopUp(response);
   }
 
+  @SuppressWarnings("resource")
+  // con is closed in commit/rollback methods
   private OBError processButton(VariablesSecureApp vars, String strKey, String strProjectType,
       String strDateFrom, String windowId) {
     Connection conn = null;
--- a/src/org/openbravo/erpCommon/ad_actionButton/UpdateMaintenanceScheduled.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_actionButton/UpdateMaintenanceScheduled.java	Fri Jun 03 10:22:43 2016 +0200
@@ -83,16 +83,18 @@
   private void printPageDataSheet(HttpServletResponse response, VariablesSecureApp vars,
       String strKey, String strWindowId, String strTabId, String strPartDateFrom,
       String strPartDateTo, String strMaintType) throws IOException, ServletException {
+    String localStrMaintType = strMaintType;
+    String localStrPartDateTo = strPartDateTo;
     if (log4j.isDebugEnabled())
       log4j.debug("Output: values ");
     String[] discard = { "" };
     UpdateMaintenanceScheduledData[] data = null;
-    if (strMaintType == null)
-      strMaintType = "";
-    if (strPartDateTo == null)
-      strPartDateTo = "";
+    if (localStrMaintType == null)
+      localStrMaintType = "";
+    if (localStrPartDateTo == null)
+      localStrPartDateTo = "";
     data = UpdateMaintenanceScheduledData.select(this, vars.getLanguage(), strPartDateFrom,
-        strPartDateTo, strMaintType);
+        localStrPartDateTo, localStrMaintType);
 
     XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
         "org/openbravo/erpCommon/ad_actionButton/UpdateMaintenanceScheduled", discard)
@@ -106,8 +108,8 @@
     xmlDocument.setParameter("tabId", strTabId);
 
     xmlDocument.setParameter("partDateFrom", strPartDateFrom);
-    xmlDocument.setParameter("partDateTo", strPartDateTo);
-    xmlDocument.setParameter("maintType", strMaintType);
+    xmlDocument.setParameter("partDateTo", localStrPartDateTo);
+    xmlDocument.setParameter("maintType", localStrMaintType);
 
     xmlDocument.setParameter("calendar", vars.getLanguage().substring(0, 2));
     xmlDocument.setParameter("dateFromdisplayFormat", vars.getSessionValue("#AD_SqlDateFormat"));
@@ -120,7 +122,7 @@
               "UpdateMaintenanceScheduled"), Utility.getContext(this, vars, "#User_Client",
               "UpdateMaintenanceScheduled"), 0);
       Utility.fillSQLParameters(this, vars, null, comboTableData, "UpdateMaintenanceScheduled",
-          strMaintType);
+          localStrMaintType);
       xmlDocument.setData("reportMaintType", "liststructure", comboTableData.select(false));
       comboTableData = null;
     } catch (Exception ex) {
--- a/src/org/openbravo/erpCommon/ad_callouts/CalloutHelper.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_callouts/CalloutHelper.java	Fri Jun 03 10:22:43 2016 +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) 2001-2010 Openbravo SLU 
+ * All portions are Copyright (C) 2001-2016 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -30,6 +30,7 @@
 import org.openbravo.data.FieldProvider;
 import org.openbravo.utils.FormatUtilities;
 
+@SuppressWarnings("serial")
 public abstract class CalloutHelper extends HttpSecureAppServlet {
 
   public void init(ServletConfig config) {
--- a/src/org/openbravo/erpCommon/ad_callouts/SE_Expense_Amount.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_callouts/SE_Expense_Amount.java	Fri Jun 03 10:22:43 2016 +0200
@@ -68,6 +68,7 @@
   private void printPage(HttpServletResponse response, VariablesSecureApp vars,
       String strExpenseAmt, String strDateexpense, String strcCurrencyId, String strTimeExpenseId,
       String strTabId) throws IOException, ServletException {
+    String localStrDateexpense = strDateexpense;
     if (log4j.isDebugEnabled())
       log4j.debug("Output: dataSheet");
     XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
@@ -87,8 +88,8 @@
     OBError myMessage = null;
     myMessage = new OBError();
 
-    if (strDateexpense.equals("")) {
-      strDateexpense = SEExpenseAmountData.selectReportDate(this, strTimeExpenseId).equals("") ? DateTimeData
+    if (localStrDateexpense.equals("")) {
+      localStrDateexpense = SEExpenseAmountData.selectReportDate(this, strTimeExpenseId).equals("") ? DateTimeData
           .today(this) : SEExpenseAmountData.selectReportDate(this, strTimeExpenseId);
     }
 
@@ -117,7 +118,7 @@
       int stdPrecisionConv = Integer.valueOf(strPrecisionConv).intValue();
       try {
         convertedAmount = SEExpenseAmountData.selectConvertedAmt(this, strExpenseAmt,
-            strcCurrencyId, c_Currency_To_ID, strDateexpense, vars.getClient(), org.getId());
+            strcCurrencyId, c_Currency_To_ID, localStrDateexpense, vars.getClient(), org.getId());
       } catch (ServletException e) {
         convertedAmount = "";
         myMessage = Utility.translateError(this, vars, vars.getLanguage(), e.getMessage());
--- a/src/org/openbravo/erpCommon/ad_callouts/SE_Expense_BP_Project.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_callouts/SE_Expense_BP_Project.java	Fri Jun 03 10:22:43 2016 +0200
@@ -60,6 +60,8 @@
   private void printPage(HttpServletResponse response, VariablesSecureApp vars,
       String strBPartnerId, String strProjectId, String strChanged, String strTabId,
       String strWindowId) throws IOException, ServletException {
+    String localStrProjectId = strProjectId;
+    String localStrBPartnerId = strBPartnerId;
     if (log4j.isDebugEnabled())
       log4j.debug("Output: dataSheet");
     XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
@@ -73,44 +75,44 @@
       resultado.append("new Array(\"inpcProjectphaseId\", \"\"),\n");
       resultado.append("new Array(\"inpcProjecttaskId\", \"\")\n");
       // If project changed, select project's business partner (if any).
-      if (strProjectId != null && !strProjectId.equals("")) {
+      if (localStrProjectId != null && !localStrProjectId.equals("")) {
         String strBPartnerName = "";
-        String strBPartner = SEExpenseBPProjectData.selectBPId(this, strProjectId);
+        String strBPartner = SEExpenseBPProjectData.selectBPId(this, localStrProjectId);
         if (strBPartner != null && !strBPartner.equals("")) {
-          strBPartnerId = strBPartner;
-          strBPartnerName = SEExpenseBPProjectData.selectBPName(this, strProjectId);
-          resultado.append(", new Array(\"inpcBpartnerId\", \"" + strBPartnerId + "\")\n");
+          localStrBPartnerId = strBPartner;
+          strBPartnerName = SEExpenseBPProjectData.selectBPName(this, localStrProjectId);
+          resultado.append(", new Array(\"inpcBpartnerId\", \"" + localStrBPartnerId + "\")\n");
           resultado.append(", new Array(\"inpcBpartnerId_R\", \"" + strBPartnerName + "\")\n");
         }
       }
     } else if (strChanged.equals("inpcBpartnerId")) {
       // If business partner changed...
       String strReset = "0";
-      if (strBPartnerId != null && !strBPartnerId.equals("")) {
+      if (localStrBPartnerId != null && !localStrBPartnerId.equals("")) {
         String strProject = "";
-        if (strProjectId != null && !strProjectId.equals("")) {
+        if (localStrProjectId != null && !localStrProjectId.equals("")) {
           // ...if project is not null, check if it corresponds with
           // the business partner
-          String strBPartnerProject = SEExpenseBPProjectData.selectBPProject(this, strBPartnerId,
-              strProjectId);
+          String strBPartnerProject = SEExpenseBPProjectData.selectBPProject(this,
+              localStrBPartnerId, localStrProjectId);
           // ...if there is no relationship between project and
           // business partner, take the last project of that business
           // partner (if any).
           if (strBPartnerProject == null || strBPartnerProject.equals("")) {
             // strReset = "1";
-            strProject = SEExpenseBPProjectData.selectProjectId(this, strBPartnerId);
+            strProject = SEExpenseBPProjectData.selectProjectId(this, localStrBPartnerId);
             if (strProject != null && !strProject.equals("")) {
-              strProjectId = strProject;
-              resultado.append("new Array(\"inpcProjectId\", \"" + strProjectId + "\")\n");
+              localStrProjectId = strProject;
+              resultado.append("new Array(\"inpcProjectId\", \"" + localStrProjectId + "\")\n");
             } else {
-              strProjectId = "";
+              localStrProjectId = "";
             }
           }
         } else {
           // ...if project is null, take the last project of that
           // business partner (if any).
           strReset = "1";
-          strProject = SEExpenseBPProjectData.selectProjectId(this, strBPartnerId);
+          strProject = SEExpenseBPProjectData.selectProjectId(this, localStrBPartnerId);
           resultado.append("new Array(\"inpcProjectId\", \"" + strProject + "\"),\n");
         }
         if (strReset.equals("1")) {
--- a/src/org/openbravo/erpCommon/ad_callouts/SE_Expense_Product.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_callouts/SE_Expense_Product.java	Fri Jun 03 10:22:43 2016 +0200
@@ -78,6 +78,7 @@
       String strDateexpense, String strmProductId, String strsTimeexpenseId, String strqty,
       String strcCurrencyId, String strInvPrice, String strChanged, String strTabId,
       String strWindowId, String strlastNetUnitPrice) throws IOException, ServletException {
+    String localStrDateexpense = strDateexpense;
     if (log4j.isDebugEnabled())
       log4j.debug("Output: dataSheet");
     XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
@@ -95,9 +96,10 @@
     final Organization org = OBDal.getInstance()
         .get(org.openbravo.model.timeandexpense.Sheet.class, strsTimeexpenseId).getOrganization();
 
-    if (strDateexpense.equals("")) {
-      strDateexpense = SEExpenseProductData.selectReportDate(this, strsTimeexpenseId).equals("") ? DateTimeData
-          .today(this) : SEExpenseProductData.selectReportDate(this, strsTimeexpenseId);
+    if (localStrDateexpense.equals("")) {
+      localStrDateexpense = SEExpenseProductData.selectReportDate(this, strsTimeexpenseId).equals(
+          "") ? DateTimeData.today(this) : SEExpenseProductData.selectReportDate(this,
+          strsTimeexpenseId);
     }
 
     BigDecimal invPrice = BigDecimal.ZERO;
@@ -113,7 +115,7 @@
         || (strChanged.equals("inpmProductId") && invPrice.compareTo(lastNetUnitPrice) == 0)) {
       for (int i = 0; data != null && i < data.length && noPrice; i++) {
         if (data[i].validfrom == null || data[i].validfrom.equals("")
-            || !DateTimeData.compare(this, strDateexpense, data[i].validfrom).equals("-1")) {
+            || !DateTimeData.compare(this, localStrDateexpense, data[i].validfrom).equals("-1")) {
           noPrice = false;
           // Price
           priceActual = data[i].pricestd;
@@ -129,7 +131,7 @@
         data = SEExpenseProductData.selectBasePriceList(this, strmProductId, strmPricelistId);
         for (int i = 0; data != null && i < data.length && noPrice; i++) {
           if (data[i].validfrom == null || data[i].validfrom.equals("")
-              || !DateTimeData.compare(this, strDateexpense, data[i].validfrom).equals("-1")) {
+              || !DateTimeData.compare(this, localStrDateexpense, data[i].validfrom).equals("-1")) {
             noPrice = false;
             // Price
             priceActual = data[i].pricestd;
@@ -190,7 +192,7 @@
       if (!cCurrencyID.equals(c_Currency_To_ID)) {
         try {
           convertedAmount = SEExpenseProductData.selectConvertedAmt(this, amount.toPlainString(),
-              cCurrencyID, c_Currency_To_ID, strDateexpense, vars.getClient(), org.getId());
+              cCurrencyID, c_Currency_To_ID, localStrDateexpense, vars.getClient(), org.getId());
         } catch (ServletException e) {
           convertedAmount = "";
           myMessage = Utility.translateError(this, vars, vars.getLanguage(), e.getMessage());
--- a/src/org/openbravo/erpCommon/ad_callouts/SE_Payment_MultiCurrency.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_callouts/SE_Payment_MultiCurrency.java	Fri Jun 03 10:22:43 2016 +0200
@@ -41,7 +41,8 @@
 public class SE_Payment_MultiCurrency extends SimpleCallout {
 
   private static final long serialVersionUID = 1L;
-  static Logger log4j = Logger.getLogger(SE_Payment_MultiCurrency.class);
+  private static final Logger sePaymentMultiCurrencyLog4j = Logger
+      .getLogger(SE_Payment_MultiCurrency.class);
 
   @Override
   protected void execute(CalloutInfo info) throws ServletException {
@@ -110,8 +111,9 @@
         }
       }
     } else {
-      log4j.error("SE_Payment_MultiCurrency. The following field executed the callout"
-          + lastFieldChanged);
+      sePaymentMultiCurrencyLog4j
+          .error("SE_Payment_MultiCurrency. The following field executed the callout"
+              + lastFieldChanged);
     }
 
   }
@@ -160,7 +162,7 @@
         }
       }
     } catch (Exception e) {
-      log4j.error(e);
+      sePaymentMultiCurrencyLog4j.error(e);
       return null;
     } finally {
       OBContext.restorePreviousMode();
@@ -184,7 +186,7 @@
       SimpleDateFormat outputFormat = new SimpleDateFormat(dateFormat);
       return (outputFormat.parse(strDate));
     } catch (ParseException e) {
-      log4j.error(e.getMessage(), e);
+      sePaymentMultiCurrencyLog4j.error(e.getMessage(), e);
       return null;
     }
   }
--- a/src/org/openbravo/erpCommon/ad_callouts/SE_PeriodNo.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_callouts/SE_PeriodNo.java	Fri Jun 03 10:22:43 2016 +0200
@@ -59,6 +59,7 @@
   private void printPage(HttpServletResponse response, VariablesSecureApp vars, String strYearId,
       String strWindowId, String strOrgId, String strCalendarId, String strChanged)
       throws IOException, ServletException {
+    String localStrCalendarId = strCalendarId;
 
     XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
         "org/openbravo/erpCommon/ad_callouts/CallOut").createXmlDocument();
@@ -103,7 +104,7 @@
         for (int i = 0; i < tdv.length; i++) {
           resultado.append("new Array(\"" + tdv[i].getField("id") + "\", \""
               + tdv[i].getField("Name") + "\")");
-          strCalendarId = tdv[i].getField("id");
+          localStrCalendarId = tdv[i].getField("id");
           if (i < tdv.length - 1)
             resultado.append(",\n");
         }
@@ -114,7 +115,7 @@
 
       // Update the years
       try {
-        tdv = SEPeriodNoData.getYears(this, strCalendarId);
+        tdv = SEPeriodNoData.getYears(this, localStrCalendarId);
       } catch (Exception ex) {
         throw new ServletException(ex);
       }
--- a/src/org/openbravo/erpCommon/ad_callouts/SE_ProjectLine_Value.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_callouts/SE_ProjectLine_Value.java	Fri Jun 03 10:22:43 2016 +0200
@@ -71,6 +71,7 @@
       String strmProductId, String strPriceListVersion, String strTabId, String strProjectId,
       String strPhaseId, String strADOrgID, String strPriceStd, String strCreatePL, String strStatus)
       throws IOException, ServletException {
+    String localStrProjectId = strProjectId;
     if (log4j.isDebugEnabled())
       log4j.debug("Output: dataSheet");
     XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
@@ -88,18 +89,18 @@
       data = SEProjectLineValueData.select(this, strmProductId);
       String strDate = DateTimeData.today(this);
       if (strPhaseId != null && !strPhaseId.equals("")) {
-        if (strProjectId == null || strProjectId.equals("")) {
-          strProjectId = SEProjectLineValueData.selectPhaseProject(this, strPhaseId);
+        if (localStrProjectId == null || localStrProjectId.equals("")) {
+          localStrProjectId = SEProjectLineValueData.selectPhaseProject(this, strPhaseId);
         }
       }
-      data1 = SEProjectLineValueData.selectProject(this, strProjectId);
+      data1 = SEProjectLineValueData.selectProject(this, localStrProjectId);
       String strCBPartnerLocationID = data1[0].bplocation;
       String strMWarehouseID = data1[0].warehouse;
       String strProjCat = data1[0].projcat;
 
       if (!strPriceListVersion.equals("")) {
         String plannedprice = SEProjectLineValueData.selectPlannedPrice(this, strPriceListVersion,
-            strmProductId, strProjectId);
+            strmProductId, localStrProjectId);
         if (plannedprice != null && !plannedprice.equals("")) {
           if (!strProjCat.equals("S")) {
             resultado.append("new Array(\"inpplannedprice\", "
@@ -121,7 +122,8 @@
             && strMWarehouseID != null && !strMWarehouseID.equals("")) {
           String strIsSOTrx = "Y";
           String strCTaxID = Tax.get(this, strmProductId, strDate, strADOrgID, strMWarehouseID,
-              strCBPartnerLocationID, strCBPartnerLocationID, strProjectId, strIsSOTrx.equals("Y"));
+              strCBPartnerLocationID, strCBPartnerLocationID, localStrProjectId,
+              strIsSOTrx.equals("Y"));
           if (strCTaxID != null && !strCTaxID.equals("")) {
             resultado.append(", new Array(\"inpcTaxId\", \""
                 + (strCTaxID.equals("") ? "\"\"" : strCTaxID) + "\"),\n");
--- a/src/org/openbravo/erpCommon/ad_callouts/SE_Sales_Pricelist.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_callouts/SE_Sales_Pricelist.java	Fri Jun 03 10:22:43 2016 +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 Openbravo SLU
+ * All portions are Copyright (C) 2012-2016 Openbravo SLU
  * All Rights Reserved.
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -20,6 +20,7 @@
 
 import javax.servlet.ServletException;
 
+@SuppressWarnings("serial")
 public class SE_Sales_Pricelist extends SimpleCallout {
 
   @Override
--- a/src/org/openbravo/erpCommon/ad_callouts/SL_Assets.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_callouts/SL_Assets.java	Fri Jun 03 10:22:43 2016 +0200
@@ -63,21 +63,24 @@
   private void printPage(HttpServletResponse response, VariablesSecureApp vars, String strTabId,
       String strAssetvalue, String strResidualvalue, String strAmortizationvalue,
       String strLastChanged) throws IOException, ServletException {
+    String localStrResidualvalue = strResidualvalue;
+    String localStrAssetvalue = strAssetvalue;
+    String localStrAmortizationvalue = strAmortizationvalue;
     if (log4j.isDebugEnabled())
       log4j.debug("Output: dataSheet");
     XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
         "org/openbravo/erpCommon/ad_callouts/CallOut").createXmlDocument();
 
-    if (strAssetvalue.equals(""))
-      strAssetvalue = "0";
-    if (strResidualvalue.equals(""))
-      strResidualvalue = "0";
-    if (strAmortizationvalue.equals(""))
-      strAmortizationvalue = "0";
+    if (localStrAssetvalue.equals(""))
+      localStrAssetvalue = "0";
+    if (localStrResidualvalue.equals(""))
+      localStrResidualvalue = "0";
+    if (localStrAmortizationvalue.equals(""))
+      localStrAmortizationvalue = "0";
 
-    BigDecimal fAssetvalue = new BigDecimal(strAssetvalue);
-    BigDecimal fResidualvalue = new BigDecimal(strResidualvalue);
-    BigDecimal fAmortizationvalue = new BigDecimal(strAmortizationvalue);
+    BigDecimal fAssetvalue = new BigDecimal(localStrAssetvalue);
+    BigDecimal fResidualvalue = new BigDecimal(localStrResidualvalue);
+    BigDecimal fAmortizationvalue = new BigDecimal(localStrAmortizationvalue);
     // Float fAssetvalue = Float.valueOf(strAssetvalue);
     // Float fResidualvalue = Float.valueOf(strResidualvalue);
     // Float fAmortizationvalue = Float.valueOf(strAmortizationvalue);
@@ -100,9 +103,9 @@
       fResidualvalue = fAssetvalue.subtract(fAmortizationvalue);
     }
 
-    strAssetvalue = fAssetvalue.toString();
-    strResidualvalue = fResidualvalue.toString();
-    strAmortizationvalue = fAmortizationvalue.toString();
+    localStrAssetvalue = fAssetvalue.toString();
+    localStrResidualvalue = fResidualvalue.toString();
+    localStrAmortizationvalue = fAmortizationvalue.toString();
 
     StringBuffer resultado = new StringBuffer();
     resultado.append("var calloutName='SL_Assets';\n\n");
--- a/src/org/openbravo/erpCommon/ad_callouts/SL_BankDebt_Amount.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_callouts/SL_BankDebt_Amount.java	Fri Jun 03 10:22:43 2016 +0200
@@ -65,6 +65,7 @@
   private void printPage(HttpServletResponse response, VariablesSecureApp vars, String strChanged,
       String strDebtPayment, String strTabId, String strBankStatement, String strCurrency,
       String strDescription) throws IOException, ServletException {
+    String localStrDescription = strDescription;
     if (log4j.isDebugEnabled())
       log4j.debug("Output: dataSheet");
     XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
@@ -76,10 +77,10 @@
     if (!strDebtPayment.equals("")) {
       Amount = SLCashJournalAmountsData.amountDebtPaymentBank(this, strBankStatement,
           strDebtPayment);
-      if (!strDescription.equals("")) {
-        strDescription = strDescription + " - ";
+      if (!localStrDescription.equals("")) {
+        localStrDescription = localStrDescription + " - ";
       }
-      strDescription = strDescription
+      localStrDescription = localStrDescription
           + SLCashJournalAmountsData.debtPaymentDescription(this, strDebtPayment);
       conv = SLBankStmtAmountData.isConversion(this, strCurrency, strDebtPayment);
     } else {
@@ -91,8 +92,8 @@
     StringBuffer resultado = new StringBuffer();
     resultado.append("var calloutName='SL_BankDebt_Amount';\n\n");
     resultado.append("var respuesta = new Array(");
-    resultado.append("new Array(\"inpdescription\", \"" + FormatUtilities.replaceJS(strDescription)
-        + "\"),");
+    resultado.append("new Array(\"inpdescription\", \""
+        + FormatUtilities.replaceJS(localStrDescription) + "\"),");
     resultado.append("new Array(\"inptrxamt\", " + Amount + "),");
     resultado.append("new Array(\"inpcurrconv\", \"" + conv + "\"),");
     resultado.append("new Array(\"inpconvertchargeamt\", " + ConvChargeAmt + "),");
--- a/src/org/openbravo/erpCommon/ad_callouts/SL_CreateFromMultiple_Conversion.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_callouts/SL_CreateFromMultiple_Conversion.java	Fri Jun 03 10:22:43 2016 +0200
@@ -65,23 +65,24 @@
   private void printPage(HttpServletResponse response, VariablesSecureApp vars, String strUOM,
       String strMProductUOMID, String strQuantityOrder, String strTabId) throws IOException,
       ServletException {
+    String localStrUOM = strUOM;
     if (log4j.isDebugEnabled())
       log4j.debug("Output: dataSheet");
     XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
         "org/openbravo/erpCommon/ad_callouts/CallOut").createXmlDocument();
-    if (strUOM.startsWith("\""))
-      strUOM = strUOM.substring(1, strUOM.length() - 1);
-    int stdPrecision = Integer.valueOf(SLInvoiceConversionData.stdPrecision(this, strUOM))
+    if (localStrUOM.startsWith("\""))
+      localStrUOM = localStrUOM.substring(1, localStrUOM.length() - 1);
+    int stdPrecision = Integer.valueOf(SLInvoiceConversionData.stdPrecision(this, localStrUOM))
         .intValue();
     String strInitUOM = SLInvoiceConversionData.initUOMId(this, strMProductUOMID);
     String strMultiplyRate;
     boolean check = false;
 
-    strMultiplyRate = SLInvoiceConversionData.multiplyRate(this, strInitUOM, strUOM);
-    if (strInitUOM.equals(strUOM))
+    strMultiplyRate = SLInvoiceConversionData.multiplyRate(this, strInitUOM, localStrUOM);
+    if (strInitUOM.equals(localStrUOM))
       strMultiplyRate = "1";
     if (strMultiplyRate.equals(""))
-      strMultiplyRate = SLInvoiceConversionData.divideRate(this, strUOM, strInitUOM);
+      strMultiplyRate = SLInvoiceConversionData.divideRate(this, localStrUOM, strInitUOM);
     if (strMultiplyRate.equals("")) {
       strMultiplyRate = "1";
       if (!strMProductUOMID.equals(""))
--- a/src/org/openbravo/erpCommon/ad_callouts/SL_CreateFromMultiple_Product.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_callouts/SL_CreateFromMultiple_Product.java	Fri Jun 03 10:22:43 2016 +0200
@@ -75,6 +75,7 @@
       String strQty, String strUOM, String strAttribute, String strQtyOrder, String strPUOM,
       String strMProductID, String strIsSOTrx, String strWharehouse, String strTabId)
       throws IOException, ServletException {
+    String localStrPUOM = strPUOM;
     if (log4j.isDebugEnabled())
       log4j.debug("Output: dataSheet");
     XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
@@ -102,8 +103,8 @@
     String strHasSecondaryUOM = SLOrderProductData.hasSecondaryUOM(this, strMProductID);
     resultado.append("new Array(\"inphasseconduom\", " + strHasSecondaryUOM + "),\n");
     resultado.append("new Array(\"inpmProductUomId\", ");
-    if (strPUOM.startsWith("\""))
-      strPUOM = strPUOM.substring(1, strPUOM.length() - 1);
+    if (localStrPUOM.startsWith("\""))
+      localStrPUOM = localStrPUOM.substring(1, localStrPUOM.length() - 1);
     if (vars.getLanguage().equals("en_US")) {
       FieldProvider[] tld = null;
       try {
@@ -124,7 +125,7 @@
         for (int i = 0; i < tld.length; i++) {
           resultado.append("new Array(\"" + tld[i].getField("id") + "\", \""
               + FormatUtilities.replaceJS(tld[i].getField("name")) + "\", \""
-              + (tld[i].getField("id").equalsIgnoreCase(strPUOM) ? "true" : "false") + "\")");
+              + (tld[i].getField("id").equalsIgnoreCase(localStrPUOM) ? "true" : "false") + "\")");
           if (i < tld.length - 1)
             resultado.append(",\n");
         }
@@ -152,7 +153,7 @@
         for (int i = 0; i < tld.length; i++) {
           resultado.append("new Array(\"" + tld[i].getField("id") + "\", \""
               + FormatUtilities.replaceJS(tld[i].getField("name")) + "\", \""
-              + (tld[i].getField("id").equalsIgnoreCase(strPUOM) ? "true" : "false") + "\")");
+              + (tld[i].getField("id").equalsIgnoreCase(localStrPUOM) ? "true" : "false") + "\")");
           if (i < tld.length - 1)
             resultado.append(",\n");
         }
--- a/src/org/openbravo/erpCommon/ad_callouts/SL_GlobalUse_Conversion.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_callouts/SL_GlobalUse_Conversion.java	Fri Jun 03 10:22:43 2016 +0200
@@ -64,23 +64,24 @@
   private void printPage(HttpServletResponse response, VariablesSecureApp vars, String strUOM,
       String strMProductUOMID, String strQuantityOrder, String strTabId) throws IOException,
       ServletException {
+    String localStrUOM = strUOM;
     if (log4j.isDebugEnabled())
       log4j.debug("Output: dataSheet");
     XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
         "org/openbravo/erpCommon/ad_callouts/CallOut").createXmlDocument();
-    if (strUOM.startsWith("\""))
-      strUOM = strUOM.substring(1, strUOM.length() - 1);
-    int stdPrecision = Integer.valueOf(SLInvoiceConversionData.stdPrecision(this, strUOM))
+    if (localStrUOM.startsWith("\""))
+      localStrUOM = localStrUOM.substring(1, localStrUOM.length() - 1);
+    int stdPrecision = Integer.valueOf(SLInvoiceConversionData.stdPrecision(this, localStrUOM))
         .intValue();
     String strInitUOM = SLInvoiceConversionData.initUOMId(this, strMProductUOMID);
     String strMultiplyRate;
     boolean check = false;
 
-    strMultiplyRate = SLInvoiceConversionData.multiplyRate(this, strInitUOM, strUOM);
-    if (strInitUOM.equals(strUOM))
+    strMultiplyRate = SLInvoiceConversionData.multiplyRate(this, strInitUOM, localStrUOM);
+    if (strInitUOM.equals(localStrUOM))
       strMultiplyRate = "1";
     if (strMultiplyRate.equals(""))
-      strMultiplyRate = SLInvoiceConversionData.divideRate(this, strUOM, strInitUOM);
+      strMultiplyRate = SLInvoiceConversionData.divideRate(this, localStrUOM, strInitUOM);
     if (strMultiplyRate.equals("")) {
       strMultiplyRate = "1";
       if (!strMProductUOMID.equals(""))
--- a/src/org/openbravo/erpCommon/ad_callouts/SL_GlobalUse_Product.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_callouts/SL_GlobalUse_Product.java	Fri Jun 03 10:22:43 2016 +0200
@@ -69,6 +69,7 @@
 
   private void printPage(HttpServletResponse response, VariablesSecureApp vars, String strTabId,
       String strMProductID, String strPAttr) throws IOException, ServletException {
+    String localStrPAttr = strPAttr;
     if (log4j.isDebugEnabled())
       log4j.debug("Output: dataSheet");
     XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
@@ -84,11 +85,12 @@
             + "\"),\n");
     String strHasSecondaryUOM = SLGlobalUseProductData.hasSecondaryUOM(this, strMProductID);
     resultado.append("new Array(\"inphasseconduom\", \"" + strHasSecondaryUOM + "\"),\n");
-    if (strPAttr.startsWith("\""))
-      strPAttr = strPAttr.substring(1, strPAttr.length() - 1);
-    resultado.append("new Array(\"inpmAttributesetinstanceId\", \"" + strPAttr + "\"),\n");
+    if (localStrPAttr.startsWith("\""))
+      localStrPAttr = localStrPAttr.substring(1, localStrPAttr.length() - 1);
+    resultado.append("new Array(\"inpmAttributesetinstanceId\", \"" + localStrPAttr + "\"),\n");
     resultado.append("new Array(\"inpmAttributesetinstanceId_R\", \""
-        + FormatUtilities.replaceJS(SLInOutLineProductData.attribute(this, strPAttr)) + "\"),\n");
+        + FormatUtilities.replaceJS(SLInOutLineProductData.attribute(this, localStrPAttr))
+        + "\"),\n");
     String strAttrSet, strAttrSetValueType;
     strAttrSet = strAttrSetValueType = "";
     OBContext.setAdminMode();
--- a/src/org/openbravo/erpCommon/ad_callouts/SL_InOut_Conversion.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_callouts/SL_InOut_Conversion.java	Fri Jun 03 10:22:43 2016 +0200
@@ -65,23 +65,24 @@
   private void printPage(HttpServletResponse response, VariablesSecureApp vars, String strUOM,
       String strMProductUOMID, String strQuantityOrder, String strTabId) throws IOException,
       ServletException {
+    String localStrUOM = strUOM;
     if (log4j.isDebugEnabled())
       log4j.debug("Output: dataSheet");
     XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
         "org/openbravo/erpCommon/ad_callouts/CallOut").createXmlDocument();
-    if (strUOM.startsWith("\""))
-      strUOM = strUOM.substring(1, strUOM.length() - 1);
-    int stdPrecision = Integer.valueOf(SLInvoiceConversionData.stdPrecision(this, strUOM))
+    if (localStrUOM.startsWith("\""))
+      localStrUOM = localStrUOM.substring(1, localStrUOM.length() - 1);
+    int stdPrecision = Integer.valueOf(SLInvoiceConversionData.stdPrecision(this, localStrUOM))
         .intValue();
     String strInitUOM = SLInvoiceConversionData.initUOMId(this, strMProductUOMID);
     String strMultiplyRate;
     boolean check = false;
 
-    strMultiplyRate = SLInvoiceConversionData.multiplyRate(this, strInitUOM, strUOM);
-    if (strInitUOM.equals(strUOM))
+    strMultiplyRate = SLInvoiceConversionData.multiplyRate(this, strInitUOM, localStrUOM);
+    if (strInitUOM.equals(localStrUOM))
       strMultiplyRate = "1";
     if (strMultiplyRate.equals(""))
-      strMultiplyRate = SLInvoiceConversionData.divideRate(this, strUOM, strInitUOM);
+      strMultiplyRate = SLInvoiceConversionData.divideRate(this, localStrUOM, strInitUOM);
     if (strMultiplyRate.equals("")) {
       strMultiplyRate = "1";
       if (!strMProductUOMID.equals(""))
--- a/src/org/openbravo/erpCommon/ad_callouts/SL_Internal_Consumption_Conversion.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_callouts/SL_Internal_Consumption_Conversion.java	Fri Jun 03 10:22:43 2016 +0200
@@ -64,23 +64,24 @@
   private void printPage(HttpServletResponse response, VariablesSecureApp vars, String strChanged,
       String strUOM, String strMProductUOMID, String strQuantityOrder, String strTabId)
       throws IOException, ServletException {
+    String localStrUOM = strUOM;
     if (log4j.isDebugEnabled())
       log4j.debug("Output: dataSheet");
     XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
         "org/openbravo/erpCommon/ad_callouts/CallOut").createXmlDocument();
-    if (strUOM.startsWith("\""))
-      strUOM = strUOM.substring(1, strUOM.length() - 1);
-    int stdPrecision = Integer.valueOf(SLInvoiceConversionData.stdPrecision(this, strUOM))
+    if (localStrUOM.startsWith("\""))
+      localStrUOM = localStrUOM.substring(1, localStrUOM.length() - 1);
+    int stdPrecision = Integer.valueOf(SLInvoiceConversionData.stdPrecision(this, localStrUOM))
         .intValue();
     String strInitUOM = SLInvoiceConversionData.initUOMId(this, strMProductUOMID);
     String strMultiplyRate;
     boolean check = false;
 
-    strMultiplyRate = SLInvoiceConversionData.multiplyRate(this, strInitUOM, strUOM);
-    if (strInitUOM.equals(strUOM))
+    strMultiplyRate = SLInvoiceConversionData.multiplyRate(this, strInitUOM, localStrUOM);
+    if (strInitUOM.equals(localStrUOM))
       strMultiplyRate = "1";
     if (strMultiplyRate.equals(""))
-      strMultiplyRate = SLInvoiceConversionData.divideRate(this, strUOM, strInitUOM);
+      strMultiplyRate = SLInvoiceConversionData.divideRate(this, localStrUOM, strInitUOM);
     if (strMultiplyRate.equals("")) {
       strMultiplyRate = "1";
       if (!strMProductUOMID.equals(""))
--- a/src/org/openbravo/erpCommon/ad_callouts/SL_Internal_Consumption_Product.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_callouts/SL_Internal_Consumption_Product.java	Fri Jun 03 10:22:43 2016 +0200
@@ -76,6 +76,9 @@
   private void printPage(HttpServletResponse response, VariablesSecureApp vars, String strChanged,
       String strProduct, String strPLocator, String strPAttr, String strPQty, String strPUOM,
       String strQty, String strUOM, String strTabId) throws IOException, ServletException {
+    String localStrPUOM = strPUOM;
+    String localStrPLocator = strPLocator;
+    String localStrPAttr = strPAttr;
     if (log4j.isDebugEnabled())
       log4j.debug("Output: dataSheet");
     XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
@@ -85,19 +88,20 @@
     resultado.append("var calloutName='SL_Internal_Consumption_Product';\n\n");
     resultado.append("var respuesta = new Array(");
     resultado.append("new Array(\"inpcUomId\", \"" + strUOM + "\"),\n");
-    if (strPLocator.startsWith("\""))
-      strPLocator = strPLocator.substring(1, strPLocator.length() - 1);
-    resultado.append("new Array(\"inpmLocatorId\", \"" + strPLocator + "\"),\n");
+    if (localStrPLocator.startsWith("\""))
+      localStrPLocator = localStrPLocator.substring(1, localStrPLocator.length() - 1);
+    resultado.append("new Array(\"inpmLocatorId\", \"" + localStrPLocator + "\"),\n");
     resultado.append("new Array(\"inpmLocatorId_R\", \""
         + FormatUtilities.replaceJS(SLInternalConsumptionProductData.selectLocator(this,
-            strPLocator)) + "\"),\n");
+            localStrPLocator)) + "\"),\n");
     String strHasSecondaryUOM = SLOrderProductData.hasSecondaryUOM(this, strProduct);
     resultado.append("new Array(\"inphasseconduom\", " + strHasSecondaryUOM + "),\n");
-    if (strPAttr.startsWith("\""))
-      strPAttr = strPAttr.substring(1, strPAttr.length() - 1);
-    resultado.append("new Array(\"inpmAttributesetinstanceId\", \"" + strPAttr + "\"),\n");
+    if (localStrPAttr.startsWith("\""))
+      localStrPAttr = localStrPAttr.substring(1, localStrPAttr.length() - 1);
+    resultado.append("new Array(\"inpmAttributesetinstanceId\", \"" + localStrPAttr + "\"),\n");
     resultado.append("new Array(\"inpmAttributesetinstanceId_R\", \""
-        + FormatUtilities.replaceJS(SLInOutLineProductData.attribute(this, strPAttr)) + "\"),\n");
+        + FormatUtilities.replaceJS(SLInOutLineProductData.attribute(this, localStrPAttr))
+        + "\"),\n");
     String strAttrSet, strAttrSetValueType;
     strAttrSet = strAttrSetValueType = "";
     OBContext.setAdminMode();
@@ -112,18 +116,19 @@
     } finally {
       OBContext.restorePreviousMode();
     }
-    resultado.append("new Array(\"inpattributeset\", \"" 
-        + (strAttrSet == null || strAttrSet.equals("") ? "" : FormatUtilities.replaceJS(strAttrSet))
-        + "\"),\n");
+    resultado
+        .append("new Array(\"inpattributeset\", \""
+            + (strAttrSet == null || strAttrSet.equals("") ? "" : FormatUtilities
+                .replaceJS(strAttrSet)) + "\"),\n");
     resultado.append("new Array(\"inpattrsetvaluetype\", \""
-        + (strAttrSetValueType == null || strAttrSetValueType.equals("") ? "" : FormatUtilities.replaceJS(strAttrSetValueType))
-    	+ "\"),\n");
+        + (strAttrSetValueType == null || strAttrSetValueType.equals("") ? "" : FormatUtilities
+            .replaceJS(strAttrSetValueType)) + "\"),\n");
     resultado.append("new Array(\"inpmovementqty\", " + (strQty.equals("") ? "\"\"" : strQty)
         + "),\n");
     resultado.append("new Array(\"inpquantityorder\", " + (strPQty.equals("") ? "\"\"" : strPQty)
         + "),\n");
-    if (strPUOM.startsWith("\""))
-      strPUOM = strPUOM.substring(1, strPUOM.length() - 1);
+    if (localStrPUOM.startsWith("\""))
+      localStrPUOM = localStrPUOM.substring(1, localStrPUOM.length() - 1);
     resultado.append("new Array(\"inpmProductUomId\", ");
     if (vars.getLanguage().equals("en_US")) {
       FieldProvider[] tld = null;
@@ -145,7 +150,7 @@
         for (int i = 0; i < tld.length; i++) {
           resultado.append("new Array(\"" + tld[i].getField("id") + "\", \""
               + FormatUtilities.replaceJS(tld[i].getField("name")) + "\", \""
-              + ((tld[i].getField("id").equals(strPUOM)) ? "true" : "false") + "\")");
+              + ((tld[i].getField("id").equals(localStrPUOM)) ? "true" : "false") + "\")");
           if (i < tld.length - 1)
             resultado.append(",\n");
         }
@@ -173,7 +178,7 @@
         for (int i = 0; i < tld.length; i++) {
           resultado.append("new Array(\"" + tld[i].getField("id") + "\", \""
               + FormatUtilities.replaceJS(tld[i].getField("name")) + "\", \""
-              + ((tld[i].getField("id").equals(strPUOM)) ? "true" : "false") + "\")");
+              + ((tld[i].getField("id").equals(localStrPUOM)) ? "true" : "false") + "\")");
           if (i < tld.length - 1)
             resultado.append(",\n");
         }
--- a/src/org/openbravo/erpCommon/ad_callouts/SL_Inventory_Conversion.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_callouts/SL_Inventory_Conversion.java	Fri Jun 03 10:22:43 2016 +0200
@@ -65,23 +65,24 @@
   private void printPage(HttpServletResponse response, VariablesSecureApp vars, String strUOM,
       String strMProductUOMID, String strQuantityOrder, String strTabId) throws IOException,
       ServletException {
+    String localStrUOM = strUOM;
     if (log4j.isDebugEnabled())
       log4j.debug("Output: dataSheet");
     XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
         "org/openbravo/erpCommon/ad_callouts/CallOut").createXmlDocument();
-    if (strUOM.startsWith("\""))
-      strUOM = strUOM.substring(1, strUOM.length() - 1);
-    int stdPrecision = Integer.valueOf(SLInvoiceConversionData.stdPrecision(this, strUOM))
+    if (localStrUOM.startsWith("\""))
+      localStrUOM = localStrUOM.substring(1, localStrUOM.length() - 1);
+    int stdPrecision = Integer.valueOf(SLInvoiceConversionData.stdPrecision(this, localStrUOM))
         .intValue();
     String strInitUOM = SLInvoiceConversionData.initUOMId(this, strMProductUOMID);
     String strMultiplyRate;
     boolean check = false;
 
-    strMultiplyRate = SLInvoiceConversionData.multiplyRate(this, strInitUOM, strUOM);
-    if (strInitUOM.equals(strUOM))
+    strMultiplyRate = SLInvoiceConversionData.multiplyRate(this, strInitUOM, localStrUOM);
+    if (strInitUOM.equals(localStrUOM))
       strMultiplyRate = "1";
     if (strMultiplyRate.equals(""))
-      strMultiplyRate = SLInvoiceConversionData.divideRate(this, strUOM, strInitUOM);
+      strMultiplyRate = SLInvoiceConversionData.divideRate(this, localStrUOM, strInitUOM);
     if (strMultiplyRate.equals("")) {
       strMultiplyRate = "1";
       if (!strMProductUOMID.equals(""))
--- a/src/org/openbravo/erpCommon/ad_callouts/SL_InvoiceTax_Amt.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_callouts/SL_InvoiceTax_Amt.java	Fri Jun 03 10:22:43 2016 +0200
@@ -63,6 +63,10 @@
   private void printPage(HttpServletResponse response, VariablesSecureApp vars, String strChanged,
       String strTaxAmt, String strTaxBaseAmt, String strTaxId, String strInvoiceId)
       throws IOException, ServletException {
+    String localStrTaxId = strTaxId;
+    String localStrTaxBaseAmt = strTaxBaseAmt;
+    String localStrTaxAmt = strTaxAmt;
+    String localStrInvoiceId = strInvoiceId;
     if (log4j.isDebugEnabled())
       log4j.debug("Output: dataSheet");
     XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
@@ -71,20 +75,21 @@
     StringBuffer resultado = new StringBuffer();
 
     // Discount...
-    if (strTaxAmt.startsWith("\""))
-      strTaxAmt = strTaxAmt.substring(1, strTaxAmt.length() - 1);
-    if (strTaxBaseAmt.startsWith("\""))
-      strTaxBaseAmt = strTaxBaseAmt.substring(1, strTaxBaseAmt.length() - 1);
-    if (strTaxId.startsWith("\""))
-      strTaxId = strTaxId.substring(1, strTaxId.length() - 1);
-    if (strInvoiceId.startsWith("\""))
-      strInvoiceId = strInvoiceId.substring(1, strTaxId.length() - 1);
+    if (localStrTaxAmt.startsWith("\""))
+      localStrTaxAmt = localStrTaxAmt.substring(1, localStrTaxAmt.length() - 1);
+    if (localStrTaxBaseAmt.startsWith("\""))
+      localStrTaxBaseAmt = localStrTaxBaseAmt.substring(1, localStrTaxBaseAmt.length() - 1);
+    if (localStrTaxId.startsWith("\""))
+      localStrTaxId = localStrTaxId.substring(1, localStrTaxId.length() - 1);
+    if (localStrInvoiceId.startsWith("\""))
+      localStrInvoiceId = localStrInvoiceId.substring(1, localStrTaxId.length() - 1);
 
-    SLInvoiceTaxAmtData[] data = SLInvoiceTaxAmtData.select(this, strTaxId, strInvoiceId);
+    SLInvoiceTaxAmtData[] data = SLInvoiceTaxAmtData.select(this, localStrTaxId, localStrInvoiceId);
 
-    BigDecimal taxAmt = (strTaxAmt.equals("") ? new BigDecimal(0.0) : new BigDecimal(strTaxAmt));
-    BigDecimal taxBaseAmt = (strTaxBaseAmt.equals("") ? new BigDecimal(0.0) : new BigDecimal(
-        strTaxBaseAmt));
+    BigDecimal taxAmt = (localStrTaxAmt.equals("") ? new BigDecimal(0.0) : new BigDecimal(
+        localStrTaxAmt));
+    BigDecimal taxBaseAmt = (localStrTaxBaseAmt.equals("") ? new BigDecimal(0.0) : new BigDecimal(
+        localStrTaxBaseAmt));
     BigDecimal taxRate = (data[0].rate.equals("") ? new BigDecimal(1)
         : new BigDecimal(data[0].rate));
     Integer taxScale = new Integer(data[0].priceprecision);
--- a/src/org/openbravo/erpCommon/ad_callouts/SL_Invoice_Conversion.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_callouts/SL_Invoice_Conversion.java	Fri Jun 03 10:22:43 2016 +0200
@@ -65,23 +65,24 @@
   private void printPage(HttpServletResponse response, VariablesSecureApp vars, String strUOM,
       String strMProductUOMID, String strQuantityOrder, String strTabId) throws IOException,
       ServletException {
+    String localStrUOM = strUOM;
     if (log4j.isDebugEnabled())
       log4j.debug("Output: dataSheet");
     XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
         "org/openbravo/erpCommon/ad_callouts/CallOut").createXmlDocument();
-    if (strUOM.startsWith("\""))
-      strUOM = strUOM.substring(1, strUOM.length() - 1);
-    int stdPrecision = Integer.valueOf(SLInvoiceConversionData.stdPrecision(this, strUOM))
+    if (localStrUOM.startsWith("\""))
+      localStrUOM = localStrUOM.substring(1, localStrUOM.length() - 1);
+    int stdPrecision = Integer.valueOf(SLInvoiceConversionData.stdPrecision(this, localStrUOM))
         .intValue();
     String strInitUOM = SLInvoiceConversionData.initUOMId(this, strMProductUOMID);
     String strMultiplyRate;
     boolean check = false;
 
-    strMultiplyRate = SLInvoiceConversionData.multiplyRate(this, strInitUOM, strUOM);
-    if (strInitUOM.equals(strUOM))
+    strMultiplyRate = SLInvoiceConversionData.multiplyRate(this, strInitUOM, localStrUOM);
+    if (strInitUOM.equals(localStrUOM))
       strMultiplyRate = "1";
     if (strMultiplyRate.equals(""))
-      strMultiplyRate = SLInvoiceConversionData.divideRate(this, strUOM, strInitUOM);
+      strMultiplyRate = SLInvoiceConversionData.divideRate(this, localStrUOM, strInitUOM);
     if (strMultiplyRate.equals("")) {
       strMultiplyRate = "1";
       if (!strMProductUOMID.equals(""))
--- a/src/org/openbravo/erpCommon/ad_callouts/SL_JournalLineAmt.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_callouts/SL_JournalLineAmt.java	Fri Jun 03 10:22:43 2016 +0200
@@ -86,10 +86,9 @@
         "org/openbravo/erpCommon/ad_callouts/CallOut").createXmlDocument();
     String strAcctSchema = SLJournalLineAmtData.selectGeneralLedger(this, strGLJournal);
     SLJournalLineAmtData[] data = SLJournalLineAmtData.select(this, strAcctSchema);
-    String strPrecision = "2", strTargetCurrencyId = "";
+    String strPrecision = "2";
     if (data != null && data.length > 0) {
       strPrecision = data[0].stdprecision.equals("") ? "2" : data[0].stdprecision;
-      strTargetCurrencyId = data[0].cCurrencyId.equals("") ? "0" : data[0].cCurrencyId;
     }
     GLJournal gLJournal = OBDal.getInstance().get(GLJournal.class, strGLJournal);
     BigDecimal CurrencyRateValue = gLJournal.getRate();
--- a/src/org/openbravo/erpCommon/ad_callouts/SL_Journal_Period.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_callouts/SL_Journal_Period.java	Fri Jun 03 10:22:43 2016 +0200
@@ -72,6 +72,7 @@
       String strDateAcctNew, String strDateDocNew, String strcPeriodIdNew, String strWindowId,
       String strChanged, String strTabId, String strCurrencyId, String strAcctSchemaId,
       String strCurrencyRateType) throws IOException, ServletException {
+    String localStrChanged = strChanged;
     if (log4j.isDebugEnabled())
       log4j.debug("Output: dataSheet");
     XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
@@ -96,12 +97,12 @@
     String strDateAcct = strDateAcctNew;
     String strcPeriodId = strcPeriodIdNew;
     // When DateDoc is changed, update DateAcct
-    if (strChanged.equals("inpdatedoc")) {
+    if (localStrChanged.equals("inpdatedoc")) {
       strDateAcct = strDateDocNew;
-      strChanged = "inpdateacct";
+      localStrChanged = "inpdateacct";
     }
     // When DateAcct is changed, set C_Period_ID
-    if (strChanged.equals("inpdateacct")) {
+    if (localStrChanged.equals("inpdateacct")) {
       strcPeriodId = SLJournalPeriodData.period(this, stradClientId, stradOrgId, strDateAcct);
       if (strcPeriodId.equals("")) {
         StringBuffer resultado = new StringBuffer();
@@ -121,7 +122,7 @@
 
     }
     boolean isStandardPeriod = true;
-    if (strChanged.equals("inpcPeriodId") && !strcPeriodId.equals("")) {
+    if (localStrChanged.equals("inpcPeriodId") && !strcPeriodId.equals("")) {
       // When C_Period_ID is changed, check if in DateAcct range and set
       // to end date if not
       SLJournalPeriodData[] data = SLJournalPeriodData.select(this, strcPeriodId);
--- a/src/org/openbravo/erpCommon/ad_callouts/SL_MachineCost.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_callouts/SL_MachineCost.java	Fri Jun 03 10:22:43 2016 +0200
@@ -73,6 +73,11 @@
       String strDaysYear, String strDayHours, String strImproductiveHoursYear,
       String strCostUomYear, String strCost, String strCostUom) throws IOException,
       ServletException {
+    String localStrYearValue = strYearValue;
+    String localStrImproductiveHoursYear = strImproductiveHoursYear;
+    String localStrCostUomYear = strCostUomYear;
+    String localStrCost = strCost;
+    String localStrAmortization = strAmortization;
     if (log4j.isDebugEnabled())
       log4j.debug("Output: dataSheet");
     XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
@@ -81,78 +86,81 @@
     if (strChanged.equals("inppurchaseamt") || strChanged.equals("inptoolsetamt")
         || strChanged.equals("inpyearvalue")) {
       if (strPurchaseAmt != null && !strPurchaseAmt.equals("") && strToolsetAmt != null
-          && !strToolsetAmt.equals("") && strYearValue != null && !strYearValue.equals("")) {
+          && !strToolsetAmt.equals("") && localStrYearValue != null
+          && !localStrYearValue.equals("")) {
         BigDecimal fPurchaseAmt = new BigDecimal(strPurchaseAmt);
         BigDecimal fToolsetAmt = new BigDecimal(strToolsetAmt);
-        BigDecimal fYearValue = new BigDecimal(strYearValue);
+        BigDecimal fYearValue = new BigDecimal(localStrYearValue);
         BigDecimal fAmortization = (fPurchaseAmt.add(fToolsetAmt)).divide(fYearValue, 12,
             BigDecimal.ROUND_HALF_EVEN);
-        strAmortization = fAmortization.toString();
+        localStrAmortization = fAmortization.toString();
 
-        if (strCostUomYear != null && !strCostUomYear.equals("")) {
-          BigDecimal fCostUomYear = new BigDecimal(strCostUomYear);
+        if (localStrCostUomYear != null && !localStrCostUomYear.equals("")) {
+          BigDecimal fCostUomYear = new BigDecimal(localStrCostUomYear);
           BigDecimal fCost = fYearValue.divide(fCostUomYear, 12, BigDecimal.ROUND_HALF_EVEN);
-          strCost = fCost.toPlainString();
+          localStrCost = fCost.toPlainString();
         }
       }
     } else if (strChanged.equals("inpamortization")) {
       if (strPurchaseAmt != null && !strPurchaseAmt.equals("") && strToolsetAmt != null
-          && !strToolsetAmt.equals("") && strAmortization != null && !strAmortization.equals("")) {
+          && !strToolsetAmt.equals("") && localStrAmortization != null
+          && !localStrAmortization.equals("")) {
         BigDecimal fPurchaseAmt = new BigDecimal(strPurchaseAmt);
         BigDecimal fToolsetAmt = new BigDecimal(strToolsetAmt);
-        BigDecimal fAmortization = new BigDecimal(strAmortization);
+        BigDecimal fAmortization = new BigDecimal(localStrAmortization);
         BigDecimal fYearValue = (fPurchaseAmt.add(fToolsetAmt)).divide(fAmortization, 12,
             BigDecimal.ROUND_HALF_EVEN);
-        strYearValue = fYearValue.toPlainString();
+        localStrYearValue = fYearValue.toPlainString();
 
-        if (strCostUomYear != null && !strCostUomYear.equals("")) {
-          BigDecimal fCostUomYear = new BigDecimal(strCostUomYear);
+        if (localStrCostUomYear != null && !localStrCostUomYear.equals("")) {
+          BigDecimal fCostUomYear = new BigDecimal(localStrCostUomYear);
           BigDecimal fCost = fYearValue.divide(fCostUomYear, 12, BigDecimal.ROUND_HALF_EVEN);
-          strCost = fCost.toPlainString();
+          localStrCost = fCost.toPlainString();
         }
       }
     } else if (strChanged.equals("inpdaysyear") || strChanged.equals("inpdayhours")
         || strChanged.equals("inpimproductivehoursyear")) {
       if (strDaysYear != null && !strDaysYear.equals("") && strDayHours != null
-          && !strDayHours.equals("") && strImproductiveHoursYear != null
-          && !strImproductiveHoursYear.equals("")) {
+          && !strDayHours.equals("") && localStrImproductiveHoursYear != null
+          && !localStrImproductiveHoursYear.equals("")) {
         BigDecimal fDaysYear = new BigDecimal(strDaysYear);
         BigDecimal fDayHours = new BigDecimal(strDayHours);
-        BigDecimal fImproductiveHoursYear = new BigDecimal(strImproductiveHoursYear);
+        BigDecimal fImproductiveHoursYear = new BigDecimal(localStrImproductiveHoursYear);
         BigDecimal fCostUomYear = (fDaysYear.multiply(fDayHours)).subtract(fImproductiveHoursYear);
-        strCostUomYear = fCostUomYear.toPlainString();
+        localStrCostUomYear = fCostUomYear.toPlainString();
 
-        if (strYearValue != null && !strYearValue.equals("")) {
-          BigDecimal fYearValue = new BigDecimal(strYearValue);
+        if (localStrYearValue != null && !localStrYearValue.equals("")) {
+          BigDecimal fYearValue = new BigDecimal(localStrYearValue);
           BigDecimal fCost = fYearValue.divide(fCostUomYear, 12, BigDecimal.ROUND_HALF_EVEN);
-          strCost = fCost.toPlainString();
+          localStrCost = fCost.toPlainString();
         }
       }
     } else if (strChanged.equals("inpcostuomyear")) {
       if (strCostUom.equals("H"))
         if (strDaysYear != null && !strDaysYear.equals("") && strDayHours != null
-            && !strDayHours.equals("") && strCostUomYear != null && !strCostUomYear.equals("")) {
+            && !strDayHours.equals("") && localStrCostUomYear != null
+            && !localStrCostUomYear.equals("")) {
           BigDecimal fDaysYear = new BigDecimal(strDaysYear);
           BigDecimal fDayHours = new BigDecimal(strDayHours);
-          BigDecimal fCostUomYear = new BigDecimal(strCostUomYear);
+          BigDecimal fCostUomYear = new BigDecimal(localStrCostUomYear);
           BigDecimal fImproductiveHoursYear = (fDaysYear.multiply(fDayHours))
               .subtract(fCostUomYear);
-          strImproductiveHoursYear = fImproductiveHoursYear.toPlainString();
+          localStrImproductiveHoursYear = fImproductiveHoursYear.toPlainString();
         }
-      if (strYearValue != null && !strYearValue.equals("") && strCostUomYear != null
-          && !strCostUomYear.equals("")) {
-        BigDecimal fYearValue = new BigDecimal(strYearValue);
-        BigDecimal fCostUomYear = new BigDecimal(strCostUomYear);
+      if (localStrYearValue != null && !localStrYearValue.equals("") && localStrCostUomYear != null
+          && !localStrCostUomYear.equals("")) {
+        BigDecimal fYearValue = new BigDecimal(localStrYearValue);
+        BigDecimal fCostUomYear = new BigDecimal(localStrCostUomYear);
         BigDecimal fCost = fYearValue.divide(fCostUomYear, 12, BigDecimal.ROUND_HALF_EVEN);
-        strCost = fCost.toPlainString();
+        localStrCost = fCost.toPlainString();
       }
     } else if (strChanged.equals("inpcost")) {
-      if (strCost != null && !strCost.equals("") && strCostUomYear != null
-          && !strCostUomYear.equals("")) {
-        BigDecimal fCostUomYear = new BigDecimal(strCostUomYear);
-        BigDecimal fCost = new BigDecimal(strCost);
+      if (localStrCost != null && !localStrCost.equals("") && localStrCostUomYear != null
+          && !localStrCostUomYear.equals("")) {
+        BigDecimal fCostUomYear = new BigDecimal(localStrCostUomYear);
+        BigDecimal fCost = new BigDecimal(localStrCost);
         BigDecimal fYearValue = fCost.multiply(fCostUomYear);
-        strYearValue = fYearValue.toPlainString();
+        localStrYearValue = fYearValue.toPlainString();
 
         if (strPurchaseAmt != null && !strPurchaseAmt.equals("") && strToolsetAmt != null
             && !strToolsetAmt.equals("")) {
@@ -160,7 +168,7 @@
           BigDecimal fToolsetAmt = new BigDecimal(strToolsetAmt);
           BigDecimal fAmortization = (fPurchaseAmt.add(fToolsetAmt)).divide(fYearValue, 12,
               BigDecimal.ROUND_HALF_EVEN);
-          strAmortization = fAmortization.toPlainString();
+          localStrAmortization = fAmortization.toPlainString();
         }
       }
     }
@@ -174,11 +182,11 @@
     if (!"".equals(strToolsetAmt) && strToolsetAmt != null) {
       resultado.append("new Array(\"inptoolsetamt\", " + strToolsetAmt + "),\n");
     }
-    if (!"".equals(strYearValue) && strYearValue != null) {
-      resultado.append("new Array(\"inpyearvalue\", " + strYearValue + "),\n");
+    if (!"".equals(localStrYearValue) && localStrYearValue != null) {
+      resultado.append("new Array(\"inpyearvalue\", " + localStrYearValue + "),\n");
     }
-    if (!"".equals(strAmortization) && strAmortization != null) {
-      resultado.append("new Array(\"inpamortization\", " + strAmortization + "), \n");
+    if (!"".equals(localStrAmortization) && localStrAmortization != null) {
+      resultado.append("new Array(\"inpamortization\", " + localStrAmortization + "), \n");
     }
     if (!"".equals(strDaysYear) && strDaysYear != null) {
       resultado.append("new Array(\"inpdaysyear\", " + strDaysYear + "),\n");
@@ -186,15 +194,15 @@
     if (!"".equals(strDayHours) && strDayHours != null) {
       resultado.append("new Array(\"inpdayhours\", " + strDayHours + "),\n");
     }
-    if (!"".equals(strImproductiveHoursYear) && strImproductiveHoursYear != null) {
-      resultado.append("new Array(\"inpimproductivehoursyear\", " + strImproductiveHoursYear
+    if (!"".equals(localStrImproductiveHoursYear) && localStrImproductiveHoursYear != null) {
+      resultado.append("new Array(\"inpimproductivehoursyear\", " + localStrImproductiveHoursYear
           + "),\n");
     }
-    if (!"".equals(strCostUomYear) && strCostUomYear != null) {
-      resultado.append("new Array(\"inpcostuomyear\", " + strCostUomYear + "),\n");
+    if (!"".equals(localStrCostUomYear) && localStrCostUomYear != null) {
+      resultado.append("new Array(\"inpcostuomyear\", " + localStrCostUomYear + "),\n");
     }
-    if (!"".equals(strCost) && strCost != null) {
-      resultado.append("new Array(\"inpcost\", " + strCost + ") \n");
+    if (!"".equals(localStrCost) && localStrCost != null) {
+      resultado.append("new Array(\"inpcost\", " + localStrCost + ") \n");
     }
     resultado.append(");\n");
     xmlDocument.setParameter("array", resultado.toString());
--- a/src/org/openbravo/erpCommon/ad_callouts/SL_Movement_Conversion.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_callouts/SL_Movement_Conversion.java	Fri Jun 03 10:22:43 2016 +0200
@@ -65,23 +65,24 @@
   private void printPage(HttpServletResponse response, VariablesSecureApp vars, String strUOM,
       String strMProductUOMID, String strQuantityOrder, String strTabId) throws IOException,
       ServletException {
+    String localStrUOM = strUOM;
     if (log4j.isDebugEnabled())
       log4j.debug("Output: dataSheet");
     XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
         "org/openbravo/erpCommon/ad_callouts/CallOut").createXmlDocument();
-    if (strUOM.startsWith("\""))
-      strUOM = strUOM.substring(1, strUOM.length() - 1);
-    int stdPrecision = Integer.valueOf(SLInvoiceConversionData.stdPrecision(this, strUOM))
+    if (localStrUOM.startsWith("\""))
+      localStrUOM = localStrUOM.substring(1, localStrUOM.length() - 1);
+    int stdPrecision = Integer.valueOf(SLInvoiceConversionData.stdPrecision(this, localStrUOM))
         .intValue();
     String strInitUOM = SLInvoiceConversionData.initUOMId(this, strMProductUOMID);
     String strMultiplyRate;
     boolean check = false;
 
-    strMultiplyRate = SLInvoiceConversionData.multiplyRate(this, strInitUOM, strUOM);
-    if (strInitUOM.equals(strUOM))
+    strMultiplyRate = SLInvoiceConversionData.multiplyRate(this, strInitUOM, localStrUOM);
+    if (strInitUOM.equals(localStrUOM))
       strMultiplyRate = "1";
     if (strMultiplyRate.equals(""))
-      strMultiplyRate = SLInvoiceConversionData.divideRate(this, strUOM, strInitUOM);
+      strMultiplyRate = SLInvoiceConversionData.divideRate(this, localStrUOM, strInitUOM);
     if (strMultiplyRate.equals("")) {
       strMultiplyRate = "1";
       if (!strMProductUOMID.equals(""))
--- a/src/org/openbravo/erpCommon/ad_callouts/SL_Order_Conversion.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_callouts/SL_Order_Conversion.java	Fri Jun 03 10:22:43 2016 +0200
@@ -65,22 +65,23 @@
   private void printPage(HttpServletResponse response, VariablesSecureApp vars, String strUOM,
       String strMProductUOMID, String strQuantityOrder, String strChanged, String strTabId)
       throws IOException, ServletException {
+    String localStrUOM = strUOM;
     if (log4j.isDebugEnabled())
       log4j.debug("Output: dataSheet");
     XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
         "org/openbravo/erpCommon/ad_callouts/CallOut").createXmlDocument();
-    if (strUOM.startsWith("\""))
-      strUOM = strUOM.substring(1, strUOM.length() - 1);
-    String strPrecision = SLInvoiceConversionData.stdPrecision(this, strUOM);
+    if (localStrUOM.startsWith("\""))
+      localStrUOM = localStrUOM.substring(1, localStrUOM.length() - 1);
+    String strPrecision = SLInvoiceConversionData.stdPrecision(this, localStrUOM);
     int stdPrecision = strPrecision.equals("") ? 0 : Integer.valueOf(strPrecision).intValue();
     String strInitUOM = SLInvoiceConversionData.initUOMId(this, strMProductUOMID);
     String strMultiplyRate;
     boolean check = false;
-    strMultiplyRate = SLInvoiceConversionData.multiplyRate(this, strInitUOM, strUOM);
-    if (strInitUOM.equals(strUOM))
+    strMultiplyRate = SLInvoiceConversionData.multiplyRate(this, strInitUOM, localStrUOM);
+    if (strInitUOM.equals(localStrUOM))
       strMultiplyRate = "1";
     if (strMultiplyRate.equals(""))
-      strMultiplyRate = SLInvoiceConversionData.divideRate(this, strUOM, strInitUOM);
+      strMultiplyRate = SLInvoiceConversionData.divideRate(this, localStrUOM, strInitUOM);
     if (strMultiplyRate.equals("")) {
       strMultiplyRate = "1";
       if (!strMProductUOMID.equals(""))
--- a/src/org/openbravo/erpCommon/ad_callouts/SL_Order_UpdateLinesDate.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_callouts/SL_Order_UpdateLinesDate.java	Fri Jun 03 10:22:43 2016 +0200
@@ -18,13 +18,9 @@
  */
 package org.openbravo.erpCommon.ad_callouts;
 
-import java.text.SimpleDateFormat;
-import java.util.Date;
-
 import javax.servlet.ServletException;
 
 import org.hibernate.criterion.Restrictions;
-import org.openbravo.base.session.OBPropertiesProvider;
 import org.openbravo.dal.core.OBContext;
 import org.openbravo.dal.service.OBCriteria;
 import org.openbravo.dal.service.OBDal;
@@ -44,11 +40,6 @@
     try {
       OBContext.setAdminMode();
       String lastChanged = info.getStringParameter("inpLastFieldChanged", null);
-      String lastChangedValue = info.getStringParameter(lastChanged, null);
-      String format = OBPropertiesProvider.getInstance().getOpenbravoProperties()
-          .getProperty("dateFormat.java");
-      SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
-      Date d = simpleDateFormat.parse(lastChangedValue);
       String id = info.getStringParameter("C_Order_ID", null);
 
       /*
--- a/src/org/openbravo/erpCommon/ad_callouts/SL_PC_Case_Product.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_callouts/SL_PC_Case_Product.java	Fri Jun 03 10:22:43 2016 +0200
@@ -64,18 +64,19 @@
 
   private void printPage(HttpServletResponse response, VariablesSecureApp vars, String strTabId,
       String strMProductID, String strPAttr) throws IOException, ServletException {
+    String localStrPAttr = strPAttr;
     XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
         "org/openbravo/erpCommon/ad_callouts/CallOut").createXmlDocument();
 
     StringBuffer result = new StringBuffer();
     result.append("var calloutName='SL_PC_Case_Product';\n\n");
     result.append("var respuesta = new Array(");
-    if (strPAttr.startsWith("\""))
-      strPAttr = strPAttr.substring(1, strPAttr.length() - 1);
-    result.append("new Array(\"inpmAttributesetinstanceId\", \"" + strPAttr + "\"),\n");
+    if (localStrPAttr.startsWith("\""))
+      localStrPAttr = localStrPAttr.substring(1, localStrPAttr.length() - 1);
+    result.append("new Array(\"inpmAttributesetinstanceId\", \"" + localStrPAttr + "\"),\n");
     String strattrsetvaluesdescr = "";
     final AttributeSetInstance attributesetinstance = OBDal.getInstance().get(
-        AttributeSetInstance.class, strPAttr);
+        AttributeSetInstance.class, localStrPAttr);
     if (attributesetinstance != null) {
       strattrsetvaluesdescr = attributesetinstance.getDescription();
     }
--- a/src/org/openbravo/erpCommon/ad_callouts/SL_Payment_Amounts.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_callouts/SL_Payment_Amounts.java	Fri Jun 03 10:22:43 2016 +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) 2001-2010 Openbravo SLU 
+ * All portions are Copyright (C) 2001-2016 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -39,8 +39,6 @@
 public class SL_Payment_Amounts extends HttpSecureAppServlet {
   private static final long serialVersionUID = 1L;
 
-  private static final BigDecimal ZERO = new BigDecimal(0.0);
-
   public void init(ServletConfig config) {
     super.init(config);
     boolHist = false;
@@ -85,25 +83,15 @@
     BigDecimal payamt, discountamt, writeoffamt, overunderamt, convert, invtotamt;
 
     payamt = new BigDecimal(strPayamt);
-    if (payamt == null)
-      payamt = ZERO;
     discountamt = new BigDecimal(strDiscountamt);
-    if (discountamt == null)
-      discountamt = ZERO;
     writeoffamt = new BigDecimal(strWriteoffamt);
-    if (writeoffamt == null)
-      writeoffamt = ZERO;
     overunderamt = new BigDecimal(strOverunderamt);
-    if (overunderamt == null)
-      overunderamt = ZERO;
 
     StringBuffer resultado = new StringBuffer();
     resultado.append("var calloutName='SL_Payment_Amounts';\n\n");
     resultado.append("var respuesta = new Array(");
     if (strChanged.equals("inpisoverunderpayment")) {
       overunderamt = new BigDecimal(strOverunderamt);
-      if (overunderamt == null)
-        overunderamt = ZERO;
       resultado.append("new Array(\"inpoverunderamt\", " + overunderamt.toString() + ")");
     }
 
@@ -174,8 +162,6 @@
       if (log4j.isDebugEnabled())
         log4j.debug("PAYMENT: " + data[0].grand + "CURRENCYID: " + data[0].currencyid);
       invtotamt = new BigDecimal(data[0].grand);
-      if (invtotamt == null)
-        invtotamt = ZERO;
       if (strcCurrencyId.equals(data[0].currencyid)) {
       } else {
         String strconvert = SLPaymentAmountsData.selectConversion(this, data[0].currencyid,
@@ -188,8 +174,6 @@
     } else if (strChanged.equals("inpdiscountamt")) {
       SLPaymentAmountsData[] data = SLPaymentAmountsData.select(this, strcInvoiceId);
       invtotamt = new BigDecimal(data[0].grand);
-      if (invtotamt == null)
-        invtotamt = ZERO;
       if (strcCurrencyId.equals(data[0].currencyid)) {
       } else {
         String strconvert = SLPaymentAmountsData.selectConversion(this, data[0].currencyid,
@@ -202,8 +186,6 @@
     } else if (strChanged.equals("inpwriteoffamt")) {
       SLPaymentAmountsData[] data = SLPaymentAmountsData.select(this, strcInvoiceId);
       invtotamt = new BigDecimal(data[0].grand);
-      if (invtotamt == null)
-        invtotamt = ZERO;
       if (strcCurrencyId.equals(data[0].currencyid)) {
       } else {
         String strconvert = SLPaymentAmountsData.selectConversion(this, data[0].currencyid,
@@ -216,8 +198,6 @@
     } else if (strChanged.equals("inpoverunderamt")) {
       SLPaymentAmountsData[] data = SLPaymentAmountsData.select(this, strcInvoiceId);
       invtotamt = new BigDecimal(data[0].grand);
-      if (invtotamt == null)
-        invtotamt = ZERO;
       invtotamt = invtotamt.subtract(overunderamt).subtract(writeoffamt).subtract(discountamt);
       resultado.append("new Array(\"inppayamt\", " + invtotamt.toString() + ")");
     }
--- a/src/org/openbravo/erpCommon/ad_callouts/SL_Production_Conversion.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_callouts/SL_Production_Conversion.java	Fri Jun 03 10:22:43 2016 +0200
@@ -64,23 +64,24 @@
   private void printPage(HttpServletResponse response, VariablesSecureApp vars, String strUOM,
       String strMProductUOMID, String strQuantityOrder, String strTabId) throws IOException,
       ServletException {
+    String localStrUOM = strUOM;
     if (log4j.isDebugEnabled())
       log4j.debug("Output: dataSheet");
     XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
         "org/openbravo/erpCommon/ad_callouts/CallOut").createXmlDocument();
-    if (strUOM.startsWith("\""))
-      strUOM = strUOM.substring(1, strUOM.length() - 1);
-    int stdPrecision = Integer.valueOf(SLInvoiceConversionData.stdPrecision(this, strUOM))
+    if (localStrUOM.startsWith("\""))
+      localStrUOM = localStrUOM.substring(1, localStrUOM.length() - 1);
+    int stdPrecision = Integer.valueOf(SLInvoiceConversionData.stdPrecision(this, localStrUOM))
         .intValue();
     String strInitUOM = SLInvoiceConversionData.initUOMId(this, strMProductUOMID);
     String strMultiplyRate;
     boolean check = false;
 
-    strMultiplyRate = SLInvoiceConversionData.multiplyRate(this, strInitUOM, strUOM);
-    if (strInitUOM.equals(strUOM))
+    strMultiplyRate = SLInvoiceConversionData.multiplyRate(this, strInitUOM, localStrUOM);
+    if (strInitUOM.equals(localStrUOM))
       strMultiplyRate = "1";
     if (strMultiplyRate.equals(""))
-      strMultiplyRate = SLInvoiceConversionData.divideRate(this, strUOM, strInitUOM);
+      strMultiplyRate = SLInvoiceConversionData.divideRate(this, localStrUOM, strInitUOM);
     if (strMultiplyRate.equals("")) {
       strMultiplyRate = "1";
       if (!strMProductUOMID.equals(""))
--- a/src/org/openbravo/erpCommon/ad_callouts/SL_Production_Product.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_callouts/SL_Production_Product.java	Fri Jun 03 10:22:43 2016 +0200
@@ -76,6 +76,9 @@
   private void printPage(HttpServletResponse response, VariablesSecureApp vars, String strChanged,
       String strProduct, String strPLocator, String strPAttr, String strPQty, String strPUOM,
       String strQty, String strUOM, String strTabId) throws IOException, ServletException {
+    String localStrPUOM = strPUOM;
+    String localStrPLocator = strPLocator;
+    String localStrPAttr = strPAttr;
     if (log4j.isDebugEnabled())
       log4j.debug("Output: dataSheet");
     XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
@@ -85,19 +88,20 @@
     resultado.append("var calloutName='SL_Production_Product';\n\n");
     resultado.append("var respuesta = new Array(");
     resultado.append("new Array(\"inpcUomId\", \"" + strUOM + "\"),\n");
-    if (strPLocator.startsWith("\""))
-      strPLocator = strPLocator.substring(1, strPLocator.length() - 1);
-    resultado.append("new Array(\"inpmLocatorId\", \"" + strPLocator + "\"),\n");
+    if (localStrPLocator.startsWith("\""))
+      localStrPLocator = localStrPLocator.substring(1, localStrPLocator.length() - 1);
+    resultado.append("new Array(\"inpmLocatorId\", \"" + localStrPLocator + "\"),\n");
     resultado.append("new Array(\"inpmLocatorId_R\", \""
-        + FormatUtilities.replaceJS(SLProductionProductData.selectLocator(this, strPLocator))
+        + FormatUtilities.replaceJS(SLProductionProductData.selectLocator(this, localStrPLocator))
         + "\"),\n");
     String strHasSecondaryUOM = SLOrderProductData.hasSecondaryUOM(this, strProduct);
     resultado.append("new Array(\"inphasseconduom\", " + strHasSecondaryUOM + "),\n");
-    if (strPAttr.startsWith("\""))
-      strPAttr = strPAttr.substring(1, strPAttr.length() - 1);
-    resultado.append("new Array(\"inpmAttributesetinstanceId\", \"" + strPAttr + "\"),\n");
+    if (localStrPAttr.startsWith("\""))
+      localStrPAttr = localStrPAttr.substring(1, localStrPAttr.length() - 1);
+    resultado.append("new Array(\"inpmAttributesetinstanceId\", \"" + localStrPAttr + "\"),\n");
     resultado.append("new Array(\"inpmAttributesetinstanceId_R\", \""
-        + FormatUtilities.replaceJS(SLInOutLineProductData.attribute(this, strPAttr)) + "\"),\n");
+        + FormatUtilities.replaceJS(SLInOutLineProductData.attribute(this, localStrPAttr))
+        + "\"),\n");
     String strAttrSet, strAttrSetValueType;
     strAttrSet = strAttrSetValueType = "";
     OBContext.setAdminMode();
@@ -115,14 +119,15 @@
     resultado.append("new Array(\"inpattributeset\", \"" + FormatUtilities.replaceJS(strAttrSet)
         + "\"),\n");
     resultado.append("new Array(\"inpattrsetvaluetype\", \""
-        + FormatUtilities.replaceJS(strAttrSetValueType == null ? "":strAttrSetValueType) + "\"),\n");
+        + FormatUtilities.replaceJS(strAttrSetValueType == null ? "" : strAttrSetValueType)
+        + "\"),\n");
     resultado.append("new Array(\"inpmovementqty\", " + (strQty.equals("") ? "\"\"" : strQty)
         + "),\n");
     resultado.append("new Array(\"inpquantityorder\", " + (strPQty.equals("") ? "\"\"" : strPQty)
         + "),\n");
- 
-    if (strPUOM.startsWith("\""))
-      strPUOM = strPUOM.substring(1, strPUOM.length() - 1);
+
+    if (localStrPUOM.startsWith("\""))
+      localStrPUOM = localStrPUOM.substring(1, localStrPUOM.length() - 1);
     resultado.append("new Array(\"inpmProductUomId\", ");
     if (vars.getLanguage().equals("en_US")) {
       FieldProvider[] tld = null;
@@ -143,7 +148,7 @@
         for (int i = 0; i < tld.length; i++) {
           resultado.append("new Array(\"" + tld[i].getField("id") + "\", \""
               + FormatUtilities.replaceJS(tld[i].getField("name")) + "\", \""
-              + ((tld[i].getField("id").equals(strPUOM)) ? "true" : "false") + "\")");
+              + ((tld[i].getField("id").equals(localStrPUOM)) ? "true" : "false") + "\")");
           if (i < tld.length - 1)
             resultado.append(",\n");
         }
@@ -170,7 +175,7 @@
         for (int i = 0; i < tld.length; i++) {
           resultado.append("new Array(\"" + tld[i].getField("id") + "\", \""
               + FormatUtilities.replaceJS(tld[i].getField("name")) + "\", \""
-              + ((tld[i].getField("id").equals(strPUOM)) ? "true" : "false") + "\")");
+              + ((tld[i].getField("id").equals(localStrPUOM)) ? "true" : "false") + "\")");
           if (i < tld.length - 1)
             resultado.append(",\n");
         }
--- a/src/org/openbravo/erpCommon/ad_callouts/SL_RequisitionLine_Conversion.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_callouts/SL_RequisitionLine_Conversion.java	Fri Jun 03 10:22:43 2016 +0200
@@ -65,23 +65,24 @@
   private void printPage(HttpServletResponse response, VariablesSecureApp vars, String strUOM,
       String strMProductUOMID, String strQuantityOrder, String strTabId) throws IOException,
       ServletException {
+    String localStrUOM = strUOM;
     if (log4j.isDebugEnabled())
       log4j.debug("Output: dataSheet");
     XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
         "org/openbravo/erpCommon/ad_callouts/CallOut").createXmlDocument();
-    if (strUOM.startsWith("\""))
-      strUOM = strUOM.substring(1, strUOM.length() - 1);
-    int stdPrecision = Integer.valueOf(SLRequisitionLineConversionData.stdPrecision(this, strUOM))
-        .intValue();
+    if (localStrUOM.startsWith("\""))
+      localStrUOM = localStrUOM.substring(1, localStrUOM.length() - 1);
+    int stdPrecision = Integer.valueOf(
+        SLRequisitionLineConversionData.stdPrecision(this, localStrUOM)).intValue();
     String strInitUOM = SLRequisitionLineConversionData.initUOMId(this, strMProductUOMID);
     String strMultiplyRate;
     boolean check = false;
 
-    strMultiplyRate = SLRequisitionLineConversionData.multiplyRate(this, strInitUOM, strUOM);
-    if (strInitUOM.equals(strUOM))
+    strMultiplyRate = SLRequisitionLineConversionData.multiplyRate(this, strInitUOM, localStrUOM);
+    if (strInitUOM.equals(localStrUOM))
       strMultiplyRate = "1";
     if (strMultiplyRate.equals(""))
-      strMultiplyRate = SLRequisitionLineConversionData.divideRate(this, strUOM, strInitUOM);
+      strMultiplyRate = SLRequisitionLineConversionData.divideRate(this, localStrUOM, strInitUOM);
     if (strMultiplyRate.equals("")) {
       strMultiplyRate = "1";
       if (!strMProductUOMID.equals(""))
--- a/src/org/openbravo/erpCommon/ad_callouts/SL_RequisitionLine_Product.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_callouts/SL_RequisitionLine_Product.java	Fri Jun 03 10:22:43 2016 +0200
@@ -79,6 +79,8 @@
       String strMProductID, String strWindowId, String strTabId, String strAttribute,
       String strUOM, String strRequisition, String strPriceListId, String strChanged)
       throws IOException, ServletException {
+    String localStrPriceListId = strPriceListId;
+    String localStrAttribute = strAttribute;
     if (log4j.isDebugEnabled())
       log4j.debug("Output: dataSheet");
     XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
@@ -92,7 +94,7 @@
 
     OBContext.setAdminMode(true);
     try {
-      PriceList pList = OBDal.getInstance().get(PriceList.class, strPriceListId);
+      PriceList pList = OBDal.getInstance().get(PriceList.class, localStrPriceListId);
       if (pList != null) {
         strResult.append("new Array(\"inpcCurrencyId\", \"" + pList.getCurrency().getId()
             + "\"),\n");
@@ -103,16 +105,16 @@
 
     if (!strMProductID.equals("")) {
       String strDueDate = vars.getStringParameter("inpneedbydate", DateTimeData.today(this));
-      if (strPriceListId.equals(""))
-        strPriceListId = SLRequisitionLineProductData.selectPriceList(this, strRequisition);
-      if (!strPriceListId.equals("")) {
-        if (OBDal.getInstance().get(PriceList.class, strPriceListId).isPriceIncludesTax()) {
+      if (localStrPriceListId.equals(""))
+        localStrPriceListId = SLRequisitionLineProductData.selectPriceList(this, strRequisition);
+      if (!localStrPriceListId.equals("")) {
+        if (OBDal.getInstance().get(PriceList.class, localStrPriceListId).isPriceIncludesTax()) {
           strResult.append("new Array(\"inpgrossprice\", \"Y\"),\n"); // auxiliaryInput
         } else {
           strResult.append("new Array(\"inpgrossprice\",  \"N\"),\n"); // auxiliaryInput
         }
         String strPriceListVersion = SLRequisitionLineProductData.selectPriceListVersion(this,
-            strPriceListId, strDueDate);
+            localStrPriceListId, strDueDate);
         if (!strPriceListVersion.equals("")) {
           SLRequisitionLineProductData[] prices = SLRequisitionLineProductData.getPrices(this,
               strMProductID, strPriceListVersion);
@@ -142,7 +144,8 @@
               }
               strResult.append("new Array(\"inppricelist\", "
                   + (strPriceList.equals("") ? "\"\"" : strPriceList) + "),\n");
-              if (OBDal.getInstance().get(PriceList.class, strPriceListId).isPriceIncludesTax()) {
+              if (OBDal.getInstance().get(PriceList.class, localStrPriceListId)
+                  .isPriceIncludesTax()) {
                 strResult.append("new Array(\"inpgrossUnitPrice\", "
                     + (strPriceActual.equals("") ? "0" : strPriceActual) + "),\n");
               } else {
@@ -162,12 +165,13 @@
     if (strChanged.equals("inpmProductId")) {
       strResult.append("new Array(\"inpcUomId\", "
           + (strUOM.equals("") ? "\"\"" : "\"" + strUOM + "\"") + "),\n");
-      if (strAttribute.startsWith("\""))
-        strAttribute = strAttribute.substring(1, strAttribute.length() - 1);
-      strResult.append("new Array(\"inpmAttributesetinstanceId\", \"" + strAttribute + "\"),\n");
+      if (localStrAttribute.startsWith("\""))
+        localStrAttribute = localStrAttribute.substring(1, localStrAttribute.length() - 1);
+      strResult.append("new Array(\"inpmAttributesetinstanceId\", \"" + localStrAttribute
+          + "\"),\n");
       strResult.append("new Array(\"inpmAttributesetinstanceId_R\", \""
-          + FormatUtilities.replaceJS(SLRequisitionLineProductData.attribute(this, strAttribute))
-          + "\"),\n");
+          + FormatUtilities.replaceJS(SLRequisitionLineProductData.attribute(this,
+              localStrAttribute)) + "\"),\n");
       String strAttrSet, strAttrSetValueType;
       strAttrSet = strAttrSetValueType = "";
       OBContext.setAdminMode();
@@ -182,12 +186,12 @@
       } finally {
         OBContext.restorePreviousMode();
       }
-      strResult.append("new Array(\"inpattributeset\", \"" 
-          + (strAttrSet == null || strAttrSet.equals("") ? "" : FormatUtilities.replaceJS(strAttrSet))
-          + "\"),\n");
-      strResult.append("new Array(\"inpattrsetvaluetype\", \"" 
-          + (strAttrSetValueType == null || strAttrSetValueType.equals("") ? "" : FormatUtilities.replaceJS(strAttrSetValueType))
-          + "\"),\n");
+      strResult.append("new Array(\"inpattributeset\", \""
+          + (strAttrSet == null || strAttrSet.equals("") ? "" : FormatUtilities
+              .replaceJS(strAttrSet)) + "\"),\n");
+      strResult.append("new Array(\"inpattrsetvaluetype\", \""
+          + (strAttrSetValueType == null || strAttrSetValueType.equals("") ? "" : FormatUtilities
+              .replaceJS(strAttrSetValueType)) + "\"),\n");
       String strHasSecondaryUOM = SLRequisitionLineProductData.hasSecondaryUOM(this, strMProductID);
       strResult.append("new Array(\"inphasseconduom\", " + strHasSecondaryUOM + "),\n");
       strResult.append("new Array(\"inpmProductUomId\", ");
--- a/src/org/openbravo/erpCommon/ad_callouts/SL_SequenceProduct_Conversion.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_callouts/SL_SequenceProduct_Conversion.java	Fri Jun 03 10:22:43 2016 +0200
@@ -64,23 +64,24 @@
   private void printPage(HttpServletResponse response, VariablesSecureApp vars, String strUOM,
       String strMProductUOMID, String strQuantityOrder, String strTabId) throws IOException,
       ServletException {
+    String localStrUOM = strUOM;
     if (log4j.isDebugEnabled())
       log4j.debug("Output: dataSheet");
     XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
         "org/openbravo/erpCommon/ad_callouts/CallOut").createXmlDocument();
-    if (strUOM.startsWith("\""))
-      strUOM = strUOM.substring(1, strUOM.length() - 1);
-    int stdPrecision = Integer.valueOf(SLInvoiceConversionData.stdPrecision(this, strUOM))
+    if (localStrUOM.startsWith("\""))
+      localStrUOM = localStrUOM.substring(1, localStrUOM.length() - 1);
+    int stdPrecision = Integer.valueOf(SLInvoiceConversionData.stdPrecision(this, localStrUOM))
         .intValue();
     String strInitUOM = SLInvoiceConversionData.initUOMId(this, strMProductUOMID);
     String strMultiplyRate;
     boolean check = false;
 
-    strMultiplyRate = SLInvoiceConversionData.multiplyRate(this, strInitUOM, strUOM);
-    if (strInitUOM.equals(strUOM))
+    strMultiplyRate = SLInvoiceConversionData.multiplyRate(this, strInitUOM, localStrUOM);
+    if (strInitUOM.equals(localStrUOM))
       strMultiplyRate = "1";
     if (strMultiplyRate.equals(""))
-      strMultiplyRate = SLInvoiceConversionData.divideRate(this, strUOM, strInitUOM);
+      strMultiplyRate = SLInvoiceConversionData.divideRate(this, localStrUOM, strInitUOM);
     if (strMultiplyRate.equals("")) {
       strMultiplyRate = "1";
       if (!strMProductUOMID.equals(""))
--- a/src/org/openbravo/erpCommon/ad_callouts/SL_User_Name.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_callouts/SL_User_Name.java	Fri Jun 03 10:22:43 2016 +0200
@@ -65,13 +65,15 @@
   private void printPage(HttpServletResponse response, VariablesSecureApp vars, String strChanged,
       String strFirstname, String strLastname, String strName, String strUserName, String strTabId)
       throws IOException, ServletException {
+    String localStrName = strName;
+    String localStrLastname = strLastname;
     if (log4j.isDebugEnabled())
       log4j.debug("Output: dataSheet");
     XmlDocument xmlDocument = xmlEngine.readXmlTemplate(
         "org/openbravo/erpCommon/ad_callouts/CallOut").createXmlDocument();
 
-    if (!strLastname.equals(""))
-      strLastname = " " + strLastname;
+    if (!localStrLastname.equals(""))
+      localStrLastname = " " + localStrLastname;
 
     StringBuffer resultado = new StringBuffer();
     resultado.append("var calloutName='SL_User_Name';\n\n");
@@ -80,33 +82,33 @@
     int maxChar = 60;
     // do not change the name field, if the user just left it
     if (!strChanged.equals("inpname")) {
-      if (FormatUtilities.replaceJS(strFirstname + strLastname).length() > maxChar) {
-        strName = FormatUtilities.replaceJS(strFirstname + strLastname).substring(0, maxChar);
+      if (FormatUtilities.replaceJS(strFirstname + localStrLastname).length() > maxChar) {
+        localStrName = FormatUtilities.replaceJS(strFirstname + localStrLastname).substring(0,
+            maxChar);
       } else {
-        strName = FormatUtilities.replaceJS(strFirstname + strLastname);
+        localStrName = FormatUtilities.replaceJS(strFirstname + localStrLastname);
       }
-      resultado.append("new Array(\"inpname\", \"" + strName + "\"),");
+      resultado.append("new Array(\"inpname\", \"" + localStrName + "\"),");
     }
     // if we have a name filled in use that for the username
     if (strUserName.equals("")) {
-      if (!strName.equals("")) {
-        if (FormatUtilities.replaceJS(strName).length() > maxChar) {
+      if (!localStrName.equals("")) {
+        if (FormatUtilities.replaceJS(localStrName).length() > maxChar) {
           resultado.append("new Array(\"inpusername\", \""
-              + FormatUtilities.replaceJS(strName).substring(0, maxChar) + "\")");
+              + FormatUtilities.replaceJS(localStrName).substring(0, maxChar) + "\")");
         } else {
-          resultado.append("new Array(\"inpusername\", \"" + FormatUtilities.replaceJS(strName)
-              + "\")");
+          resultado.append("new Array(\"inpusername\", \""
+              + FormatUtilities.replaceJS(localStrName) + "\")");
         }
       } else {
         // else concatenate first- and lastname
-        if (FormatUtilities.replaceJS(strFirstname + strLastname).length() > maxChar) {
-          resultado
-              .append("new Array(\"inpusername\", \""
-                  + FormatUtilities.replaceJS(strFirstname + strLastname).substring(0, maxChar)
-                  + "\")");
+        if (FormatUtilities.replaceJS(strFirstname + localStrLastname).length() > maxChar) {
+          resultado.append("new Array(\"inpusername\", \""
+              + FormatUtilities.replaceJS(strFirstname + localStrLastname).substring(0, maxChar)
+              + "\")");
         } else {
           resultado.append("new Array(\"inpusername\", \""
-              + FormatUtilities.replaceJS(strFirstname + strLastname) + "\")");
+              + FormatUtilities.replaceJS(strFirstname + localStrLastname) + "\")");
         }
       }
     } else {
@@ -119,7 +121,7 @@
       }
     }
     // informs about characters cut
-    if (FormatUtilities.replaceJS(strFirstname + strLastname).length() > maxChar) {
+    if (FormatUtilities.replaceJS(strFirstname + localStrLastname).length() > maxChar) {
       resultado.append(", new Array('MESSAGE', \""
           + FormatUtilities.replaceJS(Utility.messageBD(this, "NameUsernameLengthCut",
               vars.getLanguage())) + "\")");
--- a/src/org/openbravo/erpCommon/ad_forms/Account.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_forms/Account.java	Fri Jun 03 10:22:43 2016 +0200
@@ -203,7 +203,7 @@
   public boolean save(Connection conn1, ConnectionProvider conn) throws ServletException {
     log4jAccount.debug("Account.save - Client_ID=" + AD_Client_ID + ", Org_ID=" + AD_Org_ID
         + "AcctSchema_ID=" + C_AcctSchema_ID + ", Account_ID=" + Account_ID);
-    String C_ValidCombination_ID = "";
+    String cValidCombinationId = "";
     boolean saved = false;
     RespuestaCS respuestaCS;
     try {
@@ -219,14 +219,14 @@
           C_AcctSchema_ID, Account_ID, "", "Y", alias, updatedBy, M_Product_ID, C_BPartner_ID,
           AD_OrgTrx_ID, C_LocFrom_ID, C_LocTo_ID, C_SalesRegion_ID, C_Project_ID, C_Campaign_ID,
           C_Activity_ID, User1_ID, User2_ID);
-      C_ValidCombination_ID = respuestaCS.CValidCombinationId;
+      cValidCombinationId = respuestaCS.CValidCombinationId;
       m_changed = "Y";
       saved = true;
     } catch (ServletException e) {
       log4jAccount.warn("Account.save: " + e);
       m_changed = "N";
     }
-    load(conn1, conn, C_ValidCombination_ID);
+    load(conn1, conn, cValidCombinationId);
     return saved;
   }
 
--- a/src/org/openbravo/erpCommon/ad_forms/AcctServer.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_forms/AcctServer.java	Fri Jun 03 10:22:43 2016 +0200
@@ -1075,8 +1075,8 @@
    *             in case any module may call it.
    */
   @Deprecated
-  public boolean insertNote(String AD_Client_ID, String AD_Org_ID, String AD_User_ID,
-      String AD_Table_ID, String Record_ID, String AD_MessageValue, String Text, String Reference,
+  public boolean insertNote(String aD_Client_ID, String aD_Org_ID, String AD_User_ID,
+      String aD_Table_ID, String record_ID, String AD_MessageValue, String Text, String Reference,
       VariablesSecureApp vars, ConnectionProvider conn, Connection con) {
     return false;
   }
@@ -1350,10 +1350,14 @@
 
   public static String getConvertedAmt(String Amt, String CurFrom_ID, String CurTo_ID,
       String ConvDate, String RateType, String client, String org, ConnectionProvider conn) {
+    String localRateType = RateType;
+    String localConvDate = ConvDate;
     if (log4j.isDebugEnabled())
-      log4j.debug("AcctServer - getConvertedAmount - starting method - Amt : " + Amt
-          + " - CurFrom_ID : " + CurFrom_ID + " - CurTo_ID : " + CurTo_ID + "- ConvDate: "
-          + ConvDate + " - RateType:" + RateType + " - client:" + client + "- org:" + org);
+      log4j
+          .debug("AcctServer - getConvertedAmount - starting method - Amt : " + Amt
+              + " - CurFrom_ID : " + CurFrom_ID + " - CurTo_ID : " + CurTo_ID + "- ConvDate: "
+              + localConvDate + " - RateType:" + localRateType + " - client:" + client + "- org:"
+              + org);
     if (Amt.equals(""))
       throw new IllegalArgumentException(
           "AcctServer - getConvertedAmt - required parameter missing - Amt");
@@ -1361,13 +1365,13 @@
       return Amt;
     AcctServerData[] data = null;
     try {
-      if (ConvDate != null && ConvDate.equals(""))
-        ConvDate = DateTimeData.today(conn);
+      if (localConvDate != null && localConvDate.equals(""))
+        localConvDate = DateTimeData.today(conn);
       // ConvDate IN DATE
-      if (RateType == null || RateType.equals(""))
-        RateType = "S";
-      data = AcctServerData.currencyConvert(conn, Amt, CurFrom_ID, CurTo_ID, ConvDate, RateType,
-          client, org);
+      if (localRateType == null || localRateType.equals(""))
+        localRateType = "S";
+      data = AcctServerData.currencyConvert(conn, Amt, CurFrom_ID, CurTo_ID, localConvDate,
+          localRateType, client, org);
     } catch (ServletException e) {
       log4j.warn(e);
       e.printStackTrace();
@@ -1387,17 +1391,19 @@
 
   public static BigDecimal getConvertionRate(String CurFrom_ID, String CurTo_ID, String ConvDate,
       String RateType, String client, String org, ConnectionProvider conn) {
+    String localRateType = RateType;
+    String localConvDate = ConvDate;
     if (CurFrom_ID.equals(CurTo_ID))
       return BigDecimal.ONE;
     AcctServerData[] data = null;
     try {
-      if (ConvDate != null && ConvDate.equals(""))
-        ConvDate = DateTimeData.today(conn);
+      if (localConvDate != null && localConvDate.equals(""))
+        localConvDate = DateTimeData.today(conn);
       // ConvDate IN DATE
-      if (RateType == null || RateType.equals(""))
-        RateType = "S";
-      data = AcctServerData.currencyConvertionRate(conn, CurFrom_ID, CurTo_ID, ConvDate, RateType,
-          client, org);
+      if (localRateType == null || localRateType.equals(""))
+        localRateType = "S";
+      data = AcctServerData.currencyConvertionRate(conn, CurFrom_ID, CurTo_ID, localConvDate,
+          localRateType, client, org);
     } catch (ServletException e) {
       log4j.warn(e);
       e.printStackTrace();
@@ -1492,8 +1498,8 @@
       for (int i = 0; i < data.length; i++) {
         BigDecimal qty1 = new BigDecimal(data[i].qty1);
         BigDecimal qty2 = new BigDecimal(data[i].qty2);
-        BigDecimal Qty = qty1.min(qty2);
-        if (Qty.toString().equals("0"))
+        BigDecimal qty = qty1.min(qty2);
+        if (qty.toString().equals("0"))
           continue;
         // if (log4j.isDebugEnabled())
         // log4j.debug("AcctServer - Match--dateTrx1 :->" + data[i].datetrx1
@@ -1511,15 +1517,15 @@
         if (compare.equals("-1"))
           DateTrx = dateTrx2;
         //
-        String strQty = Qty.toString();
+        String strQty = qty.toString();
         String strDateTrx = DateTrx;
-        String AD_Client_ID = data[i].adClientId;
-        String AD_Org_ID = data[i].adOrgId;
+        String adClientId = data[i].adClientId;
+        String adOrgId = data[i].adOrgId;
         String C_InvoiceLine_ID = data[i].cInvoicelineId;
         String M_InOutLine_ID = data[i].mInoutlineId;
-        String M_Product_ID = data[i].mProductId;
+        String mProductId = data[i].mProductId;
         //
-        if (createMatchInv(AD_Client_ID, AD_Org_ID, M_InOutLine_ID, C_InvoiceLine_ID, M_Product_ID,
+        if (createMatchInv(adClientId, adOrgId, M_InOutLine_ID, C_InvoiceLine_ID, mProductId,
             strDateTrx, strQty, vars, conn, con) == 1)
           counter++;
       }
@@ -1536,24 +1542,24 @@
   /**
    * Create MatchInv record
    * 
-   * @param AD_Client_ID
+   * @param aD_Client_ID
    *          Client
-   * @param AD_Org_ID
+   * @param aD_Org_ID
    *          Org
    * @param M_InOutLine_ID
    *          Receipt
    * @param C_InvoiceLine_ID
    *          Invoice
-   * @param M_Product_ID
+   * @param m_Product_ID
    *          Product
    * @param DateTrx
    *          Date
-   * @param Qty
+   * @param qty
    *          Qty
    * @return true if record created
    */
-  private int createMatchInv(String AD_Client_ID, String AD_Org_ID, String M_InOutLine_ID,
-      String C_InvoiceLine_ID, String M_Product_ID, String DateTrx, String Qty,
+  private int createMatchInv(String aD_Client_ID, String aD_Org_ID, String M_InOutLine_ID,
+      String C_InvoiceLine_ID, String m_Product_ID, String DateTrx, String qty,
       VariablesSecureApp vars, ConnectionProvider conn, Connection con) {
     // if (log4j.isDebugEnabled())
     // log4j.debug("AcctServer - createMatchInv - InvLine=" +
@@ -1563,8 +1569,8 @@
     try {
       String M_MatchInv_ID = SequenceIdData.getUUID();
       //
-      no = AcctServerData.insertMatchInv(con, conn, M_MatchInv_ID, AD_Client_ID, AD_Org_ID,
-          M_InOutLine_ID, C_InvoiceLine_ID, M_Product_ID, DateTrx, Qty);
+      no = AcctServerData.insertMatchInv(con, conn, M_MatchInv_ID, aD_Client_ID, aD_Org_ID,
+          M_InOutLine_ID, C_InvoiceLine_ID, m_Product_ID, DateTrx, qty);
     } catch (ServletException e) {
       log4j.warn(e);
       e.printStackTrace();
@@ -2099,7 +2105,7 @@
     objectFieldProvider = fieldProvider;
   }
 
-  public abstract void loadObjectFieldProvider(ConnectionProvider conn, String AD_Client_ID,
+  public abstract void loadObjectFieldProvider(ConnectionProvider conn, String aD_Client_ID,
       String Id) throws ServletException;
 
   public abstract boolean loadDocumentDetails(FieldProvider[] data, ConnectionProvider conn);
@@ -2403,18 +2409,18 @@
   // return amt;
   // }
 
-  public BigDecimal convertAmount(BigDecimal _amount, boolean isReceipt, String dateAcct,
+  public BigDecimal convertAmount(BigDecimal _amount, boolean isReceipt, String acctDate,
       String table_ID, String record_ID, String currencyIDFrom, String currencyIDTo, DocLine line,
       AcctSchema as, Fact fact, String Fact_Acct_Group_ID, String seqNo, ConnectionProvider conn)
       throws ServletException {
-    return convertAmount(_amount, isReceipt, dateAcct, table_ID, record_ID, currencyIDFrom,
+    return convertAmount(_amount, isReceipt, acctDate, table_ID, record_ID, currencyIDFrom,
         currencyIDTo, line, as, fact, Fact_Acct_Group_ID, seqNo, conn, true);
   }
 
   /*
    * Returns an amount without applying currency precision for rounding purposes
    */
-  public BigDecimal convertAmount(BigDecimal _amount, boolean isReceipt, String dateAcct,
+  public BigDecimal convertAmount(BigDecimal _amount, boolean isReceipt, String acctDate,
       String table_ID, String record_ID, String currencyIDFrom, String currencyIDTo, DocLine line,
       AcctSchema as, Fact fact, String Fact_Acct_Group_ID, String seqNo, ConnectionProvider conn,
       boolean bookDifferences) throws ServletException {
@@ -2422,7 +2428,7 @@
     if (_amount == null || _amount.compareTo(BigDecimal.ZERO) == 0) {
       return _amount;
     }
-    String conversionDate = dateAcct;
+    String conversionDate = acctDate;
     String strDateFormat = OBPropertiesProvider.getInstance().getOpenbravoProperties()
         .getProperty("dateFormat.java");
     final SimpleDateFormat dateFormat = new SimpleDateFormat(strDateFormat);
@@ -2481,7 +2487,7 @@
       conversionRateCurrentDoc = getConversionRateDoc(TABLEID_Transaction, transaction.getId(),
           currencyIDFrom, currencyIDTo);
     } else {
-      conversionDate = dateAcct;
+      conversionDate = acctDate;
     }
     if (conversionRateCurrentDoc != null) {
       amtTo = applyRate(_amount, conversionRateCurrentDoc, true);
@@ -2549,28 +2555,33 @@
   public static String getConvertedAmt(String Amt, String CurFrom_ID, String CurTo_ID,
       String ConvDate, String RateType, String client, String org, String recordId, String docType,
       ConnectionProvider conn) {
+    String localRateType = RateType;
+    String localConvDate = ConvDate;
+    String amt = Amt;
     boolean useSystemConversionRate = true;
     if (log4j.isDebugEnabled())
-      log4j.debug("AcctServer - getConvertedAmount - starting method - Amt : " + Amt
-          + " - CurFrom_ID : " + CurFrom_ID + " - CurTo_ID : " + CurTo_ID + "- ConvDate: "
-          + ConvDate + " - RateType:" + RateType + " - client:" + client + "- org:" + org);
+      log4j
+          .debug("AcctServer - getConvertedAmount - starting method - Amt : " + amt
+              + " - CurFrom_ID : " + CurFrom_ID + " - CurTo_ID : " + CurTo_ID + "- ConvDate: "
+              + localConvDate + " - RateType:" + localRateType + " - client:" + client + "- org:"
+              + org);
 
-    if (Amt.equals(""))
+    if (amt.equals(""))
       throw new IllegalArgumentException(
           "AcctServer - getConvertedAmt - required parameter missing - Amt");
     if ((CurFrom_ID.equals(CurTo_ID) && !docType.equals(EXCHANGE_DOCTYPE_Transaction))
-        || Amt.equals("0"))
-      return Amt;
+        || amt.equals("0"))
+      return amt;
     AcctServerData[] data = null;
     OBContext.setAdminMode();
     try {
-      if (ConvDate != null && ConvDate.equals(""))
-        ConvDate = DateTimeData.today(conn);
+      if (localConvDate != null && localConvDate.equals(""))
+        localConvDate = DateTimeData.today(conn);
       // ConvDate IN DATE
-      if (RateType == null || RateType.equals(""))
-        RateType = "S";
-      data = AcctServerData.currencyConvert(conn, Amt, CurFrom_ID, CurTo_ID, ConvDate, RateType,
-          client, org);
+      if (localRateType == null || localRateType.equals(""))
+        localRateType = "S";
+      data = AcctServerData.currencyConvert(conn, amt, CurFrom_ID, CurTo_ID, localConvDate,
+          localRateType, client, org);
       // Search if exists any conversion rate at document level
 
       OBCriteria<ConversionRateDoc> docRateCriteria = OBDal.getInstance().createCriteria(
@@ -2590,10 +2601,10 @@
           strDateFormat = OBPropertiesProvider.getInstance().getOpenbravoProperties()
               .getProperty("dateFormat.java");
           final SimpleDateFormat dateFormat = new SimpleDateFormat(strDateFormat);
-          ConvDate = dateFormat.format(reversedCriteria.list().get(0).getReversedInvoice()
+          localConvDate = dateFormat.format(reversedCriteria.list().get(0).getReversedInvoice()
               .getAccountingDate());
-          data = AcctServerData.currencyConvert(conn, Amt, CurFrom_ID, CurTo_ID, ConvDate,
-              RateType, client, org);
+          data = AcctServerData.currencyConvert(conn, amt, CurFrom_ID, CurTo_ID, localConvDate,
+              localRateType, client, org);
           docRateCriteria.add(Restrictions.eq(
               ConversionRateDoc.PROPERTY_INVOICE,
               OBDal.getInstance().get(Invoice.class,
@@ -2615,13 +2626,9 @@
         APRM_FinaccTransactionV a = OBDal.getInstance()
             .get(APRM_FinaccTransactionV.class, recordId);
         if (a.getForeignCurrency() != null) { // && !a.getForeignCurrency().getId().equals(CurTo_ID)
-          String strDateFormat;
-          strDateFormat = OBPropertiesProvider.getInstance().getOpenbravoProperties()
-              .getProperty("dateFormat.java");
-          final SimpleDateFormat dateFormat = new SimpleDateFormat(strDateFormat);
-          Amt = a.getForeignAmount().toString();
-          data = AcctServerData.currencyConvert(conn, Amt, a.getForeignCurrency().getId(),
-              CurTo_ID, ConvDate, RateType, client, org);
+          amt = a.getForeignAmount().toString();
+          data = AcctServerData.currencyConvert(conn, amt, a.getForeignCurrency().getId(),
+              CurTo_ID, localConvDate, localRateType, client, org);
           docRateCriteria.add(Restrictions.eq(ConversionRateDoc.PROPERTY_TOCURRENCY, OBDal
               .getInstance().get(Currency.class, CurTo_ID)));
           docRateCriteria.add(Restrictions.eq(ConversionRateDoc.PROPERTY_CURRENCY, OBDal
@@ -2640,7 +2647,7 @@
           || docType.equals(EXCHANGE_DOCTYPE_Transaction)) {
         List<ConversionRateDoc> conversionRates = docRateCriteria.list();
         if (!conversionRates.isEmpty() && !useSystemConversionRate) {
-          BigDecimal Amount = new BigDecimal(Amt);
+          BigDecimal Amount = new BigDecimal(amt);
           BigDecimal AmountConverted = Amount.multiply(conversionRates.get(0).getRate()).setScale(
               2, BigDecimal.ROUND_HALF_UP);
           return AmountConverted.toString();
--- a/src/org/openbravo/erpCommon/ad_forms/DocAmortization.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_forms/DocAmortization.java	Fri Jun 03 10:22:43 2016 +0200
@@ -102,9 +102,9 @@
     return serialVersionUID;
   }
 
-  public void loadObjectFieldProvider(ConnectionProvider conn, String AD_Client_ID, String Id)
+  public void loadObjectFieldProvider(ConnectionProvider conn, String aD_Client_ID, String Id)
       throws ServletException {
-    setObjectFieldProvider(DocAmortizationData.selectRegistro(conn, AD_Client_ID, Id));
+    setObjectFieldProvider(DocAmortizationData.selectRegistro(conn, aD_Client_ID, Id));
   }
 
   /**
--- a/src/org/openbravo/erpCommon/ad_forms/DocBank.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_forms/DocBank.java	Fri Jun 03 10:22:43 2016 +0200
@@ -81,9 +81,9 @@
     super(AD_Client_ID, AD_Org_ID, connectionProvider);
   }
 
-  public void loadObjectFieldProvider(ConnectionProvider conn, String AD_Client_ID, String Id)
+  public void loadObjectFieldProvider(ConnectionProvider conn, String aD_Client_ID, String Id)
       throws ServletException {
-    setObjectFieldProvider(DocBankData.selectRegistro(conn, AD_Client_ID, Id));
+    setObjectFieldProvider(DocBankData.selectRegistro(conn, aD_Client_ID, Id));
   }
 
   /**
@@ -233,7 +233,7 @@
     log4jDocBank.debug("createFact - object created");
     // Header -- there may be different currency amounts
     BigDecimal TrxAmt = null;
-    BigDecimal ChargeAmt = null;
+    BigDecimal docBankChargeAmt = null;
     BigDecimal ConvertChargeAmt = null;
     String strDateAcct = "FirstIteration";
     // BigDecimal InterestAmt = null;
@@ -251,7 +251,7 @@
       // setC_Period_ID(line.m_DateAcct);
       // BankAsset DR CR (Statement)
       TrxAmt = new BigDecimal(line.m_TrxAmt);
-      ChargeAmt = new BigDecimal(line.chargeAmt);
+      docBankChargeAmt = new BigDecimal(line.chargeAmt);
       ConvertChargeAmt = new BigDecimal(line.convertChargeAmt);
       log4jDocBank.debug("createFact - p_lines.length = " + p_lines.length + " - i=" + i);
       log4jDocBank.debug("createFact - Record_ID = " + Record_ID);
@@ -289,7 +289,7 @@
       fact.createLine(
           lineAux,
           new Account(conn, DocLineBankData.selectChargeAccount(conn, C_BankAccount_ID,
-              as.m_C_AcctSchema_ID)), line.m_C_Currency_ID, ChargeAmt.toString(), "",
+              as.m_C_AcctSchema_ID)), line.m_C_Currency_ID, docBankChargeAmt.toString(), "",
           Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, conn);
       // Interest DR CR (Interest)
       /*
--- a/src/org/openbravo/erpCommon/ad_forms/DocCash.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_forms/DocCash.java	Fri Jun 03 10:22:43 2016 +0200
@@ -82,10 +82,10 @@
     super(AD_Client_ID, AD_Org_ID, connectionProvider);
   }
 
-  public void loadObjectFieldProvider(ConnectionProvider conn, String AD_Client_ID, String Id)
+  public void loadObjectFieldProvider(ConnectionProvider conn, String aD_Client_ID, String Id)
       throws ServletException {
     log4jDocCash.debug("************************** DocCash - loadObjectFieldProvider - ID - " + Id);
-    setObjectFieldProvider(DocCashData.selectRegistro(conn, AD_Client_ID, Id));
+    setObjectFieldProvider(DocCashData.selectRegistro(conn, aD_Client_ID, Id));
   }
 
   /**
--- a/src/org/openbravo/erpCommon/ad_forms/DocDPManagement.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_forms/DocDPManagement.java	Fri Jun 03 10:22:43 2016 +0200
@@ -32,23 +32,23 @@
 
 public class DocDPManagement extends AcctServer {
   private static final long serialVersionUID = 1L;
-  static Logger log4j = Logger.getLogger(DocDPManagement.class);
+  private static Logger docDPManagementLog4j = Logger.getLogger(DocDPManagement.class);
 
   private String SeqNo = "0";
 
   /**
-   * @return the log4j
+   * @return the docDPManagementLog4j
    */
   public static Logger getLog4j() {
-    return log4j;
+    return docDPManagementLog4j;
   }
 
   /**
-   * @param log4j
-   *          the log4j to set
+   * @param docDPManagementLog4j
+   *          the docDPManagementLog4j to set
    */
-  public static void setLog4j(Logger log4j) {
-    DocDPManagement.log4j = log4j;
+  public static void setLog4j(Logger docDPManagementLog4j) {
+    DocDPManagement.docDPManagementLog4j = docDPManagementLog4j;
   }
 
   /**
@@ -84,9 +84,9 @@
     super(AD_Client_ID, AD_Org_ID, connectionProvider);
   }
 
-  public void loadObjectFieldProvider(ConnectionProvider conn, String AD_Client_ID, String Id)
+  public void loadObjectFieldProvider(ConnectionProvider conn, String aD_Client_ID, String Id)
       throws ServletException {
-    setObjectFieldProvider(DocDPManagementData.selectRegistro(conn, AD_Client_ID, Id));
+    setObjectFieldProvider(DocDPManagementData.selectRegistro(conn, aD_Client_ID, Id));
   }
 
   /**
@@ -100,7 +100,7 @@
     loadDocumentType(); // lines require doc type
     // Contained Objects
     p_lines = loadLines(conn);
-    log4j.debug("Record_ID = " + Record_ID + " - Lines=" + p_lines.length);
+    docDPManagementLog4j.debug("Record_ID = " + Record_ID + " - Lines=" + p_lines.length);
     return false;
   } // loadDocumentDetails
 
@@ -115,9 +115,10 @@
 
     try {
       data = DocLineDPManagementData.select(conn, Record_ID);
-      log4j.debug("LoadLines: data.length " + data.length + " record_ID " + Record_ID);
+      docDPManagementLog4j.debug("LoadLines: data.length " + data.length + " record_ID "
+          + Record_ID);
     } catch (ServletException e) {
-      log4j.warn(e);
+      docDPManagementLog4j.warn(e);
     }
 
     //
@@ -173,14 +174,15 @@
             .newInstance();
         return newTemplate.createFact(this, as, conn, con, vars);
       } catch (Exception e) {
-        log4j.error("Error while creating new instance for DocDPManagementTemplate - " + e);
+        docDPManagementLog4j
+            .error("Error while creating new instance for DocDPManagementTemplate - " + e);
       }
     }
-    log4j.debug("createFact - Inicio");
+    docDPManagementLog4j.debug("createFact - Inicio");
     // create Fact Header
     Fact fact = null;
     String Fact_Acct_Group_ID = SequenceIdData.getUUID();
-    log4j.debug("createFact - object created");
+    docDPManagementLog4j.debug("createFact - object created");
     // Lines
     fact = new Fact(this, as, Fact.POST_Actual);
     for (int i = 0; p_lines != null && i < p_lines.length; i++) {
@@ -218,10 +220,10 @@
    * @param oldSeqNo
    */
   public String nextSeqNo(String oldSeqNo) {
-    log4j.debug("DocDPManagement - oldSeqNo = " + oldSeqNo);
+    docDPManagementLog4j.debug("DocDPManagement - oldSeqNo = " + oldSeqNo);
     BigDecimal seqNo = new BigDecimal(oldSeqNo);
     SeqNo = (seqNo.add(new BigDecimal("10"))).toString();
-    log4j.debug("DocDPManagement - nextSeqNo = " + SeqNo);
+    docDPManagementLog4j.debug("DocDPManagement - nextSeqNo = " + SeqNo);
     return SeqNo;
   }
 
@@ -247,7 +249,7 @@
     try {
       data = DocDPManagementData.paymentInformation(conn, strRecordId);
     } catch (ServletException e) {
-      log4j.error(e.getMessage(), e);
+      docDPManagementLog4j.error(e.getMessage(), e);
       setStatus(STATUS_Error);
       return false;
     }
@@ -303,9 +305,9 @@
       if (validCombination_ID.equals(""))
         return null;
       acc = Account.getAccount(conn, validCombination_ID);
-      log4j.debug("DocDPManagement - getAccount - " + acc.Account_ID);
+      docDPManagementLog4j.debug("DocDPManagement - getAccount - " + acc.Account_ID);
     } catch (ServletException e) {
-      log4j.warn(e);
+      docDPManagementLog4j.warn(e);
     }
     return acc;
   } // getAccount
--- a/src/org/openbravo/erpCommon/ad_forms/DocFINFinAccTransaction.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_forms/DocFINFinAccTransaction.java	Fri Jun 03 10:22:43 2016 +0200
@@ -72,7 +72,8 @@
   BigDecimal generatedCredit = ZERO;
   boolean exceptionPosting = false;
 
-  private static final Logger log4j = Logger.getLogger(DocFINFinAccTransaction.class);
+  private static final Logger docFINFinAccTransactionLog4j = Logger
+      .getLogger(DocFINFinAccTransaction.class);
 
   String SeqNo = "0";
 
@@ -348,7 +349,7 @@
         }
 
       } catch (Exception e) {
-        log4j.error("Error while retreiving user1 and user2 - ", e);
+        docFINFinAccTransactionLog4j.error("Error while retreiving user1 and user2 - ", e);
       }
 
     } finally {
@@ -447,8 +448,8 @@
               .forName(strClassname).newInstance();
           return newTemplate.createFact(this, as, conn, con, vars);
         } catch (Exception e) {
-          log4j.error("Error while creating new instance for DocFINFinAccTransactionTemplate - "
-              + e);
+          docFINFinAccTransactionLog4j
+              .error("Error while creating new instance for DocFINFinAccTransactionTemplate - " + e);
         }
       }
       FIN_FinaccTransaction transaction = OBDal.getInstance().get(FIN_FinaccTransaction.class,
@@ -828,7 +829,7 @@
     }
     sb.append("]");
     //
-    log4j.debug(" Balance=" + retValue + sb.toString());
+    docFINFinAccTransactionLog4j.debug(" Balance=" + retValue + sb.toString());
     return retValue;
   } // getBalance
 
@@ -1296,7 +1297,7 @@
             as.getC_AcctSchema_ID());
       }
     } catch (ServletException e) {
-      log4j.warn(e);
+      docFINFinAccTransactionLog4j.warn(e);
       e.printStackTrace();
     }
     // Get Acct
@@ -1307,14 +1308,15 @@
       return null;
     // No account
     if (Account_ID.equals("")) {
-      log4j.warn("AcctServer - getAccount - NO account Type=" + AcctType + ", Record=" + Record_ID);
+      docFINFinAccTransactionLog4j.warn("AcctServer - getAccount - NO account Type=" + AcctType
+          + ", Record=" + Record_ID);
       return null;
     }
     Account acct = null;
     try {
       acct = Account.getAccount(conn, Account_ID);
     } catch (ServletException e) {
-      log4j.warn(e);
+      docFINFinAccTransactionLog4j.warn(e);
       e.printStackTrace();
     }
     return acct;
--- a/src/org/openbravo/erpCommon/ad_forms/DocFINPayment.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_forms/DocFINPayment.java	Fri Jun 03 10:22:43 2016 +0200
@@ -60,7 +60,7 @@
 import org.openbravo.model.financialmgmt.payment.FinAccPaymentMethod;
 
 public class DocFINPayment extends AcctServer {
-  static Logger log4j = Logger.getLogger(DocFINPayment.class);
+  private static final Logger docFINPaymentLog4j = Logger.getLogger(DocFINPayment.class);
 
   String SeqNo = "0";
   String generatedAmount = "";
@@ -355,7 +355,8 @@
               .newInstance();
           return newTemplate.createFact(this, as, conn, con, vars);
         } catch (Exception e) {
-          log4j.error("Error while creating new instance for DocFINPaymentTemplate - ", e);
+          docFINPaymentLog4j.error(
+              "Error while creating new instance for DocFINPaymentTemplate - ", e);
         }
       }
 
@@ -573,7 +574,7 @@
     }
     sb.append("]");
     //
-    log4j.debug(" Balance=" + retValue + sb.toString());
+    docFINPaymentLog4j.debug(" Balance=" + retValue + sb.toString());
     return retValue;
   } // getBalance
 
@@ -744,22 +745,22 @@
       MultiCurrency = true;
     String Amt = getConvertedAmt(Amount, C_Currency_ID_From, C_Currency_ID_To, conversionDate, "",
         AD_Client_ID, AD_Org_ID, conn);
-    if (log4j.isDebugEnabled())
-      log4j.debug("Amt:" + Amt);
+    if (docFINPaymentLog4j.isDebugEnabled())
+      docFINPaymentLog4j.debug("Amt:" + Amt);
 
     String AmtTo = getConvertedAmt(Amount, C_Currency_ID_From, C_Currency_ID_To, mDateAcct, "",
         AD_Client_ID, AD_Org_ID, conn);
-    if (log4j.isDebugEnabled())
-      log4j.debug("AmtTo:" + AmtTo);
+    if (docFINPaymentLog4j.isDebugEnabled())
+      docFINPaymentLog4j.debug("AmtTo:" + AmtTo);
 
     BigDecimal AmtDiff = (new BigDecimal(AmtTo)).subtract(new BigDecimal(Amt));
-    if (log4j.isDebugEnabled())
-      log4j.debug("AmtDiff:" + AmtDiff);
+    if (docFINPaymentLog4j.isDebugEnabled())
+      docFINPaymentLog4j.debug("AmtDiff:" + AmtDiff);
 
-    if (log4j.isDebugEnabled()) {
-      log4j.debug("curr from:" + C_Currency_ID_From + " Curr to:" + C_Currency_ID_To + " convDate:"
-          + conversionDate + " DateAcct:" + mDateAcct);
-      log4j.debug("Amt:" + Amt + " AmtTo:" + AmtTo + " Diff:" + AmtDiff.toString());
+    if (docFINPaymentLog4j.isDebugEnabled()) {
+      docFINPaymentLog4j.debug("curr from:" + C_Currency_ID_From + " Curr to:" + C_Currency_ID_To
+          + " convDate:" + conversionDate + " DateAcct:" + mDateAcct);
+      docFINPaymentLog4j.debug("Amt:" + Amt + " AmtTo:" + AmtTo + " Diff:" + AmtDiff.toString());
     }
 
     if ((isReceipt && AmtDiff.compareTo(new BigDecimal("0.00")) == 1)
--- a/src/org/openbravo/erpCommon/ad_forms/DocFINReconciliation.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_forms/DocFINReconciliation.java	Fri Jun 03 10:22:43 2016 +0200
@@ -71,7 +71,8 @@
   public static final String TRXTYPE_BPWithdrawal = "BPW";
   public static final String TRXTYPE_BankFee = "BF";
 
-  private static final Logger log4j = Logger.getLogger(DocFINReconciliation.class);
+  private static final Logger docFINReconciliationLog4j = Logger
+      .getLogger(DocFINReconciliation.class);
 
   String SeqNo = "0";
 
@@ -390,7 +391,7 @@
             FieldProviderFactory.setField(data[i], "cCostcenterId", trxInfo[0].cCostcenterId);
           }
         } catch (Exception e) {
-          log4j.error("Error while retreiving user1 and user2 - ", e);
+          docFINReconciliationLog4j.error("Error while retreiving user1 and user2 - ", e);
         }
       }
     } finally {
@@ -446,7 +447,7 @@
           FieldProviderFactory.setField(data[0], "cCostcenterId", trxInfo[0].cCostcenterId);
         }
       } catch (Exception e) {
-        log4j.error("Error while retreiving user1 and user2 - ", e);
+        docFINReconciliationLog4j.error("Error while retreiving user1 and user2 - ", e);
       }
     } finally {
       OBContext.restorePreviousMode();
@@ -492,7 +493,7 @@
           FieldProviderFactory.setField(data[0], "user2Id", trxInfo[0].user2Id);
         }
       } catch (Exception e) {
-        log4j.error("Error while retreiving user1 and user2 - ", e);
+        docFINReconciliationLog4j.error("Error while retreiving user1 and user2 - ", e);
       }
     } finally {
       OBContext.restorePreviousMode();
@@ -578,7 +579,8 @@
               strClassname).newInstance();
           return newTemplate.createFact(this, as, conn, con, vars);
         } catch (Exception e) {
-          log4j.error("Error while creating new instance for DocFINReconciliationTemplate - " + e);
+          docFINReconciliationLog4j
+              .error("Error while creating new instance for DocFINReconciliationTemplate - " + e);
         }
       }
       String Fact_Acct_Group_ID = SequenceIdData.getUUID();
@@ -648,6 +650,7 @@
   public Fact createFactPayment(DocLine_FINReconciliation line, AcctSchema as,
       ConnectionProvider conn, Fact fact, String Fact_Acct_Group_ID, String Fact_Acct_Group_ID2)
       throws ServletException {
+    Fact localFact = fact;
     FIN_Payment payment = OBDal.getInstance().get(FIN_Payment.class, line.getFinPaymentId());
     FIN_FinaccTransaction transaction = OBDal.getInstance().get(FIN_FinaccTransaction.class,
         line.getFinFinAccTransactionId());
@@ -659,10 +662,10 @@
       // Should map with the amount booked in the transaction and adjust with currency gain/loss
       transactionAmount = convertAmount(new BigDecimal(line.getAmount()), !payment.isReceipt(),
           dateFormat.format(transaction.getDateAcct()), TABLEID_Transaction, transaction.getId(),
-          C_Currency_ID, as.m_C_Currency_ID, line, as, fact, Fact_Acct_Group_ID, nextSeqNo(SeqNo),
-          conn);
+          C_Currency_ID, as.m_C_Currency_ID, line, as, localFact, Fact_Acct_Group_ID,
+          nextSeqNo(SeqNo), conn);
       line.m_Record_Id2 = transaction.getId();
-      fact.createLine(line, getAccountTransactionPayment(conn, payment, as), C_Currency_ID,
+      localFact.createLine(line, getAccountTransactionPayment(conn, payment, as), C_Currency_ID,
           !payment.isReceipt() ? transactionAmount.toString() : "",
           payment.isReceipt() ? transactionAmount.toString() : "", Fact_Acct_Group_ID,
           nextSeqNo(SeqNo), DocumentType, line.m_DateAcct, null, conn);
@@ -698,18 +701,18 @@
             finPaymentDetailID);
         detail.setInvoiceTaxCashVAT_V(finPaymentDetailID);
         detail.setInvoiceTaxCashVAT_V(data[i].getField("MergedPaymentDetailId"));
-        fact = createFactPaymentDetails(detail, paymentDetail, as, conn, fact, Fact_Acct_Group_ID,
-            Fact_Acct_Group_ID2);
+        localFact = createFactPaymentDetails(detail, paymentDetail, as, conn, localFact,
+            Fact_Acct_Group_ID, Fact_Acct_Group_ID2);
       }
     } else {
       BigDecimal paymentAmount = new BigDecimal(line.getAmount());
       // Should map with the amount booked in the payment and adjust with currency gain/loss
       paymentAmount = convertAmount(new BigDecimal(line.getAmount()), !payment.isReceipt(),
           dateFormat.format(transaction.getDateAcct()), TABLEID_Payment, line.getFinPaymentId(),
-          C_Currency_ID, as.m_C_Currency_ID, line, as, fact, Fact_Acct_Group_ID, nextSeqNo(SeqNo),
-          conn);
+          C_Currency_ID, as.m_C_Currency_ID, line, as, localFact, Fact_Acct_Group_ID,
+          nextSeqNo(SeqNo), conn);
       line.m_Record_Id2 = payment.getId();
-      fact.createLine(line, getAccountPayment(conn, payment, as), C_Currency_ID,
+      localFact.createLine(line, getAccountPayment(conn, payment, as), C_Currency_ID,
           !payment.isReceipt() ? paymentAmount.toString() : "",
           payment.isReceipt() ? paymentAmount.toString() : "", Fact_Acct_Group_ID,
           nextSeqNo(SeqNo), DocumentType, line.m_DateAcct, null, conn);
@@ -720,9 +723,10 @@
     paymentTypeLine.copyInfo(line);
     paymentTypeLine.m_Record_Id2 = "";
     paymentTypeLine.setFinFinAccTransactionId(transaction.getId());
-    fact.createLine(paymentTypeLine, getAccountReconciliation(conn, payment, as), C_Currency_ID,
-        payment.isReceipt() ? line.getAmount() : "", !payment.isReceipt() ? line.getAmount() : "",
-        Fact_Acct_Group_ID, "999999", DocumentType, line.m_DateAcct, null, conn);
+    localFact.createLine(paymentTypeLine, getAccountReconciliation(conn, payment, as),
+        C_Currency_ID, payment.isReceipt() ? line.getAmount() : "",
+        !payment.isReceipt() ? line.getAmount() : "", Fact_Acct_Group_ID, "999999", DocumentType,
+        line.m_DateAcct, null, conn);
     if (!getDocumentPaymentConfirmation(payment)
         && !getDocumentTransactionConfirmation(transaction)) {
       // Pre-payment is consumed when Used Credit Amount not equals Zero. When consuming Credit no
@@ -737,8 +741,8 @@
           String creditAmountConverted = convertAmount(creditPayment.getAmount(), isReceiptPayment,
               DateAcct, TABLEID_Payment, creditPayment.getCreditPaymentUsed().getId(),
               creditPayment.getCreditPaymentUsed().getCurrency().getId(), as.m_C_Currency_ID, line,
-              as, fact, Fact_Acct_Group_ID, nextSeqNo(SeqNo), conn, false).toString();
-          fact.createLine(
+              as, localFact, Fact_Acct_Group_ID, nextSeqNo(SeqNo), conn, false).toString();
+          localFact.createLine(
               line,
               getAccountBPartner(creditPayment.getCreditPaymentUsed().getBusinessPartner().getId(),
                   as, isReceiptPayment, true, conn), creditPayment.getCreditPaymentUsed()
@@ -751,16 +755,18 @@
         }
         if (!payment.isReceipt() && amtDiff.compareTo(BigDecimal.ZERO) == 1 || payment.isReceipt()
             && amtDiff.compareTo(BigDecimal.ZERO) == -1) {
-          fact.createLine(null, getAccount(AcctServer.ACCTTYPE_ConvertGainDefaultAmt, as, conn),
-              payment.getCurrency().getId(), "", amtDiff.abs().toString(), Fact_Acct_Group_ID,
+          localFact.createLine(null,
+              getAccount(AcctServer.ACCTTYPE_ConvertGainDefaultAmt, as, conn), payment
+                  .getCurrency().getId(), "", amtDiff.abs().toString(), Fact_Acct_Group_ID,
               nextSeqNo(SeqNo), DocumentType, conn);
         } else {
-          fact.createLine(null, getAccount(AcctServer.ACCTTYPE_ConvertChargeDefaultAmt, as, conn),
-              payment.getCurrency().getId(), amtDiff.abs().toString(), "", Fact_Acct_Group_ID,
+          localFact.createLine(null,
+              getAccount(AcctServer.ACCTTYPE_ConvertChargeDefaultAmt, as, conn), payment
+                  .getCurrency().getId(), amtDiff.abs().toString(), "", Fact_Acct_Group_ID,
               nextSeqNo(SeqNo), DocumentType, conn);
         }
         if (creditPayments.isEmpty()) {
-          fact.createLine(
+          localFact.createLine(
               line,
               getAccountBPartner(payment.getBusinessPartner().getId(), as, payment.isReceipt(),
                   true, conn), payment.getCurrency().getId(), (payment.isReceipt() ? payment
@@ -772,7 +778,7 @@
     }
 
     SeqNo = "0";
-    return fact;
+    return localFact;
   }
 
   @Deprecated
@@ -1041,7 +1047,7 @@
     }
     sb.append("]");
     //
-    log4j.debug(" Balance=" + retValue + sb.toString());
+    docFINReconciliationLog4j.debug(" Balance=" + retValue + sb.toString());
     return retValue;
   } // getBalance
 
@@ -1649,7 +1655,7 @@
       data = AcctServerData.periodOpen(connectionProvider, client, documentType, org, date);
       return data[0].period;
     } catch (ServletException e) {
-      log4j.warn(e);
+      docFINReconciliationLog4j.warn(e);
       e.printStackTrace();
     }
     return null;
@@ -1674,13 +1680,13 @@
         return acct;
       // No account
       if (Account_ID.equals("")) {
-        log4j.warn("AcctServer - getAccount - NO account Type=" + AcctType + ", Record="
-            + Record_ID);
+        docFINReconciliationLog4j.warn("AcctServer - getAccount - NO account Type=" + AcctType
+            + ", Record=" + Record_ID);
         return acct;
       }
       acct = Account.getAccount(conn, Account_ID);
     } catch (ServletException e) {
-      log4j.warn(e);
+      docFINReconciliationLog4j.warn(e);
       e.printStackTrace();
     } finally {
       if (acct == null) {
--- a/src/org/openbravo/erpCommon/ad_forms/DocGLJournal.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_forms/DocGLJournal.java	Fri Jun 03 10:22:43 2016 +0200
@@ -52,16 +52,16 @@
 
   public String m_PostingType = Fact.POST_Actual;
 
-  public void loadObjectFieldProvider(ConnectionProvider conn, String AD_Client_ID, String Id)
+  public void loadObjectFieldProvider(ConnectionProvider conn, String aD_Client_ID, String Id)
       throws ServletException {
     AcctSchema docAcctSchema = new AcctSchema(conn, DocGLJournalData.selectAcctSchema(conn,
-        AD_Client_ID, Id));
+        aD_Client_ID, Id));
     ArrayList<Object> list = new ArrayList<Object>();
     list.add(docAcctSchema);
     AcctSchema[] retValue = new AcctSchema[list.size()];
     list.toArray(retValue);
     this.m_as = retValue;
-    setObjectFieldProvider(DocGLJournalData.select(conn, AD_Client_ID, Id));
+    setObjectFieldProvider(DocGLJournalData.select(conn, aD_Client_ID, Id));
   }
 
   /**
@@ -304,23 +304,6 @@
     return true;
   }
 
-  private String isperiodOpen(ConnectionProvider conn, String periodId) {
-    if ("".equals(periodId)) {
-      return "";
-    }
-    try {
-      DocGLJournalData[] data = DocGLJournalData.periodOpen(conn, periodId);
-      if (data != null && data.length > 0) {
-        return periodId;
-      } else {
-        return "";
-      }
-    } catch (ServletException e) {
-      e.printStackTrace();
-      return "";
-    }
-  }
-
   public String getServletInfo() {
     return "Servlet for the accounting";
   } // end of getServletInfo() method
--- a/src/org/openbravo/erpCommon/ad_forms/DocInternalConsumption.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_forms/DocInternalConsumption.java	Fri Jun 03 10:22:43 2016 +0200
@@ -58,9 +58,9 @@
   }
 
   @Override
-  public void loadObjectFieldProvider(ConnectionProvider conn, String AD_Client_ID, String Id)
+  public void loadObjectFieldProvider(ConnectionProvider conn, String aD_Client_ID, String Id)
       throws ServletException {
-    setObjectFieldProvider(DocInternalConsumptionData.select(conn, AD_Client_ID, Id));
+    setObjectFieldProvider(DocInternalConsumptionData.select(conn, aD_Client_ID, Id));
   }
 
   /**
--- a/src/org/openbravo/erpCommon/ad_forms/DocInvoice.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_forms/DocInvoice.java	Fri Jun 03 10:22:43 2016 +0200
@@ -1557,11 +1557,13 @@
   private BigDecimal createLineForTaxUndeductable(int invoiceLineTaxCount, int totalInvoiceLineTax,
       BigDecimal cumulativeTaxLineAmount, BigDecimal taxAmount, DocInvoiceData[] data,
       ConnectionProvider conn, Fact fact, DocLine docLine, String Fact_Acct_Group_ID) {
+    int localInvoiceLineTaxCount = invoiceLineTaxCount;
+    BigDecimal localCumulativeTaxLineAmount = cumulativeTaxLineAmount;
     for (int j = 0; j < data.length; j++) {
-      invoiceLineTaxCount++;
+      localInvoiceLineTaxCount++;
       // We have to adjust the amount in last line of tax
-      if (invoiceLineTaxCount == totalInvoiceLineTax) {
-        data[j].taxamt = taxAmount.subtract(cumulativeTaxLineAmount).toPlainString();
+      if (localInvoiceLineTaxCount == totalInvoiceLineTax) {
+        data[j].taxamt = taxAmount.subtract(localCumulativeTaxLineAmount).toPlainString();
       }
       try {
         // currently applicable for API and APC
@@ -1581,13 +1583,14 @@
               this.C_Currency_ID, "", data[j].taxamt, Fact_Acct_Group_ID, nextSeqNo(SeqNo),
               DocumentType, conn);
         }
-        cumulativeTaxLineAmount = cumulativeTaxLineAmount.add(new BigDecimal(data[j].taxamt));
+        localCumulativeTaxLineAmount = localCumulativeTaxLineAmount.add(new BigDecimal(
+            data[j].taxamt));
       } catch (ServletException e) {
         log4jDocInvoice.error("Exception in createLineForTaxUndeductable method: " + e);
       }
 
     }
 
-    return cumulativeTaxLineAmount;
+    return localCumulativeTaxLineAmount;
   }
 }
--- a/src/org/openbravo/erpCommon/ad_forms/DocLine.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_forms/DocLine.java	Fri Jun 03 10:22:43 2016 +0200
@@ -27,7 +27,7 @@
 public class DocLine {
   static Logger log4jDocLine = Logger.getLogger(DocLine.class);
 
-  public BigDecimal ZERO = new BigDecimal("0");
+  public BigDecimal ZERO = BigDecimal.ZERO;
 
   public String p_DocumentType = "";
   /** ID - Trx Header */
--- a/src/org/openbravo/erpCommon/ad_forms/DocLine_Invoice.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_forms/DocLine_Invoice.java	Fri Jun 03 10:22:43 2016 +0200
@@ -79,7 +79,6 @@
   }
 
   public void setAmount(String LineNetAmt, String PriceList, String Qty) {
-    BigDecimal ZERO = new BigDecimal("0");
     m_LineNetAmt = (LineNetAmt == "0") ? ZERO.toString() : LineNetAmt;
     BigDecimal b_Qty = new BigDecimal(Qty);
     BigDecimal b_PriceList = new BigDecimal(PriceList);
--- a/src/org/openbravo/erpCommon/ad_forms/DocOrder.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_forms/DocOrder.java	Fri Jun 03 10:22:43 2016 +0200
@@ -44,9 +44,9 @@
     super(AD_Client_ID, AD_Org_ID, connectionProvider);
   }
 
-  public void loadObjectFieldProvider(ConnectionProvider conn, String AD_Client_ID, String Id)
+  public void loadObjectFieldProvider(ConnectionProvider conn, String aD_Client_ID, String Id)
       throws ServletException {
-    setObjectFieldProvider(DocOrderData.selectRegistro(conn, AD_Client_ID, Id));
+    setObjectFieldProvider(DocOrderData.selectRegistro(conn, aD_Client_ID, Id));
   }
 
   /**
@@ -93,8 +93,8 @@
         String Line_ID = data[i].getField("cOrderlineId");
         DocLine docLine = new DocLine(DocumentType, Record_ID, Line_ID);
         docLine.loadAttributes(data[i], this);
-        String Qty = data[i].getField("qtyordered");
-        docLine.setQty(Qty);
+        String qty = data[i].getField("qtyordered");
+        docLine.setQty(qty);
         String LineNetAmt = data[i].getField("linenetamt");
         // BigDecimal PriceList = rs.getBigDecimal("PriceList");
         docLine.setAmount(LineNetAmt);
--- a/src/org/openbravo/erpCommon/ad_forms/DocPayment.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_forms/DocPayment.java	Fri Jun 03 10:22:43 2016 +0200
@@ -32,11 +32,10 @@
 
 public class DocPayment extends AcctServer {
   private static final long serialVersionUID = 1L;
-  static Logger log4j = Logger.getLogger(DocPayment.class);
+  private static Logger docPaymentLog4j = Logger.getLogger(DocPayment.class);
 
   private String SeqNo = "0";
   private String SettlementType = "";
-  static final BigDecimal ZERO = BigDecimal.ZERO;
 
   /**
    * Constructor
@@ -48,9 +47,9 @@
     super(AD_Client_ID, AD_Org_ID, connectionProvider);
   }
 
-  public void loadObjectFieldProvider(ConnectionProvider conn, String AD_Client_ID, String Id)
+  public void loadObjectFieldProvider(ConnectionProvider conn, String aD_Client_ID, String Id)
       throws ServletException {
-    setObjectFieldProvider(DocPaymentData.selectRegistro(conn, AD_Client_ID, Id));
+    setObjectFieldProvider(DocPaymentData.selectRegistro(conn, aD_Client_ID, Id));
   }
 
   /**
@@ -64,8 +63,8 @@
     SettlementType = data[0].getField("settlementtype");
     // Contained Objects
     p_lines = loadLines(conn);
-    if (log4j.isDebugEnabled())
-      log4j.debug("DocPayment - loadDocumentDetails - Lines=" + p_lines.length);
+    if (docPaymentLog4j.isDebugEnabled())
+      docPaymentLog4j.debug("DocPayment - loadDocumentDetails - Lines=" + p_lines.length);
     return false;
   } // loadDocumentDetails
 
@@ -105,16 +104,16 @@
           docLine.dpStatus = DocLinePaymentData.getDPStatus(connectionProvider, Record_ID,
               data[i].getField("cDebtPaymentId"));
         } catch (ServletException e) {
-          log4j.error(e);
+          docPaymentLog4j.error(e);
           docLine.dpStatus = "";
         }
-        if (log4j.isDebugEnabled())
-          log4j.debug("DocPayment - loadLines - docLine.IsDirectPosting - "
+        if (docPaymentLog4j.isDebugEnabled())
+          docPaymentLog4j.debug("DocPayment - loadLines - docLine.IsDirectPosting - "
               + docLine.IsDirectPosting);
         list.add(docLine);
       }
     } catch (ServletException e) {
-      log4j.warn(e);
+      docPaymentLog4j.warn(e);
     }
     // Return Array
     DocLine[] dl = new DocLine[list.size()];
@@ -167,11 +166,11 @@
             .newInstance();
         return newTemplate.createFact(this, as, conn, con, vars);
       } catch (Exception e) {
-        log4j.error("Error while creating new instance for DocPaymentTemplate - " + e);
+        docPaymentLog4j.error("Error while creating new instance for DocPaymentTemplate - " + e);
       }
     }
-    if (log4j.isDebugEnabled())
-      log4j.debug("DocPayment - createFact - p_lines.length - " + p_lines.length);
+    if (docPaymentLog4j.isDebugEnabled())
+      docPaymentLog4j.debug("DocPayment - createFact - p_lines.length - " + p_lines.length);
     Fact fact = new Fact(this, as, Fact.POST_Actual);
     String Fact_Acct_Group_ID = SequenceIdData.getUUID();
 
@@ -180,8 +179,9 @@
     for (int i = 0; p_lines != null && i < p_lines.length; i++) {
       DocLine_Payment line = (DocLine_Payment) p_lines[i];
 
-      if (log4j.isDebugEnabled())
-        log4j.debug("DocPayment - createFact - line.conversionDate - " + line.conversionDate);
+      if (docPaymentLog4j.isDebugEnabled())
+        docPaymentLog4j.debug("DocPayment - createFact - line.conversionDate - "
+            + line.conversionDate);
       // For manual payment with direct posting = 'N' (no posting occurred at payment creation so no
       // conversion, for currency gain-loss, is needed)
       String convertedAmt = "";
@@ -222,12 +222,12 @@
                   : finalConvertedAmt), (line.isReceipt.equals("Y") ? finalConvertedAmt : ""),
               Fact_Acct_Group_ID, nextSeqNo(SeqNo), DocumentType, conn);
         } else { // 2.2* Generated DP
-          if (log4j.isDebugEnabled())
-            log4j.debug("Genenarted DP");
+          if (docPaymentLog4j.isDebugEnabled())
+            docPaymentLog4j.debug("Genenarted DP");
           if (!line.isPaid.equals("Y")
               || !(line.C_Settlement_Cancel_ID == null || line.C_Settlement_Cancel_ID.equals(""))) {
-            if (log4j.isDebugEnabled())
-              log4j.debug("Not paid");
+            if (docPaymentLog4j.isDebugEnabled())
+              docPaymentLog4j.debug("Not paid");
             fact.createLine(
                 line,
                 getAccountBPartner(line.m_C_BPartner_ID, as, line.isReceipt.equals("Y"),
@@ -238,19 +238,21 @@
           }
         }
 
-        if (log4j.isDebugEnabled())
-          log4j.debug("DocPayment - createFact - No manual  - isReceipt: " + line.isReceipt);
+        if (docPaymentLog4j.isDebugEnabled())
+          docPaymentLog4j.debug("DocPayment - createFact - No manual  - isReceipt: "
+              + line.isReceipt);
       } else {// 3* MANUAL debt-payments (generated in a Manual stt)
-        if (log4j.isDebugEnabled())
-          log4j.debug("Manual DP - DirectPosting: " + line.IsDirectPosting + " - SettType:"
-              + SettlementType);
+        if (docPaymentLog4j.isDebugEnabled())
+          docPaymentLog4j.debug("Manual DP - DirectPosting: " + line.IsDirectPosting
+              + " - SettType:" + SettlementType);
         if (line.IsDirectPosting.equals("Y")) { // Direct posting:
           // transitory Account
           BigDecimal amount = ZERO;
           DocPaymentData[] data = DocPaymentData.selectDirectManual(conn, as.m_C_AcctSchema_ID,
               line.Line_ID);
-          if (log4j.isDebugEnabled())
-            log4j.debug("data[0].amount:" + data[0].amount + " - convertedAmt:" + convertedAmt);
+          if (docPaymentLog4j.isDebugEnabled())
+            docPaymentLog4j.debug("data[0].amount:" + data[0].amount + " - convertedAmt:"
+                + convertedAmt);
 
           if (convertedAmt != null && !convertedAmt.equals(""))
             amount = new BigDecimal(convertedAmt);
@@ -258,9 +260,9 @@
           if (changeGenerate)
             amount = amount.negate();
           BigDecimal transitoryAmount = new BigDecimal(convertedAmt);
-          if (log4j.isDebugEnabled())
-            log4j.debug("Manual DP - amount:" + amount + " - transitoryAmount:" + transitoryAmount
-                + " - Receipt:" + line.isReceipt);
+          if (docPaymentLog4j.isDebugEnabled())
+            docPaymentLog4j.debug("Manual DP - amount:" + amount + " - transitoryAmount:"
+                + transitoryAmount + " - Receipt:" + line.isReceipt);
           // Line is cloned to add withholding and/or tax info
           DocLine_Payment lineAux = DocLine_Payment.clone(line);
           lineAux.setM_C_WithHolding_ID(data[0].cWithholdingId);
@@ -303,9 +305,9 @@
                 "", AD_Client_ID, AD_Org_ID, conn);
             amountcredit = getConvertedAmt(amountcredit, as.m_C_Currency_ID, C_Currency_ID,
                 DateAcct, "", AD_Client_ID, AD_Org_ID, conn);
-            if (log4j.isDebugEnabled())
-              log4j.debug("DocPayment - createFact - Conceptos - AmountDebit: " + amountdebit
-                  + " - AmountCredit: " + amountcredit);
+            if (docPaymentLog4j.isDebugEnabled())
+              docPaymentLog4j.debug("DocPayment - createFact - Conceptos - AmountDebit: "
+                  + amountdebit + " - AmountCredit: " + amountcredit);
             // Line is cloned to add withholding and/or tax info
             DocLine_Payment lineAux = DocLine_Payment.clone(line);
             lineAux.setM_C_WithHolding_ID(data[j].cWithholdingId);
@@ -353,12 +355,12 @@
             try {
               acct = Account.getAccount(conn, Account_ID);
             } catch (ServletException e) {
-              log4j.warn(e);
+              docPaymentLog4j.warn(e);
               e.printStackTrace();
             }
           } else {
-            log4j.warn("AcctServer - getAccount - NO account Type=" + AcctServer.ACCTTYPE_WriteOff
-                + ", Record=" + Record_ID);
+            docPaymentLog4j.warn("AcctServer - getAccount - NO account Type="
+                + AcctServer.ACCTTYPE_WriteOff + ", Record=" + Record_ID);
           }
           fact.createLine(line, acct, C_Currency_ID, (line.isReceipt.equals("Y") ? line.WriteOffAmt
               : ""), (line.isReceipt.equals("Y") ? "" : line.WriteOffAmt), Fact_Acct_Group_ID,
@@ -426,24 +428,24 @@
       }
     } // END of the C_Debt_Payment loop
     SeqNo = "0";
-    if (log4j.isDebugEnabled())
-      log4j.debug("DocPayment - createFact - finish");
+    if (docPaymentLog4j.isDebugEnabled())
+      docPaymentLog4j.debug("DocPayment - createFact - finish");
     return fact;
   }
 
   /**
-   * @return the log4j
+   * @return the docPaymentLog4j
    */
   public static Logger getLog4j() {
-    return log4j;
+    return docPaymentLog4j;
   }
 
   /**
-   * @param log4j
-   *          the log4j to set
+   * @param docPaymentLog4j
+   *          the docPaymentLog4j to set
    */
-  public static void setLog4j(Logger log4j) {
-    DocPayment.log4j = log4j;
+  public static void setLog4j(Logger docPaymentLog4j) {
+    DocPayment.docPaymentLog4j = docPaymentLog4j;
   }
 
   /**
@@ -487,50 +489,51 @@
    * @return the zERO
    */
   public static BigDecimal getZERO() {
-    return ZERO;
+    return BigDecimal.ZERO;
   }
 
-  public String convertAmount(String Amount, boolean isReceipt, String DateAcct,
-      String conversionDate, String C_Currency_ID_From, String C_Currency_ID, DocLine line,
+  public String convertAmount(String Amount, boolean isReceipt, String acctDate,
+      String conversionDate, String C_Currency_ID_From, String c_Currency_ID, DocLine line,
       AcctSchema as, Fact fact, String Fact_Acct_Group_ID, ConnectionProvider conn)
       throws ServletException {
-    if (log4j.isDebugEnabled())
-      log4j.debug("Amount:" + Amount + " curr from:" + C_Currency_ID_From + " Curr to:"
-          + C_Currency_ID + " convDate:" + conversionDate + " DateAcct:" + DateAcct);
-    if (Amount == null || Amount.equals(""))
-      Amount = "0";
-    if (C_Currency_ID_From.equals(C_Currency_ID))
-      return Amount;
+    String amount = Amount;
+    if (docPaymentLog4j.isDebugEnabled())
+      docPaymentLog4j.debug("Amount:" + amount + " curr from:" + C_Currency_ID_From + " Curr to:"
+          + c_Currency_ID + " convDate:" + conversionDate + " DateAcct:" + acctDate);
+    if (amount == null || amount.equals(""))
+      amount = "0";
+    if (C_Currency_ID_From.equals(c_Currency_ID))
+      return amount;
     else
       MultiCurrency = true;
-    String Amt = getConvertedAmt(Amount, C_Currency_ID_From, C_Currency_ID, conversionDate, "",
+    String Amt = getConvertedAmt(amount, C_Currency_ID_From, c_Currency_ID, conversionDate, "",
         AD_Client_ID, AD_Org_ID, conn);
-    if (log4j.isDebugEnabled())
-      log4j.debug("Amt:" + Amt);
+    if (docPaymentLog4j.isDebugEnabled())
+      docPaymentLog4j.debug("Amt:" + Amt);
 
-    String AmtTo = getConvertedAmt(Amount, C_Currency_ID_From, C_Currency_ID, DateAcct, "",
+    String AmtTo = getConvertedAmt(amount, C_Currency_ID_From, c_Currency_ID, acctDate, "",
         AD_Client_ID, AD_Org_ID, conn);
-    if (log4j.isDebugEnabled())
-      log4j.debug("AmtTo:" + AmtTo);
+    if (docPaymentLog4j.isDebugEnabled())
+      docPaymentLog4j.debug("AmtTo:" + AmtTo);
 
     BigDecimal AmtDiff = (new BigDecimal(AmtTo)).subtract(new BigDecimal(Amt));
-    if (log4j.isDebugEnabled())
-      log4j.debug("AmtDiff:" + AmtDiff);
+    if (docPaymentLog4j.isDebugEnabled())
+      docPaymentLog4j.debug("AmtDiff:" + AmtDiff);
 
-    if (log4j.isDebugEnabled()) {
-      log4j.debug("curr from:" + C_Currency_ID_From + " Curr to:" + C_Currency_ID + " convDate:"
-          + conversionDate + " DateAcct:" + DateAcct);
-      log4j.debug("Amt:" + Amt + " AmtTo:" + AmtTo + " Diff:" + AmtDiff.toString());
+    if (docPaymentLog4j.isDebugEnabled()) {
+      docPaymentLog4j.debug("curr from:" + C_Currency_ID_From + " Curr to:" + c_Currency_ID
+          + " convDate:" + conversionDate + " DateAcct:" + acctDate);
+      docPaymentLog4j.debug("Amt:" + Amt + " AmtTo:" + AmtTo + " Diff:" + AmtDiff.toString());
     }
 
     if ((isReceipt && AmtDiff.compareTo(new BigDecimal("0.00")) == 1)
         || (!isReceipt && AmtDiff.compareTo(new BigDecimal("0.00")) == -1)) {
       fact.createLine(line, getAccount(AcctServer.ACCTTYPE_ConvertGainDefaultAmt, as, conn),
-          C_Currency_ID, "", AmtDiff.abs().toString(), Fact_Acct_Group_ID, nextSeqNo(SeqNo),
+          c_Currency_ID, "", AmtDiff.abs().toString(), Fact_Acct_Group_ID, nextSeqNo(SeqNo),
           DocumentType, conn);
     } else {
       fact.createLine(line, getAccount(AcctServer.ACCTTYPE_ConvertChargeDefaultAmt, as, conn),
-          C_Currency_ID, AmtDiff.abs().toString(), "", Fact_Acct_Group_ID, nextSeqNo(SeqNo),
+          c_Currency_ID, AmtDiff.abs().toString(), "", Fact_Acct_Group_ID, nextSeqNo(SeqNo),
           DocumentType, conn);
     }
 
@@ -550,8 +553,8 @@
       String dpStatus, ConnectionProvider conn) {
     DocPaymentData[] data = null;
     try {
-      if (log4j.isDebugEnabled())
-        log4j.debug("DocPayment - getAccountBPartner - DocumentType = " + DocumentType);
+      if (docPaymentLog4j.isDebugEnabled())
+        docPaymentLog4j.debug("DocPayment - getAccountBPartner - DocumentType = " + DocumentType);
       if (isReceipt) {
         data = DocPaymentData.selectBPartnerCustomerAcct(conn, cBPartnerId,
             as.getC_AcctSchema_ID(), dpStatus);
@@ -560,7 +563,7 @@
             dpStatus);
       }
     } catch (ServletException e) {
-      log4j.warn(e);
+      docPaymentLog4j.warn(e);
     }
     // Get Acct
     String Account_ID = "";
@@ -570,7 +573,7 @@
       return null;
     // No account
     if (Account_ID.equals("")) {
-      log4j.warn("DocPayment - getAccountBPartner - NO account BPartner=" + cBPartnerId
+      docPaymentLog4j.warn("DocPayment - getAccountBPartner - NO account BPartner=" + cBPartnerId
           + ", Record=" + Record_ID + ", status " + dpStatus);
       return null;
     }
@@ -579,7 +582,7 @@
     try {
       acct = Account.getAccount(conn, Account_ID);
     } catch (ServletException e) {
-      log4j.warn(e);
+      docPaymentLog4j.warn(e);
     }
     return acct;
   } // getAccount
@@ -600,7 +603,7 @@
       data = DocPaymentData.selectBankStatementLineAcct(conn, strcBankstatementlineId,
           as.getC_AcctSchema_ID());
     } catch (ServletException e) {
-      log4j.warn(e);
+      docPaymentLog4j.warn(e);
     }
     // Get Acct
     String Account_ID = "";
@@ -610,8 +613,9 @@
       return null;
     // No account
     if (Account_ID.equals("")) {
-      log4j.warn("DocPayment - getAccountBankStatementLine - NO account BankStatementLine="
-          + strcBankstatementlineId + ", Record=" + Record_ID);
+      docPaymentLog4j
+          .warn("DocPayment - getAccountBankStatementLine - NO account BankStatementLine="
+              + strcBankstatementlineId + ", Record=" + Record_ID);
       return null;
     }
     // Return Account
@@ -619,7 +623,7 @@
     try {
       acct = Account.getAccount(conn, Account_ID);
     } catch (ServletException e) {
-      log4j.warn(e);
+      docPaymentLog4j.warn(e);
     }
     return acct;
   } // getAccount
@@ -639,7 +643,7 @@
     try {
       data = DocPaymentData.selectCashLineAcct(conn, strcCashlineId, as.getC_AcctSchema_ID());
     } catch (ServletException e) {
-      log4j.warn(e);
+      docPaymentLog4j.warn(e);
     }
     // Get Acct
     String Account_ID = "";
@@ -649,8 +653,8 @@
       return null;
     // No account
     if (Account_ID.equals("")) {
-      log4j.warn("DocPayment - getAccountCashLine - NO account CashLine=" + strcCashlineId
-          + ", Record=" + Record_ID);
+      docPaymentLog4j.warn("DocPayment - getAccountCashLine - NO account CashLine="
+          + strcCashlineId + ", Record=" + Record_ID);
       return null;
     }
     // Return Account
@@ -658,18 +662,18 @@
     try {
       acct = Account.getAccount(conn, Account_ID);
     } catch (ServletException e) {
-      log4j.warn(e);
+      docPaymentLog4j.warn(e);
     }
     return acct;
   } // getAccount
 
   public String nextSeqNo(String oldSeqNo) {
-    if (log4j.isDebugEnabled())
-      log4j.debug("DocPayment - oldSeqNo = " + oldSeqNo);
+    if (docPaymentLog4j.isDebugEnabled())
+      docPaymentLog4j.debug("DocPayment - oldSeqNo = " + oldSeqNo);
     BigDecimal seqNo = new BigDecimal(oldSeqNo);
     SeqNo = (seqNo.add(new BigDecimal("10"))).toString();
-    if (log4j.isDebugEnabled())
-      log4j.debug("DocPayment - nextSeqNo = " + SeqNo);
+    if (docPaymentLog4j.isDebugEnabled())
+      docPaymentLog4j.debug("DocPayment - nextSeqNo = " + SeqNo);
     return SeqNo;
   }
 
@@ -683,7 +687,7 @@
     try {
       data = DocPaymentData.paymentsInformation(conn, strRecordId);
     } catch (ServletException e) {
-      log4j.error(e.getMessage(), e);
+      docPaymentLog4j.error(e.getMessage(), e);
       setStatus(STATUS_Error);
       return false;
     }
--- a/src/org/openbravo/erpCommon/ad_forms/Fact.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_forms/Fact.java	Fri Jun 03 10:22:43 2016 +0200
@@ -164,12 +164,6 @@
    *          debit amount, can be null
    * @param creditAmt
    *          credit amount, can be null
-   * @param Fact_Acct_Group_ID
-   * 
-   * @param SeqNo
-   * 
-   * @param DocBaseType
-   * 
    * @param conversionDate
    *          Date to convert currencies if required
    * @param conversionRate
@@ -180,6 +174,9 @@
       String debitAmt, String creditAmt, String Fact_Acct_Group_ID, String SeqNo,
       String DocBaseType, String conversionDate, BigDecimal conversionRate, ConnectionProvider conn) {
 
+    String localConversionDate = conversionDate;
+    String localCreditAmt = creditAmt;
+    String localDebitAmt = debitAmt;
     String strNegate = "";
     try {
       strNegate = AcctServerData.selectNegate(conn, m_acctSchema.m_C_AcctSchema_ID, DocBaseType);
@@ -189,8 +186,8 @@
     }
     if (strNegate.equals(""))
       strNegate = "Y";
-    BigDecimal DebitAmt = new BigDecimal(debitAmt.equals("") ? "0.00" : debitAmt);
-    BigDecimal CreditAmt = new BigDecimal(creditAmt.equals("") ? "0.00" : creditAmt);
+    BigDecimal DebitAmt = new BigDecimal(localDebitAmt.equals("") ? "0.00" : localDebitAmt);
+    BigDecimal CreditAmt = new BigDecimal(localCreditAmt.equals("") ? "0.00" : localCreditAmt);
     if (DebitAmt.compareTo(BigDecimal.ZERO) == 0 && CreditAmt.compareTo(BigDecimal.ZERO) == 0) {
       return null;
     }
@@ -206,9 +203,9 @@
 
       if (DebitAmt.compareTo(ZERO) < 0) {
         CreditAmt = CreditAmt.add(DebitAmt.abs());
-        creditAmt = CreditAmt.toString();
+        localCreditAmt = CreditAmt.toString();
         DebitAmt = BigDecimal.ZERO;
-        debitAmt = DebitAmt.toString();
+        localDebitAmt = DebitAmt.toString();
         if ("GLJ".equals(DocBaseType)) {
           convertedCreditAmt = convertedCreditAmt.add(convertedDebitAmt.abs());
           convertedDebitAmt = BigDecimal.ZERO;
@@ -217,9 +214,9 @@
       }
       if (CreditAmt.compareTo(ZERO) < 0) {
         DebitAmt = DebitAmt.add(CreditAmt.abs());
-        debitAmt = DebitAmt.toString();
+        localDebitAmt = DebitAmt.toString();
         CreditAmt = BigDecimal.ZERO;
-        creditAmt = CreditAmt.toString();
+        localCreditAmt = CreditAmt.toString();
         if ("GLJ".equals(DocBaseType)) {
           convertedDebitAmt = convertedDebitAmt.add(convertedCreditAmt.abs());
           convertedCreditAmt = BigDecimal.ZERO;
@@ -239,7 +236,8 @@
       }
     }
 
-    log4jFact.debug("createLine - " + account + " - Dr=" + debitAmt + ", Cr=" + creditAmt);
+    log4jFact
+        .debug("createLine - " + account + " - Dr=" + localDebitAmt + ", Cr=" + localCreditAmt);
     log4jFact.debug("Starting createline");
     // Data Check
     if (account == null) {
@@ -260,21 +258,21 @@
     line.setAccount(m_acctSchema, account);
     log4jFact.debug("account set");
 
-    log4jFact.debug("C_Currency_ID: " + C_Currency_ID + " - debitAmt: " + debitAmt
-        + " - creditAmt: " + creditAmt);
+    log4jFact.debug("C_Currency_ID: " + C_Currency_ID + " - debitAmt: " + localDebitAmt
+        + " - creditAmt: " + localCreditAmt);
     // Amounts - one needs to be both not zero
-    if (!line.setAmtSource(C_Currency_ID, debitAmt, creditAmt))
+    if (!line.setAmtSource(C_Currency_ID, localDebitAmt, localCreditAmt))
       return null;
-    if (conversionDate == null || conversionDate.isEmpty()) {
-      conversionDate = m_doc.DateAcct;
+    if (localConversionDate == null || localConversionDate.isEmpty()) {
+      localConversionDate = m_doc.DateAcct;
     }
     log4jFact.debug("C_Currency_ID: " + m_acctSchema.getC_Currency_ID() + " - ConversionDate: "
-        + conversionDate + " - CurrencyRateType: " + m_acctSchema.getCurrencyRateType());
+        + localConversionDate + " - CurrencyRateType: " + m_acctSchema.getCurrencyRateType());
     // Convert
     if (conversionRate != null) {
       line.convertByRate(m_acctSchema.getC_Currency_ID(), conversionRate);
     } else {
-      line.convert(m_acctSchema.getC_Currency_ID(), conversionDate,
+      line.convert(m_acctSchema.getC_Currency_ID(), localConversionDate,
           m_acctSchema.getCurrencyRateType(), conn);
     }
     // Optionally overwrite Acct Amount
@@ -696,7 +694,6 @@
     } else { // Adjust biggest (Balance Sheet) line amount
       BigDecimal BSamount = ZERO;
       FactLine BSline = null;
-      BigDecimal PLamount = ZERO;
       FactLine PLline = null;
       int signum = diff.signum();
       // Find line
@@ -710,7 +707,6 @@
           BSline = l;
         } else if (!l.isBalanceSheet() && ((amt.compareTo(BSamount) > 0 && signum != 1))
             || ((amt.compareTo(BSamount) < 0 && signum == 1))) {
-          PLamount = amt;
           PLline = l;
         }
       }
--- a/src/org/openbravo/erpCommon/ad_forms/FactLine.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_forms/FactLine.java	Fri Jun 03 10:22:43 2016 +0200
@@ -1013,17 +1013,18 @@
   public StringBuffer getDescription(ConnectionProvider connectionProvider,
       String strC_Bpartner_ID, String strC_AcctSchema_ID, String strAD_Table_ID,
       String strRecord_ID, String strLine) throws ServletException {
+    String localStrLine = strLine;
     StringBuffer description = new StringBuffer();
     String strSql = AcctServerData.selectDescription(connectionProvider, strAD_Table_ID,
         strC_AcctSchema_ID);
     try {
       if (!strSql.equals("")/* && strLine!=null && !strLine.equals("") */) {
         strSql = strSql.replaceAll("@RecordId@", "'" + strRecord_ID + "'");
-        if (strLine == null || strLine.equals(""))
-          strLine = "NULL";
+        if (localStrLine == null || localStrLine.equals(""))
+          localStrLine = "NULL";
         else
-          strLine = "'" + strLine + "'";
-        strSql = strSql.replaceAll("@Line@", strLine);
+          localStrLine = "'" + localStrLine + "'";
+        strSql = strSql.replaceAll("@Line@", localStrLine);
         Statement st = connectionProvider.getStatement();
         ResultSet result;
         try {
@@ -1117,29 +1118,6 @@
     }
   }
 
-  /**
-   * Convert a BigDecimal to a BigDecimal with a specified number of decimal places
-   * 
-   * @param in
-   *          BigDecimal to set the precision
-   * @param precision
-   *          (Max) Number of decimal places to output Note: precision generally refers to the total
-   *          number of digits in a number, but within Openbravo it refers to the number of
-   *          significant digits after the decimal point.
-   * @return BigDecimal with specified number of significant decimal places
-   */
-  private BigDecimal toNumberWithPrecision(BigDecimal in, long precision) {
-    if (in == null) {
-      return null;
-    }
-    try {
-      return in.setScale((int) precision, RoundingMode.HALF_UP);
-    } catch (ArithmeticException e) {
-      log4jFactLine.error(e.getMessage(), e);
-      return null;
-    }
-  }
-
   public String getCurrency() {
     return m_C_Currency_ID;
   }
--- a/src/org/openbravo/erpCommon/ad_forms/InitialClientSetup.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_forms/InitialClientSetup.java	Fri Jun 03 10:22:43 2016 +0200
@@ -38,7 +38,7 @@
 
 public class InitialClientSetup extends HttpSecureAppServlet {
 
-  private static final Logger log4j = Logger.getLogger(InitialClientSetup.class);
+  private static final Logger initialClientSetupLog4j = Logger.getLogger(InitialClientSetup.class);
   private static final long serialVersionUID = 1L;
 
   public void doPost(HttpServletRequest request, HttpServletResponse response)
@@ -51,7 +51,7 @@
       String strModules = vars.getInStringParameter("inpNodes", IsIDFilter.instance);
       StringBuffer strLog = new StringBuffer();
       OBError obeResultado = process(request, response, vars, strModules, strLog);
-      log4j.debug("InitialClientSetup - after processFile");
+      initialClientSetupLog4j.debug("InitialClientSetup - after processFile");
       printPageResult(response, vars, obeResultado, strLog);
     } else
       pageError(response);
@@ -165,7 +165,7 @@
   private OBError process(HttpServletRequest request, HttpServletResponse response,
       VariablesSecureApp vars, String strModules, StringBuffer strLog) throws IOException {
 
-    log4j.debug("process() - Initial Client Setup Process Start - strModules - " + strModules);
+    initialClientSetupLog4j.debug("process() - Initial Client Setup Process Start - strModules - " + strModules);
 
     String strClientName = vars.getStringParameter("inpClient");
     String strClientUser = vars.getStringParameter("inpClientUser");
@@ -173,7 +173,7 @@
     String strCurrency = vars.getStringParameter("inpCurrency");
     org.apache.commons.fileupload.FileItem fileCoAFilePath = vars.getMultiFile("inpFile");
     boolean bCreateAccounting = isTrue(vars.getStringParameter("inpCreateAccounting"));
-    log4j.debug("process() - Client name: " + strClientName + ". Client user name: "
+    initialClientSetupLog4j.debug("process() - Client name: " + strClientName + ". Client user name: "
         + strClientUser);
     org.openbravo.erpCommon.businessUtility.InitialClientSetup ics = new org.openbravo.erpCommon.businessUtility.InitialClientSetup();
     OBError obeResult = ics.createClient(vars, strCurrency, strClientName, strClientUser,
--- a/src/org/openbravo/erpCommon/ad_forms/MaterialReceiptPending.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_forms/MaterialReceiptPending.java	Fri Jun 03 10:22:43 2016 +0200
@@ -256,6 +256,7 @@
 
   private OBError processPurchaseOrder(VariablesSecureApp vars, String strcOrderLineId)
       throws IOException, ServletException {
+    String localStrcOrderLineId = strcOrderLineId;
     String strMessageResult = "";
     String strMessageType = "Success";
     String strWindowName = WindowTabsData.selectWindowInfo(this, vars.getLanguage(), "184");
@@ -263,7 +264,7 @@
     OBError myMessageAux = new OBError();
     myMessage = new OBError();
     myMessage.setTitle("");
-    if (strcOrderLineId.equals("")) {
+    if (localStrcOrderLineId.equals("")) {
       myMessage = Utility.translateError(this, vars, vars.getLanguage(), "ProcessRunError");
       return myMessage;
     }
@@ -272,11 +273,11 @@
     OBContext.setAdminMode();
     try {
       conn = this.getTransactionConnection();
-      if (strcOrderLineId.startsWith("("))
-        strcOrderLineId = strcOrderLineId.substring(1, strcOrderLineId.length() - 1);
-      if (!strcOrderLineId.equals("")) {
-        strcOrderLineId = Replace.replace(strcOrderLineId, "'", "");
-        StringTokenizer st = new StringTokenizer(strcOrderLineId, ",", false);
+      if (localStrcOrderLineId.startsWith("("))
+        localStrcOrderLineId = localStrcOrderLineId.substring(1, localStrcOrderLineId.length() - 1);
+      if (!localStrcOrderLineId.equals("")) {
+        localStrcOrderLineId = Replace.replace(localStrcOrderLineId, "'", "");
+        StringTokenizer st = new StringTokenizer(localStrcOrderLineId, ",", false);
         String strmInoutId = "";
         String docTargetType = "";
         String docType = "";
--- a/src/org/openbravo/erpCommon/ad_forms/ModuleManagement.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_forms/ModuleManagement.java	Fri Jun 03 10:22:43 2016 +0200
@@ -2026,13 +2026,15 @@
     boolean found = false;
     String agreement = "";
     while (!found && inst != null && i < inst.length) {
-      if (found = inst[i].getModuleID().equals(record))
+      found = inst[i].getModuleID().equals(record);
+      if (found)
         agreement = inst[i].getLicenseAgreement();
       i++;
     }
     i = 0;
     while (!found && upd != null && i < upd.length) {
-      if (found = upd[i].getModuleID().equals(record))
+      found = upd[i].getModuleID().equals(record);
+      if (found)
         agreement = upd[i].getLicenseAgreement();
       i++;
     }
--- a/src/org/openbravo/erpCommon/ad_forms/ProductInfo.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_forms/ProductInfo.java	Fri Jun 03 10:22:43 2016 +0200
@@ -11,7 +11,7 @@
  * Portions created by Jorg Janke are Copyright (C) 1999-2001 Jorg Janke, parts
  * created by ComPiere are Copyright (C) ComPiere, Inc.;   All Rights Reserved.
  * Contributor(s): Openbravo SLU
- * Contributions are Copyright (C) 2001-2012 Openbravo S.L.U.
+ * Contributions are Copyright (C) 2001-2016 Openbravo S.L.U.
  ******************************************************************************
  */
 package org.openbravo.erpCommon.ad_forms;
@@ -278,10 +278,6 @@
       return null;
     }
     BigDecimal cost = new BigDecimal(getProductItemCost(date, as, "", conn, con));
-    if (cost == null) {
-      log4jProductInfo.debug("getProductCosts - No Costs");
-      return null;
-    }
     log4jProductInfo.debug("getProductCosts - qty = " + m_qty);
     if (strQty == null || strQty.equals("")) {
       BigDecimal qty = new BigDecimal(m_qty);
--- a/src/org/openbravo/erpCommon/ad_help/HelpWindow.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_help/HelpWindow.java	Fri Jun 03 10:22:43 2016 +0200
@@ -90,6 +90,7 @@
   public static String generateWindow(ConnectionProvider conn, XmlEngine xmlEngine,
       VariablesSecureApp vars, boolean discardEdit, String strKeyId) throws IOException,
       ServletException {
+    String localStrKeyId = strKeyId;
     OBContext.setAdminMode();
     if (log4j.isDebugEnabled())
       log4j.debug("Output: Help Window");
@@ -141,14 +142,14 @@
       discard[nDiscards++] = new String("discardEdit");
     }
 
-    if (!discardEdit && strKeyId.equals("")) {
+    if (!discardEdit && localStrKeyId.equals("")) {
       strType = vars.getRequiredStringParameter("inpwindowType");
       window = false;
       if (strType.equals("X")) {
         strCommand = "FORM";
-        strKeyId = vars.getRequiredStringParameter("inpwindowName");
+        localStrKeyId = vars.getRequiredStringParameter("inpwindowName");
         DisplayHelpData[] dataForm = DisplayHelpData.selectFormTrl(conn, vars.getLanguage(),
-            strKeyId);
+            localStrKeyId);
         if (dataForm != null && dataForm.length > 0) {
           strWindowName = dataForm[0].name;
           strWindowHelp = dataForm[0].help;
@@ -159,9 +160,9 @@
         }
       } else if (strType.equals("P") || strType.equals("R")) {
         strCommand = "PROCESS";
-        strKeyId = vars.getRequiredStringParameter("inpwindowName");
+        localStrKeyId = vars.getRequiredStringParameter("inpwindowName");
         DisplayHelpData[] dataProcess = DisplayHelpData.selectProcessTrl(conn, vars.getLanguage(),
-            strKeyId);
+            localStrKeyId);
         if (dataProcess != null && dataProcess.length > 0) {
           strWindowName = dataProcess[0].name;
           strWindowHelp = dataProcess[0].help;
@@ -180,7 +181,7 @@
     List<TabGridConfigParameter> tabGridConfigParams = new ArrayList<TabGridConfigParameter>();
     DisplayHelpData[] data = DisplayHelpData.set();
     if (window) {
-      data = DisplayHelpData.selectTrl(conn, vars.getLanguage(), strKeyId);
+      data = DisplayHelpData.selectTrl(conn, vars.getLanguage(), localStrKeyId);
       if (data != null && data.length > 0) {
         strWindowName = data[0].windowname;
         strBaseName = data[0].basename;
@@ -188,7 +189,7 @@
       } else {
         discard[nDiscards++] = new String("discardEdit");
       }
-      strWindowHelp = DisplayHelpData.windowHelpTrl(conn, vars.getLanguage(), strKeyId);
+      strWindowHelp = DisplayHelpData.windowHelpTrl(conn, vars.getLanguage(), localStrKeyId);
       strCommand = "WINDOW";
 
       // Grid Configuration at System Level
@@ -213,7 +214,7 @@
 
       // Grid Configuration at Tab Level
       OBQuery<GCTab> tabGridConfigQuery = OBDal.getInstance().createQuery(GCTab.class,
-          "tab.window.id = '" + strKeyId + "'");
+          "tab.window.id = '" + localStrKeyId + "'");
       List<GCTab> tabGridConfigList = tabGridConfigQuery.list();
       for (GCTab gcTab : tabGridConfigList) {
         String tabId = gcTab.getTab().getId();
@@ -307,7 +308,7 @@
     xmlDocument.setParameter("directory", "var baseDirectory = \"" + xmlEngine.strReplaceWith
         + "/\";\n");
     xmlDocument.setParameter("theme", vars.getTheme());
-    xmlDocument.setParameter("windowId", strKeyId);
+    xmlDocument.setParameter("windowId", localStrKeyId);
     xmlDocument.setParameter("windowName", strWindowName);
     xmlDocument.setParameter("windowHelp", strWindowHelp);
     xmlDocument.setParameter("command", strCommand);
--- a/src/org/openbravo/erpCommon/ad_process/AcctServerProcess.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_process/AcctServerProcess.java	Fri Jun 03 10:22:43 2016 +0200
@@ -76,18 +76,17 @@
 
   /**
    * 
-   * @param vars
-   * @param bundle
    * @throws ServletException
    */
   private void processClient(VariablesSecureApp vars, ProcessBundle bundle) throws ServletException {
+    VariablesSecureApp localVars = vars;
     final String processId = bundle.getProcessId();
     final String pinstanceId = bundle.getPinstanceId();
     final ProcessContext ctx = bundle.getContext();
     isDirect = bundle.getChannel() == Channel.DIRECT;
 
     if (log4j.isDebugEnabled()) {
-      log4j.debug("Processing client: " + vars.getClient());
+      log4j.debug("Processing client: " + localVars.getClient());
     }
 
     if (isDirect) {
@@ -95,7 +94,7 @@
     } else {
       addLog("Starting background process.");
     }
-    if (vars == null) {
+    if (localVars == null) {
       try {
         final AcctServerProcessData[] dataOrg = AcctServerProcessData.selectUserOrg(connection,
             processId);
@@ -107,7 +106,7 @@
           }
           return;
         }
-        vars = new VariablesSecureApp(dataOrg[0].adUserId, ctx.getClient(), dataOrg[0].adOrgId);
+        localVars = new VariablesSecureApp(dataOrg[0].adUserId, ctx.getClient(), dataOrg[0].adOrgId);
       } catch (final ServletException ex) {
         log4j.error(ex.getMessage());
         return;
@@ -149,7 +148,7 @@
     // If UseRequestOrganizationExecutingRequestProcess preference exists
     // use process Organization
     if (AcctServerProcessData.useRequestProcessOrg(connection)) {
-      strOrg = vars.getOrg();
+      strOrg = localVars.getOrg();
     }
     if (!strTable.equals("")) {
       tables = new String[1];
@@ -159,7 +158,7 @@
     }
     String strTableDesc;
     for (int i = 0; i < tables.length; i++) {
-      final AcctServer acct = AcctServer.get(tables[i], vars.getClient(), strOrg, connection);
+      final AcctServer acct = AcctServer.get(tables[i], localVars.getClient(), strOrg, connection);
       if (acct == null)
         continue;
       acct.setBatchSize(BATCH_SIZE);
@@ -183,7 +182,7 @@
         }
 
         try {
-          acct.run(vars, strDateFrom, strDateTo);
+          acct.run(localVars, strDateFrom, strDateTo);
         } catch (final Exception ex) {
           log4j.error(ex.getMessage(), ex);
           return;
--- a/src/org/openbravo/erpCommon/ad_process/CopyFromGLJournal.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_process/CopyFromGLJournal.java	Fri Jun 03 10:22:43 2016 +0200
@@ -21,7 +21,6 @@
 import java.io.IOException;
 import java.io.PrintWriter;
 import java.sql.Connection;
-import java.text.SimpleDateFormat;
 
 import javax.servlet.ServletConfig;
 import javax.servlet.ServletException;
@@ -85,8 +84,6 @@
 
   private OBError processButton(VariablesSecureApp vars, String strKey, String strGLJournalBatch,
       String windowId) {
-    String strDateFormat = vars.getJavaDateFormat();
-    SimpleDateFormat dateFormat = new SimpleDateFormat(strDateFormat);
 
     if (log4j.isDebugEnabled())
       log4j.debug("Save: GLJournal");
--- a/src/org/openbravo/erpCommon/ad_process/CreateTaxReport.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_process/CreateTaxReport.java	Fri Jun 03 10:22:43 2016 +0200
@@ -230,6 +230,7 @@
   private void childData(VariablesSecureApp vars, Vector<Object> vectorArray,
       String strTaxReportId, String strPeriodFrom, String strPeriodTo, String strOrg, int level,
       String strParent, int rownum) throws IOException, ServletException {
+    int localRownum = rownum;
     if (log4j.isDebugEnabled())
       log4j.debug("**********************strTaxReportId: " + strTaxReportId);
     if (log4j.isDebugEnabled())
@@ -253,7 +254,7 @@
     String strTaxId = CreateTaxReportData.selectTax(this, strTaxReportId);
     if (log4j.isDebugEnabled())
       log4j.debug("**********************strTaxId: " + strTaxId);
-    CreateTaxReportData[] data = CreateTaxReportData.select(this, String.valueOf(rownum),
+    CreateTaxReportData[] data = CreateTaxReportData.select(this, String.valueOf(localRownum),
         strParent, String.valueOf(level),
         Utility.getContext(this, vars, "#User_Client", "CreateTaxReport"),
         Utility.stringList(strOrg), strPeriodFrom, DateTimeData.nDaysAfter(this, strPeriodTo, "1"),
@@ -261,7 +262,7 @@
     if (data == null || data.length == 0)
       data = CreateTaxReportData.set();
     else
-      rownum++;
+      localRownum++;
     vectorArray.addElement(data[0]);
     if (log4j.isDebugEnabled())
       log4j.debug("**********************data[0]*********************data[0].id: " + data[0].id
@@ -274,8 +275,8 @@
     for (int i = 0; i < dataAux.length; i++) {
       // if (dataAux[i].issummary.equals("Y")){
       childData(vars, vectorArray, dataAux[i].id, strPeriodFrom, strPeriodTo, strOrg, level + 1,
-          data[0].id, rownum);
-      rownum++;
+          data[0].id, localRownum);
+      localRownum++;
       // }
     }
   }
--- a/src/org/openbravo/erpCommon/ad_process/ExpenseAPInvoice.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_process/ExpenseAPInvoice.java	Fri Jun 03 10:22:43 2016 +0200
@@ -49,7 +49,7 @@
 public class ExpenseAPInvoice extends HttpSecureAppServlet {
   private static final long serialVersionUID = 1L;
   private static final BigDecimal ZERO = BigDecimal.ZERO;
-  static Logger log4j = Logger.getLogger(ExpenseAPInvoice.class);
+  private static final Logger expenseAPInvoiceLog4j = Logger.getLogger(ExpenseAPInvoice.class);
 
   public void init(ServletConfig config) {
     super.init(config);
@@ -87,8 +87,8 @@
 
   private OBError processExpense(VariablesSecureApp vars, String strcBpartnerId,
       String strDatereportFrom, String strDatereportTo, String strDateInvoiced) {
-    if (log4j.isDebugEnabled())
-      log4j.debug("Save: Expense AP Invoice");
+    if (expenseAPInvoiceLog4j.isDebugEnabled())
+      expenseAPInvoiceLog4j.debug("Save: Expense AP Invoice");
     int line = 0;
 
     String strcInvoiceId = "";
@@ -303,8 +303,8 @@
             data[i].adOrgId, data[i].mProductId, data[i].cUomId, strPricestd, strPricelist,
             strPricelimit, data[i].description, strcTaxID);
 
-        if (log4j.isDebugEnabled())
-          log4j.debug("dataInvoiceline: " + dataInvoiceline.length);
+        if (expenseAPInvoiceLog4j.isDebugEnabled())
+          expenseAPInvoiceLog4j.debug("dataInvoiceline: " + dataInvoiceline.length);
         if (dataInvoiceline == null || dataInvoiceline.length == 0) {
           // If it is a new line, calculates c_invoiceline_id and qty
           strcInvoiceLineId = SequenceIdData.getUUID();
@@ -315,8 +315,8 @@
             strLine = "10";
           line += Integer.valueOf(strLine);
 
-          if (log4j.isDebugEnabled())
-            log4j.debug("*****************+client: "
+          if (expenseAPInvoiceLog4j.isDebugEnabled())
+            expenseAPInvoiceLog4j.debug("*****************+client: "
                 + (data[i].invoiceprice.equals("") ? dataPrice[0].pricestd : data[i].invoiceprice));
           // Calculate Acc and Def Plan from Product
           String isDeferred = "N";
@@ -326,7 +326,6 @@
           String periodNumber = accDefPlanData.get("periodNumber");
           String startingPeriodId = accDefPlanData.get("startingPeriodId");
           // As it is a Expense invoice:
-          boolean isSOTRX = false;
           if (!"".equals(planType) && !"".equals(periodNumber) && !"".equals(startingPeriodId)) {
             isDeferred = "Y";
           } else {
@@ -435,7 +434,7 @@
       } catch (Exception ignored) {
       }
       f.printStackTrace();
-      log4j.warn("Rollback in transaction");
+      expenseAPInvoiceLog4j.warn("Rollback in transaction");
       myMessage.setType("Error");
       myMessage.setTitle(Utility.messageBD(this, "Error", vars.getLanguage()));
       myMessage.setMessage(Utility.messageBD(this, "PriceListVersionNotFound", vars.getLanguage())
@@ -452,7 +451,7 @@
       } catch (Exception ignored) {
       }
       e.printStackTrace();
-      log4j.warn("Rollback in transaction");
+      expenseAPInvoiceLog4j.warn("Rollback in transaction");
       myMessage.setType("Error");
       myMessage.setTitle(Utility.messageBD(this, "Error", vars.getLanguage()));
       if (e.getMessage().equals("PricelistNotdefined")) {
@@ -485,8 +484,8 @@
   private void printPage(HttpServletResponse response, VariablesSecureApp vars,
       String strcBpartnerId, String strDatereportFrom, String strDatereportTo,
       String strDateInvoiced) throws IOException, ServletException {
-    if (log4j.isDebugEnabled())
-      log4j.debug("Output: process ExpenseAPInvoice");
+    if (expenseAPInvoiceLog4j.isDebugEnabled())
+      expenseAPInvoiceLog4j.debug("Output: process ExpenseAPInvoice");
 
     ActionButtonDefaultData[] data = null;
     String strHelp = "", strDescription = "", strProcessId = "187";
--- a/src/org/openbravo/erpCommon/ad_process/PinstanceProcedure.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_process/PinstanceProcedure.java	Fri Jun 03 10:22:43 2016 +0200
@@ -18,7 +18,6 @@
  */
 package org.openbravo.erpCommon.ad_process;
 
-import org.apache.log4j.Logger;
 import org.openbravo.erpCommon.reference.PInstanceProcessData;
 import org.openbravo.erpCommon.utility.OBError;
 import org.openbravo.erpCommon.utility.Utility;
@@ -33,8 +32,6 @@
  */
 public class PinstanceProcedure extends ProcedureProcess {
 
-  static Logger log = Logger.getLogger(PinstanceProcedure.class);
-
   private String pinstanceId;
 
   /**
--- a/src/org/openbravo/erpCommon/ad_process/ProcedureProcess.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_process/ProcedureProcess.java	Fri Jun 03 10:22:43 2016 +0200
@@ -106,7 +106,6 @@
 
         if (params != null) {
           for (int i = 0; i < params.length; i++) {
-            String type = types[i];
             String value = params[i];
 
             int iParameter = i + 1;
--- a/src/org/openbravo/erpCommon/ad_process/Register.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_process/Register.java	Fri Jun 03 10:22:43 2016 +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-2016 Openbravo SLU 
  * All Rights Reserved. 
  * Contributor(s):  ______________________________________.
  ************************************************************************
@@ -21,6 +21,7 @@
 
 import org.openbravo.base.secureApp.HttpSecureAppServlet;
 
+@SuppressWarnings("serial")
 public class Register extends HttpSecureAppServlet {
 
   /*
--- a/src/org/openbravo/erpCommon/ad_process/TestHeartbeat.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_process/TestHeartbeat.java	Fri Jun 03 10:22:43 2016 +0200
@@ -108,7 +108,7 @@
               .init(connectionProvider);
           Map<String, Object> params = bundle.getParams();
           params.put("action", "DECLINE");
-          final String beatExecutionId = new ProcessRunner(bundle).execute(connectionProvider);
+          new ProcessRunner(bundle).execute(connectionProvider);
         }
 
         // Deactivating the process at SystemInfo
--- a/src/org/openbravo/erpCommon/ad_process/buildStructure/BuildMainStepTranslation.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_process/buildStructure/BuildMainStepTranslation.java	Fri Jun 03 10:22:43 2016 +0200
@@ -121,9 +121,9 @@
     stepTranslations.add(stepTranslation);
   }
 
-  public BuildStepTranslation getBuildStepTranslationForCode(String code) {
+  public BuildStepTranslation getBuildStepTranslationForCode(String theCode) {
     for (BuildStepTranslation stepTranslation : stepTranslations) {
-      if (stepTranslation.getCode().equals(code)) {
+      if (stepTranslation.getCode().equals(theCode)) {
         return stepTranslation;
       }
     }
--- a/src/org/openbravo/erpCommon/ad_reports/GeneralAccountingReports.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_reports/GeneralAccountingReports.java	Fri Jun 03 10:22:43 2016 +0200
@@ -32,6 +32,7 @@
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
+import org.apache.commons.lang.StringUtils;
 import org.hibernate.Query;
 import org.hibernate.Session;
 import org.hibernate.criterion.Restrictions;
@@ -129,8 +130,10 @@
           strDateFromRef, strDateToRef, strAsDateTo, strAsDateToRef, strElementValue,
           strConImporte, strOrg, strLevel, strConCodigo, strcAcctSchemaId, strPageNo);
     } else if (vars.commandIn("LEDGER")) {
-      String strOrg = vars
-          .getGlobalVariable("inpOrganizacion", "GeneralAccountingReports|Org", "0");
+      String strOrg = vars.getStringParameter("inpOrganizacion");
+      if (StringUtils.isEmpty(strOrg)) {
+        strOrg = vars.getOrg();
+      }
       String strcAcctSchemaId = OBLedgerUtils.getOrgLedger(strOrg);
       response.setContentType("text/html; charset=UTF-8");
       PrintWriter out = response.getWriter();
@@ -149,20 +152,25 @@
       String strAsDateToRef, String strElementValue, String strConImporte, String strOrg,
       String strLevel, String strConCodigo, String strcAcctSchemaId, String strPageNo)
       throws IOException, ServletException {
+    String localStrElementValue = strElementValue;
+    String localStrDateToRef = strDateToRef;
+    String localStrDateFrom = strDateFrom;
+    String localStrDateFromRef = strDateFromRef;
+    String localStrDateTo = strDateTo;
     if (log4j.isDebugEnabled())
       log4j.debug("Output: pdf");
 
-    String strCalculateOpening = strElementValue.substring(0, 1);
-    strElementValue = strElementValue.substring(1, strElementValue.length());
+    String strCalculateOpening = localStrElementValue.substring(0, 1);
+    localStrElementValue = localStrElementValue.substring(1, localStrElementValue.length());
     GeneralAccountingReportsData[] strGroups = GeneralAccountingReportsData.selectGroups(this,
-        strElementValue);
+        localStrElementValue);
 
     try {
       strGroups[strGroups.length - 1].pagebreak = "";
 
       String[][] strElementValueDes = new String[strGroups.length][];
       if (log4j.isDebugEnabled())
-        log4j.debug("strElementValue:" + strElementValue + " - strGroups.length:"
+        log4j.debug("strElementValue:" + localStrElementValue + " - strGroups.length:"
             + strGroups.length);
       for (int i = 0; i < strGroups.length; i++) {
         GeneralAccountingReportsData[] strElements = GeneralAccountingReportsData.selectElements(
@@ -199,10 +207,10 @@
         String strYearsToCloseRef = "";
         if (strCalculateOpening.equals("Y")) {
           strCalculateOpening = "N";
-          strDateTo = strAsDateTo;
-          strDateToRef = strAsDateToRef;
-          strDateFrom = "";
-          strDateFromRef = "";
+          localStrDateTo = strAsDateTo;
+          localStrDateToRef = strAsDateToRef;
+          localStrDateFrom = "";
+          localStrDateFromRef = "";
           String[] yearsInfo = getYearsToClose(startingEndingDate.get("startingDate"), strOrg,
               year.getCalendar(), strcAcctSchemaId, false);
           strYearsToClose = yearsInfo[0];
@@ -236,22 +244,23 @@
           AccountTreeData[] accounts = AccountTreeData.selectFactAcct(this,
               Utility.getContext(this, vars, "#AccessibleOrgTree", "GeneralAccountingReports"),
               Utility.getContext(this, vars, "#User_Client", "GeneralAccountingReports"),
-              strDateFrom, DateTimeData.nDaysAfter(this, strDateTo, "1"), strcAcctSchemaId,
-              Tree.getMembers(this, strTreeOrg, strOrg), "'" + year.getFiscalYear() + "'"
-                  + strYearsToClose, openingEntryOwner, strDateFromRef,
-              DateTimeData.nDaysAfter(this, strDateToRef, "1"), "'" + yearRef.getFiscalYear() + "'"
-                  + strYearsToCloseRef, openingEntryOwnerRef);
+              localStrDateFrom, DateTimeData.nDaysAfter(this, localStrDateTo, "1"),
+              strcAcctSchemaId, Tree.getMembers(this, strTreeOrg, strOrg),
+              "'" + year.getFiscalYear() + "'" + strYearsToClose, openingEntryOwner,
+              localStrDateFromRef, DateTimeData.nDaysAfter(this, localStrDateToRef, "1"), "'"
+                  + yearRef.getFiscalYear() + "'" + strYearsToCloseRef, openingEntryOwnerRef);
           {
             if (log4j.isDebugEnabled())
               log4j.debug("*********** strIncomeSummaryAccount: " + strIncomeSummaryAccount);
-            String strISyear = processIncomeSummary(strDateFrom,
-                DateTimeData.nDaysAfter(this, strDateTo, "1"), "'" + year.getFiscalYear() + "'"
-                    + strYearsToClose, strTreeOrg, strOrg, strcAcctSchemaId);
+            String strISyear = processIncomeSummary(localStrDateFrom,
+                DateTimeData.nDaysAfter(this, localStrDateTo, "1"), "'" + year.getFiscalYear()
+                    + "'" + strYearsToClose, strTreeOrg, strOrg, strcAcctSchemaId);
             if (log4j.isDebugEnabled())
               log4j.debug("*********** strISyear: " + strISyear);
-            String strISyearRef = processIncomeSummary(strDateFromRef,
-                DateTimeData.nDaysAfter(this, strDateToRef, "1"), "'" + yearRef.getFiscalYear()
-                    + "'" + strYearsToCloseRef, strTreeOrg, strOrg, strcAcctSchemaId);
+            String strISyearRef = processIncomeSummary(localStrDateFromRef,
+                DateTimeData.nDaysAfter(this, localStrDateToRef, "1"),
+                "'" + yearRef.getFiscalYear() + "'" + strYearsToCloseRef, strTreeOrg, strOrg,
+                strcAcctSchemaId);
             if (log4j.isDebugEnabled())
               log4j.debug("*********** strISyearRef: " + strISyearRef);
             accounts = appendRecords(accounts, strIncomeSummaryAccount, strISyear, strISyearRef);
@@ -282,24 +291,24 @@
         parameters.put("companyName",
             GeneralAccountingReportsData.companyName(this, vars.getClient()));
         parameters.put("date", DateTimeData.today(this));
-        if (strDateFrom.equals(""))
-          strDateFrom = OBDateUtils.formatDate(startingEndingDate.get("startingDate"));
-        if (strDateTo.equals(""))
-          strDateTo = OBDateUtils.formatDate(startingEndingDate.get("endingDate"));
-        if (strDateFromRef.equals(""))
-          strDateFromRef = OBDateUtils.formatDate(startingEndingDateRef.get("startingDate"));
-        if (strDateToRef.equals(""))
-          strDateToRef = OBDateUtils.formatDate(startingEndingDateRef.get("endingDate"));
-        parameters.put("period", strDateFrom + " - " + strDateTo);
-        parameters.put("periodRef", strDateFromRef + " - " + strDateToRef);
+        if (localStrDateFrom.equals(""))
+          localStrDateFrom = OBDateUtils.formatDate(startingEndingDate.get("startingDate"));
+        if (localStrDateTo.equals(""))
+          localStrDateTo = OBDateUtils.formatDate(startingEndingDate.get("endingDate"));
+        if (localStrDateFromRef.equals(""))
+          localStrDateFromRef = OBDateUtils.formatDate(startingEndingDateRef.get("startingDate"));
+        if (localStrDateToRef.equals(""))
+          localStrDateToRef = OBDateUtils.formatDate(startingEndingDateRef.get("endingDate"));
+        parameters.put("period", localStrDateFrom + " - " + localStrDateTo);
+        parameters.put("periodRef", localStrDateFromRef + " - " + localStrDateToRef);
         parameters.put("agnoInitial", year.getFiscalYear());
         parameters.put("agnoRef", yearRef.getFiscalYear());
 
         parameters.put(
             "principalTitle",
             strCalculateOpening.equals("Y") ? GeneralAccountingReportsData.rptTitle(this,
-                strElementValue) + " (Provisional)" : GeneralAccountingReportsData.rptTitle(this,
-                strElementValue));
+                localStrElementValue) + " (Provisional)" : GeneralAccountingReportsData.rptTitle(
+                this, localStrElementValue));
 
         parameters.put("pageNo", strPageNo);
 
--- a/src/org/openbravo/erpCommon/ad_reports/MInOutTraceReports.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_reports/MInOutTraceReports.java	Fri Jun 03 10:22:43 2016 +0200
@@ -173,19 +173,21 @@
   private MInOutTraceReportsData[] processData(VariablesSecureApp vars,
       MInOutTraceReportsData[] data, String strIn, String strmProductIdGlobal,
       Hashtable<String, Integer> calculated, Vector<Integer> count) throws ServletException {
-    if (data == null || data.length == 0) {
-      return data;
+    MInOutTraceReportsData[] localData = data;
+    if (localData == null || localData.length == 0) {
+      return localData;
     }
-    for (int i = 0; i < data.length; i++) {
-      data[i].html = processChilds(vars, data[i].mAttributesetinstanceId, data[i].mProductId,
-          data[i].mLocatorId, strIn, true, strmProductIdGlobal, calculated, count);
-      if ("".equals(data[i].html)) {
-        // Delete data[i] from array
-        data = (MInOutTraceReportsData[]) ArrayUtils.removeElement(data, data[i]);
+    for (int i = 0; i < localData.length; i++) {
+      localData[i].html = processChilds(vars, localData[i].mAttributesetinstanceId,
+          localData[i].mProductId, localData[i].mLocatorId, strIn, true, strmProductIdGlobal,
+          calculated, count);
+      if ("".equals(localData[i].html)) {
+        // Delete localData[i] from array
+        localData = (MInOutTraceReportsData[]) ArrayUtils.removeElement(localData, localData[i]);
         i--;
       }
     }
-    return data;
+    return localData;
   }
 
   private String insertTabHtml(boolean border) {
--- a/src/org/openbravo/erpCommon/ad_reports/ReportAgingBalance.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_reports/ReportAgingBalance.java	Fri Jun 03 10:22:43 2016 +0200
@@ -117,6 +117,7 @@
       VariablesSecureApp vars, String strisReceipt, String strcolumn1, String strcolumn2,
       String strcolumn3, String strcolumn4, String strcBpartnerId, String strOrgTrx,
       String strfirstPrint, final String strCurrencyId) throws IOException, ServletException {
+    String localStrisReceipt = strisReceipt;
     ReportAgingBalanceData[] data = null;
     // Jarenor
     /*
@@ -127,12 +128,12 @@
     String strTreeOrg = TreeData.getTreeOrg(this, vars.getClient());
     String strOrgFamily = getFamily(strTreeOrg, strOrgTrx);
 
-    if (strisReceipt.equals(""))
-      strisReceipt = "N";
+    if (localStrisReceipt.equals(""))
+      localStrisReceipt = "N";
 
     try {
       data = ReportAgingBalanceData.select(this, vars.getLanguage(), strOrgTrx, strCurrencyId,
-          strcolumn1, strcolumn2, strcolumn3, strcolumn4, strisReceipt, strcBpartnerId,
+          strcolumn1, strcolumn2, strcolumn3, strcolumn4, localStrisReceipt, strcBpartnerId,
           strOrgFamily, Utility.getContext(this, vars, "#User_Client", "ReportAgingBalance"),
           Utility.getContext(this, vars, "#AccessibleOrgTree", "ReportAgingBalance"));
     } catch (ServletException ex) {
@@ -155,6 +156,7 @@
       String strisReceipt, String strcolumn1, String strcolumn2, String strcolumn3,
       String strcolumn4, String strcBpartnerId, String strOrgTrx, String strfirstPrint,
       final String strCurrencyId) throws IOException, ServletException {
+    String localStrisReceipt = strisReceipt;
     if (log4j.isDebugEnabled())
       log4j.debug("Output: dataSheet");
     response.setContentType("text/html; charset=UTF-8");
@@ -166,13 +168,13 @@
     String strTreeOrg = TreeData.getTreeOrg(this, vars.getClient());
     String strOrgFamily = getFamily(strTreeOrg, strOrgTrx);
 
-    if (strisReceipt.equals(""))
-      strisReceipt = "N";
+    if (localStrisReceipt.equals(""))
+      localStrisReceipt = "N";
 
     if (vars.commandIn("FIND")) {
       try {
         data = ReportAgingBalanceData.select(this, vars.getLanguage(), strOrgTrx, strCurrencyId,
-            strcolumn1, strcolumn2, strcolumn3, strcolumn4, strisReceipt, strcBpartnerId,
+            strcolumn1, strcolumn2, strcolumn3, strcolumn4, localStrisReceipt, strcBpartnerId,
             strOrgFamily, Utility.getContext(this, vars, "#User_Client", "ReportAgingBalance"),
             Utility.getContext(this, vars, "#AccessibleOrgTree", "ReportAgingBalance"));
       } catch (final ServletException ex) {
@@ -227,8 +229,8 @@
 
     xmlDocument.setParameter("directory", "var baseDirectory = \"" + strReplaceWith + "/\";\n");
     xmlDocument.setParameter("paramLanguage", "defaultLang=\"" + vars.getLanguage() + "\";");
-    xmlDocument.setParameter("receipt", strisReceipt);
-    xmlDocument.setParameter("payable", strisReceipt);
+    xmlDocument.setParameter("receipt", localStrisReceipt);
+    xmlDocument.setParameter("payable", localStrisReceipt);
     xmlDocument.setParameter("column1", strcolumn1);
     xmlDocument.setParameter("column2", strcolumn2);
     xmlDocument.setParameter("column3", strcolumn3);
--- a/src/org/openbravo/erpCommon/ad_reports/ReportCashflowForecast.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_reports/ReportCashflowForecast.java	Fri Jun 03 10:22:43 2016 +0200
@@ -84,16 +84,9 @@
       String strBankAccount, String strDateMax, String strBreakDate, boolean showDefault)
       throws IOException, ServletException {
 
-    ToolBar toolbar = new ToolBar(this, vars.getLanguage(), "ReportCashflowForecast", false, "",
-        "", "", false, "ad_reports", strReplaceWith, false, true);
-
     // ReportCashflowForecastData[] dataSummary =
     // ReportCashflowForecastData.select(this,Utility.getContext(this, vars, "#User_Client",
     // "ReportBank"), Utility.getContext(this, vars, "#AccessibleOrgTree", "ReportBank"));
-    ReportCashflowForecastData[] dataSummary = ReportCashflowForecastData.select(this,
-        vars.getLanguage(), strDateMax, "",
-        Utility.getContext(this, vars, "#User_Client", "ReportBank"),
-        Utility.getContext(this, vars, "#AccessibleOrgTree", "ReportBank"));
 
     if (!showDefault) {
       ReportCashflowForecastData[] dataDetail = null;
--- a/src/org/openbravo/erpCommon/ad_reports/ReportGeneralLedger.html	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_reports/ReportGeneralLedger.html	Fri Jun 03 10:22:43 2016 +0200
@@ -149,8 +149,6 @@
     updateMenuIcon('buttonMenu');
 
     setWindowElementFocus('firstElement');
-    setDefaultLedger();
-
   }
 
   function onResizeDo(){
--- a/src/org/openbravo/erpCommon/ad_reports/ReportGeneralLedger.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_reports/ReportGeneralLedger.java	Fri Jun 03 10:22:43 2016 +0200
@@ -60,8 +60,8 @@
     VariablesSecureApp vars = new VariablesSecureApp(request);
 
     if (vars.commandIn("DEFAULT")) {
-      String strcAcctSchemaId = vars.getGlobalVariable("inpcAcctSchemaId",
-          "ReportGeneralLedger|cAcctSchemaId", "");
+      String strOrg = vars.getGlobalVariable("inpOrg", "ReportGeneralLedger|Org", "0");
+      String strcAcctSchemaId = OBLedgerUtils.getOrgLedger(strOrg);
       String strDateFrom = vars
           .getGlobalVariable("inpDateFrom", "ReportGeneralLedger|DateFrom", "");
       String strDateTo = vars.getGlobalVariable("inpDateTo", "ReportGeneralLedger|DateTo", "");
@@ -85,7 +85,6 @@
       strcelementvaluetodes = (strcelementvaluetodes.equals("null")) ? "" : strcelementvaluetodes;
       vars.setSessionValue("inpElementValueIdFrom_DES", strcelementvaluefromdes);
       vars.setSessionValue("inpElementValueIdTo_DES", strcelementvaluetodes);
-      String strOrg = vars.getGlobalVariable("inpOrg", "ReportGeneralLedger|Org", "0");
       String strcBpartnerId = vars.getInGlobalVariable("inpcBPartnerId_IN",
           "ReportGeneralLedger|cBpartnerId", "", IsIDFilter.instance);
       String strmProductId = vars.getInGlobalVariable("inpmProductId_IN",
@@ -203,7 +202,7 @@
             strcProjectId, strGroupBy, strcAcctSchemaId, strShowOpenBalances);
       }
     } else if (vars.commandIn("LEDGER")) {
-      String strOrg = vars.getGlobalVariable("inpOrg", "ReportGeneralLedger|Org", "0");
+      String strOrg = vars.getStringParameter("inpOrg");
       String strcAcctSchemaId = OBLedgerUtils.getOrgLedger(strOrg);
       response.setContentType("text/html; charset=UTF-8");
       PrintWriter out = response.getWriter();
@@ -222,6 +221,8 @@
       String strmProductId, String strcProjectId, String strGroupBy, String strcAcctSchemaId,
       String strcelementvaluefromdes, String strcelementvaluetodes, String strShowOpenBalances)
       throws IOException, ServletException {
+    String localStrcelementvaluetodes = strcelementvaluetodes;
+    String localStrcelementvalueto = strcelementvalueto;
     String strRecordRange = Utility.getContext(this, vars, "#RecordRange", "ReportGeneralLedger");
     int intRecordRange = (strRecordRange.equals("") ? 0 : Integer.parseInt(strRecordRange));
     String strInitRecord = vars.getSessionValue("ReportGeneralLedger.initRecordNumber");
@@ -280,26 +281,26 @@
       BigDecimal previousCredit = BigDecimal.ZERO;
       String strAllaccounts = "Y";
       if (strcelementvaluefrom != null && !strcelementvaluefrom.equals("")) {
-        if (strcelementvalueto.equals("")) {
-          strcelementvalueto = strcelementvaluefrom;
-          strcelementvaluetodes = ReportGeneralLedgerData.selectSubaccountDescription(this,
-              strcelementvalueto);
-          vars.setSessionValue("inpElementValueIdTo_DES", strcelementvaluetodes);
+        if (localStrcelementvalueto.equals("")) {
+          localStrcelementvalueto = strcelementvaluefrom;
+          localStrcelementvaluetodes = ReportGeneralLedgerData.selectSubaccountDescription(this,
+              localStrcelementvalueto);
+          vars.setSessionValue("inpElementValueIdTo_DES", localStrcelementvaluetodes);
 
         }
         strAllaccounts = "N";
         log4j.debug("##################### strcelementvaluefrom= " + strcelementvaluefrom);
-        log4j.debug("##################### strcelementvalueto= " + strcelementvalueto);
+        log4j.debug("##################### strcelementvalueto= " + localStrcelementvalueto);
       } else {
-        strcelementvalueto = "";
-        strcelementvaluetodes = "";
-        vars.setSessionValue("inpElementValueIdTo_DES", strcelementvaluetodes);
+        localStrcelementvalueto = "";
+        localStrcelementvaluetodes = "";
+        vars.setSessionValue("inpElementValueIdTo_DES", localStrcelementvaluetodes);
       }
       Long initMainSelect = System.currentTimeMillis();
       ReportGeneralLedgerData scroll = null;
       try {
         scroll = ReportGeneralLedgerData.select2(this, rowNum, strGroupByText, strGroupBy,
-            strAllaccounts, strcelementvaluefrom, strcelementvalueto,
+            strAllaccounts, strcelementvaluefrom, localStrcelementvalueto,
             Utility.getContext(this, vars, "#AccessibleOrgTree", "ReportGeneralLedger"),
             Utility.getContext(this, vars, "#User_Client", "ReportGeneralLedger"),
             "Y".equals(strShowOpenBalances) ? strDateTo : null, strcAcctSchemaId, strDateFrom,
@@ -333,7 +334,7 @@
             // firstPagBlock = true;
             Long init = System.currentTimeMillis();
             dataTotal = ReportGeneralLedgerData.select2Total(this, rowNum, strGroupByText,
-                strGroupBy, strAllaccounts, strcelementvaluefrom, strcelementvalueto,
+                strGroupBy, strAllaccounts, strcelementvaluefrom, localStrcelementvalueto,
                 Utility.getContext(this, vars, "#AccessibleOrgTree", "ReportGeneralLedger"),
                 Utility.getContext(this, vars, "#User_Client", "ReportGeneralLedger"),
                 strcAcctSchemaId, "", DateTimeData.nDaysAfter(this, data[0].dateacct, "1"),
@@ -341,7 +342,7 @@
                 data[0].id, data[0].groupbyid, null, null, null, data[0].dateacctnumber
                     + data[0].factaccttype + data[0].factAcctGroupId + data[0].factAcctId);
             dataSubtotal = ReportGeneralLedgerData.select2sum(this, rowNum, strGroupByText,
-                strGroupBy, strAllaccounts, strcelementvaluefrom, strcelementvalueto,
+                strGroupBy, strAllaccounts, strcelementvaluefrom, localStrcelementvalueto,
                 Utility.getContext(this, vars, "#AccessibleOrgTree", "ReportGeneralLedger"),
                 Utility.getContext(this, vars, "#User_Client", "ReportGeneralLedger"),
                 strcAcctSchemaId, strDateFrom, toDatePlusOne, strOrgFamily,
@@ -495,9 +496,9 @@
     xmlDocument.setParameter("amtTo", strAmtTo);
     xmlDocument.setParameter("adOrgId", strOrg);
     xmlDocument.setParameter("cAcctschemaId", strcAcctSchemaId);
-    xmlDocument.setParameter("paramElementvalueIdTo", strcelementvalueto);
+    xmlDocument.setParameter("paramElementvalueIdTo", localStrcelementvalueto);
     xmlDocument.setParameter("paramElementvalueIdFrom", strcelementvaluefrom);
-    xmlDocument.setParameter("inpElementValueIdTo_DES", strcelementvaluetodes);
+    xmlDocument.setParameter("inpElementValueIdTo_DES", localStrcelementvaluetodes);
     xmlDocument.setParameter("inpElementValueIdFrom_DES", strcelementvaluefromdes);
     xmlDocument.setParameter("groupbyselected", strGroupBy);
     xmlDocument.setParameter("showOpenBalances", strShowOpenBalances);
@@ -554,6 +555,7 @@
       String strcBpartnerId, String strmProductId, String strcProjectId, String strGroupBy,
       String strcAcctSchemaId, String strPageNo, String strShowOpenBalances) throws IOException,
       ServletException {
+    String localStrcelementvalueto = strcelementvalueto;
     log4j.debug("Output: PDF");
     response.setContentType("text/html; charset=UTF-8");
     String strTreeOrg = TreeData.getTreeOrg(this, vars.getClient());
@@ -574,15 +576,15 @@
     }
 
     if (strcelementvaluefrom != null && !strcelementvaluefrom.equals("")) {
-      if (strcelementvalueto.equals(""))
-        strcelementvalueto = strcelementvaluefrom;
+      if (localStrcelementvalueto.equals(""))
+        localStrcelementvalueto = strcelementvaluefrom;
       strAllaccounts = "N";
     }
 
     ReportGeneralLedgerData data = null;
     try {
       data = ReportGeneralLedgerData.select2(this, "0", strGroupByText, strGroupBy, strAllaccounts,
-          strcelementvaluefrom, strcelementvalueto,
+          strcelementvaluefrom, localStrcelementvalueto,
           Utility.getContext(this, vars, "#AccessibleOrgTree", "ReportGeneralLedger"),
           Utility.getContext(this, vars, "#User_Client", "ReportGeneralLedger"),
           "Y".equals(strShowOpenBalances) ? strDateTo : null, strcAcctSchemaId, strDateFrom,
@@ -634,6 +636,7 @@
       String strAmtTo, String strcelementvaluefrom, String strcelementvalueto, String strOrg,
       String strcBpartnerId, String strmProductId, String strcProjectId, String strGroupBy,
       String strcAcctSchemaId, String strShowOpenBalances) throws IOException, ServletException {
+    String localStrcelementvalueto = strcelementvalueto;
     log4j.debug("Output: XLS");
     response.setContentType("text/html; charset=UTF-8");
     String strTreeOrg = TreeData.getTreeOrg(this, vars.getClient());
@@ -651,15 +654,15 @@
     }
 
     if (strcelementvaluefrom != null && !strcelementvaluefrom.equals("")) {
-      if (strcelementvalueto.equals(""))
-        strcelementvalueto = strcelementvaluefrom;
+      if (localStrcelementvalueto.equals(""))
+        localStrcelementvalueto = strcelementvaluefrom;
       strAllaccounts = "N";
     }
 
     ReportGeneralLedgerData data = null;
     try {
       data = ReportGeneralLedgerData.selectXLS2(this, strAllaccounts, strcelementvaluefrom,
-          strcelementvalueto,
+          localStrcelementvalueto,
           Utility.getContext(this, vars, "#AccessibleOrgTree", "ReportGeneralLedger"),
           Utility.getContext(this, vars, "#User_Client", "ReportGeneralLedger"),
           "Y".equals(strShowOpenBalances) ? strDateTo : null, strcAcctSchemaId, strDateFrom,
--- a/src/org/openbravo/erpCommon/ad_reports/ReportGeneralLedgerJournal.html	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_reports/ReportGeneralLedgerJournal.html	Fri Jun 03 10:22:43 2016 +0200
@@ -316,7 +316,6 @@
         updateMenuIcon('buttonMenu');
 
         setWindowElementFocus('firstElement');
-        setDefaultLedger();
         displayDocumentNo();
         displayAdvancedFilters();
         selectDocument();
--- a/src/org/openbravo/erpCommon/ad_reports/ReportGeneralLedgerJournal.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_reports/ReportGeneralLedgerJournal.java	Fri Jun 03 10:22:43 2016 +0200
@@ -90,8 +90,8 @@
       log4j.debug("Command: " + vars.getStringParameter("Command"));
 
     if (vars.commandIn("DEFAULT")) {
-      String strcAcctSchemaId = vars.getGlobalVariable("inpcAcctSchemaId",
-          "ReportGeneralLedger|cAcctSchemaId", "");
+      String strOrg = vars.getGlobalVariable("inpOrg", "ReportGeneralLedgerJournal|Org", "0");
+      String strcAcctSchemaId = OBLedgerUtils.getOrgLedger(strOrg);
       String strDateFrom = vars.getGlobalVariable("inpDateFrom",
           "ReportGeneralLedgerJournal|DateFrom", "");
       String strDateTo = vars.getGlobalVariable("inpDateTo", "ReportGeneralLedgerJournal|DateTo",
@@ -100,7 +100,6 @@
           "ReportGeneralLedgerJournal|Document", "");
       String strDocumentNo = vars.getGlobalVariable("inpDocumentNo",
           "ReportGeneralLedgerJournal|DocumentNo", "");
-      String strOrg = vars.getGlobalVariable("inpOrg", "ReportGeneralLedgerJournal|Org", "0");
       String strShowClosing = vars.getGlobalVariable("inpShowClosing",
           "ReportGeneralLedgerJournal|ShowClosing", "Y");
       String strShowReg = vars.getGlobalVariable("inpShowReg",
@@ -412,7 +411,7 @@
       out.println("objson = " + combobox);
       out.close();
     } else if (vars.commandIn("LEDGER")) {
-      String strOrg = vars.getGlobalVariable("inpOrg", "ReportGeneralLedgerJournal|Org", "0");
+      String strOrg = vars.getStringParameter("inpOrg");
       String strcAcctSchemaId = OBLedgerUtils.getOrgLedger(strOrg);
       response.setContentType("text/html; charset=UTF-8");
       PrintWriter out = response.getWriter();
--- a/src/org/openbravo/erpCommon/ad_reports/ReportInvoiceCustomerDimensionalAnalysesJR.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_reports/ReportInvoiceCustomerDimensionalAnalysesJR.java	Fri Jun 03 10:22:43 2016 +0200
@@ -560,6 +560,12 @@
       String strProducttype, String strcDocTypeId, String strOrder, String strMayor,
       String strMenor, String strPartnerSalesrepId, String strCurrencyId, String strVoid,
       String strOutput) throws IOException, ServletException {
+    String localStrShown = strShown;
+    String localStrOrg = strOrg;
+    String localStrDateToRef3 = strDateToRef3;
+    String localStrDateToRef2 = strDateToRef2;
+    String localStrDateFromRef2 = strDateFromRef2;
+    String localStrDateFromRef3 = strDateFromRef3;
     if (log4j.isDebugEnabled())
       log4j.debug("Output: print html");
     String strOrderby = "";
@@ -572,25 +578,27 @@
         "discard", "discard", "discard", "discard", "discard", "discard", "discard", "discard",
         "discard", "discard", "discard", "discard", "discard", "discard", "discard", "discard",
         "discard", "discard", "discard", "discard", "discard", "discard" };
-    if (strOrg.equals(""))
-      strOrg = vars.getOrg();
+    if (localStrOrg.equals(""))
+      localStrOrg = vars.getOrg();
     boolean multiComparative2 = false;
     boolean multiComparative3 = false;
     if (strComparative.equals("Y")) {
       discard1[0] = "selEliminarBody2";
-      if (StringUtils.isNotBlank(strDateFromRef2) && StringUtils.isNotBlank(strDateToRef2)) {
+      if (StringUtils.isNotBlank(localStrDateFromRef2)
+          && StringUtils.isNotBlank(localStrDateToRef2)) {
         multiComparative2 = true;
-        if (StringUtils.isNotBlank(strDateFromRef3) && StringUtils.isNotBlank(strDateToRef3)) {
+        if (StringUtils.isNotBlank(localStrDateFromRef3)
+            && StringUtils.isNotBlank(localStrDateToRef3)) {
           multiComparative3 = true;
         } else {
-          strDateFromRef3 = "";
-          strDateToRef3 = "";
+          localStrDateFromRef3 = "";
+          localStrDateToRef3 = "";
         }
       } else {
-        strDateFromRef2 = "";
-        strDateToRef2 = "";
-        strDateFromRef3 = "";
-        strDateToRef3 = "";
+        localStrDateFromRef2 = "";
+        localStrDateToRef2 = "";
+        localStrDateFromRef3 = "";
+        localStrDateToRef3 = "";
       }
     }
     String strTitle = "";
@@ -635,12 +643,12 @@
     ReportInvoiceCustomerDimensionalAnalysesJRData[] data = null;
     ReportInvoiceCustomerDimensionalAnalysesJRData dataXLS = null;
     String[] strShownArray = { "", "", "", "", "", "", "", "", "", "" };
-    if (strShown.startsWith("("))
-      strShown = strShown.substring(1, strShown.length() - 1);
-    if (!strShown.equals("")) {
-      strShown = Replace.replace(strShown, "'", "");
-      strShown = Replace.replace(strShown, " ", "");
-      StringTokenizer st = new StringTokenizer(strShown, ",", false);
+    if (localStrShown.startsWith("("))
+      localStrShown = localStrShown.substring(1, localStrShown.length() - 1);
+    if (!localStrShown.equals("")) {
+      localStrShown = Replace.replace(localStrShown, "'", "");
+      localStrShown = Replace.replace(localStrShown, " ", "");
+      StringTokenizer st = new StringTokenizer(localStrShown, ",", false);
       int intContador = 0;
       while (st.hasMoreTokens()) {
         strShownArray[intContador] = st.nextToken();
@@ -791,24 +799,25 @@
       limit = Integer.parseInt(Utility.getPreference(vars, "ReportsLimit", ""));
       if (limit > 0) {
         mycount = Integer
-            .parseInt((strComparative.equals("Y")) ? ReportInvoiceCustomerDimensionalAnalysesJRData
-                .selectCount(this, levelsconcat.toString(), Tree.getMembers(this,
-                    TreeData.getTreeOrg(this, vars.getClient()), strOrg), Utility.getContext(this,
-                    vars, "#User_Client", "ReportInvoiceCustomerDimensionalAnalysesJR"),
-                    strPartnerGroup, strcBpartnerId, strProductCategory, strmProductId,
-                    strsalesrepId, strPartnerSalesrepId, strcProjectId, strProducttype,
-                    strcDocTypeId, strVoid.equals("Y") ? "" : "VO", strDateFrom, DateTimeData
-                        .nDaysAfter(this, strDateTo, "1"), strDateFromRef, DateTimeData.nDaysAfter(
-                        this, strDateToRef, "1"), strDateFromRef2, DateTimeData.nDaysAfter(this,
-                        strDateToRef2, "1"), strDateFromRef3, DateTimeData.nDaysAfter(this,
-                        strDateToRef3, "1")) : ReportInvoiceCustomerDimensionalAnalysesJRData
-                .selectNoComparativeCount(this, levelsconcat.toString(), Tree.getMembers(this,
-                    TreeData.getTreeOrg(this, vars.getClient()), strOrg), Utility.getContext(this,
-                    vars, "#User_Client", "ReportInvoiceCustomerDimensionalAnalysesJR"),
-                    strPartnerGroup, strcBpartnerId, strProductCategory, strmProductId,
-                    strsalesrepId, strPartnerSalesrepId, strcProjectId, strProducttype,
-                    strcDocTypeId, strVoid.equals("Y") ? "" : "VO", strDateFrom, DateTimeData
-                        .nDaysAfter(this, strDateTo, "1")));
+            .parseInt((strComparative.equals("Y")) ? ReportInvoiceCustomerDimensionalAnalysesJRData.selectCount(
+                this, levelsconcat.toString(), Tree.getMembers(this,
+                    TreeData.getTreeOrg(this, vars.getClient()), localStrOrg), Utility.getContext(
+                    this, vars, "#User_Client", "ReportInvoiceCustomerDimensionalAnalysesJR"),
+                strPartnerGroup, strcBpartnerId, strProductCategory, strmProductId, strsalesrepId,
+                strPartnerSalesrepId, strcProjectId, strProducttype, strcDocTypeId, strVoid
+                    .equals("Y") ? "" : "VO", strDateFrom, DateTimeData.nDaysAfter(this, strDateTo,
+                    "1"), strDateFromRef, DateTimeData.nDaysAfter(this, strDateToRef, "1"),
+                localStrDateFromRef2, DateTimeData.nDaysAfter(this, localStrDateToRef2, "1"),
+                localStrDateFromRef3, DateTimeData.nDaysAfter(this, localStrDateToRef3, "1"))
+                : ReportInvoiceCustomerDimensionalAnalysesJRData.selectNoComparativeCount(this,
+                    levelsconcat.toString(), Tree.getMembers(this,
+                        TreeData.getTreeOrg(this, vars.getClient()), localStrOrg), Utility
+                        .getContext(this, vars, "#User_Client",
+                            "ReportInvoiceCustomerDimensionalAnalysesJR"), strPartnerGroup,
+                    strcBpartnerId, strProductCategory, strmProductId, strsalesrepId,
+                    strPartnerSalesrepId, strcProjectId, strProducttype, strcDocTypeId, strVoid
+                        .equals("Y") ? "" : "VO", strDateFrom, DateTimeData.nDaysAfter(this,
+                        strDateTo, "1")));
       }
     } catch (NumberFormatException e) {
     }
@@ -827,9 +836,9 @@
       if ("xls".equals(strOutput)) {
         try {
           dataXLS = ReportInvoiceCustomerDimensionalAnalysesJRData.selectXLS(this, strCurrencyId,
-              Tree.getMembers(this, TreeData.getTreeOrg(this, vars.getClient()), strOrg), Utility
-                  .getContext(this, vars, "#User_Client",
-                      "ReportInvoiceCustomerDimensionalAnalysesJR"), strDateFrom, DateTimeData
+              Tree.getMembers(this, TreeData.getTreeOrg(this, vars.getClient()), localStrOrg),
+              Utility.getContext(this, vars, "#User_Client",
+                  "ReportInvoiceCustomerDimensionalAnalysesJR"), strDateFrom, DateTimeData
                   .nDaysAfter(this, strDateTo, "1"), strPartnerGroup, strcBpartnerId,
               strProductCategory, strmProductId, strsalesrepId, strPartnerSalesrepId,
               strcProjectId, strProducttype, strcDocTypeId, strVoid.equals("Y") ? "" : "VO");
@@ -842,38 +851,42 @@
             if (multiComparative2) {
               if (multiComparative3) {
                 // Multi-comparative B: 1 base date, 3 reference dates
-                data = ReportInvoiceCustomerDimensionalAnalysesJRData.select3(this, strCurrencyId,
-                    strTextShow[0], strTextShow[1], strTextShow[2], strTextShow[3], strTextShow[4],
-                    strTextShow[5], strTextShow[6], strTextShow[7], strTextShow[8], strTextShow[9],
-                    Tree.getMembers(this, TreeData.getTreeOrg(this, vars.getClient()), strOrg),
-                    Utility.getContext(this, vars, "#User_Client",
-                        "ReportInvoiceCustomerDimensionalAnalysesJR"), strDateFrom, DateTimeData
-                        .nDaysAfter(this, strDateTo, "1"), strPartnerGroup, strcBpartnerId,
-                    strProductCategory, strmProductId, strsalesrepId, strPartnerSalesrepId,
-                    strcProjectId, strProducttype, strcDocTypeId, strVoid.equals("Y") ? "" : "VO",
-                    strDateFromRef, DateTimeData.nDaysAfter(this, strDateToRef, "1"),
-                    strDateFromRef2, DateTimeData.nDaysAfter(this, strDateToRef2, "1"),
-                    strDateFromRef3, DateTimeData.nDaysAfter(this, strDateToRef3, "1"), strOrderby);
+                data = ReportInvoiceCustomerDimensionalAnalysesJRData
+                    .select3(this, strCurrencyId, strTextShow[0], strTextShow[1], strTextShow[2],
+                        strTextShow[3], strTextShow[4], strTextShow[5], strTextShow[6],
+                        strTextShow[7], strTextShow[8], strTextShow[9], Tree.getMembers(this,
+                            TreeData.getTreeOrg(this, vars.getClient()), localStrOrg), Utility
+                            .getContext(this, vars, "#User_Client",
+                                "ReportInvoiceCustomerDimensionalAnalysesJR"), strDateFrom,
+                        DateTimeData.nDaysAfter(this, strDateTo, "1"), strPartnerGroup,
+                        strcBpartnerId, strProductCategory, strmProductId, strsalesrepId,
+                        strPartnerSalesrepId, strcProjectId, strProducttype, strcDocTypeId, strVoid
+                            .equals("Y") ? "" : "VO", strDateFromRef, DateTimeData.nDaysAfter(this,
+                            strDateToRef, "1"), localStrDateFromRef2, DateTimeData.nDaysAfter(this,
+                            localStrDateToRef2, "1"), localStrDateFromRef3, DateTimeData
+                            .nDaysAfter(this, localStrDateToRef3, "1"), strOrderby);
               } else {
                 // Multi-comparative A: 1 base date, 2 reference dates
-                data = ReportInvoiceCustomerDimensionalAnalysesJRData.select2(this, strCurrencyId,
-                    strTextShow[0], strTextShow[1], strTextShow[2], strTextShow[3], strTextShow[4],
-                    strTextShow[5], strTextShow[6], strTextShow[7], strTextShow[8], strTextShow[9],
-                    Tree.getMembers(this, TreeData.getTreeOrg(this, vars.getClient()), strOrg),
-                    Utility.getContext(this, vars, "#User_Client",
-                        "ReportInvoiceCustomerDimensionalAnalysesJR"), strDateFrom, DateTimeData
-                        .nDaysAfter(this, strDateTo, "1"), strPartnerGroup, strcBpartnerId,
-                    strProductCategory, strmProductId, strsalesrepId, strPartnerSalesrepId,
-                    strcProjectId, strProducttype, strcDocTypeId, strVoid.equals("Y") ? "" : "VO",
-                    strDateFromRef, DateTimeData.nDaysAfter(this, strDateToRef, "1"),
-                    strDateFromRef2, DateTimeData.nDaysAfter(this, strDateToRef2, "1"), strOrderby);
+                data = ReportInvoiceCustomerDimensionalAnalysesJRData
+                    .select2(this, strCurrencyId, strTextShow[0], strTextShow[1], strTextShow[2],
+                        strTextShow[3], strTextShow[4], strTextShow[5], strTextShow[6],
+                        strTextShow[7], strTextShow[8], strTextShow[9], Tree.getMembers(this,
+                            TreeData.getTreeOrg(this, vars.getClient()), localStrOrg), Utility
+                            .getContext(this, vars, "#User_Client",
+                                "ReportInvoiceCustomerDimensionalAnalysesJR"), strDateFrom,
+                        DateTimeData.nDaysAfter(this, strDateTo, "1"), strPartnerGroup,
+                        strcBpartnerId, strProductCategory, strmProductId, strsalesrepId,
+                        strPartnerSalesrepId, strcProjectId, strProducttype, strcDocTypeId, strVoid
+                            .equals("Y") ? "" : "VO", strDateFromRef, DateTimeData.nDaysAfter(this,
+                            strDateToRef, "1"), localStrDateFromRef2, DateTimeData.nDaysAfter(this,
+                            localStrDateToRef2, "1"), strOrderby);
               }
             } else {
               // Regular comparative: 1 base date, 1 reference date
               data = ReportInvoiceCustomerDimensionalAnalysesJRData.select(this, strCurrencyId,
                   strTextShow[0], strTextShow[1], strTextShow[2], strTextShow[3], strTextShow[4],
                   strTextShow[5], strTextShow[6], strTextShow[7], strTextShow[8], strTextShow[9],
-                  Tree.getMembers(this, TreeData.getTreeOrg(this, vars.getClient()), strOrg),
+                  Tree.getMembers(this, TreeData.getTreeOrg(this, vars.getClient()), localStrOrg),
                   Utility.getContext(this, vars, "#User_Client",
                       "ReportInvoiceCustomerDimensionalAnalysesJR"), strDateFrom, DateTimeData
                       .nDaysAfter(this, strDateTo, "1"), strPartnerGroup, strcBpartnerId,
@@ -890,7 +903,7 @@
                 strCurrencyId, strTextShow[0], strTextShow[1], strTextShow[2], strTextShow[3],
                 strTextShow[4], strTextShow[5], strTextShow[6], strTextShow[7], strTextShow[8],
                 strTextShow[9], Tree.getMembers(this, TreeData.getTreeOrg(this, vars.getClient()),
-                    strOrg), Utility.getContext(this, vars, "#User_Client",
+                    localStrOrg), Utility.getContext(this, vars, "#User_Client",
                     "ReportInvoiceCustomerDimensionalAnalysesJR"), strDateFrom, DateTimeData
                     .nDaysAfter(this, strDateTo, "1"), strPartnerGroup, strcBpartnerId,
                 strProductCategory, strmProductId, strsalesrepId, strPartnerSalesrepId,
--- a/src/org/openbravo/erpCommon/ad_reports/ReportInvoiceCustomerDimensionalAnalysesJR_legacy.java	Wed Jun 01 13:42:08 2016 +0200
+++ b/src/org/openbravo/erpCommon/ad_reports/ReportInvoiceCustomerDimensionalAnalysesJR_legacy.java	Fri Jun 03 10:22:43 2016 +0200
@@ -427,6 +427,8 @@
       String strProducttype, String strOrder, String strMayor, String strMenor,
       String strPartnerSalesrepId, String strCurrencyId, String strOutput) throws IOException,
       ServletException {
+    String localStrShown = strShown;
+    String localStrOrg = strOrg;
     if (log4j.isDebugEnabled())
       log4j.debug("Output: print html");
     String strOrderby = "";
@@ -439,8 +441,8 @@
         "discard", "discard", "discard", "discard", "discard", "discard", "discard", "discard",
         "discard", "discard", "discard", "discard", "discard", "discard", "discard", "discard",
         "discard", "discard", "discard", "discard", "discard", "discard" };
-    if (strOrg.equals(""))
-      strOrg = vars.getOrg();
+    if (localStrOrg.equals(""))
+      localStrOrg = vars.getOrg();
     if (strComparative.equals("Y"))
       discard1[0] = "selEliminarBody2";
     String strTitle = "";
@@ -490,12 +492,12 @@
 
     ReportInvoiceCustomerDimensionalAnalysesJRLegacyData[] data = null;
     String[] strShownArray = { "", "", "", "", "", "", "", "", "", "" };
-    if (strShown.startsWith("("))
-      strShown = strShown.substring(1, strShown.length() - 1);
-    if (!strShown.equals("")) {
-      strShown = Replace.replace(strShown, "'", "");
-      strShown = Replace.replace(strShown, " ", "");
-      StringTokenizer st = new StringTokenizer(strShown, ",", false);
+    if (localStrShown.startsWith("("))
+      localStrShown = localStrShown.substring(1, localStrShown.length() - 1);
+    if (!localStrShown.equals("")) {
+      localStrShown = Replace.replace(localStrShown, "'", "");
+      localStrShown = Replace.replace(localStrShown, " ", "");
+      StringTokenizer st = new StringTokenizer(localStrShown, ",", false);
       int intContador = 0;
       while (st.hasMoreTokens()) {
         strShownArray[intContador] = st.nextToken();
@@ -647,19 +649,20 @@
       limit = Integer.parseInt(Utility.getPreference(vars, "ReportsLimit", ""));
       if (limit > 0) {
         mycount = Integer
-            .parseInt((strComparative.equals("Y")) ? ReportInvoiceCustomerDimensionalAnalysesJRLegacyData
-                .selectCount(this, levelsconcat.toString(), Tree.getMembers(this,
-                    TreeData.getTreeOrg(this, vars.getClient()), strOrg), Utility.getContext(this,
-                    vars, "#User_Client", "ReportInvoiceCustomerDimensionalAnalysesJR_legacy"),
-                    strPartnerGroup, strcBpartnerId, strProductCategory, strmProductId,
-                    strsalesrepId, strPartnerSalesrepId, strcProjectId, strProducttype,
-                    strDateFrom, DateTimeData.nDaysAfter(this, strDateTo, "1"), strDateFromRef,
-                    DateTimeData.nDaysAfter(this, strDateToRef, "1"))
+            .parseInt((strComparative.equals("Y")) ? ReportInvoiceCustomerDimensionalAnalysesJRLegacyData.selectCount(
+                this, levelsconcat.toString(), Tree.getMembers(this,
+                    TreeData.getTreeOrg(this, vars.getClient()), localStrOrg), Utility
+                    .getContext(this, vars, "#User_Client",