private void addOperations(
     PreparedStatement statement, long testId, String version, MeasuredOperationList operations)
     throws SQLException {
   for (MeasuredOperation operation : operations) {
     statement.setLong(1, testId);
     statement.setString(2, version);
     statement.setBigDecimal(
         3, operation.getTotalTime().toUnits(Duration.MILLI_SECONDS).getValue());
     statement.setBigDecimal(
         4, operation.getConfigurationTime().toUnits(Duration.MILLI_SECONDS).getValue());
     statement.setBigDecimal(
         5, operation.getExecutionTime().toUnits(Duration.MILLI_SECONDS).getValue());
     statement.setBigDecimal(
         6, operation.getTotalMemoryUsed().toUnits(DataAmount.BYTES).getValue());
     statement.setBigDecimal(
         7, operation.getTotalHeapUsage().toUnits(DataAmount.BYTES).getValue());
     statement.setBigDecimal(8, operation.getMaxHeapUsage().toUnits(DataAmount.BYTES).getValue());
     statement.setBigDecimal(
         9, operation.getMaxUncollectedHeap().toUnits(DataAmount.BYTES).getValue());
     statement.setBigDecimal(
         10, operation.getMaxCommittedHeap().toUnits(DataAmount.BYTES).getValue());
     statement.execute();
   }
 }
  /** Business logic to execute. */
  public final Response executeCommand(
      Object inputPar,
      UserSessionParameters userSessionPars,
      HttpServletRequest request,
      HttpServletResponse response,
      HttpSession userSession,
      ServletContext context) {
    String serverLanguageId = ((JAIOUserSessionParameters) userSessionPars).getServerLanguageId();
    Connection conn = null;
    PreparedStatement pstmt = null;
    try {
      conn = ConnectionManager.getConnection(context);

      // fires the GenericEvent.CONNECTION_CREATED event...
      EventsManager.getInstance()
          .processEvent(
              new GenericEvent(
                  this,
                  getRequestName(),
                  GenericEvent.CONNECTION_CREATED,
                  (JAIOUserSessionParameters) userSessionPars,
                  request,
                  response,
                  userSession,
                  context,
                  conn,
                  inputPar,
                  null));

      ArrayList oldVOs = ((ArrayList[]) inputPar)[0];
      ArrayList newVOs = ((ArrayList[]) inputPar)[1];
      RoleFunctionCompanyVO oldVO = null;
      RoleFunctionCompanyVO newVO = null;
      Response res = null;

      for (int i = 0; i < oldVOs.size(); i++) {
        oldVO = (RoleFunctionCompanyVO) oldVOs.get(i);
        newVO = (RoleFunctionCompanyVO) newVOs.get(i);

        if (!oldVO.getCanView().booleanValue()) {
          // no record in SYS02 yet...
          if (newVO.getCanView().booleanValue()) {
            pstmt =
                conn.prepareStatement(
                    "insert into SYS02_COMPANIES_ACCESS(PROGRESSIVE_SYS04,FUNCTION_CODE_SYS06,CAN_INS,CAN_UPD,CAN_DEL,COMPANY_CODE_SYS01) "
                        + "values(?,?,?,?,?,?)");
            pstmt.setBigDecimal(1, newVO.getProgressiveSys04SYS02());
            pstmt.setString(2, newVO.getFunctionCodeSys06SYS02());
            pstmt.setString(3, newVO.getCanInsSYS02().booleanValue() ? "Y" : "N");
            pstmt.setString(4, newVO.getCanUpdSYS02().booleanValue() ? "Y" : "N");
            pstmt.setString(5, newVO.getCanDelSYS02().booleanValue() ? "Y" : "N");
            pstmt.setString(6, newVO.getCompanyCodeSys01SYS02());
            pstmt.execute();
          }
        } else {
          // record already exists in SYS02...
          if (newVO.getCanView().booleanValue()) {
            // record in SYS02 will be updated...
            pstmt =
                conn.prepareStatement(
                    "update SYS02_COMPANIES_ACCESS set CAN_INS=?,CAN_UPD=?,CAN_DEL=? where "
                        + "PROGRESSIVE_SYS04=? and FUNCTION_CODE_SYS06=? and COMPANY_CODE_SYS01=? ");
            pstmt.setString(1, newVO.getCanInsSYS02().booleanValue() ? "Y" : "N");
            pstmt.setString(2, newVO.getCanUpdSYS02().booleanValue() ? "Y" : "N");
            pstmt.setString(3, newVO.getCanDelSYS02().booleanValue() ? "Y" : "N");
            pstmt.setBigDecimal(4, newVO.getProgressiveSys04SYS02());
            pstmt.setString(5, newVO.getFunctionCodeSys06SYS02());
            pstmt.setString(6, newVO.getCompanyCodeSys01SYS02());
            pstmt.execute();
          } else {
            // delete record from SYS02...
            pstmt =
                conn.prepareStatement(
                    "delete from SYS02_COMPANIES_ACCESS where PROGRESSIVE_SYS04=? and FUNCTION_CODE_SYS06=? and COMPANY_CODE_SYS01=?");
            pstmt.setBigDecimal(1, newVO.getProgressiveSys04SYS02());
            pstmt.setString(2, newVO.getFunctionCodeSys06SYS02());
            pstmt.setString(3, newVO.getCompanyCodeSys01SYS02());
            pstmt.execute();
          }
        }
      }

      Response answer = new VOListResponse(newVOs, false, newVOs.size());

      // fires the GenericEvent.BEFORE_COMMIT event...
      EventsManager.getInstance()
          .processEvent(
              new GenericEvent(
                  this,
                  getRequestName(),
                  GenericEvent.BEFORE_COMMIT,
                  (JAIOUserSessionParameters) userSessionPars,
                  request,
                  response,
                  userSession,
                  context,
                  conn,
                  inputPar,
                  answer));

      conn.commit();

      // fires the GenericEvent.AFTER_COMMIT event...
      EventsManager.getInstance()
          .processEvent(
              new GenericEvent(
                  this,
                  getRequestName(),
                  GenericEvent.AFTER_COMMIT,
                  (JAIOUserSessionParameters) userSessionPars,
                  request,
                  response,
                  userSession,
                  context,
                  conn,
                  inputPar,
                  answer));

      return answer;
    } catch (Throwable ex) {
      Logger.error(
          userSessionPars.getUsername(),
          this.getClass().getName(),
          "executeCommand",
          "Error while updating company-role-function settings",
          ex);
      try {
        pstmt.close();
      } catch (Exception ex2) {
      }
      try {
        conn.rollback();
      } catch (Exception ex3) {
      }
      return new ErrorResponse(ex.getMessage());
    } finally {
      try {
        ConnectionManager.releaseConnection(conn, context);
      } catch (Exception ex1) {
      }
    }
  }
 public void createFeeDetail(CFSecurityAuthorization Authorization, CFAccFeeDetailBuff Buff) {
   final String S_ProcName = "createFeeDetail";
   if (!schema.isTransactionOpen()) {
     throw CFLib.getDefaultExceptionFactory()
         .newUsageException(getClass(), S_ProcName, "Transaction not open");
   }
   ResultSet resultSet = null;
   try {
     long TenantId = Buff.getRequiredTenantId();
     long FeeId = Buff.getRequiredFeeId();
     String Description = Buff.getRequiredDescription();
     BigDecimal AmountCharged = Buff.getRequiredAmountCharged();
     Connection cnx = schema.getCnx();
     String sql =
         "exec sp_create_feedtl ?, ?, ?, ?, ?, ?"
             + ", "
             + "?"
             + ", "
             + "?"
             + ", "
             + "?"
             + ", "
             + "?";
     if (stmtCreateByPKey == null) {
       stmtCreateByPKey = cnx.prepareStatement(sql);
     }
     int argIdx = 1;
     stmtCreateByPKey.setLong(
         argIdx++, (Authorization == null) ? 0 : Authorization.getSecClusterId());
     stmtCreateByPKey.setString(
         argIdx++, (Authorization == null) ? "" : Authorization.getSecUserId().toString());
     stmtCreateByPKey.setString(
         argIdx++, (Authorization == null) ? "" : Authorization.getSecSessionId().toString());
     stmtCreateByPKey.setLong(
         argIdx++, (Authorization == null) ? 0 : Authorization.getSecClusterId());
     stmtCreateByPKey.setLong(
         argIdx++, (Authorization == null) ? 0 : Authorization.getSecTenantId());
     stmtCreateByPKey.setString(argIdx++, "FEDT");
     stmtCreateByPKey.setLong(argIdx++, TenantId);
     stmtCreateByPKey.setLong(argIdx++, FeeId);
     stmtCreateByPKey.setString(argIdx++, Description);
     stmtCreateByPKey.setBigDecimal(argIdx++, AmountCharged);
     resultSet = stmtCreateByPKey.executeQuery();
     if (resultSet.next()) {
       CFAccFeeDetailBuff createdBuff = unpackFeeDetailResultSetToBuff(resultSet);
       if (resultSet.next()) {
         resultSet.last();
         throw CFLib.getDefaultExceptionFactory()
             .newRuntimeException(
                 getClass(),
                 S_ProcName,
                 "Did not expect multi-record response, " + resultSet.getRow() + " rows selected");
       }
       Buff.setRequiredTenantId(createdBuff.getRequiredTenantId());
       Buff.setRequiredFeeId(createdBuff.getRequiredFeeId());
       Buff.setRequiredFeeDetailId(createdBuff.getRequiredFeeDetailId());
       Buff.setRequiredDescription(createdBuff.getRequiredDescription());
       Buff.setRequiredAmountCharged(createdBuff.getRequiredAmountCharged());
       Buff.setRequiredRevision(createdBuff.getRequiredRevision());
       Buff.setCreatedByUserId(createdBuff.getCreatedByUserId());
       Buff.setCreatedAt(createdBuff.getCreatedAt());
       Buff.setUpdatedByUserId(createdBuff.getUpdatedByUserId());
       Buff.setUpdatedAt(createdBuff.getUpdatedAt());
     } else {
       throw CFLib.getDefaultExceptionFactory()
           .newRuntimeException(
               getClass(),
               S_ProcName,
               "Expected a single-record response, " + resultSet.getRow() + " rows selected");
     }
   } catch (SQLException e) {
     throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
   } finally {
     if (resultSet != null) {
       try {
         resultSet.close();
       } catch (SQLException e) {
       }
       resultSet = null;
     }
   }
 }
  /** Business logic to execute. */
  public final Response executeCommand(
      Object inputPar,
      UserSessionParameters userSessionPars,
      HttpServletRequest request,
      HttpServletResponse response,
      HttpSession userSession,
      ServletContext context) {
    Connection conn = null;
    PreparedStatement pstmt = null;
    try {
      conn = ConnectionManager.getConnection(context);

      // fires the GenericEvent.CONNECTION_CREATED event...
      EventsManager.getInstance()
          .processEvent(
              new GenericEvent(
                  this,
                  getRequestName(),
                  GenericEvent.CONNECTION_CREATED,
                  (JAIOUserSessionParameters) userSessionPars,
                  request,
                  response,
                  userSession,
                  context,
                  conn,
                  inputPar,
                  null));

      Object[] pars = (Object[]) inputPar;
      DetailPurchaseDocRowVO voTemplate = (DetailPurchaseDocRowVO) pars[0];
      VariantsMatrixVO matrixVO = (VariantsMatrixVO) pars[1];
      Object[][] cells = (Object[][]) pars[2];
      BigDecimal currencyDecimals = (BigDecimal) pars[3];

      Map attribute2dbField = new HashMap();
      attribute2dbField.put("companyCodeSys01DOC07", "COMPANY_CODE_SYS01");
      attribute2dbField.put("docTypeDOC07", "DOC_TYPE");
      attribute2dbField.put("docYearDOC07", "DOC_YEAR");
      attribute2dbField.put("docNumberDOC07", "DOC_NUMBER");
      attribute2dbField.put("rowNumberDOC07", "ROW_NUMBER");
      attribute2dbField.put("itemCodeItm01DOC07", "ITEM_CODE_ITM01");
      attribute2dbField.put("supplierItemCodePur02DOC07", "SUPPLIER_ITEM_CODE_PUR02");
      attribute2dbField.put("vatCodeItm01DOC07", "VAT_CODE_ITM01");
      attribute2dbField.put("valuePur04DOC07", "VALUE_PUR04");
      attribute2dbField.put("valueDOC07", "VALUE");
      attribute2dbField.put("qtyDOC07", "QTY");
      attribute2dbField.put("discountValueDOC07", "DISCOUNT_VALUE");
      attribute2dbField.put("discountPercDOC07", "DISCOUNT_PERC");
      attribute2dbField.put("vatValueDOC07", "VAT_VALUE");

      attribute2dbField.put("vatDescriptionDOC07", "VAT_DESCRIPTION");
      attribute2dbField.put("startDatePur04DOC07", "START_DATE_PUR04");
      attribute2dbField.put("endDatePur04DOC07", "END_DATE_PUR04");
      attribute2dbField.put("umCodePur02DOC07", "UM_CODE_PUR02");
      attribute2dbField.put("decimalsReg02DOC07", "DECIMALS_REG02");
      attribute2dbField.put("minPurchaseQtyPur02DOC07", "MIN_PURCHASE_QTY_PUR02");
      attribute2dbField.put("multipleQtyPur02DOC07", "MULTIPLE_QTY_PUR02");
      attribute2dbField.put("valueReg01DOC07", "VALUE_REG01");
      attribute2dbField.put("deductibleReg01DOC07", "DEDUCTIBLE_REG01");
      attribute2dbField.put("taxableIncomeDOC07", "TAXABLE_INCOME");
      attribute2dbField.put("progressiveHie02DOC07", "PROGRESSIVE_HIE02");
      attribute2dbField.put("deliveryDateDOC07", "DELIVERY_DATE");
      attribute2dbField.put("inQtyDOC07", "IN_QTY");
      attribute2dbField.put("orderQtyDOC07", "ORDER_QTY");
      attribute2dbField.put("invoiceQtyDOC07", "INVOICE_QTY");

      attribute2dbField.put("variantTypeItm06DOC07", "VARIANT_TYPE_ITM06");
      attribute2dbField.put("variantCodeItm11DOC07", "VARIANT_CODE_ITM11");
      attribute2dbField.put("variantTypeItm07DOC07", "VARIANT_TYPE_ITM07");
      attribute2dbField.put("variantCodeItm12DOC07", "VARIANT_CODE_ITM12");
      attribute2dbField.put("variantTypeItm08DOC07", "VARIANT_TYPE_ITM08");
      attribute2dbField.put("variantCodeItm13DOC07", "VARIANT_CODE_ITM13");
      attribute2dbField.put("variantTypeItm09DOC07", "VARIANT_TYPE_ITM09");
      attribute2dbField.put("variantCodeItm14DOC07", "VARIANT_CODE_ITM14");
      attribute2dbField.put("variantTypeItm10DOC07", "VARIANT_TYPE_ITM10");
      attribute2dbField.put("variantCodeItm15DOC07", "VARIANT_CODE_ITM15");

      DetailPurchaseDocRowVO vo = null;
      VariantsMatrixColumnVO colVO = null;
      VariantsMatrixRowVO rowVO = null;
      Response res = null;
      for (int i = 0; i < cells.length; i++) {
        rowVO = (VariantsMatrixRowVO) matrixVO.getRowDescriptors().get(i);

        if (matrixVO.getColumnDescriptors().size() == 0) {

          if (cells[i][0] != null) {
            vo = (DetailPurchaseDocRowVO) voTemplate.clone();

            if (!containsVariant(matrixVO, "ITM11_VARIANTS_1")) {
              // e.g. color but not no size...
              vo.setVariantCodeItm11DOC07(ApplicationConsts.JOLLY);
              vo.setVariantTypeItm06DOC07(ApplicationConsts.JOLLY);
            } else {
              vo.setVariantCodeItm11DOC07(rowVO.getVariantCodeITM11());
              vo.setVariantTypeItm06DOC07(rowVO.getVariantTypeITM06());
            }
            if (!containsVariant(matrixVO, "ITM12_VARIANTS_2")) {
              vo.setVariantCodeItm12DOC07(ApplicationConsts.JOLLY);
              vo.setVariantTypeItm07DOC07(ApplicationConsts.JOLLY);
            } else {
              vo.setVariantCodeItm12DOC07(rowVO.getVariantCodeITM11());
              vo.setVariantTypeItm07DOC07(rowVO.getVariantTypeITM06());
            }
            if (!containsVariant(matrixVO, "ITM13_VARIANTS_3")) {
              vo.setVariantCodeItm13DOC07(ApplicationConsts.JOLLY);
              vo.setVariantTypeItm08DOC07(ApplicationConsts.JOLLY);
            } else {
              vo.setVariantCodeItm13DOC07(rowVO.getVariantCodeITM11());
              vo.setVariantTypeItm08DOC07(rowVO.getVariantTypeITM06());
            }
            if (!containsVariant(matrixVO, "ITM14_VARIANTS_4")) {
              vo.setVariantCodeItm14DOC07(ApplicationConsts.JOLLY);
              vo.setVariantTypeItm09DOC07(ApplicationConsts.JOLLY);
            } else {
              vo.setVariantCodeItm14DOC07(rowVO.getVariantCodeITM11());
              vo.setVariantTypeItm09DOC07(rowVO.getVariantTypeITM06());
            }
            if (!containsVariant(matrixVO, "ITM15_VARIANTS_5")) {
              vo.setVariantCodeItm15DOC07(ApplicationConsts.JOLLY);
              vo.setVariantTypeItm10DOC07(ApplicationConsts.JOLLY);
            } else {
              vo.setVariantCodeItm15DOC07(rowVO.getVariantCodeITM11());
              vo.setVariantTypeItm10DOC07(rowVO.getVariantTypeITM06());
            }

            vo.setQtyDOC07((BigDecimal) cells[i][0]);

            PurchaseUtils.updateTotals(vo, currencyDecimals.intValue());

            /*
                        vo.setVariantCodeItm12DOC07(ApplicationConsts.JOLLY);
                        vo.setVariantCodeItm13DOC07(ApplicationConsts.JOLLY);
                        vo.setVariantCodeItm14DOC07(ApplicationConsts.JOLLY);
                        vo.setVariantCodeItm15DOC07(ApplicationConsts.JOLLY);

                        vo.setVariantTypeItm07DOC07(ApplicationConsts.JOLLY);
                        vo.setVariantTypeItm08DOC07(ApplicationConsts.JOLLY);
                        vo.setVariantTypeItm09DOC07(ApplicationConsts.JOLLY);
                        vo.setVariantTypeItm10DOC07(ApplicationConsts.JOLLY);
            */
            vo.setInQtyDOC07(new BigDecimal(0));
            vo.setOrderQtyDOC07(vo.getQtyDOC07());
            if (vo.getInvoiceQtyDOC07() == null) vo.setInvoiceQtyDOC07(new BigDecimal(0));
            vo.setRowNumberDOC07(
                progBean.getInternalProgressive("DOC07_PURCHASE_ITEMS", "ROW_NUMBER", conn));

            // insert into DOC07...
            res =
                QueryUtil.insertTable(
                    conn,
                    userSessionPars,
                    vo,
                    "DOC07_PURCHASE_ITEMS",
                    attribute2dbField,
                    "Y",
                    "N",
                    context,
                    true);

            if (res.isError()) {
              conn.rollback();
              return res;
            }
          } // end if on not null

        } else
          for (int k = 0; k < matrixVO.getColumnDescriptors().size(); k++) {

            colVO = (VariantsMatrixColumnVO) matrixVO.getColumnDescriptors().get(k);
            if (cells[i][k] != null) {
              vo = (DetailPurchaseDocRowVO) voTemplate.clone();

              vo.setQtyDOC07((BigDecimal) cells[i][k]);

              PurchaseUtils.updateTotals(vo, currencyDecimals.intValue());

              vo.setVariantCodeItm11DOC07(rowVO.getVariantCodeITM11());
              vo.setVariantTypeItm06DOC07(rowVO.getVariantTypeITM06());

              vo.setVariantCodeItm12DOC07(
                  colVO.getVariantCodeITM12() == null
                      ? ApplicationConsts.JOLLY
                      : colVO.getVariantCodeITM12());
              vo.setVariantCodeItm13DOC07(
                  colVO.getVariantCodeITM13() == null
                      ? ApplicationConsts.JOLLY
                      : colVO.getVariantCodeITM13());
              vo.setVariantCodeItm14DOC07(
                  colVO.getVariantCodeITM14() == null
                      ? ApplicationConsts.JOLLY
                      : colVO.getVariantCodeITM14());
              vo.setVariantCodeItm15DOC07(
                  colVO.getVariantCodeITM15() == null
                      ? ApplicationConsts.JOLLY
                      : colVO.getVariantCodeITM15());

              vo.setVariantTypeItm07DOC07(
                  colVO.getVariantTypeITM07() == null
                      ? ApplicationConsts.JOLLY
                      : colVO.getVariantTypeITM07());
              vo.setVariantTypeItm08DOC07(
                  colVO.getVariantTypeITM08() == null
                      ? ApplicationConsts.JOLLY
                      : colVO.getVariantTypeITM08());
              vo.setVariantTypeItm09DOC07(
                  colVO.getVariantTypeITM09() == null
                      ? ApplicationConsts.JOLLY
                      : colVO.getVariantTypeITM09());
              vo.setVariantTypeItm10DOC07(
                  colVO.getVariantTypeITM10() == null
                      ? ApplicationConsts.JOLLY
                      : colVO.getVariantTypeITM10());

              vo.setInQtyDOC07(new BigDecimal(0));
              vo.setOrderQtyDOC07(vo.getQtyDOC07());
              if (vo.getInvoiceQtyDOC07() == null) vo.setInvoiceQtyDOC07(new BigDecimal(0));
              vo.setRowNumberDOC07(
                  progBean.getInternalProgressive("DOC07_PURCHASE_ITEMS", "ROW_NUMBER", conn));

              // insert into DOC07...
              res =
                  QueryUtil.insertTable(
                      conn,
                      userSessionPars,
                      vo,
                      "DOC07_PURCHASE_ITEMS",
                      attribute2dbField,
                      "Y",
                      "N",
                      context,
                      true);

              if (res.isError()) {
                conn.rollback();
                return res;
              }
            } // end if on not null
          } // end inner for
      } // end outer for

      // recalculate totals...
      PurchaseDocPK pk =
          new PurchaseDocPK(
              vo.getCompanyCodeSys01DOC07(),
              vo.getDocTypeDOC07(),
              vo.getDocYearDOC07(),
              vo.getDocNumberDOC07());
      Response docResponse =
          docBean.loadPurchaseDoc(
              conn, pk, userSessionPars, request, response, userSession, context);
      if (docResponse.isError()) {
        conn.rollback();
        return docResponse;
      }
      DetailPurchaseDocVO docVO = (DetailPurchaseDocVO) ((VOResponse) docResponse).getVo();
      Response totalResponse =
          totalBean.calcDocTotals(
              conn, docVO, userSessionPars, request, response, userSession, context);
      if (totalResponse.isError()) {
        conn.rollback();
        return totalResponse;
      }

      pstmt =
          conn.prepareStatement(
              "update DOC06_PURCHASE set TAXABLE_INCOME=?,TOTAL_VAT=?,TOTAL=?,DOC_STATE=? where COMPANY_CODE_SYS01=? and DOC_TYPE=? and DOC_YEAR=? and DOC_NUMBER=?");
      pstmt.setBigDecimal(1, docVO.getTaxableIncomeDOC06());
      pstmt.setBigDecimal(2, docVO.getTotalVatDOC06());
      pstmt.setBigDecimal(3, docVO.getTotalDOC06());
      pstmt.setString(4, ApplicationConsts.HEADER_BLOCKED);
      pstmt.setString(5, vo.getCompanyCodeSys01DOC07());
      pstmt.setString(6, vo.getDocTypeDOC07());
      pstmt.setBigDecimal(7, vo.getDocYearDOC07());
      pstmt.setBigDecimal(8, vo.getDocNumberDOC07());
      pstmt.execute();

      Response answer = new VOResponse(vo);

      // fires the GenericEvent.BEFORE_COMMIT event...
      EventsManager.getInstance()
          .processEvent(
              new GenericEvent(
                  this,
                  getRequestName(),
                  GenericEvent.BEFORE_COMMIT,
                  (JAIOUserSessionParameters) userSessionPars,
                  request,
                  response,
                  userSession,
                  context,
                  conn,
                  inputPar,
                  answer));

      conn.commit();

      // fires the GenericEvent.AFTER_COMMIT event...
      EventsManager.getInstance()
          .processEvent(
              new GenericEvent(
                  this,
                  getRequestName(),
                  GenericEvent.AFTER_COMMIT,
                  (JAIOUserSessionParameters) userSessionPars,
                  request,
                  response,
                  userSession,
                  context,
                  conn,
                  inputPar,
                  answer));

      return answer;
    } catch (Throwable ex) {
      Logger.error(
          userSessionPars.getUsername(),
          this.getClass().getName(),
          "executeCommand",
          "Error while inserting new purchase order rows",
          ex);
      try {
        conn.rollback();
      } catch (Exception ex3) {
      }
      return new ErrorResponse(ex.getMessage());
    } finally {
      try {
        pstmt.close();
      } catch (Exception ex2) {
      }
      try {
        ConnectionManager.releaseConnection(conn, context);
      } catch (Exception ex1) {
      }
    }
  }
