/**
   * Translate the given code into some message from the application dictionary.
   *
   * @param conn Handler for the database connection.
   * @param strCode String with the code to search.
   * @param strLanguage String with the translation language.
   * @param escape Escape \n and " characters
   * @return String with the translated message.
   */
  public static String messageBD(
      ConnectionProvider conn, String strCode, String strLanguage, boolean escape) {
    String strMessage = "";
    if (strLanguage == null || strLanguage.equals("")) strLanguage = "en_US";

    try {
      log4j.debug("Utility.messageBD - Message Code: " + strCode);
      strMessage = MessageBDData.message(conn, strLanguage, strCode);
    } catch (final Exception ignore) {
      log4j.error("Error getting message", ignore);
    }
    log4j.debug("Utility.messageBD - Message description: " + strMessage);
    if (strMessage == null || strMessage.equals("")) {
      try {
        strMessage = MessageBDData.columnname(conn, strLanguage, strCode);
      } catch (final Exception e) {
        log4j.error("Error getting message", e);
        strMessage = strCode;
      }
    }
    if (strMessage == null || strMessage.equals("")) {
      strMessage = strCode;
    }
    if (escape) {
      strMessage = Replace.replace(Replace.replace(strMessage, "\n", "\\n"), "\"", """);
    }
    return strMessage;
  }
  /**
   * Translate the given code into some message from the application dictionary. It searches first
   * in AD_Message table and if there are not matchings then in AD_Element table.
   *
   * @param strCode String with the search key to search.
   * @return String with the translated message.
   */
  public static String messageBD(String strCode) {
    String strMessage = "";
    final String strLanguageId = OBContext.getOBContext().getLanguage().getId();

    // Search strCode in AD_Message table.
    try {
      OBContext.setAdminMode(false);
      log4j.debug("messageBD - Message Code: " + strCode);
      OBCriteria<Message> obcMessage = OBDal.getInstance().createCriteria(Message.class);
      obcMessage.add(Restrictions.eq(Message.PROPERTY_SEARCHKEY, strCode).ignoreCase());
      if (obcMessage.count() > 0) {
        Message msg = obcMessage.list().get(0);
        strMessage = msg.getMessageText();
        for (MessageTrl msgTrl : msg.getADMessageTrlList()) {
          if (DalUtil.getId(msgTrl.getLanguage()).equals(strLanguageId)) {
            strMessage = msgTrl.getMessageText();
            break;
          }
        }
      }
    } catch (final Exception ignore) {
      log4j.error("Error getting message", ignore);
    } finally {
      OBContext.restorePreviousMode();
    }
    log4j.debug("messageBD - Message description: " + strMessage);
    // if message is still empty search in AD_Element
    if ("".equals(strMessage)) {
      try {
        OBContext.setAdminMode(false);
        OBCriteria<Element> obcElement = OBDal.getInstance().createCriteria(Element.class);
        obcElement.add(Restrictions.eq(Element.PROPERTY_DBCOLUMNNAME, strCode).ignoreCase());
        if (obcElement.count() > 0) {
          Element element = obcElement.list().get(0);
          strMessage = element.getName();
          for (ElementTrl elementTrl : element.getADElementTrlList()) {
            if (DalUtil.getId(elementTrl.getLanguage()).equals(strLanguageId)) {
              strMessage = elementTrl.getName();
            }
          }
        }
      } catch (final Exception e) {
        log4j.error("Error getting message", e);
        strMessage = strCode;
      } finally {
        OBContext.restorePreviousMode();
      }
    }
    if ("".equals(strMessage)) {
      strMessage = strCode;
    }
    strMessage = Replace.replace(Replace.replace(strMessage, "\n", "\\n"), "\"", "&quot;");
    return strMessage;
  }
  private void printPageHtml(
      HttpServletRequest request,
      HttpServletResponse response,
      VariablesSecureApp vars,
      String strComparative,
      String strDateFrom,
      String strDateTo,
      String strPartnerGroup,
      String strcBpartnerId,
      String strProductCategory,
      String strmProductId,
      String strNotShown,
      String strShown,
      String strDateFromRef,
      String strDateToRef,
      String strOrg,
      String strsalesrepId,
      String strmWarehouseId,
      String strOrder,
      String strMayor,
      String strMenor,
      String strRatioMayor,
      String strRatioMenor,
      String strCurrencyId)
      throws IOException, ServletException {
    if (log4j.isDebugEnabled()) log4j.debug("Output: print html");
    XmlDocument xmlDocument = null;
    String strOrderby = "";
    String[] discard = {"", "", "", "", "", "", ""};
    String[] discard1 = {
      "selEliminarBody1",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "discard",
      "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 (strComparative.equals("Y")) discard1[0] = "selEliminarBody2";
    String strTitle = "";
    strTitle =
        Utility.messageBD(this, "From", vars.getLanguage())
            + " "
            + strDateFrom
            + " "
            + Utility.messageBD(this, "To", vars.getLanguage())
            + " "
            + strDateTo;
    if (!strPartnerGroup.equals(""))
      strTitle =
          strTitle
              + ", "
              + Utility.messageBD(this, "ForBPartnerGroup", vars.getLanguage())
              + " "
              + ReportRefundSalesDimensionalAnalysesData.selectBpgroup(this, strPartnerGroup);
    if (!strProductCategory.equals(""))
      strTitle =
          strTitle
              + ", "
              + Utility.messageBD(this, "ProductCategory", vars.getLanguage())
              + " "
              + ReportRefundSalesDimensionalAnalysesData.selectProductCategory(
                  this, strProductCategory);
    if (!strsalesrepId.equals(""))
      strTitle =
          strTitle
              + ", "
              + Utility.messageBD(this, "TheSalesRep", vars.getLanguage())
              + " "
              + ReportRefundSalesDimensionalAnalysesData.selectSalesrep(this, strsalesrepId);
    if (!strmWarehouseId.equals(""))
      strTitle =
          strTitle
              + " "
              + Utility.messageBD(this, "And", vars.getLanguage())
              + " "
              + Utility.messageBD(this, "TheWarehouse", vars.getLanguage())
              + " "
              + ReportRefundSalesDimensionalAnalysesData.selectMwarehouse(this, strmWarehouseId);

    ReportRefundSalesDimensionalAnalysesData[] 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);
      int intContador = 0;
      while (st.hasMoreTokens()) {
        strShownArray[intContador] = st.nextToken();
        intContador++;
      }
    }
    String[] strTextShow = {"", "", "", "", "", "", ""};
    int intDiscard = 0;
    int intAuxDiscard = -1;
    for (int i = 0; i < 7; i++) {
      if (strShownArray[i].equals("1")) {
        strTextShow[i] = "C_BP_GROUP.NAME";
        intDiscard++;
      } else if (strShownArray[i].equals("2")) {
        strTextShow[i] =
            "AD_COLUMN_IDENTIFIER(to_char('C_Bpartner'), to_char( C_BPARTNER.C_BPARTNER_ID), to_char('"
                + vars.getLanguage()
                + "'))";
        intDiscard++;
      } else if (strShownArray[i].equals("3")) {
        strTextShow[i] = "M_PRODUCT_CATEGORY.NAME";
        intDiscard++;
      } else if (strShownArray[i].equals("4")) {
        strTextShow[i] =
            "AD_COLUMN_IDENTIFIER(to_char('M_Product'), to_char( M_PRODUCT.M_PRODUCT_ID), to_char('"
                + vars.getLanguage()
                + "'))|| CASE WHEN uomsymbol IS NULL THEN '' ELSE to_char(' ('||uomsymbol||')') END";
        intAuxDiscard = i;
        intDiscard++;
      } else if (strShownArray[i].equals("5")) {
        strTextShow[i] = "C_ORDER.DOCUMENTNO";
        intDiscard++;
      } else if (strShownArray[i].equals("6")) {
        strTextShow[i] = "AD_USER.FIRSTNAME||' '||' '||AD_USER.LASTNAME";
        intDiscard++;
      } else if (strShownArray[i].equals("7")) {
        strTextShow[i] = "M_WAREHOUSE.NAME";
        intDiscard++;
      } else {
        strTextShow[i] = "''";
        discard[i] = "display:none;";
      }
    }
    if (intDiscard != 0 || intAuxDiscard != -1) {
      int k = 1;
      if (intDiscard == 1) {
        strOrderby = " ORDER BY NIVEL" + k + ",";
      } else {
        strOrderby = " ORDER BY ";
      }
      while (k < intDiscard) {
        strOrderby = strOrderby + "NIVEL" + k + ",";
        k++;
      }
      if (k == 1) {
        if (strOrder.equals("Normal")) {
          strOrderby = " ORDER BY NIVEL" + k;
        } else if (strOrder.equals("Amountasc")) {
          strOrderby = " ORDER BY LINENETAMT ASC";
        } else if (strOrder.equals("Amountdesc")) {
          strOrderby = " ORDER BY LINENETAMT DESC";
        } else if (strOrder.equals("Ratioasc")) {
          strOrderby = " ORDER BY RATIO ASC";
        } else if (strOrder.equals("Ratiodesc")) {
          strOrderby = " ORDER BY RATIO DESC";
        } else {
          strOrderby = "1";
        }
      } else {
        if (strOrder.equals("Normal")) {
          strOrderby += "NIVEL" + k;
        } else if (strOrder.equals("Amountasc")) {
          strOrderby += "LINENETAMT ASC";
        } else if (strOrder.equals("Amountdesc")) {
          strOrderby += "LINENETAMT DESC";
        } else if (strOrder.equals("Ratioasc")) {
          strOrderby += "RATIO ASC";
        } else if (strOrder.equals("Ratiodesc")) {
          strOrderby += "RATIO DESC";
        } else {
          strOrderby = "1";
        }
      }

    } else {
      strOrderby = " ORDER BY 1";
    }
    String strHaving = "";
    if (!strMayor.equals("") && !strMenor.equals("")) {
      strHaving = " HAVING SUM(LINENETAMT) > " + strMayor + " AND SUM(LINENETAMT) < " + strMenor;
    } else if (!strMayor.equals("") && strMenor.equals("")) {
      strHaving = " HAVING SUM(LINENETAMT) > " + strMayor;
    } else if (strMayor.equals("") && !strMenor.equals("")) {
      strHaving = " HAVING SUM(LINENETAMT) < " + strMenor;
    } else {
    }
    if (strHaving.equals("")) {
      if (!strRatioMayor.equals("") && !strRatioMenor.equals("")) {
        strHaving =
            " HAVING C_DIVIDE(SUM(REFUNDAMT), (SUM(LINENETAMT)+SUM(REFUNDAMT)))*100 > "
                + strRatioMayor
                + " AND C_DIVIDE(SUM(REFUNDAMT), (SUM(LINENETAMT)+SUM(REFUNDAMT)))*100 < "
                + strRatioMenor;
      } else if (!strRatioMayor.equals("") && strRatioMenor.equals("")) {
        strHaving =
            " HAVING C_DIVIDE(SUM(REFUNDAMT), (SUM(LINENETAMT)+SUM(REFUNDAMT)))*100 > "
                + strRatioMayor;
      } else if (strRatioMayor.equals("") && !strRatioMenor.equals("")) {
        strHaving =
            " HAVING C_DIVIDE(SUM(REFUNDAMT), (SUM(LINENETAMT)+SUM(REFUNDAMT)))*100 < "
                + strRatioMenor;
      } else {
      }
    } else {
      if (!strRatioMayor.equals("") && !strRatioMenor.equals("")) {
        strHaving +=
            " AND C_DIVIDE(SUM(REFUNDAMT), (SUM(LINENETAMT)+SUM(REFUNDAMT)))*100 > "
                + strRatioMayor
                + " AND C_DIVIDE(SUM(REFUNDAMT), (SUM(LINENETAMT)+SUM(REFUNDAMT)))*100 < "
                + strRatioMenor;
      } else if (!strRatioMayor.equals("") && strRatioMenor.equals("")) {
        strHaving +=
            " AND C_DIVIDE(SUM(REFUNDAMT), (SUM(LINENETAMT)+SUM(REFUNDAMT)))*100 > "
                + strRatioMayor;
      } else if (strRatioMayor.equals("") && !strRatioMenor.equals("")) {
        strHaving +=
            " AND C_DIVIDE(SUM(REFUNDAMT), (SUM(LINENETAMT)+SUM(REFUNDAMT)))*100 < "
                + strRatioMenor;
      } else {
      }
    }
    strOrderby = strHaving + strOrderby;

    // Checks if there is a conversion rate for each of the transactions of
    // the report
    String strConvRateErrorMsg = "";
    OBError myMessage = null;
    myMessage = new OBError();
    if (strComparative.equals("Y")) {
      try {
        data =
            ReportRefundSalesDimensionalAnalysesData.select(
                this,
                strCurrencyId,
                strTextShow[0],
                strTextShow[1],
                strTextShow[2],
                strTextShow[3],
                strTextShow[4],
                strTextShow[5],
                strTextShow[6],
                Tree.getMembers(this, TreeData.getTreeOrg(this, vars.getClient()), strOrg),
                Utility.getContext(
                    this, vars, "#User_Client", "ReportRefundInvoiceCustomerDimensionalAnalyses"),
                strDateFrom,
                DateTimeData.nDaysAfter(this, strDateTo, "1"),
                strPartnerGroup,
                strcBpartnerId,
                strProductCategory,
                strmProductId,
                strsalesrepId,
                strmWarehouseId,
                strDateFromRef,
                DateTimeData.nDaysAfter(this, strDateToRef, "1"),
                strOrderby);
      } catch (ServletException ex) {
        myMessage = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
      }
    } else {
      try {
        data =
            ReportRefundSalesDimensionalAnalysesData.selectNoComparative(
                this,
                strCurrencyId,
                strTextShow[0],
                strTextShow[1],
                strTextShow[2],
                strTextShow[3],
                strTextShow[4],
                strTextShow[5],
                strTextShow[6],
                Tree.getMembers(this, TreeData.getTreeOrg(this, vars.getClient()), strOrg),
                Utility.getContext(
                    this, vars, "#User_Client", "ReportRefundInvoiceCustomerDimensionalAnalyses"),
                strDateFrom,
                DateTimeData.nDaysAfter(this, strDateTo, "1"),
                strPartnerGroup,
                strcBpartnerId,
                strProductCategory,
                strmProductId,
                strsalesrepId,
                strmWarehouseId,
                strOrderby);
      } catch (ServletException ex) {
        myMessage = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
      }
    }
    strConvRateErrorMsg = myMessage.getMessage();
    // If a conversion rate is missing for a certain transaction, an error
    // message window pops-up.
    if (!strConvRateErrorMsg.equals("") && strConvRateErrorMsg != null) {
      advisePopUp(
          request,
          response,
          "ERROR",
          Utility.messageBD(this, "NoConversionRateHeader", vars.getLanguage()),
          strConvRateErrorMsg);
    } else { // Otherwise, the report is launched
      if (data.length == 0 || data == null) {
        data = ReportRefundSalesDimensionalAnalysesData.set();
      } else {
        int contador = intDiscard;
        if (intAuxDiscard != -1) contador = intAuxDiscard;
        int k = 1;
        if (strComparative.equals("Y")) {
          for (int j = contador; j > 0; j--) {
            discard1[k] = "fieldTotalQtyNivel" + String.valueOf(j);
            discard1[k + 12] = "fieldTotalRefundQtyNivel" + String.valueOf(j);
            discard1[k + 24] = "fieldUomsymbol" + String.valueOf(j);
            discard1[k + 6] = "fieldTotalRefQtyNivel" + String.valueOf(j);
            discard1[k + 18] = "fieldTotalRefRefundQtyNivel" + String.valueOf(j);
            k++;
          }
        } else {
          for (int j = contador; j > 0; j--) {
            discard1[k] = "fieldNoncomparativeTotalQtyNivel" + String.valueOf(j);
            discard1[k + 10] = "fieldNoncomparativeTotalRefundQtyNivel" + String.valueOf(j);
            discard1[k + 20] = "fieldNoncomparativeUomsymbol" + String.valueOf(j);
            k++;
          }
        }
      }
      xmlDocument =
          xmlEngine
              .readXmlTemplate(
                  "org/openbravo/erpCommon/ad_reports/ReportRefundSalesDimensionalAnalysesEdition",
                  discard1)
              .createXmlDocument();
      xmlDocument.setParameter("directory", "var baseDirectory = \"" + strReplaceWith + "/\";\n");
      xmlDocument.setParameter("language", "defaultLang=\"" + vars.getLanguage() + "\";");
      xmlDocument.setParameter("theme", vars.getTheme());
      xmlDocument.setParameter("eliminar2", discard[1]);
      xmlDocument.setParameter("eliminar3", discard[2]);
      xmlDocument.setParameter("eliminar4", discard[3]);
      xmlDocument.setParameter("eliminar5", discard[4]);
      xmlDocument.setParameter("eliminar6", discard[5]);
      xmlDocument.setParameter("eliminar7", discard[6]);
      xmlDocument.setParameter("title", strTitle);
      String strCurISOSym = Utility.stringISOSymbol(this, strCurrencyId);
      strCurISOSym = strCurISOSym.replace('(', ' ');
      strCurISOSym = strCurISOSym.replace(')', ' ');
      xmlDocument.setParameter("convisosym", strCurISOSym);
      xmlDocument.setParameter("constante", "100");
      if (strComparative.equals("Y")) {
        xmlDocument.setData("structure1", data);
      } else {
        xmlDocument.setData("structure2", data);
      }
      response.setContentType("text/html; charset=UTF-8");
      PrintWriter out = response.getWriter();
      out.println(xmlDocument.print());
      out.close();
    }
  }
 /**
  * Formats a message String into a String for html presentation. Escapes the &, <, >, " and ®, and
  * replace the \n by <br>
  * and \r for space.
  *
  * <p>IMPORTANT! : this method is designed to transform the output of Utility.messageBD method,
  * and this method replaces \n by \\n and \" by &quote. Because of that, the first replacements
  * revert this previous replacements.
  *
  * @param message message with java formating
  * @return html format message
  */
 public static String formatMessageBDToHtml(String message) {
   return Replace.replace(
       Replace.replace(
           Replace.replace(
               Replace.replace(
                   Replace.replace(
                       Replace.replace(
                           Replace.replace(
                               Replace.replace(
                                   Replace.replace(
                                       Replace.replace(
                                           Replace.replace(message, "\\n", "\n"), "&quot", "\""),
                                       "&",
                                       "&amp;"),
                                   "\"",
                                   "&quot;"),
                               "<",
                               "&lt;"),
                           ">",
                           "&gt;"),
                       "\n",
                       "<br/>"),
                   "\r",
                   " "),
               "®",
               "&reg;"),
           "&lt;![CDATA[",
           "<![CDATA["),
       "]]&gt;",
       "]]>");
 }
  private int saveRecord(VariablesSecureApp vars, OBError myError, char type)
      throws IOException, ServletException {
    BusinessPartnerCategoryData data = null;
    int total = 0;
    if (org.openbravo.erpCommon.utility.WindowAccessData.hasReadOnlyAccess(
        this, vars.getRole(), tabId)) {
      OBError newError =
          Utility.translateError(
              this,
              vars,
              vars.getLanguage(),
              Utility.messageBD(this, "NoWriteAccess", vars.getLanguage()));
      myError.setError(newError);
      vars.setMessage(tabId, myError);
    } else {
      Connection con = null;
      try {
        con = this.getTransactionConnection();
        data = getEditVariables(con, vars);
        data.dateTimeFormat = vars.getSessionValue("#AD_SqlDateTimeFormat");
        String strSequence = "";
        if (type == 'I') {
          strSequence = SequenceIdData.getUUID();
          if (log4j.isDebugEnabled()) log4j.debug("Sequence: " + strSequence);
          data.cBpGroupId = strSequence;
        }
        if (Utility.isElementInList(
                Utility.getContext(this, vars, "#User_Client", windowId, accesslevel),
                data.adClientId)
            && Utility.isElementInList(
                Utility.getContext(this, vars, "#User_Org", windowId, accesslevel), data.adOrgId)) {
          if (type == 'I') {
            total = data.insert(con, this);
          } else {
            // Check the version of the record we are saving is the one in DB
            if (BusinessPartnerCategoryData.getCurrentDBTimestamp(this, data.cBpGroupId)
                .equals(vars.getStringParameter("updatedTimestamp"))) {
              total = data.update(con, this);
            } else {
              myError.setMessage(
                  Replace.replace(
                      Replace.replace(
                          Utility.messageBD(this, "SavingModifiedRecord", vars.getLanguage()),
                          "\\n",
                          "<br/>"),
                      "&quot;",
                      "\""));
              myError.setType("Error");
              vars.setSessionValue(tabId + "|concurrentSave", "true");
            }
          }

        } else {
          OBError newError =
              Utility.translateError(
                  this,
                  vars,
                  vars.getLanguage(),
                  Utility.messageBD(this, "NoWriteAccess", vars.getLanguage()));
          myError.setError(newError);
        }
        releaseCommitConnection(con);
      } catch (Exception ex) {
        OBError newError = Utility.translateError(this, vars, vars.getLanguage(), ex.getMessage());
        myError.setError(newError);
        try {
          releaseRollbackConnection(con);
        } catch (final Exception e) { // do nothing
        }
      }

      if (myError.isEmpty() && total == 0) {
        OBError newError =
            Utility.translateError(this, vars, vars.getLanguage(), "@CODE=DBExecuteError");
        myError.setError(newError);
      }
      vars.setMessage(tabId, myError);

      if (!myError.isEmpty()) {
        if (data != null) {
          if (type == 'I') {
            data.cBpGroupId = "";
          } else {

          }
          vars.setEditionData(tabId, data);
        }
      } else {
        vars.setSessionValue(windowId + "|C_BP_Group_ID", data.cBpGroupId);
      }
    }
    return total;
  }