@Test
  public void testNewResultSet_GetMergeCost() throws Exception {

    // Mocks
    ConnectionManager connectionManager = mock(ConnectionManager.class);
    Connection connection = mock(Connection.class);
    PreparedStatement preparedStatement = mock(PreparedStatement.class);
    java.sql.ResultSet resultSet = mock(java.sql.ResultSet.class);

    // Behaviour
    when(connectionManager.getConnection(any(SQLiteIndex.class))).thenReturn(connection);
    when(connection.prepareStatement(
            "SELECT COUNT(objectKey) FROM " + TABLE_NAME + " WHERE value = ?;"))
        .thenReturn(preparedStatement);
    when(preparedStatement.executeQuery()).thenReturn(resultSet);
    when(resultSet.getStatement()).thenReturn(preparedStatement);
    when(resultSet.next()).thenReturn(true);
    when(resultSet.getInt(1)).thenReturn(3);

    // Iterator
    ResultSet<Car> carsWithAbs =
        new SQLiteIndex<String, Car, Integer>(
                Car.FEATURES, OBJECT_TO_ID, ID_TO_OBJECT, connectionManager)
            .retrieve(equal(Car.FEATURES, "abs"), new QueryOptions());

    Assert.assertNotNull(carsWithAbs);
    int size = carsWithAbs.getMergeCost();

    assertEquals(3, size);
    verify(connection, times(1)).close();
  }
  /**
   * Insert transportation routes
   *
   * @param transportationRouteList List of transportation routes to insert (id == null)
   * @throws Exception
   */
  public void insertTransportationRoutes(Collection<TransportationRoute> transportationRouteList)
      throws Exception {
    try {
      String query =
          String.format(
              "INSERT INTO %s (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
              table,
              id,
              name,
              validFrom,
              validUntil,
              transportationID,
              operator,
              network,
              extRef,
              description,
              descriptionFrom,
              descriptionTo,
              routeNo);
      PreparedStatement ps = ConnectionManager.getInstance().prepareStatement(query);

      for (TransportationRoute transportationRoute : transportationRouteList) {
        if (transportationRoute.getId() != null || transportationRoute.getType() == null) {
          continue;
        }

        transportationRoute.setId(UUID.randomUUID());
        PGobject toInsertUUID = new PGobject();
        toInsertUUID.setType("uuid");
        toInsertUUID.setValue(String.valueOf(transportationRoute.getId()));

        ps.setObject(1, toInsertUUID);
        ps.setString(2, transportationRoute.getName());
        ps.setTimestamp(3, transportationRoute.getValidFrom());
        ps.setTimestamp(4, transportationRoute.getValidUntil());
        ps.setObject(5, transportationRoute.getType().getId());
        ps.setString(6, transportationRoute.getOperator());
        ps.setString(7, transportationRoute.getNetwork());
        ps.setString(8, transportationRoute.getExtRef());
        ps.setString(9, transportationRoute.getDescription());
        ps.setString(10, transportationRoute.getDescriptionFrom());
        ps.setString(11, transportationRoute.getDescriptionTo());
        ps.setString(12, transportationRoute.getRouteNo());

        ps.addBatch();
      }

      ps.executeBatch();
      ps.close();

      ScheduleDAO scheduleDAO = new ScheduleDAO();
      scheduleDAO.insertOrUpdateSchedules(transportationRouteList);
    } catch (Exception e) {
      ConnectionManager.getInstance().closeConnection(true);

      throw new Exception("Transportation route insert failed: " + e.getMessage());
    }
  }
  @Test
  public void testInit_NonEmptyCollection() throws Exception {

    // Mock
    ConnectionManager connectionManager = mock(ConnectionManager.class);
    Connection connection = mock(Connection.class);
    Connection connection1 = mock(Connection.class);
    Statement statement = mock(Statement.class);
    PreparedStatement preparedStatement = mock(PreparedStatement.class);

    when(connection1.prepareStatement("INSERT OR IGNORE INTO " + TABLE_NAME + " values(?, ?);"))
        .thenReturn(preparedStatement);
    when(connectionManager.getConnection(any(SQLiteIndex.class)))
        .thenReturn(connection)
        .thenReturn(connection1);
    when(connectionManager.isApplyUpdateForIndexEnabled(any(SQLiteIndex.class))).thenReturn(true);
    when(connection.createStatement()).thenReturn(statement);
    when(preparedStatement.executeBatch()).thenReturn(new int[] {2});

    // The objects to add
    Set<Car> initWithObjects = new HashSet<Car>(2);
    initWithObjects.add(
        new Car(1, "Ford", "Focus", Car.Color.BLUE, 5, 9000.50, Arrays.asList("abs", "gps")));
    initWithObjects.add(
        new Car(2, "Honda", "Civic", Car.Color.RED, 5, 5000.00, Arrays.asList("airbags")));

    SQLiteIndex<String, Car, Integer> carFeaturesOffHeapIndex =
        new SQLiteIndex<String, Car, Integer>(
            Car.FEATURES, OBJECT_TO_ID, ID_TO_OBJECT, connectionManager);

    carFeaturesOffHeapIndex.init(initWithObjects, new QueryOptions());

    // Verify
    verify(statement, times(1))
        .executeUpdate(
            "CREATE TABLE IF NOT EXISTS "
                + TABLE_NAME
                + " (objectKey INTEGER, value TEXT, PRIMARY KEY (objectKey, value)) WITHOUT ROWID;");
    verify(statement, times(1))
        .executeUpdate(
            "CREATE INDEX IF NOT EXISTS " + INDEX_NAME + " ON " + TABLE_NAME + " (value);");
    verify(statement, times(2)).close();
    verify(connection, times(1)).close();

    verify(preparedStatement, times(2)).setObject(1, 1);
    verify(preparedStatement, times(1)).setObject(1, 2);
    verify(preparedStatement, times(1)).setObject(2, "abs");
    verify(preparedStatement, times(1)).setObject(2, "gps");
    verify(preparedStatement, times(1)).setObject(2, "airbags");
    verify(preparedStatement, times(3)).addBatch();
    verify(preparedStatement, times(1)).executeBatch();
    verify(preparedStatement, times(1)).close();
    verify(connection1, times(1)).close();
  }
  /**
   * Update transportation routes
   *
   * @param transportationRouteList List of transportation routes to insert (id != null)
   * @throws Exception
   */
  public void updateTransportationRoutes(Collection<TransportationRoute> transportationRouteList)
      throws Exception {
    try {
      String query =
          String.format(
              "UPDATE %s SET %s=?, %s=?, %s=?, %s=?, %s=?, %s=?, %s=?, %s=?, %s=?, %s=?, %s=? where %s=?",
              table,
              name,
              validFrom,
              validUntil,
              transportationID,
              operator,
              network,
              extRef,
              description,
              descriptionFrom,
              descriptionTo,
              routeNo,
              id);
      PreparedStatement ps = ConnectionManager.getInstance().prepareStatement(query);

      for (TransportationRoute transportationRoute : transportationRouteList) {
        if (transportationRoute.getId() == null || transportationRoute.getType() == null) {
          continue;
        }

        ps.setString(1, transportationRoute.getName());
        ps.setTimestamp(2, transportationRoute.getValidFrom());
        ps.setTimestamp(3, transportationRoute.getValidUntil());
        ps.setObject(4, transportationRoute.getType().getId());
        ps.setString(5, transportationRoute.getOperator());
        ps.setString(6, transportationRoute.getNetwork());
        ps.setString(7, transportationRoute.getExtRef());
        ps.setString(8, transportationRoute.getDescription());
        ps.setString(9, transportationRoute.getDescriptionFrom());
        ps.setString(10, transportationRoute.getDescriptionTo());
        ps.setString(11, transportationRoute.getRouteNo());
        ps.setObject(12, transportationRoute.getId());

        ps.addBatch();
      }

      ps.executeBatch();
      ps.close();

      ScheduleDAO scheduleDAO = new ScheduleDAO();
      scheduleDAO.insertOrUpdateSchedules(transportationRouteList);
    } catch (Exception e) {
      ConnectionManager.getInstance().closeConnection(true);

      throw new Exception("Transportation route update failed: " + e.getMessage());
    }
  }
  @Test
  public void testNotifyObjectsRemoved() throws Exception {

    // Mock
    ConnectionManager connectionManager = mock(ConnectionManager.class);
    Connection connection = mock(Connection.class);
    Connection connection1 = mock(Connection.class);
    Statement statement = mock(Statement.class);
    PreparedStatement preparedStatement = mock(PreparedStatement.class);

    // Behaviour
    when(connectionManager.getConnection(any(SQLiteIndex.class)))
        .thenReturn(connection)
        .thenReturn(connection1);
    when(connectionManager.isApplyUpdateForIndexEnabled(any(SQLiteIndex.class))).thenReturn(true);
    when(connection.createStatement()).thenReturn(statement);
    when(connection1.prepareStatement("DELETE FROM " + TABLE_NAME + " WHERE objectKey = ?;"))
        .thenReturn(preparedStatement);
    when(preparedStatement.executeBatch()).thenReturn(new int[] {1});

    // The objects to add
    Set<Car> removedObjects = new HashSet<Car>(2);
    removedObjects.add(
        new Car(1, "Ford", "Focus", Car.Color.BLUE, 5, 9000.50, Arrays.asList("abs", "gps")));
    removedObjects.add(
        new Car(2, "Honda", "Civic", Car.Color.RED, 5, 5000.00, Arrays.asList("airbags")));

    @SuppressWarnings({"unchecked", "unused"})
    SQLiteIndex<String, Car, Integer> carFeaturesOffHeapIndex =
        new SQLiteIndex<String, Car, Integer>(
            Car.FEATURES, OBJECT_TO_ID, ID_TO_OBJECT, connectionManager);

    carFeaturesOffHeapIndex.removeAll(removedObjects, new QueryOptions());

    // Verify
    verify(statement, times(1))
        .executeUpdate(
            "CREATE TABLE IF NOT EXISTS "
                + TABLE_NAME
                + " (objectKey INTEGER, value TEXT, PRIMARY KEY (objectKey, value)) WITHOUT ROWID;");
    verify(statement, times(1))
        .executeUpdate(
            "CREATE INDEX IF NOT EXISTS " + INDEX_NAME + " ON " + TABLE_NAME + " (value);");
    verify(connection, times(1)).close();

    verify(preparedStatement, times(1)).setObject(1, 1);
    verify(preparedStatement, times(1)).setObject(1, 2);
    verify(preparedStatement, times(2)).addBatch();
    verify(preparedStatement, times(1)).executeBatch();
    verify(connection1, times(1)).close();
  }
  @Test
  public void testNewResultSet_Iterator_Close() throws Exception {

    QueryOptions queryOptions = new QueryOptions();

    // Mocks
    ConnectionManager connectionManager = mock(ConnectionManager.class);
    Connection connection = mock(Connection.class);
    PreparedStatement preparedStatement = mock(PreparedStatement.class);
    java.sql.ResultSet resultSet = mock(java.sql.ResultSet.class);
    @SuppressWarnings("unchecked")
    SimpleAttribute<Integer, Car> idToObject =
        (SimpleAttribute<Integer, Car>) mock(SimpleAttribute.class);

    // Behaviour
    when(connectionManager.getConnection(any(SQLiteIndex.class))).thenReturn(connection);
    when(connection.prepareStatement(
            "SELECT DISTINCT objectKey, value FROM " + TABLE_NAME + " WHERE value = ?;"))
        .thenReturn(preparedStatement);
    when(preparedStatement.executeQuery()).thenReturn(resultSet);
    when(resultSet.getStatement()).thenReturn(preparedStatement);
    when(resultSet.next()).thenReturn(true).thenReturn(true).thenReturn(false);
    when(resultSet.getInt(1)).thenReturn(1).thenReturn(3);
    when(idToObject.getValue(1, queryOptions)).thenReturn(data.get(0));
    when(idToObject.getValue(3, queryOptions)).thenReturn(data.get(2));

    // Iterator
    ResultSet<Car> carsWithAbs =
        new SQLiteIndex<String, Car, Integer>(
                Car.FEATURES, OBJECT_TO_ID, idToObject, connectionManager)
            .retrieve(equal(Car.FEATURES, "abs"), queryOptions);

    Assert.assertNotNull(carsWithAbs);
    Iterator carsWithAbsIterator = carsWithAbs.iterator();

    assertTrue(carsWithAbsIterator.hasNext());
    Assert.assertNotNull(carsWithAbsIterator.next());
    assertTrue(carsWithAbsIterator.hasNext());
    Assert.assertNotNull(carsWithAbsIterator.next());
    assertFalse(carsWithAbsIterator.hasNext());

    // The end of the iteration should close the resources
    verify(connection, times(1)).close();
    verify(preparedStatement, times(1)).close();
    verify(resultSet, times(1)).close();
  }
  @Test
  public void testNewResultSet_Contains() throws Exception {

    // Mocks
    ConnectionManager connectionManager = mock(ConnectionManager.class);
    Connection connectionContains = mock(Connection.class);
    Connection connectionDoNotContain = mock(Connection.class);
    PreparedStatement preparedStatementContains = mock(PreparedStatement.class);
    PreparedStatement preparedStatementDoNotContains = mock(PreparedStatement.class);
    java.sql.ResultSet resultSetContains = mock(java.sql.ResultSet.class);
    java.sql.ResultSet resultSetDoNotContain = mock(java.sql.ResultSet.class);

    // Behaviour
    when(connectionManager.getConnection(any(SQLiteIndex.class)))
        .thenReturn(connectionContains)
        .thenReturn(connectionDoNotContain);
    when(connectionContains.prepareStatement(
            "SELECT COUNT(objectKey) FROM " + TABLE_NAME + " WHERE value = ? AND objectKey = ?;"))
        .thenReturn(preparedStatementContains);
    when(connectionDoNotContain.prepareStatement(
            "SELECT COUNT(objectKey) FROM " + TABLE_NAME + " WHERE value = ? AND objectKey = ?;"))
        .thenReturn(preparedStatementDoNotContains);
    when(preparedStatementContains.executeQuery()).thenReturn(resultSetContains);
    when(preparedStatementDoNotContains.executeQuery()).thenReturn(resultSetDoNotContain);
    when(resultSetContains.next()).thenReturn(true).thenReturn(false);
    when(resultSetContains.getInt(1)).thenReturn(1);
    when(resultSetDoNotContain.next()).thenReturn(true).thenReturn(false);
    when(resultSetDoNotContain.getInt(1)).thenReturn(0);

    // Iterator
    ResultSet<Car> carsWithAbs =
        new SQLiteIndex<String, Car, Integer>(
                Car.FEATURES, OBJECT_TO_ID, ID_TO_OBJECT, connectionManager)
            .retrieve(equal(Car.FEATURES, "abs"), new QueryOptions());

    Assert.assertNotNull(carsWithAbs);
    boolean resultContains = carsWithAbs.contains(data.get(0));
    assertTrue(resultContains);
    verify(connectionContains, times(1)).close();

    boolean resultDoNotContain = carsWithAbs.contains(data.get(1));
    assertFalse(resultDoNotContain);
    verify(connectionDoNotContain, times(1)).close();
  }
  /**
   * Get all transportation routes
   *
   * @return List
   */
  public List<TransportationRoute> getAllTransportationRoutes() throws Exception {
    // Get all transportation types
    TransportationTypeDAO transportationTypeDAO = new TransportationTypeDAO();
    HashMap<String, TransportationType> transportationTypes =
        ListConverter.getEntityListAsHashMap(transportationTypeDAO.getAllTransportationTypes());

    // Fetch transportation routes
    ArrayList<TransportationRoute> transportationRoutes = new ArrayList<>();
    try {
      String query = String.format("Select * from %s", table);
      ResultSet result = ConnectionManager.getInstance().createStatement().executeQuery(query);

      while (result.next()) {
        TransportationRoute transportationRoute = new TransportationRoute();

        transportationRoute.setId(UUID.fromString(result.getString(id)));
        transportationRoute.setName(result.getString(name));
        transportationRoute.setValidFrom(result.getTimestamp(validFrom));
        transportationRoute.setValidUntil(result.getTimestamp(validUntil));
        transportationRoute.setType(transportationTypes.get(result.getString(transportationID)));
        transportationRoute.setOperator(result.getString(operator));
        transportationRoute.setNetwork(result.getString(network));
        transportationRoute.setExtRef(result.getString(extRef));
        transportationRoute.setDescriptionFrom(result.getString(descriptionFrom));
        transportationRoute.setDescriptionTo(result.getString(descriptionTo));
        transportationRoute.setDescription(result.getString(description));
        transportationRoute.setRouteNo(result.getString(routeNo));

        transportationRoutes.add(transportationRoute);
      }

      ScheduleDAO scheduleDAO = new ScheduleDAO();
      for (TransportationRoute transportationRoute : transportationRoutes) {
        transportationRoute.setSchedules(scheduleDAO.getValidSchedules(transportationRoute));
      }
    } catch (Exception e) {
      ConnectionManager.getInstance().closeConnection(true);

      throw new Exception("Transportation route fetch failed: " + e.getMessage());
    }

    return transportationRoutes;
  }
  @Test
  public void testNotifyObjectsCleared() throws Exception {

    // Mock
    ConnectionManager connectionManager = mock(ConnectionManager.class);
    Connection connection = mock(Connection.class);
    Connection connection1 = mock(Connection.class);
    Statement statement = mock(Statement.class);
    Statement statement1 = mock(Statement.class);

    // Behaviour
    when(connectionManager.getConnection(any(SQLiteIndex.class)))
        .thenReturn(connection)
        .thenReturn(connection1);
    when(connectionManager.isApplyUpdateForIndexEnabled(any(SQLiteIndex.class))).thenReturn(true);
    when(connection.createStatement()).thenReturn(statement);
    when(connection1.createStatement()).thenReturn(statement1);

    @SuppressWarnings({"unchecked", "unused"})
    SQLiteIndex<String, Car, Integer> carFeaturesOffHeapIndex =
        new SQLiteIndex<String, Car, Integer>(
            Car.FEATURES, OBJECT_TO_ID, ID_TO_OBJECT, connectionManager);

    carFeaturesOffHeapIndex.clear(new QueryOptions());

    // Verify
    verify(statement, times(1))
        .executeUpdate(
            "CREATE TABLE IF NOT EXISTS "
                + TABLE_NAME
                + " (objectKey INTEGER, value TEXT, PRIMARY KEY (objectKey, value)) WITHOUT ROWID;");
    verify(statement, times(1))
        .executeUpdate(
            "CREATE INDEX IF NOT EXISTS " + INDEX_NAME + " ON " + TABLE_NAME + " (value);");
    verify(connection, times(1)).close();

    verify(statement1, times(1)).executeUpdate("DELETE FROM " + TABLE_NAME + ";");
    verify(connection1, times(1)).close();
  }
  /** 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;
    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));

      String sql =
          "select SCH01_EMPLOYEES.COMPANY_CODE_SYS01,SCH01_EMPLOYEES.PROGRESSIVE_REG04,SCH01_EMPLOYEES.EMPLOYEE_CODE,"
              + "REG07_TASKS.TASK_CODE,REG04_SUBJECTS.NAME_1,REG04_SUBJECTS.NAME_2,SYS10_TRANSLATIONS.DESCRIPTION,SCH01_EMPLOYEES.PHONE_NUMBER,SCH01_EMPLOYEES.OFFICE "
              + "from SCH01_EMPLOYEES,SYS10_TRANSLATIONS,REG07_TASKS,REG04_SUBJECTS where "
              + "SCH01_EMPLOYEES.COMPANY_CODE_SYS01=REG07_TASKS.COMPANY_CODE_SYS01 and "
              + "SCH01_EMPLOYEES.TASK_CODE_REG07=REG07_TASKS.TASK_CODE and "
              + "REG07_TASKS.PROGRESSIVE_SYS10=SYS10_TRANSLATIONS.PROGRESSIVE and "
              + "SYS10_TRANSLATIONS.LANGUAGE_CODE=? and "
              + "SCH01_EMPLOYEES.COMPANY_CODE_SYS01=REG04_SUBJECTS.COMPANY_CODE_SYS01 and "
              + "SCH01_EMPLOYEES.PROGRESSIVE_REG04=REG04_SUBJECTS.PROGRESSIVE and "
              + "SCH01_EMPLOYEES.ENABLED='Y'";

      GridParams gridParams = (GridParams) inputPar;

      if (gridParams.getOtherGridParams().get(ApplicationConsts.COMPANY_CODE_SYS01) != null) {
        sql +=
            " and SCH01_EMPLOYEES.COMPANY_CODE_SYS01='"
                + gridParams.getOtherGridParams().get(ApplicationConsts.COMPANY_CODE_SYS01)
                + "'";
      } else {
        // retrieve companies list...
        ArrayList companiesList =
            ((JAIOUserSessionParameters) userSessionPars).getCompanyBa().getCompaniesList("SCH01");
        String companies = "";
        for (int i = 0; i < companiesList.size(); i++)
          companies += "'" + companiesList.get(i).toString() + "',";
        companies = companies.substring(0, companies.length() - 1);

        sql += " and SCH01_EMPLOYEES.COMPANY_CODE_SYS01 in (" + companies + ")";
      }

      Map attribute2dbField = new HashMap();
      attribute2dbField.put("companyCodeSys01SCH01", "SCH01_EMPLOYEES.COMPANY_CODE_SYS01");
      attribute2dbField.put("progressiveReg04SCH01", "SCH01_EMPLOYEES.PROGRESSIVE_REG04");
      attribute2dbField.put("name_1REG04", "REG04_SUBJECTS.NAME_1");
      attribute2dbField.put("name_2REG04", "REG04_SUBJECTS.NAME_2");
      attribute2dbField.put("phoneNumberSCH01", "SCH01_EMPLOYEES.PHONE_NUMBER");
      attribute2dbField.put("officeSCH01", "SCH01_EMPLOYEES.OFFICE");
      attribute2dbField.put("employeeCodeSCH01", "SCH01_EMPLOYEES.EMPLOYEE_CODE");
      attribute2dbField.put("descriptionSYS10", "SYS10_TRANSLATIONS.DESCRIPTION");
      attribute2dbField.put("taskCodeReg07SCH01", "REG07_TASKS.TASK_CODE");

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

      if (gridParams.getOtherGridParams().get(ApplicationConsts.TASK_CODE_REG07) != null) {
        sql +=
            " and SCH01_EMPLOYEES.TASK_CODE_REG07='"
                + gridParams.getOtherGridParams().get(ApplicationConsts.TASK_CODE_REG07)
                + "'";
      }

      // read from SCH01 table...
      Response answer =
          QueryUtil.getQuery(
              conn,
              userSessionPars,
              sql,
              values,
              attribute2dbField,
              GridEmployeeVO.class,
              "Y",
              "N",
              context,
              gridParams,
              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 employees list",
          ex);
      return new ErrorResponse(ex.getMessage());
    } finally {
      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) {
    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) {
      }
    }
  }
  /** 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;
    Statement stmt = 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));
      java.util.List list = (ArrayList) inputPar;

      HierarItemDiscountVO vo = null;
      ResultSet rset = null;
      stmt = conn.createStatement();
      for (int i = 0; i < list.size(); i++) {
        vo = (HierarItemDiscountVO) list.get(i);
        vo.setDiscountTypeSAL03(ApplicationConsts.DISCOUNT_CUSTOMER);

        // retrieve COMPANY_CODE from progressiveHIE01...
        rset =
            stmt.executeQuery(
                "select COMPANY_CODE_SYS01 from ITM02_ITEM_TYPES where PROGRESSIVE_HIE02 in "
                    + "(select PROGRESSIVE_HIE02 from HIE01_LEVELS where PROGRESSIVE="
                    + vo.getProgressiveHie01SAL05()
                    + ")");
        if (rset.next()) vo.setCompanyCodeSys01SAL03(rset.getString(1));
        else {
          rset.close();
          conn.rollback();
          return new ErrorResponse("Item hierarchy not found.");
        }
        rset.close();

        DiscountBean.insertDiscount(conn, vo);

        stmt.execute(
            "insert into SAL05_ITEM_HIERAR_DISCOUNTS(COMPANY_CODE_SYS01,PROGRESSIVE_HIE01,DISCOUNT_CODE_SAL03) "
                + "values('"
                + vo.getCompanyCodeSys01SAL03()
                + "',"
                + vo.getProgressiveHie01SAL05()
                + ",'"
                + vo.getDiscountCodeSAL03()
                + "')");
      }

      Response answer = new VOListResponse(list, false, list.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 inserting hierarchy item discounts",
          ex);
      try {
        conn.rollback();
      } catch (Exception ex3) {
      }
      return new ErrorResponse(ex.getMessage());
    } finally {
      try {
        stmt.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();

    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));
      String sql =
          "select WAR04_WAREHOUSE_MOTIVES.QTY_SIGN,WAR04_WAREHOUSE_MOTIVES.ITEM_TYPE,WAR02_WAREHOUSE_MOVEMENTS.PROGRESSIVE,WAR02_WAREHOUSE_MOVEMENTS.COMPANY_CODE_SYS01,"
              + "WAR02_WAREHOUSE_MOVEMENTS.WAREHOUSE_CODE_WAR01,WAR02_WAREHOUSE_MOVEMENTS.ITEM_CODE_ITM01,WAR02_WAREHOUSE_MOVEMENTS.PROGRESSIVE_HIE01,"
              + "SYS10_LOC.DESCRIPTION,WAR02_WAREHOUSE_MOVEMENTS.MOVEMENT_DATE,WAR02_WAREHOUSE_MOVEMENTS.USERNAME,WAR02_WAREHOUSE_MOVEMENTS.NOTE,"
              + "WAR02_WAREHOUSE_MOVEMENTS.DELTA_QTY,WAR02_WAREHOUSE_MOVEMENTS.WAREHOUSE_MOTIVE_WAR04,SYS10_WAR04.DESCRIPTION,SYS10_ITM01.DESCRIPTION,"
              + "WAR01_WAREHOUSES.DESCRIPTION,"
              + "WAR02_WAREHOUSE_MOVEMENTS.VARIANT_TYPE_ITM06,WAR02_WAREHOUSE_MOVEMENTS.VARIANT_CODE_ITM11,"
              + "WAR02_WAREHOUSE_MOVEMENTS.VARIANT_TYPE_ITM07,WAR02_WAREHOUSE_MOVEMENTS.VARIANT_CODE_ITM12,"
              + "WAR02_WAREHOUSE_MOVEMENTS.VARIANT_TYPE_ITM08,WAR02_WAREHOUSE_MOVEMENTS.VARIANT_CODE_ITM13,"
              + "WAR02_WAREHOUSE_MOVEMENTS.VARIANT_TYPE_ITM09,WAR02_WAREHOUSE_MOVEMENTS.VARIANT_CODE_ITM14,"
              + "WAR02_WAREHOUSE_MOVEMENTS.VARIANT_TYPE_ITM10,WAR02_WAREHOUSE_MOVEMENTS.VARIANT_CODE_ITM15 "
              + " from "
              + "WAR04_WAREHOUSE_MOTIVES,WAR02_WAREHOUSE_MOVEMENTS,SYS10_TRANSLATIONS SYS10_LOC,SYS10_TRANSLATIONS SYS10_WAR04,"
              + "SYS10_TRANSLATIONS SYS10_ITM01,WAR01_WAREHOUSES,ITM01_ITEMS where "
              + "WAR02_WAREHOUSE_MOVEMENTS.WAREHOUSE_MOTIVE_WAR04=WAR04_WAREHOUSE_MOTIVES.WAREHOUSE_MOTIVE and "
              + "WAR04_WAREHOUSE_MOTIVES.PROGRESSIVE_SYS10=SYS10_WAR04.PROGRESSIVE and "
              + "SYS10_WAR04.LANGUAGE_CODE=? and "
              + "WAR02_WAREHOUSE_MOVEMENTS.PROGRESSIVE_HIE01=SYS10_LOC.PROGRESSIVE and "
              + "SYS10_LOC.LANGUAGE_CODE=? and "
              + "WAR02_WAREHOUSE_MOVEMENTS.COMPANY_CODE_SYS01=ITM01_ITEMS.COMPANY_CODE_SYS01 and "
              + "WAR02_WAREHOUSE_MOVEMENTS.ITEM_CODE_ITM01=ITM01_ITEMS.ITEM_CODE and "
              + "ITM01_ITEMS.PROGRESSIVE_SYS10=SYS10_ITM01.PROGRESSIVE and "
              + "SYS10_ITM01.LANGUAGE_CODE=? and "
              + "WAR02_WAREHOUSE_MOVEMENTS.COMPANY_CODE_SYS01=WAR01_WAREHOUSES.COMPANY_CODE_SYS01 and "
              + "WAR02_WAREHOUSE_MOVEMENTS.WAREHOUSE_CODE_WAR01=WAR01_WAREHOUSES.WAREHOUSE_CODE ";

      Map attribute2dbField = new HashMap();
      attribute2dbField.put("qtySignWAR04", "WAR04_WAREHOUSE_MOTIVES.QTY_SIGN");
      attribute2dbField.put("itemTypeWAR04", "WAR04_WAREHOUSE_MOTIVES.ITEM_TYPE");
      attribute2dbField.put("progressiveWAR02", "WAR02_WAREHOUSE_MOVEMENTS.PROGRESSIVE");
      attribute2dbField.put(
          "companyCodeSys01WAR02", "WAR02_WAREHOUSE_MOVEMENTS.COMPANY_CODE_SYS01");
      attribute2dbField.put(
          "warehouseCodeWar01WAR02", "WAR02_WAREHOUSE_MOVEMENTS.WAREHOUSE_CODE_WAR01");
      attribute2dbField.put("itemCodeItm01WAR02", "WAR02_WAREHOUSE_MOVEMENTS.ITEM_CODE_ITM01");
      attribute2dbField.put("progressiveHie01WAR02", "WAR02_WAREHOUSE_MOVEMENTS.PROGRESSIVE_HIE01");
      attribute2dbField.put("locationDescriptionSYS10", "SYS10_LOC.DESCRIPTION");
      attribute2dbField.put("movementDateWAR02", "WAR02_WAREHOUSE_MOVEMENTS.MOVEMENT_DATE");
      attribute2dbField.put("usernameWAR02", "WAR02_WAREHOUSE_MOVEMENTS.USERNAME");
      attribute2dbField.put("noteWAR02", "WAR02_WAREHOUSE_MOVEMENTS.NOTE");
      attribute2dbField.put("deltaQtyWAR02", "WAR02_WAREHOUSE_MOVEMENTS.DELTA_QTY");
      attribute2dbField.put(
          "warehouseMotiveWar04WAR02", "WAR02_WAREHOUSE_MOVEMENTS.WAREHOUSE_MOTIVE_WAR04");
      attribute2dbField.put("motiveDescriptionSYS10", "SYS10_WAR04.DESCRIPTION");
      attribute2dbField.put("itemDescriptionSYS10", "SYS10_ITM01.DESCRIPTION");
      attribute2dbField.put("descriptionWAR01", "WAR01_WAREHOUSES.DESCRIPTION");

      attribute2dbField.put(
          "variantTypeItm06WAR02", "WAR02_WAREHOUSE_MOVEMENTS.VARIANT_TYPE_ITM06");
      attribute2dbField.put(
          "variantCodeItm11WAR02", "WAR02_WAREHOUSE_MOVEMENTS.VARIANT_CODE_ITM11");
      attribute2dbField.put(
          "variantTypeItm07WAR02", "WAR02_WAREHOUSE_MOVEMENTS.VARIANT_TYPE_ITM07");
      attribute2dbField.put(
          "variantCodeItm12WAR02", "WAR02_WAREHOUSE_MOVEMENTS.VARIANT_CODE_ITM12");
      attribute2dbField.put(
          "variantTypeItm08WAR02", "WAR02_WAREHOUSE_MOVEMENTS.VARIANT_TYPE_ITM08");
      attribute2dbField.put(
          "variantCodeItm13WAR02", "WAR02_WAREHOUSE_MOVEMENTS.VARIANT_CODE_ITM13");
      attribute2dbField.put(
          "variantTypeItm09WAR02", "WAR02_WAREHOUSE_MOVEMENTS.VARIANT_TYPE_ITM09");
      attribute2dbField.put(
          "variantCodeItm14WAR02", "WAR02_WAREHOUSE_MOVEMENTS.VARIANT_CODE_ITM14");
      attribute2dbField.put(
          "variantTypeItm10WAR02", "WAR02_WAREHOUSE_MOVEMENTS.VARIANT_TYPE_ITM10");
      attribute2dbField.put(
          "variantCodeItm15WAR02", "WAR02_WAREHOUSE_MOVEMENTS.VARIANT_CODE_ITM15");

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

      GridParams gridParams = (GridParams) inputPar;

      // read from WAR02 table...
      Response answer =
          QueryUtil.getQuery(
              conn,
              userSessionPars,
              sql,
              values,
              attribute2dbField,
              MovementVO.class,
              "Y",
              "N",
              context,
              gridParams,
              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 warehouse movements list",
          ex);
      return new ErrorResponse(ex.getMessage());
    } finally {
      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) {
    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));
      CallOutTaskVO vo = null;

      ArrayList list = (ArrayList) inputPar;

      Map attribute2dbField = new HashMap();
      attribute2dbField.put("callOutCodeSch10SCH12", "CALL_OUT_CODE_SCH10");
      attribute2dbField.put("companyCodeSys01SCH12", "COMPANY_CODE_SYS01");
      attribute2dbField.put("taskCodeReg07SCH12", "TASK_CODE_REG07");

      Response res = null;
      for (int i = 0; i < list.size(); i++) {
        vo = (CallOutTaskVO) list.get(i);

        // insert into SCH12...
        res =
            QueryUtil.insertTable(
                conn,
                userSessionPars,
                vo,
                "SCH12_CALL_OUT_TASKS",
                attribute2dbField,
                "Y",
                "N",
                context,
                true);
        if (res.isError()) {
          conn.rollback();
          return res;
        }
      }

      Response answer = new VOListResponse(list, false, list.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 inserting new call-out tasks",
          ex);
      try {
        conn.rollback();
      } catch (Exception ex3) {
      }
      return new ErrorResponse(ex.getMessage());
    } finally {
      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();

    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));

      // retrieve companies list...
      GridParams gridParams = (GridParams) inputPar;
      String companies =
          (String)
              gridParams
                  .getOtherGridParams()
                  .get(ApplicationConsts.COMPANY_CODE_SYS01); // used in lookup grid...
      if (companies == null) {
        ArrayList companiesList =
            ((JAIOUserSessionParameters) userSessionPars).getCompanyBa().getCompaniesList("SAL06");
        companies = "";
        for (int i = 0; i < companiesList.size(); i++)
          companies += "'" + companiesList.get(i).toString() + "',";
        companies = companies.substring(0, companies.length() - 1);
      } else companies = "'" + companies + "'";

      String sql =
          "select SAL06_CHARGES.COMPANY_CODE_SYS01,SAL06_CHARGES.CHARGE_CODE,SAL06_CHARGES.PROGRESSIVE_SYS10,"
              + "SYS10_TRANSLATIONS.DESCRIPTION,SAL06_CHARGES.VALUE,SAL06_CHARGES.PERC,SAL06_CHARGES.VAT_CODE_REG01,"
              + "SAL06_CHARGES.CURRENCY_CODE_REG03,SAL06_CHARGES.ENABLED"
              + " from SAL06_CHARGES,SYS10_TRANSLATIONS where "
              + "SAL06_CHARGES.PROGRESSIVE_SYS10=SYS10_TRANSLATIONS.PROGRESSIVE and "
              + "SYS10_TRANSLATIONS.LANGUAGE_CODE=? and "
              + "SAL06_CHARGES.ENABLED='Y' and "
              + "SAL06_CHARGES.COMPANY_CODE_SYS01 in ("
              + companies
              + ")";

      Map attribute2dbField = new HashMap();
      attribute2dbField.put("companyCodeSys01SAL06", "SAL06_CHARGES.COMPANY_CODE_SYS01");
      attribute2dbField.put("chargeCodeSAL06", "SAL06_CHARGES.CHARGE_CODE");
      attribute2dbField.put("descriptionSYS10", "SYS10_TRANSLATIONS.DESCRIPTION");
      attribute2dbField.put("progressiveSys10SAL06", "SAL06_CHARGES.PROGRESSIVE_SYS10");
      attribute2dbField.put("valueSAL06", "SAL06_CHARGES.VALUE");
      attribute2dbField.put("percSAL06", "SAL06_CHARGES.PERC");
      attribute2dbField.put("vatCodeReg01SAL06", "SAL06_CHARGES.VAT_CODE_REG01");
      attribute2dbField.put("currencyCodeReg03SAL06", "SAL06_CHARGES.CURRENCY_CODE_REG03");
      attribute2dbField.put("enabledSAL06", "SAL06_CHARGES.ENABLED");

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

      // read from SAL06 table...
      Response res =
          CustomizeQueryUtil.getQuery(
              conn,
              userSessionPars,
              sql,
              values,
              attribute2dbField,
              ChargeVO.class,
              "Y",
              "N",
              context,
              gridParams,
              50,
              true,
              new BigDecimal(292) // window identifier...
              );
      if (res.isError()) return res;

      ArrayList list = ((VOListResponse) res).getRows();
      ChargeVO vo = null;
      sql =
          "select SYS10_TRANSLATIONS.DESCRIPTION,REG01_VATS.VALUE,REG01_VATS.DEDUCTIBLE "
              + "from SYS10_TRANSLATIONS,REG01_VATS where "
              + "REG01_VATS.PROGRESSIVE_SYS10=SYS10_TRANSLATIONS.PROGRESSIVE and "
              + "SYS10_TRANSLATIONS.LANGUAGE_CODE=? and "
              + "REG01_VATS.VAT_CODE=?";
      pstmt = conn.prepareStatement(sql);
      ResultSet rset = null;
      for (int i = 0; i < list.size(); i++) {
        vo = (ChargeVO) list.get(i);
        if (vo.getVatCodeReg01SAL06() != null) {
          // retrieve vat data from REG01...
          pstmt.setString(1, serverLanguageId);
          pstmt.setString(2, vo.getVatCodeReg01SAL06());
          rset = pstmt.executeQuery();
          if (rset.next()) {
            vo.setVatDescriptionSYS10(rset.getString(1));
            vo.setVatValueREG01(rset.getBigDecimal(2));
            vo.setVatDeductibleREG01(rset.getBigDecimal(3));
          }
          rset.close();
        }
      }

      Response answer = res;

      // 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 charges 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 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) {
      }
    }
  }
  /** 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));
      DetailSaleDocVO docVO = (DetailSaleDocVO) inputPar;

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

      // insert header...
      docVO.setDocStateDOC01(ApplicationConsts.HEADER_BLOCKED);
      Response res =
          insDocBean.insertSaleDoc(
              conn, docVO, userSessionPars, request, response, userSession, context);
      if (res.isError()) {
        conn.rollback();
        return res;
      }

      SaleDocPK refPK =
          new SaleDocPK(
              docVO.getCompanyCodeSys01Doc01DOC01(),
              docVO.getDocTypeDoc01DOC01(),
              docVO.getDocYearDoc01DOC01(),
              docVO.getDocNumberDoc01DOC01());

      // retrieve ref. document item rows...
      GridParams gridParams = new GridParams();
      gridParams.getOtherGridParams().put(ApplicationConsts.SALE_DOC_PK, refPK);
      res =
          rowsAction.executeCommand(
              gridParams, userSessionPars, request, response, userSession, context);
      if (res.isError()) {
        conn.rollback();
        return res;
      }
      java.util.List rows = ((VOListResponse) res).getRows();

      // create rows..
      GridSaleDocRowVO gridRowVO = null;
      DetailSaleDocRowVO rowVO = null;
      java.util.List discRows = null;
      SaleDocRowPK docRowPK = null;
      SaleItemDiscountVO itemDiscVO = null;
      gridParams = new GridParams();
      for (int i = 0; i < rows.size(); i++) {
        gridRowVO = (GridSaleDocRowVO) rows.get(i);

        // retrieve row detail...
        docRowPK =
            new SaleDocRowPK(
                gridRowVO.getCompanyCodeSys01DOC02(),
                gridRowVO.getDocTypeDOC02(),
                gridRowVO.getDocYearDOC02(),
                gridRowVO.getDocNumberDOC02(),
                gridRowVO.getItemCodeItm01DOC02(),
                gridRowVO.getVariantTypeItm06DOC02(),
                gridRowVO.getVariantCodeItm11DOC02(),
                gridRowVO.getVariantTypeItm07DOC02(),
                gridRowVO.getVariantCodeItm12DOC02(),
                gridRowVO.getVariantTypeItm08DOC02(),
                gridRowVO.getVariantCodeItm13DOC02(),
                gridRowVO.getVariantTypeItm09DOC02(),
                gridRowVO.getVariantCodeItm14DOC02(),
                gridRowVO.getVariantTypeItm10DOC02(),
                gridRowVO.getVariantCodeItm15DOC02());

        res =
            rowAction.executeCommand(
                docRowPK, userSessionPars, request, response, userSession, context);
        if (res.isError()) {
          conn.rollback();
          return res;
        }
        rowVO = (DetailSaleDocRowVO) ((VOResponse) res).getVo();
        rowVO.setDocTypeDOC02(docVO.getDocTypeDOC01());
        rowVO.setDocNumberDOC02(docVO.getDocNumberDOC01());
        if (rowVO.getInvoiceQtyDOC02().doubleValue() < rowVO.getQtyDOC02().doubleValue()
            && rowVO.getQtyDOC02().doubleValue() == rowVO.getOutQtyDOC02().doubleValue()) {
          rowVO.setQtyDOC02(
              rowVO
                  .getQtyDOC02()
                  .subtract(
                      rowVO
                          .getInvoiceQtyDOC02()
                          .setScale(
                              rowVO.getDecimalsReg02DOC02().intValue(), BigDecimal.ROUND_HALF_UP)));
          rowVO.setTaxableIncomeDOC02(
              rowVO
                  .getQtyDOC02()
                  .multiply(rowVO.getValueSal02DOC02())
                  .setScale(docVO.getDecimalsREG03().intValue(), BigDecimal.ROUND_HALF_UP));
          rowVO.setTotalDiscountDOC02(new BigDecimal(0));

          // calculate row vat...
          double vatPerc =
              rowVO.getValueReg01DOC02().doubleValue()
                  * (1d - rowVO.getDeductibleReg01DOC02().doubleValue() / 100d)
                  / 100;
          rowVO.setVatValueDOC02(
              rowVO
                  .getTaxableIncomeDOC02()
                  .multiply(new BigDecimal(vatPerc))
                  .setScale(docVO.getDecimalsREG03().intValue(), BigDecimal.ROUND_HALF_UP));

          // calculate row total...
          rowVO.setValueDOC02(rowVO.getTaxableIncomeDOC02().add(rowVO.getVatValueDOC02()));

          res =
              insRowBean.insertSaleItem(
                  conn, rowVO, userSessionPars, request, response, userSession, context);
          if (res.isError()) {
            conn.rollback();
            return res;
          }

          // create item discounts...
          gridParams.getOtherGridParams().put(ApplicationConsts.SALE_DOC_ROW_PK, docRowPK);
          res =
              itemDiscAction.executeCommand(
                  gridParams, userSessionPars, request, response, userSession, context);
          if (res.isError()) {
            conn.rollback();
            return res;
          }
          discRows = ((VOListResponse) res).getRows();
          for (int j = 0; j < discRows.size(); j++) {
            itemDiscVO = (SaleItemDiscountVO) discRows.get(j);
            itemDiscVO.setDocTypeDOC04(docVO.getDocTypeDOC01());
            itemDiscVO.setDocNumberDOC04(docVO.getDocNumberDOC01());
            res =
                insItemDiscBean.insertSaleDocRowDiscount(
                    conn, itemDiscVO, userSessionPars, request, response, userSession, context);
            if (res.isError()) {
              conn.rollback();
              return res;
            }
          }
        }
      }

      // create charges...
      gridParams = new GridParams();
      gridParams.getOtherGridParams().put(ApplicationConsts.SALE_DOC_PK, refPK);
      res =
          chargesAction.executeCommand(
              gridParams, userSessionPars, request, response, userSession, context);
      SaleDocChargeVO chargeVO = null;
      if (res.isError()) {
        conn.rollback();
        return res;
      }
      rows = ((VOListResponse) res).getRows();
      for (int i = 0; i < rows.size(); i++) {
        chargeVO = (SaleDocChargeVO) rows.get(i);
        chargeVO.setDocTypeDOC03(docVO.getDocTypeDOC01());
        chargeVO.setDocNumberDOC03(docVO.getDocNumberDOC01());
        if (chargeVO.getValueDOC03() == null
            || chargeVO.getValueDOC03() != null
                && chargeVO.getInvoicedValueDOC03().doubleValue()
                    < chargeVO.getValueDOC03().doubleValue()) {
          if (chargeVO.getValueDOC03() != null)
            chargeVO.setValueDOC03(
                chargeVO
                    .getValueDOC03()
                    .subtract(chargeVO.getInvoicedValueDOC03())
                    .setScale(docVO.getDecimalsREG03().intValue(), BigDecimal.ROUND_HALF_UP));

          res =
              insChargeBean.insertSaleDocCharge(
                  conn, chargeVO, userSessionPars, request, response, userSession, context);
          if (res.isError()) {
            conn.rollback();
            return res;
          }
        }
      }

      // create activities...
      res =
          actAction.executeCommand(
              gridParams, userSessionPars, request, response, userSession, context);
      if (res.isError()) {
        conn.rollback();
        return res;
      }
      SaleDocActivityVO actVO = null;
      rows = ((VOListResponse) res).getRows();
      for (int i = 0; i < rows.size(); i++) {
        actVO = (SaleDocActivityVO) rows.get(i);
        actVO.setDocTypeDOC13(docVO.getDocTypeDOC01());
        actVO.setDocNumberDOC13(docVO.getDocNumberDOC01());
        if (actVO.getInvoicedValueDOC13().doubleValue() < actVO.getValueDOC13().doubleValue()) {
          actVO.setValueDOC13(
              actVO
                  .getValueDOC13()
                  .subtract(actVO.getInvoicedValueDOC13())
                  .setScale(docVO.getDecimalsREG03().intValue(), BigDecimal.ROUND_HALF_UP));
          res =
              insActBean.insertSaleActivity(
                  conn, actVO, userSessionPars, request, response, userSession, context);
          if (res.isError()) {
            conn.rollback();
            return res;
          }
        }
      }

      // create header discounts...
      res =
          discAction.executeCommand(
              gridParams, userSessionPars, request, response, userSession, context);
      if (res.isError()) {
        conn.rollback();
        return res;
      }
      SaleDocDiscountVO discVO = null;
      rows = ((VOListResponse) res).getRows();
      for (int i = 0; i < rows.size(); i++) {
        discVO = (SaleDocDiscountVO) rows.get(i);
        discVO.setDocTypeDOC05(docVO.getDocTypeDOC01());
        discVO.setDocNumberDOC05(docVO.getDocNumberDOC01());
        res =
            insDiscBean.insertSaleDocDiscount(
                conn, discVO, userSessionPars, request, response, userSession, context);
        if (res.isError()) {
          conn.rollback();
          return res;
        }
      }

      // recalculate all taxable incomes, vats, totals...
      SaleDocPK pk =
          new SaleDocPK(
              docVO.getCompanyCodeSys01DOC01(),
              docVO.getDocTypeDOC01(),
              docVO.getDocYearDOC01(),
              docVO.getDocNumberDOC01());
      res =
          totals.updateTaxableIncomes(
              conn, pk, userSessionPars, request, response, userSession, context);
      if (res.isError()) {
        conn.rollback();
        return res;
      }

      // reload doc header with updated totals...
      Response answer =
          docAction.loadSaleDoc(conn, pk, userSessionPars, request, response, userSession, context);

      // 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 creating a sale invoice from a sale 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) {
      }
    }
  }
  @Test
  @Ignore
  public void testOutThreadPerformance() throws IOException, InterruptedException {
    new Thread(
            new Runnable() {
              public void run() {
                ServerSocket serverSocket = null;
                try {
                  serverSocket = new ServerSocket(5799);
                } catch (IOException e) {
                  System.out.println("Could not listen on port: 4444");
                  System.exit(-1);
                }
                Socket clientSocket = null;
                try {
                  clientSocket = serverSocket.accept();
                  byte[] bytes = new byte[1000000];
                  while (true) {
                    clientSocket.getInputStream().read(bytes);
                  }
                } catch (IOException e) {
                  System.out.println("Accept failed: 4444");
                  System.exit(-1);
                }
              }
            })
        .start();
    HazelcastClient client = mock(HazelcastClient.class);
    ConnectionManager connectionManager = mock(ConnectionManager.class);
    when(client.getConnectionManager()).thenReturn(connectionManager);
    Connection connection = new Connection("localhost", 5799, 1);
    when(connectionManager.getConnection()).thenReturn(connection);
    PacketWriter packetWriter = new PacketWriter();
    packetWriter.setConnection(connection);
    final OutRunnable outRunnable =
        new OutRunnable(client, new HashMap<Long, Call>(), packetWriter);
    new Thread(outRunnable).start();
    final AtomicLong callCounter = new AtomicLong();
    final long start = Clock.currentTimeMillis();
    ExecutorService executorService = Executors.newFixedThreadPool(20);
    final BlockingQueue<Object> queue = new LinkedBlockingQueue<Object>();
    final Object object = new Object();
    for (int i = 0; i < 16; i++) {
      executorService.execute(
          new Runnable() {

            public void run() {
              for (; ; ) {
                try {
                  queue.take();
                } catch (InterruptedException e) {
                  e.printStackTrace(); // To change body of catch statement use File | Settings |
                  // File Templates.
                }
                Packet packet = new Packet();
                packet.set("c:default", ClusterOperation.CONCURRENT_MAP_GET, new byte[30], null);
                Call call = new Call(callCounter.incrementAndGet(), packet);
                outRunnable.enQueue(call);
              }
            }
          });
    }
    Executors.newSingleThreadExecutor()
        .submit(
            new Runnable() {
              public void run() {
                int numberOfTasks = 10000;
                //                int numberOfTasks = 11000;
                while (true) {
                  try {
                    for (int i = 0; i < numberOfTasks; i++) {
                      queue.offer(object);
                    }
                    //                        numberOfTasks = numberOfTasks + numberOfTasks/10;
                    Thread.sleep(1 * 1000);
                    System.out.println(
                        "Operations per millisecond : "
                            + callCounter.get() / (Clock.currentTimeMillis() - start));
                    System.out.println("out runnable Queue size: " + outRunnable.getQueueSize());
                  } catch (Exception e) {
                    e.printStackTrace();
                  }
                }
              }
            });
    Thread.sleep(1000000);
  }
  /** 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 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();
    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) {
      }
    }
  }
  /** 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();
    String username = ((JAIOUserSessionParameters) userSessionPars).getUsername();

    Connection conn = null;
    Statement stmt = 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));
      stmt = conn.createStatement();
      ResultSet rset =
          stmt.executeQuery(
              "select SYS04_ROLES.PROGRESSIVE,SYS04_ROLES.PROGRESSIVE_SYS10,SYS10_TRANSLATIONS.DESCRIPTION from "
                  + "SYS14_USER_ROLES,SYS04_ROLES,SYS10_TRANSLATIONS where "
                  + "SYS14_USER_ROLES.PROGRESSIVE_SYS04=SYS04_ROLES.PROGRESSIVE and "
                  + "SYS04_ROLES.PROGRESSIVE_SYS10=SYS10_TRANSLATIONS.PROGRESSIVE and "
                  + "SYS10_TRANSLATIONS.LANGUAGE_CODE='"
                  + serverLanguageId
                  + "' and "
                  + "SYS14_USER_ROLES.USERNAME_SYS03='"
                  + username
                  + "' and "
                  + "SYS04_ROLES.ENABLED='Y'");
      RoleVO vo = null;
      ArrayList list = new ArrayList();
      while (rset.next()) {
        vo = new RoleVO();
        vo.setDescriptionSYS10(rset.getString(3));
        vo.setEnabledSYS04("Y");
        vo.setProgressiveSYS04(rset.getBigDecimal(1));
        vo.setProgressiveSys10SYS04(rset.getBigDecimal(2));
        list.add(vo);
      }

      rset.close();
      Response answer = new VOListResponse(list, false, list.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));

      return answer;
    } catch (Throwable ex) {
      Logger.error(
          userSessionPars.getUsername(),
          this.getClass().getName(),
          "executeCommand",
          "Error while fetching user roles list",
          ex);
      return new ErrorResponse(ex.getMessage());
    } finally {
      try {
        stmt.close();
      } catch (Exception ex2) {
      }
      try {
        ConnectionManager.releaseConnection(conn, context);
      } catch (Exception ex1) {
      }
    }
  }