Example #5
0
  /**
   * Method called by the Form panel to update existing data.
   *
   * @param oldPersistentObject original value object, previous to the changes
   * @param persistentObject value object to save
   * @return an ErrorResponse value object in case of errors, VOResponse if the operation is
   *     successfully completed
   */
  public Response updateRecord(ValueObject oldPersistentObject, ValueObject persistentObject)
      throws Exception {
    PreparedStatement stmt = null;
    try {
      stmt =
          conn.prepareStatement(
              "update DEMO4 set TEXT=?,DECNUM=?,CURRNUM=?,THEDATE=?,COMBO=?,CHECK_BOX=?,RADIO=?,CODE=?,TA=?,FORMATTED_TEXT=?,URI=?,LINK_LABEL=?,YEAR=?,FILENAME=? where TEXT=?");
      DetailTestVO vo = (DetailTestVO) persistentObject;
      DetailTestVO oldVO = (DetailTestVO) oldPersistentObject;
      stmt.setObject(
          6, vo.getCheckValue() == null || !vo.getCheckValue().booleanValue() ? "N" : "Y");
      stmt.setString(5, vo.getCombo().getCode());
      stmt.setBigDecimal(3, vo.getCurrencyValue());
      stmt.setDate(4, vo.getDateValue());
      stmt.setBigDecimal(2, vo.getNumericValue());
      stmt.setObject(
          7,
          vo.getRadioButtonValue() == null || !vo.getRadioButtonValue().booleanValue() ? "N" : "Y");
      stmt.setString(1, vo.getStringValue());
      stmt.setString(8, vo.getLookupValue());
      stmt.setString(9, vo.getTaValue());
      stmt.setString(10, vo.getFormattedTextValue());
      stmt.setString(11, vo.getUri());
      stmt.setString(12, vo.getLinkLabel());
      stmt.setBigDecimal(13, vo.getYear());
      stmt.setString(14, vo.getFilename());
      stmt.setString(15, oldVO.getStringValue());
      stmt.execute();

      stmt.close();
      stmt = conn.prepareStatement("delete from DEMO4_LIST_VALUES where TEXT=?");
      stmt.setString(1, pk);
      stmt.execute();

      if (vo.getListValues() != null) {
        stmt.close();
        stmt = conn.prepareStatement("insert into DEMO4_LIST_VALUES(TEXT,CODE) values(?,?)");

        for (int i = 0; i < vo.getListValues().size(); i++) {
          stmt.setString(1, pk);
          stmt.setString(2, vo.getListValues().get(i).toString());
          stmt.execute();
        }
      }

      try {
        if (vo.getFilename() != null && vo.getFile() != null) {
          File f = new File(vo.getFilename());
          BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(f));
          out.write(vo.getFile());
          out.close();
        }
      } catch (Exception ex) {
        ex.printStackTrace();
      }

      // this instruction is no more needed: the grid has been linked to the Form (see Form.linkGrid
      // method...)
      //      gridFrame.reloadData();
      return new VOResponse(vo);
    } catch (SQLException ex) {
      ex.printStackTrace();
      return new ErrorResponse(ex.getMessage());
    } finally {
      try {
        stmt.close();
        conn.commit();
      } catch (SQLException ex1) {
      }
    }
  }
  /** Business logic to execute. */
  public VOListResponse loadSupplierPriceItems(
      GridParams pars, String serverLanguageId, String username, ArrayList customizedFields)
      throws Throwable {
    PreparedStatement pstmt = null;
    Connection conn = null;
    try {
      if (this.conn == null) conn = getConn();
      else conn = this.conn;

      BigDecimal rootProgressiveHIE01 =
          (BigDecimal) pars.getOtherGridParams().get(ApplicationConsts.ROOT_PROGRESSIVE_HIE01);
      BigDecimal progressiveHIE01 =
          (BigDecimal) pars.getOtherGridParams().get(ApplicationConsts.PROGRESSIVE_HIE01);
      BigDecimal progressiveHIE02 =
          (BigDecimal) pars.getOtherGridParams().get(ApplicationConsts.PROGRESSIVE_HIE02);
      BigDecimal progressiveREG04 =
          (BigDecimal) pars.getOtherGridParams().get(ApplicationConsts.PROGRESSIVE_REG04);
      String companyCodeSYS01 =
          (String) pars.getOtherGridParams().get(ApplicationConsts.COMPANY_CODE_SYS01);
      String pricelistCodePUR03 =
          (String) pars.getOtherGridParams().get(ApplicationConsts.PRICELIST);

      CompanyHierarchyLevelVO vo =
          (CompanyHierarchyLevelVO) pars.getOtherGridParams().get(ApplicationConsts.TREE_FILTER);
      if (vo != null) {
        progressiveHIE01 = vo.getProgressiveHIE01();
        progressiveHIE02 = vo.getProgressiveHie02HIE01();
      }

      String sql =
          "select PUR02_SUPPLIER_ITEMS.COMPANY_CODE_SYS01,PUR02_SUPPLIER_ITEMS.ITEM_CODE_ITM01,PUR02_SUPPLIER_ITEMS.SUPPLIER_ITEM_CODE,PUR02_SUPPLIER_ITEMS.PROGRESSIVE_REG04,"
              + "PUR02_SUPPLIER_ITEMS.PROGRESSIVE_HIE02,PUR02_SUPPLIER_ITEMS.PROGRESSIVE_HIE01,PUR02_SUPPLIER_ITEMS.MIN_PURCHASE_QTY,PUR02_SUPPLIER_ITEMS.MULTIPLE_QTY,"
              + "PUR02_SUPPLIER_ITEMS.UM_CODE_REG02,PUR02_SUPPLIER_ITEMS.ENABLED,SYS10_COMPANY_TRANSLATIONS.DESCRIPTION,REG02_MEASURE_UNITS.DECIMALS,"
              + "ITM01_ITEMS.VAT_CODE_REG01,SYS10_VAT.DESCRIPTION,REG01_VATS.DEDUCTIBLE,REG01_VATS.VALUE,"
              + "PUR04_SUPPLIER_PRICES.VALUE,PUR04_SUPPLIER_PRICES.START_DATE,PUR04_SUPPLIER_PRICES.END_DATE,"
              + "ITM01_ITEMS.USE_VARIANT_1,ITM01_ITEMS.USE_VARIANT_2,ITM01_ITEMS.USE_VARIANT_3,ITM01_ITEMS.USE_VARIANT_4,ITM01_ITEMS.USE_VARIANT_5, "
              + "ITM01_ITEMS.NO_WAREHOUSE_MOV "
              + " from PUR02_SUPPLIER_ITEMS,SYS10_COMPANY_TRANSLATIONS,ITM01_ITEMS,REG02_MEASURE_UNITS,SYS10_TRANSLATIONS SYS10_VAT,REG01_VATS,PUR04_SUPPLIER_PRICES where "
              + "PUR02_SUPPLIER_ITEMS.PROGRESSIVE_HIE02=? and "
              + "PUR02_SUPPLIER_ITEMS.UM_CODE_REG02=REG02_MEASURE_UNITS.UM_CODE and "
              + "PUR02_SUPPLIER_ITEMS.COMPANY_CODE_SYS01=ITM01_ITEMS.COMPANY_CODE_SYS01 and "
              + "PUR02_SUPPLIER_ITEMS.ITEM_CODE_ITM01=ITM01_ITEMS.ITEM_CODE and "
              + "ITM01_ITEMS.COMPANY_CODE_SYS01=SYS10_COMPANY_TRANSLATIONS.COMPANY_CODE_SYS01 and "
              + "ITM01_ITEMS.PROGRESSIVE_SYS10=SYS10_COMPANY_TRANSLATIONS.PROGRESSIVE and "
              + "SYS10_COMPANY_TRANSLATIONS.LANGUAGE_CODE=? and "
              + "PUR02_SUPPLIER_ITEMS.COMPANY_CODE_SYS01 = ? and "
              + "PUR02_SUPPLIER_ITEMS.PROGRESSIVE_REG04=? and "
              + "PUR02_SUPPLIER_ITEMS.ENABLED='Y' and "
              + "ITM01_ITEMS.VAT_CODE_REG01=REG01_VATS.VAT_CODE and "
              + "REG01_VATS.PROGRESSIVE_SYS10=SYS10_VAT.PROGRESSIVE and "
              + "SYS10_VAT.LANGUAGE_CODE=? and "
              + "PUR02_SUPPLIER_ITEMS.COMPANY_CODE_SYS01=PUR04_SUPPLIER_PRICES.COMPANY_CODE_SYS01 and "
              + "PUR02_SUPPLIER_ITEMS.PROGRESSIVE_REG04=PUR04_SUPPLIER_PRICES.PROGRESSIVE_REG04 and "
              + "PUR02_SUPPLIER_ITEMS.ITEM_CODE_ITM01=PUR04_SUPPLIER_PRICES.ITEM_CODE_ITM01 and "
              + "PUR04_SUPPLIER_PRICES.PRICELIST_CODE_PUR03=? and "
              + "PUR04_SUPPLIER_PRICES.START_DATE<=? and "
              + "PUR04_SUPPLIER_PRICES.END_DATE>? ";

      if (rootProgressiveHIE01 == null || !rootProgressiveHIE01.equals(progressiveHIE01)) {
        // retrieve all subnodes of the specified node...
        pstmt =
            conn.prepareStatement(
                "select HIE01_COMPANY_LEVELS.PROGRESSIVE,HIE01_COMPANY_LEVELS.PROGRESSIVE_HIE01,HIE01_COMPANY_LEVELS.LEV from HIE01_COMPANY_LEVELS "
                    + "where COMPANY_CODE_SYS01='"
                    + companyCodeSYS01
                    + "' and ENABLED='Y' and PROGRESSIVE_HIE02=? and PROGRESSIVE>=? "
                    + "order by LEV,PROGRESSIVE_HIE01,PROGRESSIVE");
        pstmt.setBigDecimal(1, progressiveHIE02);
        pstmt.setBigDecimal(2, progressiveHIE01);
        ResultSet rset = pstmt.executeQuery();

        HashSet currentLevelNodes = new HashSet();
        HashSet newLevelNodes = new HashSet();
        String nodes = "";
        int currentLevel = -1;
        while (rset.next()) {
          if (currentLevel != rset.getInt(3)) {
            // next level...
            currentLevel = rset.getInt(3);
            currentLevelNodes = newLevelNodes;
            newLevelNodes = new HashSet();
          }
          if (rset.getBigDecimal(1).equals(progressiveHIE01)) {
            newLevelNodes.add(rset.getBigDecimal(1));
            nodes += rset.getBigDecimal(1) + ",";
          } else if (currentLevelNodes.contains(rset.getBigDecimal(2))) {
            newLevelNodes.add(rset.getBigDecimal(1));
            nodes += rset.getBigDecimal(1) + ",";
          }
        }
        rset.close();
        pstmt.close();
        if (nodes.length() > 0) nodes = nodes.substring(0, nodes.length() - 1);
        if (rootProgressiveHIE01 != null || nodes.length() > 0)
          sql += " and PUR02_SUPPLIER_ITEMS.PROGRESSIVE_HIE01 in (" + nodes + ")";
      }

      Map attribute2dbField = new HashMap();
      attribute2dbField.put("companyCodeSys01PUR02", "PUR02_SUPPLIER_ITEMS.COMPANY_CODE_SYS01");
      attribute2dbField.put("itemCodeItm01PUR02", "PUR02_SUPPLIER_ITEMS.ITEM_CODE_ITM01");
      attribute2dbField.put("supplierItemCodePUR02", "PUR02_SUPPLIER_ITEMS.SUPPLIER_ITEM_CODE");
      attribute2dbField.put("progressiveReg04PUR02", "PUR02_SUPPLIER_ITEMS.PROGRESSIVE_REG04");
      attribute2dbField.put("progressiveHie02PUR02", "PUR02_SUPPLIER_ITEMS.PROGRESSIVE_HIE02");
      attribute2dbField.put("progressiveHie01PUR02", "PUR02_SUPPLIER_ITEMS.PROGRESSIVE_HIE01");
      attribute2dbField.put("minPurchaseQtyPUR02", "PUR02_SUPPLIER_ITEMS.MIN_PURCHASE_QTY");
      attribute2dbField.put("multipleQtyPUR02", "PUR02_SUPPLIER_ITEMS.MULTIPLE_QTY");
      attribute2dbField.put("umCodeReg02PUR02", "PUR02_SUPPLIER_ITEMS.UM_CODE_REG02");
      attribute2dbField.put("enabledPUR02", "PUR02_SUPPLIER_ITEMS.ENABLED");
      attribute2dbField.put("descriptionSYS10", "SYS10_COMPANY_TRANSLATIONS.DESCRIPTION");
      attribute2dbField.put("decimalsREG02", "REG02_MEASURE_UNITS.DECIMALS");

      attribute2dbField.put("vatCodeReg01ITM01", "ITM01_ITEMS.VAT_CODE_REG01");
      attribute2dbField.put("vatDescriptionSYS10", "SYS10_VAT.DESCRIPTION");
      attribute2dbField.put("deductibleREG01", "REG01_VATS.DEDUCTIBLE");
      attribute2dbField.put("valueREG01", "REG01_VATS.VALUE");
      attribute2dbField.put("valuePUR04", "PUR04_SUPPLIER_PRICES.VALUE");
      attribute2dbField.put("startDatePUR04", "PUR04_SUPPLIER_PRICES.START_DATE");
      attribute2dbField.put("endDatePUR04", "PUR04_SUPPLIER_PRICES.END_DATE");

      attribute2dbField.put("useVariant1ITM01", "ITM01_ITEMS.USE_VARIANT_1");
      attribute2dbField.put("useVariant2ITM01", "ITM01_ITEMS.USE_VARIANT_2");
      attribute2dbField.put("useVariant3ITM01", "ITM01_ITEMS.USE_VARIANT_3");
      attribute2dbField.put("useVariant4ITM01", "ITM01_ITEMS.USE_VARIANT_4");
      attribute2dbField.put("useVariant5ITM01", "ITM01_ITEMS.USE_VARIANT_5");

      attribute2dbField.put("noWarehouseMovITM01", "ITM01_ITEMS.NO_WAREHOUSE_MOV");

      ArrayList values = new ArrayList();
      values.add(progressiveHIE02);
      values.add(serverLanguageId);
      values.add(companyCodeSYS01);
      values.add(progressiveREG04);
      values.add(serverLanguageId);
      values.add(pricelistCodePUR03);
      values.add(new java.sql.Date(System.currentTimeMillis()));
      values.add(new java.sql.Date(System.currentTimeMillis()));

      // read from PUR02 table...
      Response answer =
          CustomizeQueryUtil.getQuery(
              conn,
              new UserSessionParameters(username),
              sql,
              values,
              attribute2dbField,
              SupplierPriceItemVO.class,
              "Y",
              "N",
              null,
              pars,
              50,
              true,
              customizedFields);
      if (answer.isError()) throw new Exception(answer.getErrorMessage());
      else return (VOListResponse) answer;

    } catch (Throwable ex) {
      Logger.error(
          username,
          this.getClass().getName(),
          "executeCommand",
          "Error while fetching supplier items list",
          ex);
      throw new Exception(ex.getMessage());
    } finally {
      try {
        pstmt.close();
      } catch (Exception exx) {
      }
      try {
        if (this.conn == null && conn != null) {
          // close only local connection
          conn.commit();
          conn.close();
        }

      } catch (Exception exx) {
      }
    }
  }
  /** Business logic to execute. */
  public final Response executeCommand(
      Object inputPar,
      UserSessionParameters userSessionPars,
      HttpServletRequest request,
      HttpServletResponse response,
      HttpSession userSession,
      ServletContext context) {
    Connection conn = null;
    PreparedStatement pstmt = null;
    try {
      conn = ConnectionManager.getConnection(context);

      // fires the GenericEvent.CONNECTION_CREATED event...
      EventsManager.getInstance()
          .processEvent(
              new GenericEvent(
                  this,
                  getRequestName(),
                  GenericEvent.CONNECTION_CREATED,
                  (JAIOUserSessionParameters) userSessionPars,
                  request,
                  response,
                  userSession,
                  context,
                  conn,
                  inputPar,
                  null));

      Response responseVO =
          bean.insertItem(
              conn,
              (JournalHeaderVO) inputPar,
              userSessionPars,
              request,
              response,
              userSession,
              context);
      if (responseVO.isError()) {
        conn.rollback();
        return responseVO;
      }

      if (inputPar instanceof JournalHeaderWithVatVO) {
        JournalHeaderWithVatVO vo = (JournalHeaderWithVatVO) inputPar;

        // insert vat rows in the specified vat register...
        Response regRes =
            vatRegisterAction.insertVatRows(
                conn, vo.getVats(), userSessionPars, request, response, userSession, context);
        if (regRes.isError()) {
          conn.rollback();
          return regRes;
        }

        // retrieve payment instalments...
        Response payRes =
            payAction.executeCommand(
                new LookupValidationParams(vo.getPaymentCodeREG10(), new HashMap()),
                userSessionPars,
                request,
                response,
                userSession,
                context);
        if (payRes.isError()) {
          conn.rollback();
          return payRes;
        }
        PaymentVO payVO = (PaymentVO) ((VOListResponse) payRes).getRows().get(0);
        GridParams gridParams = new GridParams();
        gridParams
            .getOtherGridParams()
            .put(ApplicationConsts.PAYMENT_CODE_REG10, vo.getPaymentCodeREG10());
        payRes =
            paysAction.executeCommand(
                gridParams, userSessionPars, request, response, userSession, context);
        if (payRes.isError()) {
          conn.rollback();
          return payRes;
        }
        java.util.List rows = ((VOListResponse) payRes).getRows();

        // create expirations in DOC19 ONLY if:
        // - there are more than one instalment OR
        // - there is only one instalment and this instalment has more than 0 instalment days
        if (rows.size() > 1
            || (rows.size() == 1
                && ((PaymentInstalmentVO) rows.get(0)).getInstalmentDaysREG17().intValue() > 0)) {

          // retrieve internationalization settings (Resources object)...
          ServerResourcesFactory factory =
              (ServerResourcesFactory) context.getAttribute(Controller.RESOURCES_FACTORY);
          Resources resources = factory.getResources(userSessionPars.getLanguageId());

          PaymentInstalmentVO inVO = null;
          pstmt =
              conn.prepareStatement(
                  "insert into DOC19_EXPIRATIONS(COMPANY_CODE_SYS01,DOC_TYPE,DOC_YEAR,DOC_NUMBER,DOC_SEQUENCE,PROGRESSIVE,DOC_DATE,EXPIRATION_DATE,NAME_1,NAME_2,VALUE,PAYED,DESCRIPTION,CUSTOMER_SUPPLIER_CODE,PROGRESSIVE_REG04,CURRENCY_CODE_REG03) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
          long startTime = vo.getItemDateACC05().getTime(); // item date...
          if (payVO.getStartDayREG10().equals(ApplicationConsts.START_DAY_END_MONTH)) {
            Calendar cal = Calendar.getInstance();
            if (cal.get(cal.MONTH) == 10
                || cal.get(cal.MONTH) == 3
                || cal.get(cal.MONTH) == 5
                || cal.get(cal.MONTH) == 8) cal.set(cal.DAY_OF_MONTH, 30);
            else if (cal.get(cal.MONTH) == 1) {
              if (cal.get(cal.YEAR) % 4 == 0) cal.set(cal.DAY_OF_MONTH, 29);
              else cal.set(cal.DAY_OF_MONTH, 28);
            } else cal.set(cal.DAY_OF_MONTH, 31);
            startTime = cal.getTime().getTime();
          }
          BigDecimal amount = null;

          for (int i = 0; i < rows.size(); i++) {
            inVO = (PaymentInstalmentVO) rows.get(i);
            pstmt.setString(1, vo.getCompanyCodeSys01ACC05());
            pstmt.setString(2, vo.getDocTypeDOC19());
            pstmt.setBigDecimal(3, vo.getItemYearACC05());
            pstmt.setBigDecimal(4, null);
            pstmt.setBigDecimal(5, vo.getDocSequenceDOC19());
            pstmt.setBigDecimal(
                6,
                ProgressiveUtils.getConsecutiveProgressive(
                    "DOC19_EXPIRATIONS", "PROGRESSIVE", conn));
            pstmt.setDate(7, vo.getItemDateACC05());
            pstmt.setDate(
                8,
                new java.sql.Date(
                    startTime
                        + inVO.getInstalmentDaysREG17().longValue()
                            * 86400
                            * 1000)); // expiration date
            pstmt.setString(9, vo.getName_1REG04());
            pstmt.setString(10, vo.getName_2REG04());
            amount =
                vo.getTotalValue()
                    .multiply(inVO.getPercentageREG17())
                    .divide(new BigDecimal(100), BigDecimal.ROUND_HALF_UP)
                    .setScale(vo.getTotalValue().scale(), BigDecimal.ROUND_HALF_UP); // value

            pstmt.setBigDecimal(11, amount);
            pstmt.setString(12, "N");

            if (vo.getDocTypeDOC19().equals(ApplicationConsts.SALE_GENERIC_INVOICE))
              pstmt.setString(
                  13,
                  resources.getResource("sale generic document")
                      + " "
                      + vo.getDocSequenceDOC19()
                      + "/"
                      + vo.getItemYearACC05()
                      + " - "
                      + resources.getResource("valueREG01")
                      + " "
                      + resources.getResource("rateNumberREG17")
                      + " "
                      + (i + 1)
                      + " - "
                      + inVO.getPaymentTypeDescriptionSYS10()); // description
            else
              pstmt.setString(
                  13,
                  resources.getResource("purchase generic document")
                      + " "
                      + vo.getDocSequenceDOC19()
                      + "/"
                      + vo.getItemYearACC05()
                      + " - "
                      + resources.getResource("valueREG01")
                      + " "
                      + resources.getResource("rateNumberREG17")
                      + " "
                      + (i + 1)
                      + " - "
                      + inVO.getPaymentTypeDescriptionSYS10()); // description
            pstmt.setString(14, vo.getCustomerCodeSAL07());
            pstmt.setBigDecimal(15, vo.getProgressiveREG04());
            pstmt.setString(16, vo.getCurrencyCodeREG01());
            pstmt.execute();
          }
          pstmt.close();
        }

        // create an item registration for proceeds, according to expiration settings (e.g. retail
        // selling):
        // there must be only one instalment and this instalment has 0 instalment days
        if (rows.size() == 1
            && ((PaymentInstalmentVO) rows.get(0)).getInstalmentDaysREG17().intValue() == 0) {

          // retrieve internationalization settings (Resources object)...
          ServerResourcesFactory factory =
              (ServerResourcesFactory) context.getAttribute(Controller.RESOURCES_FACTORY);
          Resources resources = factory.getResources(userSessionPars.getLanguageId());

          HashMap map = new HashMap();
          map.put(ApplicationConsts.COMPANY_CODE_SYS01, vo.getCompanyCodeSys01ACC05());
          map.put(ApplicationConsts.PARAM_CODE, ApplicationConsts.CASE_ACCOUNT);
          Response res =
              userParamAction.executeCommand(
                  map, userSessionPars, request, response, userSession, context);
          if (res.isError()) {
            conn.rollback();
            return res;
          }
          String caseAccountCode = ((VOResponse) res).getVo().toString();

          JournalHeaderVO jhVO = new JournalHeaderVO();
          jhVO.setCompanyCodeSys01ACC05(vo.getCompanyCodeSys01ACC05());
          if (vo.getDocTypeDOC19().equals(ApplicationConsts.SALE_GENERIC_INVOICE)) {
            jhVO.setDescriptionACC05(
                resources.getResource("sale generic document")
                    + " "
                    + vo.getDocSequenceDOC19()
                    + "/"
                    + vo.getItemYearACC05()
                    + " - "
                    + resources.getResource("customer")
                    + " "
                    + vo.getName_1REG04()
                    + " "
                    + (vo.getName_2REG04() == null ? "" : vo.getName_2REG04()));
            jhVO.setAccountingMotiveCodeAcc03ACC05(ApplicationConsts.MOTIVE_INVOICE_PROCEEDS);
          } else {
            jhVO.setDescriptionACC05(
                resources.getResource("purchase generic document")
                    + " "
                    + vo.getDocSequenceDOC19()
                    + "/"
                    + vo.getItemYearACC05()
                    + " - "
                    + resources.getResource("supplier")
                    + " "
                    + vo.getName_1REG04()
                    + " "
                    + (vo.getName_2REG04() == null ? "" : vo.getName_2REG04()));
            jhVO.setAccountingMotiveCodeAcc03ACC05(ApplicationConsts.MOTIVE_PURCHASE_INVOICE_PAYED);
          }

          jhVO.setItemDateACC05(new java.sql.Date(System.currentTimeMillis()));
          jhVO.setItemYearACC05(new BigDecimal(Calendar.getInstance().get(Calendar.YEAR)));

          JournalRowVO jrVO = new JournalRowVO();
          jrVO.setCompanyCodeSys01ACC06(jhVO.getCompanyCodeSys01ACC05());
          if (vo.getDocTypeDOC19().equals(ApplicationConsts.SALE_GENERIC_INVOICE)) {
            jrVO.setAccountCodeAcc02ACC06(vo.getCreditAccountCodeAcc02SAL07());
            jrVO.setAccountCodeACC06(vo.getCustomerCodeSAL07());
            jrVO.setAccountCodeTypeACC06(ApplicationConsts.ACCOUNT_TYPE_CUSTOMER);
            jrVO.setCreditAmountACC06(vo.getTotalValue());
          } else {
            jrVO.setAccountCodeAcc02ACC06(vo.getDebitAccountCodeAcc02PUR01());
            jrVO.setAccountCodeACC06(vo.getSupplierCodePUR01());
            jrVO.setAccountCodeTypeACC06(ApplicationConsts.ACCOUNT_TYPE_SUPPLIER);
            jrVO.setDebitAmountACC06(vo.getTotalValue());
          }
          jrVO.setDescriptionACC06("");
          jrVO.setItemYearAcc05ACC06(jhVO.getItemYearACC05());
          jrVO.setProgressiveAcc05ACC06(jhVO.getProgressiveACC05());
          jhVO.addJournalRow(jrVO);

          jrVO = new JournalRowVO();
          jrVO.setCompanyCodeSys01ACC06(jhVO.getCompanyCodeSys01ACC05());
          jrVO.setAccountCodeAcc02ACC06(caseAccountCode);
          jrVO.setAccountCodeACC06(caseAccountCode);
          jrVO.setAccountCodeTypeACC06(ApplicationConsts.ACCOUNT_TYPE_ACCOUNT);
          if (vo.getDocTypeDOC19().equals(ApplicationConsts.SALE_GENERIC_INVOICE)) {
            jrVO.setDebitAmountACC06(vo.getTotalValue());
          } else {
            jrVO.setCreditAmountACC06(vo.getTotalValue());
          }
          jrVO.setDescriptionACC06("");
          jrVO.setItemYearAcc05ACC06(jhVO.getItemYearACC05());
          jrVO.setProgressiveAcc05ACC06(jhVO.getProgressiveACC05());
          jhVO.addJournalRow(jrVO);
          Response proceedsRes =
              bean.insertItem(conn, jhVO, userSessionPars, request, response, userSession, context);
          if (proceedsRes.isError()) {
            conn.rollback();
            return proceedsRes;
          }
        }
      }

      Response answer = responseVO;

      // fires the GenericEvent.BEFORE_COMMIT event...
      EventsManager.getInstance()
          .processEvent(
              new GenericEvent(
                  this,
                  getRequestName(),
                  GenericEvent.BEFORE_COMMIT,
                  (JAIOUserSessionParameters) userSessionPars,
                  request,
                  response,
                  userSession,
                  context,
                  conn,
                  inputPar,
                  answer));

      conn.commit();

      // fires the GenericEvent.AFTER_COMMIT event...
      EventsManager.getInstance()
          .processEvent(
              new GenericEvent(
                  this,
                  getRequestName(),
                  GenericEvent.AFTER_COMMIT,
                  (JAIOUserSessionParameters) userSessionPars,
                  request,
                  response,
                  userSession,
                  context,
                  conn,
                  inputPar,
                  answer));

      return answer;
    } catch (Throwable ex) {
      Logger.error(
          userSessionPars.getUsername(),
          this.getClass().getName(),
          "executeCommand",
          "Error while inserting a new item in the journal",
          ex);
      try {
        conn.rollback();
      } catch (Exception ex3) {
      }
      return new ErrorResponse(ex.getMessage());
    } finally {
      try {
        pstmt.close();
      } catch (Exception ex2) {
      }
      try {
        ConnectionManager.releaseConnection(conn, context);
      } catch (Exception ex1) {
      }
    }
  }
  /** Business logic to execute. */
  public final Response executeCommand(
      Object inputPar,
      UserSessionParameters userSessionPars,
      HttpServletRequest request,
      HttpServletResponse response,
      HttpSession userSession,
      ServletContext context) {
    String serverLanguageId = ((JAIOUserSessionParameters) userSessionPars).getServerLanguageId();

    PreparedStatement pstmt = null;
    Connection conn = null;
    try {
      conn = ConnectionManager.getConnection(context);

      // fires the GenericEvent.CONNECTION_CREATED event...
      EventsManager.getInstance()
          .processEvent(
              new GenericEvent(
                  this,
                  getRequestName(),
                  GenericEvent.CONNECTION_CREATED,
                  (JAIOUserSessionParameters) userSessionPars,
                  request,
                  response,
                  userSession,
                  context,
                  conn,
                  inputPar,
                  null));

      GridParams pars = (GridParams) inputPar;

      BigDecimal rootProgressiveHIE01 =
          (BigDecimal) pars.getOtherGridParams().get(ApplicationConsts.ROOT_PROGRESSIVE_HIE01);
      BigDecimal progressiveHIE01 =
          (BigDecimal) pars.getOtherGridParams().get(ApplicationConsts.PROGRESSIVE_HIE01);
      BigDecimal progressiveHIE02 =
          (BigDecimal) pars.getOtherGridParams().get(ApplicationConsts.PROGRESSIVE_HIE02);
      Boolean productsOnly =
          (Boolean) pars.getOtherGridParams().get(ApplicationConsts.PRODUCTS_ONLY);
      Boolean compsOnly =
          (Boolean) pars.getOtherGridParams().get(ApplicationConsts.COMPONENTS_ONLY);

      HierarchyLevelVO vo =
          (HierarchyLevelVO) pars.getOtherGridParams().get(ApplicationConsts.TREE_FILTER);
      if (vo != null) {
        progressiveHIE01 = vo.getProgressiveHIE01();
        progressiveHIE02 = vo.getProgressiveHie02HIE01();
      }

      // retrieve companies list...
      ArrayList companiesList =
          ((JAIOUserSessionParameters) userSessionPars).getCompanyBa().getCompaniesList("ITM01");
      String companies = "";
      for (int i = 0; i < companiesList.size(); i++)
        companies += "'" + companiesList.get(i).toString() + "',";
      companies = companies.substring(0, companies.length() - 1);

      String sql =
          "select ITM01_ITEMS.COMPANY_CODE_SYS01,ITM01_ITEMS.ITEM_CODE,SYS10_TRANSLATIONS.DESCRIPTION,ITM01_ITEMS.PROGRESSIVE_HIE02,ITM01_ITEMS.MIN_SELLING_QTY_UM_CODE_REG02,"
              + "ITM01_ITEMS.PROGRESSIVE_HIE01,ITM01_ITEMS.SERIAL_NUMBER_REQUIRED,REG02_MEASURE_UNITS.DECIMALS "
              + " from ITM01_ITEMS,SYS10_TRANSLATIONS,REG02_MEASURE_UNITS where "
              + "ITM01_ITEMS.PROGRESSIVE_HIE02=? and "
              + "ITM01_ITEMS.PROGRESSIVE_SYS10=SYS10_TRANSLATIONS.PROGRESSIVE and "
              + "SYS10_TRANSLATIONS.LANGUAGE_CODE=? and "
              + "ITM01_ITEMS.COMPANY_CODE_SYS01 in ("
              + companies
              + ") and "
              + "ITM01_ITEMS.ENABLED='Y' and "
              + "ITM01_ITEMS.MIN_SELLING_QTY_UM_CODE_REG02=REG02_MEASURE_UNITS.UM_CODE ";

      if (productsOnly != null && productsOnly.booleanValue())
        sql += " and ITM01_ITEMS.MANUFACTURE_CODE_PRO01 is not null ";

      if (compsOnly != null && compsOnly.booleanValue())
        sql += " and ITM01_ITEMS.MANUFACTURE_CODE_PRO01 is null ";

      if (rootProgressiveHIE01 == null || !rootProgressiveHIE01.equals(progressiveHIE01)) {
        // retrieve all subnodes of the specified node...
        pstmt =
            conn.prepareStatement(
                "select HIE01_LEVELS.PROGRESSIVE,HIE01_LEVELS.PROGRESSIVE_HIE01,HIE01_LEVELS.LEV from HIE01_LEVELS "
                    + "where ENABLED='Y' and PROGRESSIVE_HIE02=? and PROGRESSIVE>=? "
                    + "order by LEV,PROGRESSIVE_HIE01,PROGRESSIVE");
        pstmt.setBigDecimal(1, progressiveHIE02);
        pstmt.setBigDecimal(2, progressiveHIE01);
        ResultSet rset = pstmt.executeQuery();

        HashSet currentLevelNodes = new HashSet();
        HashSet newLevelNodes = new HashSet();
        String nodes = "";
        int currentLevel = -1;
        while (rset.next()) {
          if (currentLevel != rset.getInt(3)) {
            // next level...
            currentLevel = rset.getInt(3);
            currentLevelNodes = newLevelNodes;
            newLevelNodes = new HashSet();
          }
          if (rset.getBigDecimal(1).equals(progressiveHIE01)) {
            newLevelNodes.add(rset.getBigDecimal(1));
            nodes += rset.getBigDecimal(1) + ",";
          } else if (currentLevelNodes.contains(rset.getBigDecimal(2))) {
            newLevelNodes.add(rset.getBigDecimal(1));
            nodes += rset.getBigDecimal(1) + ",";
          }
        }
        rset.close();
        pstmt.close();
        if (nodes.length() > 0) nodes = nodes.substring(0, nodes.length() - 1);
        sql += " and PROGRESSIVE_HIE01 in (" + nodes + ")";
      }

      Map attribute2dbField = new HashMap();
      attribute2dbField.put("companyCodeSys01ITM01", "ITM01_ITEMS.COMPANY_CODE_SYS01");
      attribute2dbField.put("itemCodeITM01", "ITM01_ITEMS.ITEM_CODE");
      attribute2dbField.put("descriptionSYS10", "SYS10_TRANSLATIONS.DESCRIPTION");
      attribute2dbField.put("progressiveHie02ITM01", "ITM01_ITEMS.PROGRESSIVE_HIE02");
      attribute2dbField.put(
          "minSellingQtyUmCodeReg02ITM01", "ITM01_ITEMS.MIN_SELLING_QTY_UM_CODE_REG02");
      attribute2dbField.put("progressiveHie01ITM01", "ITM01_ITEMS.PROGRESSIVE_HIE01");
      attribute2dbField.put("serialNumberRequiredITM01", "ITM01_ITEMS.SERIAL_NUMBER_REQUIRED");
      attribute2dbField.put("decimalsREG02", "REG02_MEASURE_UNITS.DECIMALS");

      ArrayList values = new ArrayList();
      values.add(progressiveHIE02);
      values.add(serverLanguageId);

      // read from ITM01 table...
      Response answer =
          QueryUtil.getQuery(
              conn,
              userSessionPars,
              sql,
              values,
              attribute2dbField,
              GridItemVO.class,
              "Y",
              "N",
              context,
              pars,
              50,
              true);

      // fires the GenericEvent.BEFORE_COMMIT event...
      EventsManager.getInstance()
          .processEvent(
              new GenericEvent(
                  this,
                  getRequestName(),
                  GenericEvent.BEFORE_COMMIT,
                  (JAIOUserSessionParameters) userSessionPars,
                  request,
                  response,
                  userSession,
                  context,
                  conn,
                  inputPar,
                  answer));
      return answer;

    } catch (Throwable ex) {
      Logger.error(
          userSessionPars.getUsername(),
          this.getClass().getName(),
          "executeCommand",
          "Error while fetching items list",
          ex);
      return new ErrorResponse(ex.getMessage());
    } finally {
      try {
        pstmt.close();
      } catch (Exception ex2) {
      }
      try {
        ConnectionManager.releaseConnection(conn, context);
      } catch (Exception ex1) {
      }
    }
  }
  /** Business logic to execute. */
  public VOListResponse loadOutDeliveryNotesForSaleDoc(
      GridParams pars, String serverLanguageId, String username, ArrayList companiesList)
      throws Throwable {
    PreparedStatement pstmt = null;
    Connection conn = null;
    try {
      if (this.conn == null) conn = getConn();
      else conn = this.conn;

      // retrieve companies list...
      String companies = "";
      for (int i = 0; i < companiesList.size(); i++)
        companies += "'" + companiesList.get(i).toString() + "',";
      companies = companies.substring(0, companies.length() - 1);

      String sql =
          "select DOC08_DELIVERY_NOTES.COMPANY_CODE_SYS01,DOC08_DELIVERY_NOTES.DOC_TYPE,"
              + "DOC08_DELIVERY_NOTES.DOC_YEAR,DOC08_DELIVERY_NOTES.DOC_NUMBER,DOC08_DELIVERY_NOTES.DOC_DATE, "
              + "DOC08_DELIVERY_NOTES.DESTINATION_CODE_REG18,DOC08_DELIVERY_NOTES.DESCRIPTION,"
              + "DOC08_DELIVERY_NOTES.DOC_SEQUENCE "
              + " from DOC08_DELIVERY_NOTES where "
              + "DOC08_DELIVERY_NOTES.COMPANY_CODE_SYS01 in ("
              + companies
              + ") and "
              + "DOC08_DELIVERY_NOTES.ENABLED='Y' and "
              + "DOC08_DELIVERY_NOTES.DOC_TYPE=? and "
              + "DOC08_DELIVERY_NOTES.DOC_STATE=? and "
              + "(DOC08_DELIVERY_NOTES.COMPANY_CODE_SYS01,DOC08_DELIVERY_NOTES.DOC_TYPE,DOC08_DELIVERY_NOTES.DOC_YEAR,DOC08_DELIVERY_NOTES.DOC_NUMBER) "
              + " in (select DOC10_OUT_DELIVERY_NOTE_ITEMS.COMPANY_CODE_SYS01,DOC10_OUT_DELIVERY_NOTE_ITEMS.DOC_TYPE,DOC10_OUT_DELIVERY_NOTE_ITEMS.DOC_YEAR,DOC10_OUT_DELIVERY_NOTE_ITEMS.DOC_NUMBER "
              + " from DOC10_OUT_DELIVERY_NOTE_ITEMS where "
              + " DOC10_OUT_DELIVERY_NOTE_ITEMS.COMPANY_CODE_SYS01=? and "
              + " DOC10_OUT_DELIVERY_NOTE_ITEMS.DOC_TYPE_DOC01=? and "
              + " DOC10_OUT_DELIVERY_NOTE_ITEMS.DOC_YEAR_DOC01=? and "
              + " DOC10_OUT_DELIVERY_NOTE_ITEMS.DOC_NUMBER_DOC01=? ";

      DetailSaleDocVO docVO =
          (DetailSaleDocVO)
              pars.getOtherGridParams().get(ApplicationConsts.SALE_DOC_VO); // invoice document...
      if (docVO.getDocNumberDOC01() == null)
        sql +=
            " and DOC10_OUT_DELIVERY_NOTE_ITEMS.QTY-DOC10_OUT_DELIVERY_NOTE_ITEMS.INVOICE_QTY>0)";
      else sql += ")";

      Map attribute2dbField = new HashMap();
      attribute2dbField.put("companyCodeSys01DOC08", "DOC08_DELIVERY_NOTES.COMPANY_CODE_SYS01");
      attribute2dbField.put("docTypeDOC08", "DOC08_DELIVERY_NOTES.DOC_TYPE");
      attribute2dbField.put("docYearDOC08", "DOC08_DELIVERY_NOTES.DOC_YEAR");
      attribute2dbField.put("docNumberDOC08", "DOC08_DELIVERY_NOTES.DOC_NUMBER");
      attribute2dbField.put("docDateDOC08", "DOC08_DELIVERY_NOTES.DOC_DATE");
      attribute2dbField.put(
          "destinationCodeReg18DOC08", "DOC08_DELIVERY_NOTES.DESTINATION_CODE_REG18");
      attribute2dbField.put("descriptionDOC08", "DOC08_DELIVERY_NOTES.DESCRIPTION");
      attribute2dbField.put("docSequenceDOC08", "DOC08_DELIVERY_NOTES.DOC_SEQUENCE");

      ArrayList values = new ArrayList();
      values.add(ApplicationConsts.OUT_DELIVERY_NOTE_DOC_TYPE);
      values.add(ApplicationConsts.CLOSED);
      values.add(docVO.getCompanyCodeSys01DOC01());
      values.add(docVO.getDocTypeDoc01DOC01());
      values.add(docVO.getDocYearDoc01DOC01());
      values.add(docVO.getDocNumberDoc01DOC01());

      // read from DOC08 table...
      Response res =
          QueryUtil.getQuery(
              conn,
              new UserSessionParameters(username),
              sql,
              values,
              attribute2dbField,
              OutDeliveryNotesVO.class,
              "Y",
              "N",
              null,
              pars,
              true);

      if (res.isError()) throw new Exception(res.getErrorMessage());

      // check if the invoice document has been already created and there exists delivery notes
      // linked to it...
      if (docVO.getDocNumberDOC01() != null) {
        pstmt =
            conn.prepareStatement(
                "select DOC08_DELIVERY_NOTES.DOC_NUMBER from DOC08_DELIVERY_NOTES where "
                    + "DOC08_DELIVERY_NOTES.COMPANY_CODE_SYS01 in ("
                    + companies
                    + ") and "
                    + "DOC08_DELIVERY_NOTES.ENABLED='Y' and "
                    + "DOC08_DELIVERY_NOTES.DOC_TYPE=? and "
                    + "DOC08_DELIVERY_NOTES.DOC_STATE=? and "
                    + "(DOC08_DELIVERY_NOTES.COMPANY_CODE_SYS01,DOC08_DELIVERY_NOTES.DOC_TYPE,DOC08_DELIVERY_NOTES.DOC_YEAR,DOC08_DELIVERY_NOTES.DOC_NUMBER) "
                    + " in (select DOC10_OUT_DELIVERY_NOTE_ITEMS.COMPANY_CODE_SYS01,DOC10_OUT_DELIVERY_NOTE_ITEMS.DOC_TYPE,DOC10_OUT_DELIVERY_NOTE_ITEMS.DOC_YEAR,DOC10_OUT_DELIVERY_NOTE_ITEMS.DOC_NUMBER "
                    + " from DOC10_OUT_DELIVERY_NOTE_ITEMS,DOC02_SELLING_ITEMS where "
                    + " DOC10_OUT_DELIVERY_NOTE_ITEMS.COMPANY_CODE_SYS01=? and "
                    + " DOC10_OUT_DELIVERY_NOTE_ITEMS.DOC_TYPE_DOC01=? and "
                    + " DOC10_OUT_DELIVERY_NOTE_ITEMS.DOC_YEAR_DOC01=? and "
                    + " DOC10_OUT_DELIVERY_NOTE_ITEMS.DOC_NUMBER_DOC01=? and "
                    + " DOC10_OUT_DELIVERY_NOTE_ITEMS.COMPANY_CODE_SYS01=DOC02_SELLING_ITEMS.COMPANY_CODE_SYS01 and "
                    + " DOC02_SELLING_ITEMS.DOC_TYPE=? and "
                    + " DOC02_SELLING_ITEMS.DOC_YEAR=? and "
                    + " DOC02_SELLING_ITEMS.DOC_NUMBER=? and "
                    + " DOC10_OUT_DELIVERY_NOTE_ITEMS.ITEM_CODE_ITM01=DOC02_SELLING_ITEMS.ITEM_CODE_ITM01)");

        pstmt.setString(1, ApplicationConsts.OUT_DELIVERY_NOTE_DOC_TYPE);
        pstmt.setString(2, ApplicationConsts.CLOSED);
        pstmt.setString(3, docVO.getCompanyCodeSys01DOC01());
        pstmt.setString(4, docVO.getDocTypeDoc01DOC01());
        pstmt.setBigDecimal(5, docVO.getDocYearDoc01DOC01());
        pstmt.setBigDecimal(6, docVO.getDocNumberDoc01DOC01());
        pstmt.setString(7, docVO.getDocTypeDOC01());
        pstmt.setBigDecimal(8, docVO.getDocYearDOC01());
        pstmt.setBigDecimal(9, docVO.getDocNumberDOC01());

        HashSet docNumberDOC08s = new HashSet();
        ResultSet rset = pstmt.executeQuery();
        while (rset.next()) docNumberDOC08s.add(rset.getBigDecimal(1));
        rset.close();

        java.util.List rows = ((VOListResponse) res).getRows();
        OutDeliveryNotesVO vo = null;
        for (int i = 0; i < rows.size(); i++) {
          vo = (OutDeliveryNotesVO) rows.get(i);
          if (docNumberDOC08s.contains(vo.getDocNumberDOC08())) vo.setSelected(Boolean.TRUE);
        }
      }

      Response answer = res;
      if (answer.isError()) throw new Exception(answer.getErrorMessage());
      else return (VOListResponse) answer;
    } catch (Throwable ex) {
      Logger.error(
          username,
          this.getClass().getName(),
          "executeCommand",
          "Error while fetching out delivery notes list, related to the specified sale document",
          ex);
      throw new Exception(ex.getMessage());
    } finally {
      try {
        pstmt.close();
      } catch (Exception exx) {
      }
      try {
        if (this.conn == null && conn != null) {
          // close only local connection
          conn.commit();
          conn.close();
        }

      } catch (Exception exx) {
      }
    }
  }
  /** Business logic to execute. */
  public final Response executeCommand(
      Object inputPar,
      UserSessionParameters userSessionPars,
      HttpServletRequest request,
      HttpServletResponse response,
      HttpSession userSession,
      ServletContext context) {
    Connection conn = null;
    PreparedStatement pstmt = null;
    try {
      String serverLanguageId = ((JAIOUserSessionParameters) userSessionPars).getServerLanguageId();
      conn = ConnectionManager.getConnection(context);

      // fires the GenericEvent.CONNECTION_CREATED event...
      EventsManager.getInstance()
          .processEvent(
              new GenericEvent(
                  this,
                  getRequestName(),
                  GenericEvent.CONNECTION_CREATED,
                  (JAIOUserSessionParameters) userSessionPars,
                  request,
                  response,
                  userSession,
                  context,
                  conn,
                  inputPar,
                  null));

      ArrayList oldVOs = ((ArrayList[]) inputPar)[0];
      ArrayList newVOs = ((ArrayList[]) inputPar)[1];

      Map attribute2dbField = new HashMap();
      attribute2dbField.put("companyCodeSys01DOC20", "COMPANY_CODE_SYS01");
      attribute2dbField.put("progressiveDoc14DOC20", "PROGRESSIVE_DOC14");
      attribute2dbField.put("progressiveSys10DOC20", "PROGRESSIVE_SYS10");
      attribute2dbField.put("textValueDOC20", "TEXT_VALUE");
      attribute2dbField.put("numValueDOC20", "NUM_VALUE");
      attribute2dbField.put("dateValueDOC20", "DATE_VALUE");

      HashSet pkAttributes = new HashSet();
      pkAttributes.add("companyCodeSys01DOC20");
      pkAttributes.add("progressiveDoc14DOC20");
      pkAttributes.add("progressiveSys10DOC20");

      Response res = null;
      DocPropertyVO oldVO = null;
      DocPropertyVO newVO = null;

      pstmt =
          conn.prepareStatement(
              "select PROGRESSIVE_DOC14 from DOC20_DOC_PROPERTIES where "
                  + "COMPANY_CODE_SYS01=? and PROGRESSIVE_DOC14=? and PROGRESSIVE_SYS10=?");
      ResultSet rset = null;

      for (int i = 0; i < oldVOs.size(); i++) {
        oldVO = (DocPropertyVO) oldVOs.get(i);
        newVO = (DocPropertyVO) newVOs.get(i);

        // check if the record already exists: if it does not exist, then insert it...
        pstmt.setString(1, newVO.getCompanyCodeSys01DOC20());
        pstmt.setBigDecimal(2, newVO.getProgressiveDoc14DOC20());
        pstmt.setBigDecimal(3, newVO.getProgressiveSys10DOC20());
        rset = pstmt.executeQuery();
        if (rset.next()) {
          // the record exixts: it will be updated...
          res =
              QueryUtil.updateTable(
                  conn,
                  userSessionPars,
                  pkAttributes,
                  oldVO,
                  newVO,
                  "DOC20_DOC_PROPERTIES",
                  attribute2dbField,
                  "Y",
                  "N",
                  context,
                  true);
          if (res.isError()) {
            conn.rollback();
            return res;
          }
        } else {
          // the record does not exixt: it will be inserted...
          res =
              QueryUtil.insertTable(
                  conn,
                  userSessionPars,
                  newVO,
                  "DOC20_DOC_PROPERTIES",
                  attribute2dbField,
                  "Y",
                  "N",
                  context,
                  true);
          if (res.isError()) {
            conn.rollback();
            return res;
          }
        }
        rset.close();
      }

      Response answer = new VOListResponse(newVOs, false, newVOs.size());

      // fires the GenericEvent.BEFORE_COMMIT event...
      EventsManager.getInstance()
          .processEvent(
              new GenericEvent(
                  this,
                  getRequestName(),
                  GenericEvent.BEFORE_COMMIT,
                  (JAIOUserSessionParameters) userSessionPars,
                  request,
                  response,
                  userSession,
                  context,
                  conn,
                  inputPar,
                  answer));

      conn.commit();

      // fires the GenericEvent.AFTER_COMMIT event...
      EventsManager.getInstance()
          .processEvent(
              new GenericEvent(
                  this,
                  getRequestName(),
                  GenericEvent.AFTER_COMMIT,
                  (JAIOUserSessionParameters) userSessionPars,
                  request,
                  response,
                  userSession,
                  context,
                  conn,
                  inputPar,
                  answer));

      return answer;
    } catch (Throwable ex) {
      Logger.error(
          userSessionPars.getUsername(),
          this.getClass().getName(),
          "executeCommand",
          "Error while updating property values for the specified document",
          ex);
      try {
        conn.rollback();
      } catch (Exception ex3) {
      }
      return new ErrorResponse(ex.getMessage());
    } finally {
      try {
        pstmt.close();
      } catch (Exception ex2) {
      }
      try {
        ConnectionManager.releaseConnection(conn, context);
      } catch (Exception ex1) {
      }
    }
  }
 /**
  * Saves the templates to the database.
  *
  * @throws java.sql.SQLException Thrown on sql error.
  */
 public void saveToDatabase() throws java.sql.SQLException {
   setProgressIndeterminate(true);
   setMessage("Saving Templates");
   ArrayList templates = getTemplates();
   Connection oracleConnection = getDataSource().getConnection();
   try {
     oracleConnection.setAutoCommit(false);
     Statement query = oracleConnection.createStatement();
     try {
       int templateCount = templates.size();
       // First remove any existing entries.
       StringBuffer sql = new StringBuffer("DELETE FROM ");
       sql.append(MPSBrowserView.SCHEMA);
       sql.append(".TMPL_SGNL_FLD");
       StringBuffer whereClause = new StringBuffer(" WHERE TMPL_ID IN (");
       for (int i = 0; i < templateCount; i++) {
         if (i > 0) whereClause.append(", ");
         whereClause.append("'");
         whereClause.append(((Template) templates.get(i)).getID());
         whereClause.append("'");
       }
       whereClause.append(")");
       sql.append(whereClause);
       query.execute(sql.toString());
       sql = new StringBuffer("DELETE FROM ");
       sql.append(MPSBrowserView.SCHEMA);
       sql.append(".TMPL_MACRO");
       sql.append(whereClause);
       query.execute(sql.toString());
       sql = new StringBuffer("DELETE FROM ");
       sql.append(MPSBrowserView.SCHEMA);
       sql.append(".TMPL_SGNL_REC");
       sql.append(whereClause);
       query.execute(sql.toString());
       sql = new StringBuffer("DELETE FROM ");
       sql.append(MPSBrowserView.SCHEMA);
       sql.append(".TMPL_SGNL_FLD");
       sql.append(whereClause);
       query.execute(sql.toString());
       sql = new StringBuffer("DELETE FROM ");
       sql.append(MPSBrowserView.SCHEMA);
       sql.append(".TEMPLATE");
       sql.append(whereClause);
       query.execute(sql.toString());
       sql = new StringBuffer("DELETE FROM ");
       sql.append(MPSBrowserView.SCHEMA);
       sql.append(".TMPL_ARCH_REQ");
       sql.append(whereClause);
       query.execute(sql.toString());
       sql = new StringBuffer("DELETE FROM ");
       sql.append(MPSBrowserView.SCHEMA);
       sql.append(".TMPL_ARCH_REQ_GRP");
       sql.append(whereClause);
       query.execute(sql.toString());
       sql = new StringBuffer("DELETE FROM ");
       sql.append(MPSBrowserView.SCHEMA);
       sql.append(".TMPL_ARCH_REQ_GRP_ARCH_REQ");
       sql.append(whereClause);
       query.execute(sql.toString());
       sql = new StringBuffer("INSERT INTO ");
       sql.append(MPSBrowserView.SCHEMA);
       sql.append(
           ".TEMPLATE (TMPL_ID, TMPL_DESC, EXT_SRC_FILE_NM, EXT_SRC_FILE_MOD_DTE) VALUES (?, ?, ?, ?)");
       PreparedStatement templateInsertStatement =
           oracleConnection.prepareStatement(sql.toString());
       try {
         sql = new StringBuffer("INSERT INTO ");
         sql.append(MPSBrowserView.SCHEMA);
         sql.append(".TMPL_MACRO (TMPL_ID, MACRO_ID) VALUES (?, ?)");
         PreparedStatement macroInsertStatement =
             oracleConnection.prepareStatement(sql.toString());
         try {
           sql = new StringBuffer("INSERT INTO ");
           sql.append(MPSBrowserView.SCHEMA);
           sql.append(
               ".TMPL_SGNL_REC (TMPL_ID, TMPL_SGNL_ID, REC_TYPE_ID, ARCH_IND, ARCH_FREQ, ARCH_TYPE) VALUES (?, ?, ?, ?, ?, ?)");
           PreparedStatement signalInsertStatement =
               oracleConnection.prepareStatement(sql.toString());
           try {
             sql = new StringBuffer("INSERT INTO ");
             sql.append(MPSBrowserView.SCHEMA);
             sql.append(
                 ".TMPL_SGNL_FLD (TMPL_ID, TMPL_SGNL_ID, FLD_ID, REC_TYPE_ID, VAL) VALUES (?, ?, ?, ?, ?)");
             PreparedStatement fieldInsertStatement =
                 oracleConnection.prepareStatement(sql.toString());
             try {
               sql = new StringBuffer("INSERT INTO ");
               sql.append(MPSBrowserView.SCHEMA);
               sql.append(".TMPL_ARCH_REQ (TMPL_ID, ARCH_REQ_FILE_NM) VALUES (?, ?)");
               PreparedStatement requestInsertStatement =
                   oracleConnection.prepareStatement(sql.toString());
               try {
                 sql = new StringBuffer("INSERT INTO ");
                 sql.append(MPSBrowserView.SCHEMA);
                 sql.append(".TMPL_ARCH_REQ_GRP (TMPL_ID, ARCH_REQ_GRP_FILE_NM) VALUES (?, ?)");
                 PreparedStatement groupInsertStatement =
                     oracleConnection.prepareStatement(sql.toString());
                 try {
                   sql = new StringBuffer("INSERT INTO ");
                   sql.append(MPSBrowserView.SCHEMA);
                   sql.append(
                       ".TMPL_ARCH_REQ_GRP_ARCH_REQ (TMPL_ID, ARCH_REQ_GRP_FILE_NM, ARCH_REQ_FILE_NM) VALUES (?, ?, ?)");
                   PreparedStatement requestGroupInsertStatement =
                       oracleConnection.prepareStatement(sql.toString());
                   try {
                     sql = new StringBuffer("UPDATE ");
                     sql.append(MPSBrowserView.SCHEMA);
                     sql.append(
                         ".TMPL_SGNL_REC SET ARCH_IND = ?, ARCH_FREQ = ?, ARCH_TYPE = ?, ARCH_REQ_FILE = ? WHERE TMPL_ID = ? AND TMPL_SGNL_ID = ? AND REC_TYPE_ID = ?");
                     PreparedStatement signalUpdateStatement =
                         oracleConnection.prepareStatement(sql.toString());
                     try {
                       int progress = 0;
                       setProgressMaximum(importedFieldCount + importedMacroCount);
                       setProgressValue(0);
                       setProgressIndeterminate(false);
                       for (int templateIndex = 0;
                           templateIndex < templateCount;
                           templateIndex++) {
                         Template currentTemplate = (Template) templates.get(templateIndex);
                         String currentTemplateID = currentTemplate.getID();
                         templateInsertStatement.setString(1, currentTemplateID);
                         String currentDescription = currentTemplate.getDescription();
                         if (currentDescription == null)
                           templateInsertStatement.setNull(2, Types.VARCHAR);
                         else templateInsertStatement.setString(2, currentDescription);
                         templateInsertStatement.setString(3, currentTemplate.getFileName());
                         templateInsertStatement.setTimestamp(
                             4, currentTemplate.getFileModifiedDate());
                         templateInsertStatement.execute();
                         // Need to insert macros.
                         int macroCount = currentTemplate.getMacroCount();
                         for (int macroIndex = 0; macroIndex < macroCount; macroIndex++) {
                           macroInsertStatement.setString(1, currentTemplateID);
                           String currentMacro = currentTemplate.getMacroAt(macroIndex);
                           macroInsertStatement.setString(2, currentMacro);
                           macroInsertStatement.execute();
                           setProgressValue(++progress);
                         }
                         int signalCount = currentTemplate.getSignalCount();
                         for (int signalIndex = 0; signalIndex < signalCount; signalIndex++) {
                           Signal currentSignal = currentTemplate.getSignalAt(signalIndex);
                           String currentSignalID = currentSignal.getID();
                           String currentRecordTypeID =
                               currentSignal.getType().getRecordType().getID();
                           signalInsertStatement.setString(1, currentTemplateID);
                           signalInsertStatement.setString(2, currentSignalID);
                           signalInsertStatement.setString(3, currentRecordTypeID);
                           signalInsertStatement.setString(4, currentSignal.getArchiveIndicator());
                           BigDecimal currentFrequency = currentSignal.getArchiveFrequency();
                           if (currentFrequency == null)
                             currentFrequency = new BigDecimal("60"); // 60 default in RDB
                           signalInsertStatement.setBigDecimal(5, currentFrequency);
                           String currentType = currentSignal.getArchiveType();
                           if (currentType == null)
                             currentType = "Monitor"; // 'Monitor' default in RDB
                           signalInsertStatement.setString(6, currentType);
                           signalInsertStatement.execute();
                           int fieldCount = currentSignal.getFieldCount();
                           for (int fieldIndex = 0; fieldIndex < fieldCount; fieldIndex++) {
                             SignalField currentField = currentSignal.getFieldAt(fieldIndex);
                             fieldInsertStatement.setString(1, currentTemplateID);
                             fieldInsertStatement.setString(2, currentSignalID);
                             fieldInsertStatement.setString(3, currentField.getType().getID());
                             fieldInsertStatement.setString(4, currentRecordTypeID);
                             fieldInsertStatement.setString(5, currentField.getValue());
                             fieldInsertStatement.execute();
                             if (isParseCanceled()) {
                               oracleConnection.rollback();
                               return;
                             }
                             setProgressValue(++progress);
                           }
                         }
                         // Insert archive requests.
                         int requestCount = currentTemplate.getArchiveRequestCount();
                         for (int requestIndex = 0; requestIndex < requestCount; requestIndex++) {
                           ArchiveRequest currentRequest =
                               currentTemplate.getArchiveRequestAt(requestIndex);
                           String currentRequestFileName = currentRequest.getFileName();
                           requestInsertStatement.setString(1, currentTemplateID);
                           requestInsertStatement.setString(2, currentRequestFileName);
                           requestInsertStatement.execute();
                           signalCount = currentRequest.getSignalCount();
                           for (int signalIndex = 0; signalIndex < signalCount; signalIndex++) {
                             Signal currentSignal = currentRequest.getSignalAt(signalIndex);
                             String currentSignalID = currentSignal.getID();
                             signalUpdateStatement.setString(
                                 1, currentSignal.getArchiveIndicator());
                             signalUpdateStatement.setBigDecimal(
                                 2, currentSignal.getArchiveFrequency());
                             signalUpdateStatement.setString(3, currentSignal.getArchiveType());
                             signalUpdateStatement.setString(4, currentRequestFileName);
                             signalUpdateStatement.setString(5, currentTemplateID);
                             signalUpdateStatement.setString(6, currentSignalID);
                             signalUpdateStatement.setString(
                                 7, currentSignal.getType().getRecordType().getID());
                             signalUpdateStatement.execute();
                             int fieldCount = currentSignal.getFieldCount();
                           }
                         }
                         // Insert archive groups.
                         int groupCount = currentTemplate.getArchiveGroupCount();
                         for (int groupIndex = 0; groupIndex < groupCount; groupIndex++) {
                           ArchiveGroup currentGroup =
                               currentTemplate.getArchiveGroupAt(groupIndex);
                           groupInsertStatement.setString(1, currentTemplateID);
                           String currentGroupFileName = currentGroup.getFileName();
                           groupInsertStatement.setString(2, currentGroupFileName);
                           groupInsertStatement.execute();
                           requestCount = currentGroup.getArchiveRequestCount();
                           for (int requestIndex = 0;
                               requestIndex < requestCount;
                               requestIndex++) {
                             ArchiveRequest currentRequest =
                                 currentGroup.getArchiveRequestAt(requestIndex);
                             String currentRequestFileName = currentRequest.getFileName();
                             requestGroupInsertStatement.setString(1, currentTemplateID);
                             requestGroupInsertStatement.setString(2, currentGroupFileName);
                             requestGroupInsertStatement.setString(
                                 3, currentRequest.getFileName());
                           }
                         }
                       }
                     } finally {
                       signalUpdateStatement.close();
                     }
                   } finally {
                     requestGroupInsertStatement.close();
                   }
                 } finally {
                   groupInsertStatement.close();
                 }
               } finally {
                 requestInsertStatement.close();
               }
             } finally {
               fieldInsertStatement.close();
             }
           } finally {
             signalInsertStatement.close();
           }
         } finally {
           macroInsertStatement.close();
         }
       } finally {
         templateInsertStatement.close();
       }
     } catch (java.sql.SQLException ex) {
       oracleConnection.rollback();
       throw ex;
     } finally {
       query.close();
     }
     if (isParseCanceled()) oracleConnection.rollback();
     else oracleConnection.commit();
   } finally {
     oracleConnection.close();
   }
 }