/** Business logic to execute. */
  public VOListResponse updateWindowCustomizations(
      ArrayList oldRows, ArrayList newRows, String serverLanguageId, String username)
      throws Throwable {
    Statement stmt = null;
    Connection conn = null;
    try {
      if (this.conn == null) conn = getConn();
      else conn = this.conn;

      WindowCustomizationVO oldVO = null;
      WindowCustomizationVO newVO = null;
      for (int i = 0; i < oldRows.size(); i++) {
        oldVO = (WindowCustomizationVO) oldRows.get(i);
        newVO = (WindowCustomizationVO) newRows.get(i);
        TranslationUtils.updateTranslation(
            oldVO.getDescriptionSYS10(),
            newVO.getDescriptionSYS10(),
            newVO.getProgressiveSys10SYS12(),
            serverLanguageId,
            conn);
      }

      return new VOListResponse(newRows, false, newRows.size());
    } catch (Throwable ex) {
      Logger.error(
          username,
          this.getClass().getName(),
          "executeCommand",
          "Error while updating customized columns",
          ex);
      try {
        if (this.conn == null && conn != null)
          // rollback only local connection
          conn.rollback();
      } catch (Exception ex3) {
      }

      throw new Exception(ex.getMessage());
    } finally {
      try {
        if (this.conn == null && conn != null) {
          // close only local connection
          conn.commit();
          conn.close();
        }

      } catch (Exception exx) {
      }
    }
  }
 public int[] executeBatch() throws SQLException {
   if (batch == null) {
     return new int[0];
   }
   int[] ret;
   if (args.length == 0) {
     ret = new int[batch.size()];
   } else {
     ret = new int[batch.size() / args.length];
   }
   for (int i = 0; i < ret.length; i++) {
     ret[i] = EXECUTE_FAILED;
   }
   int errs = 0;
   int index = 0;
   for (int i = 0; i < ret.length; i++) {
     for (int k = 0; k < args.length; k++) {
       BatchArg b = (BatchArg) batch.get(index++);
       args[k] = b.arg;
       blobs[k] = b.blob;
     }
     try {
       ret[i] = executeUpdate();
     } catch (SQLException e) {
       ++errs;
     }
   }
   if (errs > 0) {
     throw new BatchUpdateException("batch failed", ret);
   }
   return ret;
 }
  protected synchronized String getProcedureName(Connection dConn, Connection gConn) {
    /// avoid #42569
    ResultSet rs = null;

    try {
      rs = gConn.getMetaData().getProcedures(null, null, null);
      List procNames = ResultSetHelper.asList(rs, false);
      Log.getLogWriter().info("procedure names are " + ResultSetHelper.listToString(procNames));
      rs.close();
    } catch (SQLException se) {
      SQLHelper.handleSQLException(se);
    }

    try {
      rs = gConn.getMetaData().getFunctions(null, null, null);
    } catch (SQLException se) {
      SQLHelper.handleSQLException(se);
    }
    List funcNames = ResultSetHelper.asList(rs, false);
    Log.getLogWriter().info("function names are " + ResultSetHelper.listToString(funcNames));

    if (procedureNames == null) {
      ArrayList<String> procs = new ArrayList<String>();
      procs.addAll(ProcedureDDLStmt.modifyProcNameList);
      procs.addAll(ProcedureDDLStmt.nonModifyProcNameList);
      procedureNames = new ArrayList<String>(procs);
    }

    return procedureNames.get(SQLTest.random.nextInt(procedureNames.size()));
  }
Ejemplo n.º 4
0
  /**
   * Is standard Period closed for all Document Base Types
   *
   * @param ctx context for AD_Client
   * @param DateAcct accounting date
   * @return true if closed
   */
  public static boolean isClosed(Ctx ctx, Timestamp DateAcct) {
    if (DateAcct == null) return false;
    MAcctSchema as = MClient.get(ctx, ctx.getAD_Client_ID()).getAcctSchema();
    if (as.isAutoPeriodControl()) return !as.isAutoPeriodControlOpen(DateAcct);

    //	Get all Calendars in line with Organizations
    MClientInfo cInfo = MClientInfo.get(ctx, ctx.getAD_Client_ID(), null);
    ArrayList<Integer> calendars = new ArrayList<Integer>();
    MOrg[] orgs = MOrg.getOfClient(cInfo);
    for (MOrg org : orgs) {
      MOrgInfo info = MOrgInfo.get(ctx, org.getAD_Org_ID(), null);
      int C_Calendar_ID = info.getC_Calendar_ID();
      if (C_Calendar_ID == 0) C_Calendar_ID = cInfo.getC_Calendar_ID();
      if (!calendars.contains(C_Calendar_ID)) calendars.add(C_Calendar_ID);
    }
    //	Should not happen
    if (calendars.size() == 0) throw new IllegalArgumentException("@NotFound@ @C_Calendar_ID@");

    //	For all Calendars get Periods
    for (int i = 0; i < calendars.size(); i++) {
      int C_Calendar_ID = calendars.get(i);
      MPeriod period = MPeriod.getOfCalendar(ctx, C_Calendar_ID, DateAcct);
      //	Period not found
      if (period == null) return false;
      if (!period.isClosed()) return false;
    }
    return true; //	closed
  } //	isClosed
Ejemplo n.º 5
0
  /** Check if object support this format. If a match is found return true else return false */
  public boolean supportFormat(FileHeader hdr) {
    boolean out = false;
    try {
      for (int i = 0; i < headers.size(); i++) {
        if ((headers.get(i).formatTypeName().equals(hdr.formatTypeName()))
            && (headers.get(i).objectTypeName().equals(hdr.objectTypeName()))
            && (headers.get(i).version() == hdr.version())) {
          return true;
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    return false;
  }
Ejemplo n.º 6
0
  /**
   * Get waiting User name;
   *
   * @return An waiter ArrayList
   */
  public static ArrayList<String> getWaiter() throws SQLException {
    ArrayList<String> waiterArray = new ArrayList<String>();
    Connection conn = DBConn.GetConnection();
    PreparedStatement st = conn.prepareStatement("SELECT * FROM cs_conversion where isstart=?");
    st.setInt(1, 1);
    ResultSet rs = st.executeQuery();
    while (rs.next()) {
      if (rs.getString("username").length() != 0) {

        if (waiterArray.size() == 0) {
          waiterArray.add(rs.getString("username"));
        } else {
          for (int i = 0; i < waiterArray.size(); i++) {
            if (!rs.getString("username").equals(waiterArray.get(i).toString())) {
              waiterArray.add(rs.getString("username"));
            }
          }
        }
      }
    }
    rs.close();
    st.close();
    conn.close();
    return waiterArray;
  }
Ejemplo n.º 7
0
  // Вид формы при изменении сотрудника
  public void sotrDiaUpdate(Sotrudnik s) {
    label_id_hidden.setText(Integer.toString(s.getId_sotrudnika()));
    textField_familiya.setText(s.getFamiliya());
    textField_imya.setText(s.getImya());
    textField_otchestvo.setText(s.getOtchestvo());
    textField_phone.setText(s.getPhone());
    textField_date.setText(s.getData_priema().toString());
    comboBox_doljnost.removeAllItems();
    comboBox_kvalification.removeAllItems();

    try {
      DBClass db = new DBClass();
      ArrayList<Doljnost> d = db.doljnostFromDB();
      DBClass db2 = new DBClass();
      Doljnost dd = db2.doljnostFromDB(s);
      for (int i = 0; i < d.size(); i++) {
        comboBox_doljnost.addItem(d.get(i));
        Doljnost ddd = (Doljnost) comboBox_doljnost.getItemAt(i);
        if (dd.getNazvanie_doljnosti().equals(ddd.getNazvanie_doljnosti())) dd = ddd;
      }
      comboBox_doljnost.setSelectedItem(dd);

      DBClass db3 = new DBClass();
      ArrayList<Kvalification> k = db3.kvalificationFromDB();
      DBClass db4 = new DBClass();
      Kvalification kk = db4.kvalificationFromDB(s);
      for (int i = 0; i < k.size(); i++) {
        comboBox_kvalification.addItem(k.get(i));
        Kvalification kkk = (Kvalification) comboBox_kvalification.getItemAt(i);
        if (kk.getNazvanie_kvalification().equals(kkk.getNazvanie_kvalification())) kk = kkk;
      }

      comboBox_kvalification.setSelectedItem(kk);

    } catch (ClassNotFoundException e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(panelException, e.getMessage());
    } catch (SQLException ee) {
      ee.printStackTrace();
      JOptionPane.showMessageDialog(panelException, ee.getMessage());
    }
  }
 public int ejecutaActualizacion(String actualizacion) throws SQLException {
   int i = comprobar();
   int res = 0;
   try {
     stmt = conexion.get(i).createStatement();
     res = stmt.executeUpdate(actualizacion);
   } catch (SQLException ex) {
     Logger.getLogger(BaseDatos.class.getName()).log(Level.SEVERE, null, ex);
   }
   return res;
 }
Ejemplo n.º 9
0
 private float[][] parse(int colone, int coltwo, ResultSet rs) throws SQLException {
   ArrayList<Float> valsone = new ArrayList<Float>();
   ArrayList<Float> valstwo = new ArrayList<Float>();
   while (rs.next()) {
     valsone.add(rs.getFloat(colone + 1)); // 1 b/c ResultSet is 1 based
     valstwo.add(
         rs.getFloat(
             coltwo
                 + 4)); // 4 b/c ResultSet is 1 based and there were three columns for channel one
   }
   rs.close();
   float[][] output = new float[2][valsone.size()];
   for (int i = 0; i < valsone.size(); i++) {
     output[0][i] = valsone.get(i);
     output[1][i] = valstwo.get(i);
   }
   valsone = null;
   valstwo = null;
   return output;
 }
Ejemplo n.º 10
0
 /**
  * Gets the instances of <CODE>Template</CODE> that have an ID that is already in the database.
  *
  * @return An <CODE>ArrayList</CODE> containing the instances of <CODE>Template</CODE> already in
  *     the database.
  * @throws java.sql.SQLException Thrown on sql exception.
  */
 public ArrayList findTemplatesInDatabase() throws java.sql.SQLException {
   ArrayList templatesInDatabase = new ArrayList();
   Connection oracleConnection = getDataSource().getConnection();
   try {
     Statement query = oracleConnection.createStatement();
     try {
       StringBuffer sql = new StringBuffer("SELECT TMPL_ID FROM ");
       sql.append(MPSBrowserView.SCHEMA);
       sql.append(".TEMPLATE WHERE TMPL_ID IN (");
       ArrayList templates = getTemplates();
       int templateCount = templates.size();
       for (int i = 0; i < templateCount; i++) {
         if (i > 0) sql.append(", ");
         sql.append("'");
         sql.append(((Template) templates.get(i)).getID());
         sql.append("'");
       }
       sql.append(")");
       ResultSet result = query.executeQuery(sql.toString());
       try {
         while (result.next()) {
           String templateID = result.getString("TMPL_ID");
           for (int i = 0; i < templateCount; i++) {
             Template currentTemplate = (Template) templates.get(i);
             if (templateID.equals(currentTemplate.getID())) {
               templatesInDatabase.add(currentTemplate);
               currentTemplate.setInDatabase(true);
             }
           }
         }
       } finally {
         result.close();
       }
     } finally {
       query.close();
     }
   } finally {
     oracleConnection.close();
   }
   return templatesInDatabase;
 }
Ejemplo n.º 11
0
  // Вид формы при добавлении нового сотрудника
  public void sotrDiaInsert() {
    label_id_hidden.setText("Новый сотрудник");
    textField_familiya.setText("");
    textField_imya.setText("");
    textField_otchestvo.setText("");
    textField_phone.setText("");
    comboBox_doljnost.removeAllItems();
    comboBox_kvalification.removeAllItems();

    Calendar calend = Calendar.getInstance();
    if (calend.get(Calendar.MONTH) <= 9) {
      textField_date.setText(
          String.valueOf(
              (calend.get(Calendar.YEAR) + "-" + ("0" + (1 + calend.get(Calendar.MONTH))) + "-")
                  + (calend.get(Calendar.DATE))));
    } else
      textField_date.setText(
          String.valueOf(
              ((calend.get(Calendar.YEAR)) + "-" + (1 + calend.get(Calendar.MONTH)) + "-")
                  + (calend.get(Calendar.DATE))));
    textField_date.setEnabled(false);

    try {
      DBClass db = new DBClass();
      ArrayList<Doljnost> d = db.doljnostFromDB();
      for (int i = 0; i < d.size(); i++) {
        comboBox_doljnost.addItem(d.get(i));
      }
      DBClass db2 = new DBClass();
      ArrayList<Kvalification> k = db2.kvalificationFromDB();
      for (int i = 0; i < k.size(); i++) {
        comboBox_kvalification.addItem(k.get(i));
      }
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(panelException, e.getMessage());
    } catch (SQLException ee) {
      ee.printStackTrace();
      JOptionPane.showMessageDialog(panelException, ee.getMessage());
    }
  }
Ejemplo n.º 12
0
  /** Business logic to execute. */
  public VOResponse deleteCharges(ArrayList list, String serverLanguageId, String username)
      throws Throwable {
    Statement stmt = null;
    Connection conn = null;
    try {
      if (this.conn == null) conn = getConn();
      else conn = this.conn;
      stmt = conn.createStatement();

      ChargeVO vo = null;
      for (int i = 0; i < list.size(); i++) {
        // logically delete the record in SAL06...
        vo = (ChargeVO) list.get(i);
        stmt.execute(
            "update SAL06_CHARGES set ENABLED='N' where COMPANY_CODE_SYS01='"
                + vo.getCompanyCodeSys01SAL06()
                + "' and CHARGE_CODE='"
                + vo.getChargeCodeSAL06()
                + "'");
      }

      return new VOResponse(new Boolean(true));
    } catch (Throwable ex) {
      Logger.error(
          username,
          this.getClass().getName(),
          "executeCommand",
          "Error while deleting existing charges",
          ex);
      try {
        if (this.conn == null && conn != null)
          // rollback only local connection
          conn.rollback();
      } catch (Exception ex3) {
      }

      throw new Exception(ex.getMessage());
    } finally {
      try {
        stmt.close();
      } catch (Exception exx) {
      }
      try {
        if (this.conn == null && conn != null) {
          // close only local connection
          conn.commit();
          conn.close();
        }

      } catch (Exception exx) {
      }
    }
  }
  public ResultSet ejecutaConsulta(String consulta) {

    try {
      int i = comprobar();
      stmt = conexion.get(i).createStatement();
      retset = stmt.executeQuery(consulta);

    } catch (SQLException ex) {
      Logger.getLogger(BaseDatos.class.getName()).log(Level.SEVERE, null, ex);
    }

    return retset;
  }
  private String findDriverByUrlImpl(String url) {
    for (int i = 0; i < _driverList.size(); i++) {
      try {
        Driver driver = (Driver) _driverList.get(i);

        if (driver.acceptsURL(url)) return driver.getClass().getName();
      } catch (Exception e) {
        log.log(Level.FINE, e.toString(), e);
      }
    }

    return null;
  }
Ejemplo n.º 15
0
  private static void generateKML(boolean isHighway) {
    System.out.println("generate link kml...");
    try {
      FileWriter fstream =
          new FileWriter(root + "/" + (isHighway ? highwayKmlFile : arterialKmlFile));
      BufferedWriter out = new BufferedWriter(fstream);
      out.write("<kml><Document>");
      ArrayList<LinkInfo> linkList = isHighway ? highwayLinkList : arterialLinkList;
      for (int i = 0; i < linkList.size(); i++) {
        LinkInfo link = linkList.get(i);
        int linkId = link.getLinkId();
        int funcClass = link.getFuncClass();
        String streetName = link.getStreetName();
        if (streetName.contains("&")) streetName = streetName.replaceAll("&", " and ");
        ArrayList<PairInfo> nodeList = link.getNodeList();

        String kmlStr = "<Placemark><name>Link:" + linkId + "</name>";
        kmlStr += "<description>";
        kmlStr += "Class:" + funcClass + "\r\n";
        kmlStr += "Name:" + streetName + "\r\n";
        kmlStr += "</description>";
        kmlStr += "<LineString><tessellate>1</tessellate><coordinates>";
        for (int j = 0; j < nodeList.size(); j++) {
          PairInfo node = nodeList.get(j);
          kmlStr += node.getLongi() + "," + node.getLati() + ",0 ";
        }
        kmlStr += "</coordinates></LineString></Placemark>\n";

        out.write(kmlStr);
      }
      out.write("</Document></kml>");
      out.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
    System.out.println("generate link kml finish!");
  }
 public boolean eliminar(String delete) {
   try {
     int i = comprobar();
     stmt = conexion.get(i).createStatement();
     int del = stmt.executeUpdate(delete);
     if (del >= 1) {
       return true;
     } else {
       return false;
     }
   } catch (SQLException ex) {
     Logger.getLogger(BaseDatos.class.getName()).log(Level.SEVERE, null, ex);
     return false;
   }
 }
  public int obtenerUltimoIdActualizacion(String actualizacion, String id_campo, String tabla)
      throws SQLException {
    int i = comprobar();
    stmt = conexion.get(i).createStatement();
    int res = stmt.executeUpdate(actualizacion);
    int id = -1;
    String query = "SELECT MAX(" + id_campo + ") FROM " + tabla;

    try {
      retset = ejecutaConsulta(query);
      if (retset.next()) id = retset.getInt(1);
    } catch (SQLException ex) {
      Logger.getLogger(BaseDatos.class.getName()).log(Level.SEVERE, null, ex);
    }

    return id;
  }
Ejemplo n.º 18
0
  public static void updateDoljnost() {
    try {
      DBClass db = new DBClass();
      ArrayList<Doljnost> d = db.doljnostFromDB();
      comboBox_doljnost.removeAllItems();
      for (int i = 0; i < d.size(); i++) {
        comboBox_doljnost.addItem(d.get(i));
      }

    } catch (ClassNotFoundException e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(null, e.getMessage());
    } catch (SQLException ee) {
      ee.printStackTrace();
      JOptionPane.showMessageDialog(null, ee.getMessage());
    }
  }
Ejemplo n.º 19
0
  public static void updateKvalification() {
    try {

      DBClass db2 = new DBClass();
      ArrayList<Kvalification> k = db2.kvalificationFromDB();
      comboBox_kvalification.removeAllItems();
      for (int i = 0; i < k.size(); i++) {
        comboBox_kvalification.addItem(k.get(i));
      }
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(null, e.getMessage());
    } catch (SQLException ee) {
      ee.printStackTrace();
      JOptionPane.showMessageDialog(null, ee.getMessage());
    }
  }
  private boolean reconec() {
    try {
      Class.forName(driver);
      for (int i = 0; i < 10; i++) {
        if (conexion.get(i).isClosed()) {
          conexion.set(i, DriverManager.getConnection(servidor, usuario, clave));
        }
      }
    } catch (ClassNotFoundException e) {
      System.err.print("No se han podido cargar los controladores");
      return false;
    } catch (SQLException ex) {
      System.out.print(ex.getMessage());
      return false;
    }

    return true;
  }
  private int comprobar() {
    int i = 0;
    try {
      while (conexion.get(i).isClosed()) {
        i++;
        if (i > 10) {
          reconec();
          i = 0;
        }
      }
      if (i != 0) {
        reconec();
      }
    } catch (SQLException ex) {
      Logger.getLogger(BaseDatos.class.getName()).log(Level.SEVERE, null, ex);
    }

    return i;
  }
Ejemplo n.º 22
0
 public static String randomStringGenerator(int length) {
   Random rand = new Random();
   String password = "";
   int count = 0;
   ArrayList temp = new ArrayList();
   while (count < length) {
     temp.add((char) (rand.nextInt(90 - 65 + 1) + 65));
     count++;
     temp.add((char) (rand.nextInt(122 - 97 + 1) + 97));
     count++;
     temp.add((char) (rand.nextInt(57 - 48 + 1) + 48));
     count++;
   }
   Collections.shuffle(temp, rand);
   int i = 0;
   while (i < length) {
     password += temp.get(i);
     i++;
   }
   return password;
 }
  /** 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) {
      }
    }
  }
Ejemplo n.º 24
0
  /** Business logic to execute. */
  public VOListResponse loadCharges(
      GridParams gridParams,
      String serverLanguageId,
      String username,
      ArrayList companiesList,
      ArrayList customizedFields)
      throws Throwable {
    PreparedStatement pstmt = null;
    Connection conn = null;
    try {
      if (this.conn == null) conn = getConn();
      else conn = this.conn;

      // retrieve companies list...
      String companies =
          (String)
              gridParams
                  .getOtherGridParams()
                  .get(ApplicationConsts.COMPANY_CODE_SYS01); // used in lookup grid...
      if (companies == null) {
        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,
              new UserSessionParameters(username),
              sql,
              values,
              attribute2dbField,
              ChargeVO.class,
              "Y",
              "N",
              null,
              gridParams,
              50,
              true,
              customizedFields);
      if (res.isError()) throw new Exception(res.getErrorMessage());

      java.util.List 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;
      if (answer.isError()) throw new Exception(answer.getErrorMessage());
      else return (VOListResponse) answer;
    } catch (Throwable ex) {
      Logger.error(
          username,
          this.getClass().getName(),
          "executeCommand",
          "Error while fetching charges list",
          ex);
      throw new Exception(ex.getMessage());
    } finally {
      try {
        pstmt.close();
      } catch (Exception exx) {
      }
      try {
        if (this.conn == null && conn != null) {
          // close only local connection
          conn.commit();
          conn.close();
        }

      } catch (Exception exx) {
      }
    }
  }
Ejemplo n.º 25
0
  /** Business logic to execute. */
  public VOListResponse insertCharges(
      ArrayList list, String serverLanguageId, String username, ArrayList customizedFields)
      throws Throwable {
    Connection conn = null;
    try {
      if (this.conn == null) conn = getConn();
      else conn = this.conn;
      ChargeVO vo = null;

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

      BigDecimal progressiveSYS10 = null;
      Response res = null;
      for (int i = 0; i < list.size(); i++) {
        vo = (ChargeVO) list.get(i);
        vo.setEnabledSAL06("Y");

        // insert record in SYS10...
        progressiveSYS10 =
            TranslationUtils.insertTranslations(
                vo.getDescriptionSYS10(), vo.getCompanyCodeSys01SAL06(), conn);
        vo.setProgressiveSys10SAL06(progressiveSYS10);

        // insert into SAL06...
        res =
            CustomizeQueryUtil.insertTable(
                conn,
                new UserSessionParameters(username),
                vo,
                "SAL06_CHARGES",
                attribute2dbField,
                "Y",
                "N",
                null,
                true,
                customizedFields);
        if (res.isError()) {
          throw new Exception(res.getErrorMessage());
        }
      }

      return new VOListResponse(list, false, list.size());
    } catch (Throwable ex) {
      Logger.error(
          username,
          this.getClass().getName(),
          "executeCommand",
          "Error while inserting new charges",
          ex);
      try {
        if (this.conn == null && conn != null)
          // rollback only local connection
          conn.rollback();
      } catch (Exception ex3) {
      }

      throw new Exception(ex.getMessage());
    } finally {
      try {
        if (this.conn == null && conn != null) {
          // close only local connection
          conn.commit();
          conn.close();
        }

      } catch (Exception exx) {
      }
    }
  }
Ejemplo n.º 26
0
  /** Business logic to execute. */
  public VOListResponse updateCharges(
      ArrayList oldVOs,
      ArrayList newVOs,
      String serverLanguageId,
      String username,
      ArrayList customizedFields)
      throws Throwable {
    Connection conn = null;
    try {
      if (this.conn == null) conn = getConn();
      else conn = this.conn;

      ChargeVO oldVO = null;
      ChargeVO newVO = null;
      Response res = null;

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

        // update SYS10 table...
        TranslationUtils.updateTranslation(
            oldVO.getDescriptionSYS10(),
            newVO.getDescriptionSYS10(),
            newVO.getProgressiveSys10SAL06(),
            serverLanguageId,
            conn);

        HashSet pkAttrs = new HashSet();
        pkAttrs.add("companyCodeSys01SAL06");
        pkAttrs.add("chargeCodeSAL06");

        HashMap attr2dbFields = new HashMap();
        attr2dbFields.put("companyCodeSys01SAL06", "COMPANY_CODE_SYS01");
        attr2dbFields.put("chargeCodeSAL06", "CHARGE_CODE");
        attr2dbFields.put("progressiveSys10SAL06", "PROGRESSIVE_SYS10");
        attr2dbFields.put("valueSAL06", "VALUE");
        attr2dbFields.put("percSAL06", "PERC");
        attr2dbFields.put("vatCodeReg01SAL06", "VAT_CODE_REG01");
        attr2dbFields.put("currencyCodeReg03SAL06", "CURRENCY_CODE_REG03");

        res =
            new CustomizeQueryUtil()
                .updateTable(
                    conn,
                    new UserSessionParameters(username),
                    pkAttrs,
                    oldVO,
                    newVO,
                    "SAL06_CHARGES",
                    attr2dbFields,
                    "Y",
                    "N",
                    null,
                    true,
                    customizedFields);
        if (res.isError()) {
          throw new Exception(res.getErrorMessage());
        }
      }

      return new VOListResponse(newVOs, false, newVOs.size());
    } catch (Throwable ex) {
      Logger.error(
          username,
          this.getClass().getName(),
          "executeCommand",
          "Error while updating existing charges",
          ex);
      try {
        if (this.conn == null && conn != null)
          // rollback only local connection
          conn.rollback();
      } catch (Exception ex3) {
      }

      throw new Exception(ex.getMessage());
    } finally {
      try {
        if (this.conn == null && conn != null) {
          // close only local connection
          conn.commit();
          conn.close();
        }

      } catch (Exception exx) {
      }
    }
  }
  /**
   * Check if components required by specified products are available.
   *
   * @param products list of ProdOrderProductVO objects
   * @params compAltComps collection of <component item code,HashSet of alternative component item
   *     codes>; filled by this method (and given back by reference)
   * @return VOListResponse of ProdOrderComponentVO objects
   */
  public final Response checkComponentsAvailability(
      Connection conn,
      Hashtable compAltComps,
      ArrayList products,
      UserSessionParameters userSessionPars,
      HttpServletRequest request,
      HttpServletResponse response,
      HttpSession userSession,
      ServletContext context) {
    String serverLanguageId = ((JAIOUserSessionParameters) userSessionPars).getServerLanguageId();
    try {

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

      if (products.size() == 0) {
        return new VOListResponse(new ArrayList(), false, 0);
      }

      // fill in comps hashtable with the collection of required components...
      ItemPK pk = null;
      ProdOrderProductVO prodVO = null;
      ArrayList components = null;
      MaterialVO compVO = null;
      Response res = null;
      ProdOrderComponentVO componentVO = null;
      Hashtable comps =
          new Hashtable(); // collection of <component item code,ProdOrderComponentVO object>
      for (int i = 0; i < products.size(); i++) {
        // retrieve bill of materials for each product...
        prodVO = (ProdOrderProductVO) products.get(i);
        pk = new ItemPK(prodVO.getCompanyCodeSys01DOC23(), prodVO.getItemCodeItm01DOC23());
        res =
            bean.getBillOfMaterials(
                conn, pk, userSessionPars, request, response, userSession, context);
        if (res.isError()) {
          return res;
        }

        // extract components only (leaf nodes)...
        components =
            getComponents(
                (DefaultMutableTreeNode) ((TreeModel) ((VOResponse) res).getVo()).getRoot());
        for (int j = 0; j < components.size(); j++) {
          compVO = (MaterialVO) components.get(j);
          componentVO = (ProdOrderComponentVO) comps.get(compVO.getItemCodeItm01ITM03());
          if (componentVO == null) {
            componentVO = new ProdOrderComponentVO();
            comps.put(compVO.getItemCodeItm01ITM03(), componentVO);
            componentVO.setAvailableQty(new BigDecimal(0));
            componentVO.setCompanyCodeSys01DOC24(compVO.getCompanyCodeSys01ITM03());
            componentVO.setDescriptionSYS10(compVO.getDescriptionSYS10());
            componentVO.setDocNumberDOC24(prodVO.getDocNumberDOC23());
            componentVO.setDocYearDOC24(prodVO.getDocYearDOC23());
            componentVO.setItemCodeItm01DOC24(compVO.getItemCodeItm01ITM03());
            componentVO.setMinSellingQtyUmCodeReg02ITM01(compVO.getMinSellingQtyUmCodeReg02ITM01());
            componentVO.setQtyDOC24(new BigDecimal(0));
          }
          componentVO.setQtyDOC24(
              componentVO.getQtyDOC24().add(compVO.getQtyITM03().multiply(prodVO.getQtyDOC23())));
        }
      }

      // check components availability in the specified warehouse...
      Enumeration en = comps.keys();
      GridParams gridParams = new GridParams();
      gridParams
          .getOtherGridParams()
          .put(ApplicationConsts.COMPANY_CODE_SYS01, prodVO.getCompanyCodeSys01DOC23());
      gridParams
          .getOtherGridParams()
          .put(ApplicationConsts.WAREHOUSE_CODE, prodVO.getWarehouseCodeWar01DOC22());
      gridParams.getOtherGridParams().put(ApplicationConsts.LOAD_ALL, Boolean.TRUE);
      ItemAvailabilityVO availVO = null;
      BigDecimal availability, altAvailability, delta;
      String itemCode = null;
      ArrayList list, availList;
      AltComponentVO altVO = null;
      ArrayList alternativeComps = new ArrayList();
      ArrayList compsToRemove = new ArrayList();
      ProdOrderComponentVO altComponentVO = null;
      HashSet altCodes = null; // list of alternative component item codes...
      BigDecimal altQty = null;
      while (en.hasMoreElements()) {
        itemCode = en.nextElement().toString();
        componentVO = (ProdOrderComponentVO) comps.get(itemCode);

        gridParams
            .getOtherGridParams()
            .put(
                ApplicationConsts.ITEM_PK, new ItemPK(prodVO.getCompanyCodeSys01DOC23(), itemCode));
        res =
            avail.executeCommand(
                gridParams, userSessionPars, request, response, userSession, context);
        if (res.isError()) return res;

        availList = ((VOListResponse) res).getRows();
        componentVO.setAvailabilities(availList);
        availability = new BigDecimal(0);
        for (int i = 0; i < availList.size(); i++) {
          availVO = (ItemAvailabilityVO) availList.get(i);
          availability = availability.add(availVO.getAvailableQtyWAR03());
        }
        componentVO.setAvailableQty(availability);

        if (componentVO.getQtyDOC24().doubleValue() > componentVO.getAvailableQty().doubleValue()) {
          // check if there exist some alternative component...
          res =
              altComps.executeCommand(
                  gridParams, userSessionPars, request, response, userSession, context);
          if (res.isError()) return res;
          list = ((VOListResponse) res).getRows();
          for (int i = 0; i < list.size(); i++) {
            altVO = (AltComponentVO) list.get(i);
            gridParams
                .getOtherGridParams()
                .put(
                    ApplicationConsts.ITEM_PK,
                    new ItemPK(prodVO.getCompanyCodeSys01DOC23(), altVO.getItemCodeItm01ITM04()));
            res =
                avail.executeCommand(
                    gridParams, userSessionPars, request, response, userSession, context);
            if (res.isError()) return res;
            availList = ((VOListResponse) res).getRows();
            altAvailability = new BigDecimal(0);
            for (int j = 0; j < availList.size(); j++) {
              availVO = (ItemAvailabilityVO) availList.get(j);
              altAvailability = altAvailability.add(availVO.getAvailableQtyWAR03());
            }
            if (altAvailability.doubleValue() > 0) {
              altComponentVO = new ProdOrderComponentVO();
              altComponentVO.setAvailabilities(availList);
              altComponentVO.setAvailableQty(altAvailability);
              altComponentVO.setCompanyCodeSys01DOC24(altVO.getCompanyCodeSys01ITM04());
              altComponentVO.setDescriptionSYS10(altVO.getDescriptionSYS10());
              altComponentVO.setDocNumberDOC24(prodVO.getDocNumberDOC23());
              altComponentVO.setDocYearDOC24(prodVO.getDocYearDOC23());
              altComponentVO.setItemCodeItm01DOC24(altVO.getItemCodeItm01ITM04());
              altComponentVO.setMinSellingQtyUmCodeReg02ITM01(
                  altVO.getMinSellingQtyUmCodeReg02ITM01());
              altQty =
                  conv.convertQty(
                      altVO.getMinSellingQtyUmCodeReg02ITM01(),
                      componentVO.getMinSellingQtyUmCodeReg02ITM01(),
                      altAvailability,
                      userSessionPars,
                      request,
                      response,
                      userSession,
                      context);
              if (componentVO.getQtyDOC24().subtract(availability).doubleValue()
                  > altQty.doubleValue()) {
                delta = altQty;
                altComponentVO.setQtyDOC24(altAvailability);
              } else {
                delta = componentVO.getQtyDOC24();
                altComponentVO.setQtyDOC24(
                    conv.convertQty(
                        componentVO.getMinSellingQtyUmCodeReg02ITM01(),
                        altVO.getMinSellingQtyUmCodeReg02ITM01(),
                        delta,
                        userSessionPars,
                        request,
                        response,
                        userSession,
                        context));
              }
              componentVO.setQtyDOC24(componentVO.getQtyDOC24().subtract(delta));
              alternativeComps.add(altComponentVO);

              altCodes = (HashSet) compAltComps.get(itemCode);
              if (altCodes == null) {
                altCodes = new HashSet();
                compAltComps.put(itemCode, altCodes);
              }
              altCodes.add(altVO.getItemCodeItm01ITM04());

              if (componentVO.getQtyDOC24().doubleValue() == 0) {
                compsToRemove.add(componentVO);
                break;
              }
              if (componentVO.getQtyDOC24().subtract(availability).doubleValue() == 0) break;
            }
          }
        }
      }

      list = new ArrayList(comps.values());
      list.addAll(alternativeComps);
      list.removeAll(compsToRemove);
      return new VOListResponse(list, false, list.size());
    } catch (Throwable ex) {
      Logger.error(
          userSessionPars.getUsername(),
          this.getClass().getName(),
          "checkComponentsAvailability",
          "Error while retrieving components availability for the specified production order",
          ex);
      return new ErrorResponse(ex.getMessage());
    }
  }
Ejemplo n.º 28
0
  /**
   * ]
   *
   * @param aWebForm AddForm
   * @param request HttpServletRequest
   * @param response HttpServletResponse
   * @throws CDealException
   * @throws Exception
   */
  public static void setEdit1(
      EditForm aWebForm, HttpServletRequest request, HttpServletResponse response)
      throws CDealException, Exception {
    EditForm aWebForm1 = (EditForm) aWebForm;
    Connection mConn = null;
    PreparedStatement pstmt = null;
    String str = ""; // 要返回的 string
    String sKey = ""; // 取出的TREEMAP的KEY
    String sValue = ""; // 取出的TREEMAP的value
    TreeMap itemtype;

    // 初始化页面,初始化事项类别下拉菜单
    // 初始化页面,初始化投诉形式下拉菜单

    TreeMap COMPLAINVERSIONListName2 = new TreeMap(); // 取出aWebForm
    COMPLAINVERSIONListName2 = CCodeMap.getMapByType("行政过错职级");
    aWebForm.setCOMPLAINEDGRADELIST(COMPLAINVERSIONListName2);
    TreeMap COMPLAINVERSIONListName3 = new TreeMap(); // 取出aWebForm
    COMPLAINVERSIONListName3 = CCodeMap.getMapByType("行政管理分类");
    aWebForm.setXZGLFLList(COMPLAINVERSIONListName3);
    TreeMap COMPLAINVERSIONListName4 = new TreeMap(); // 取出aWebForm
    COMPLAINVERSIONListName4 = CCodeMap.getMapByType("行政过错表现形式");
    aWebForm.setXZGCBXXSList(COMPLAINVERSIONListName4);

    try {
      // 从CODEMAP表里取 来源分类 菜单
      ArrayList comeList = CCodeMap.getSortedMap("行政过错行为分类");
      // 从CODEMAP表里取 本级政府任务督办 菜单
      ArrayList localList = CCodeMap.getSortedMap("违反规定履行社会管理职责");
      // 从CODEMAP表里取 上级任务督办 菜单
      ArrayList upList = CCodeMap.getSortedMap("违反内部管理制度");
      // 从CODEMAP表里取 上级任务督办 菜单
      ArrayList lbList = CCodeMap.getSortedMap("其他贻误行政管理工作");
      // 添加 来源分类 到一个数组里面去.然后统一输出到页面
      str = "var XZGCXYFL=new Array('','全部'";
      int k = 0;
      for (; k < comeList.size(); k++) {
        LabelValueBean aLabelValueBean = (LabelValueBean) comeList.get(k);
        sKey = aLabelValueBean.getValue(); // 名字
        str += ",'" + sKey + "',"; // 取出的TREEMAP的KEY
        sValue = aLabelValueBean.getLabel(); // 值
        str += "'" + sValue + "'\n"; // 取出的TREEMAP的value
      }
      // CLog.println(str);
      str += ");\n";
      str += " var permissionitem = new Array (" + k + ");\n";
      str += "permissionitem[0]=new Array('','全部');\n";

      // 添加 违反规定履行社会管理职责
      int j = 1;
      str += "permissionitem[" + j + "]=new Array('','全部'";
      for (int i = 0; i < localList.size(); i++) {
        LabelValueBean aLabelValueBean = (LabelValueBean) localList.get(i);
        sKey = aLabelValueBean.getValue(); // 值
        // 添加每个部门对应的事项类别列表
        str += ",'" + sKey + "',"; // 取出的TREEMAP的KEY
        sValue = aLabelValueBean.getLabel(); // 名字
        str += "'" + sValue + "'\n"; // 取出的TREEMAP的value
      }
      str += ");\n";

      // 添加 违反内部管理制度
      j = 2;
      str += "permissionitem[" + j + "]=new Array('','全部'";
      for (int i = 0; i < upList.size(); i++) {
        LabelValueBean aLabelValueBean = (LabelValueBean) upList.get(i);
        sKey = aLabelValueBean.getValue(); // 值
        // 添加每个部门对应的事项类别列表
        str += ",'" + sKey + "',"; // 取出的TREEMAP的KEY
        sValue = aLabelValueBean.getLabel(); // 名字
        str += "'" + sValue + "'\n"; // 取出的TREEMAP的value
      }
      str += ");\n";
      // 添加 其他贻误行政管理工作
      j = 3;
      str += "permissionitem[" + j + "]=new Array('','全部'";
      for (int i = 0; i < lbList.size(); i++) {
        LabelValueBean aLabelValueBean = (LabelValueBean) lbList.get(i);
        sKey = aLabelValueBean.getValue(); // 值
        // 添加每个部门对应的事项类别列表
        str += ",'" + sKey + "',"; // 取出的TREEMAP的KEY
        sValue = aLabelValueBean.getLabel(); // 名字
        str += "'" + sValue + "'\n"; // 取出的TREEMAP的value
      }
      str += ");\n";

      // 把部门数组和许可事项输出到页面上
      aWebForm1.setPrintSql(str);
    } catch (Exception e) {
      throw new CDealException("设置进入时限监察查询处理的初始值时失败。", e);
    } finally {
      if (pstmt != null) {
        try {
          pstmt.close();
        } catch (Exception e) {
        }
        ;
      }
      if (mConn != null) {
        try {
          mConn.close();
        } catch (Exception e) {
        }
        ;
      }
    }
  }
  public static void main(String[] args) {
    // DBResourcesManager.initHibernate();

    OffertaEvento of = new OffertaEvento();
    of.setNome("ofevent");
    of.setTipologia("Concerto");
    of.setPrezzo(69);
    // of.setDataScadenza("21/08/2019");
    of.setCittà("Roma");

    Offerta offertaArray[] = {new OffertaEvento(), new OffertaPernotto(), new OffertaTrasporto()};
    /*
    for(Offerta o : offertaArray) {
        System.out.println(o.getClass().getSimpleName() + "\n");
        Method[] methods = o.getClass().getMethods();
        for (Method m : methods) {
            int l = m.getName().length();
            if (m.getName().substring(0, 3).equals("set") && !m.getName().substring(l - 2, l).equals("ID"))
                System.out.println(m.getName());
        }
    }*/
    /*
    OffertaBean object = new OffertaEventoBean();


    String query = "from "+ object.getClass().getSimpleName() + " where ";

    System.out.println(object.getClass().getSimpleName() + "\n");
    Method[] methods = object.getClass().getMethods();
    for (Method m : methods) {
        int l = m.getName().length();
        if (m.getName().substring(0, 3).equals("get") && !m.getName().substring(l - 2, l).equals("ID") && !m.getName().equals("getClass"))
        {
            String s = m.getName().substring(0,1).toLowerCase();
            String attributeLower = s + m.getName().substring(1);
            query = query + attributeLower + " = ";
        }
    }*/
    String città = "Roma";
    String dataScadenza = "11/07/2009";
    String nome = "Bubu";
    String prezzo = "4";
    String tipologia = "Museo";

    String query = "from OffertaEvento offertaEvento";

    query = query + " where ";
    if (città != null) query = query + "offertaEvento.città = '" + città + "' && ";
    if (dataScadenza != null)
      query = query + "offertaEvento.dataScadenza = '" + dataScadenza + "' && ";
    if (nome != null) query = query + "offertaEvento.nome = '" + nome + "' && ";
    if (prezzo != null) query = query + "offertaEvento.prezzo = '" + prezzo + "' && ";
    if (tipologia != null) query = query + "offertaEvento.tipologia = '" + tipologia + "'";

    System.out.println(query);

    ArrayList<String> ls = new ArrayList<String>();
    ls.add(città);
    ls.add(dataScadenza);
    ls.add(nome);
    ls.add(prezzo);
    ls.add(tipologia);
    System.out.println("\nNuova query\n");

    if (!ls.isEmpty()) query.join(" where");

    for (int i = 0; i < ls.size(); i++) {
      if (!ls.get(i).equals("") && i == 0)
        query.join(" && offertaEvento.città = '" + ls.get(i) + "'");
      if (!ls.get(i).equals("") && i == 1)
        query.join(" && offertaEvento.dataScadenza = '" + ls.get(i) + "'");
      if (!ls.get(i).equals("") && i == 2)
        query.join(" && offertaEvento.nome = '" + ls.get(i) + "'");
      if (!ls.get(i).equals("") && i == 3)
        query.join(" && offertaEvento.prezzo = '" + ls.get(i) + "'");
      if (!ls.get(i).equals("") && i == 4)
        query.join(" && offertaEvento.tipologia = '" + ls.get(i) + "'");
    }

    System.out.println(query);

    Offerta o = new OffertaEvento();

    List<Method> fields = Arrays.asList(o.getClass().getDeclaredMethods());

    Class c = o.getClass().getSuperclass();

    List<Method> superfields = Arrays.asList(c.getDeclaredMethods());

    List<Method> allfields = new ArrayList<Method>(fields);
    allfields.addAll(superfields);

    allfields.sort(
        new Comparator<Method>() {
          public int compare(Method o1, Method o2) {
            return o1.getName().compareTo(o1.getName());
          }
        });
    /*
    for(Method f: allfields){

    }*/
    java.sql.Date date = Date.valueOf(LocalDate.now());
    System.out.println(date);
    String datestring = date.toString();
    System.out.println(datestring);
    Date data2 = Date.valueOf(datestring);
    System.out.println(data2);
    // OffertaEventoDAO.store(of);

    // System.out.println(((List<OffertaEvento>)DAOFactory.getDAOFactory(TipoOfferta.OffertaEvento).getOffertaDAO().getList()).size());

    // DBResourcesManager.shutdown();

    // OffertaDaoAnnotations.findAllOffertaEntitysA("offertaevento","Concerto");
  }
Ejemplo n.º 30
0
  /**
   * Is standard Period Open for specified orgs for the client. For best performance, ensure that
   * the list of orgs does not contain duplicates.
   *
   * @param ctx
   * @param AD_Client_ID
   * @param orgs
   * @param DateAcct accounting date
   * @param DocBaseType document base type
   * @return error message or null
   */
  public static String isOpen(
      Ctx ctx, int AD_Client_ID, ArrayList<Integer> orgs, Timestamp DateAcct, String DocBaseType) {
    if (DateAcct == null) return "@NotFound@ @DateAcct@";
    if (DocBaseType == null) return "@NotFound@ @DocBaseType@";

    MAcctSchema as = MClient.get(ctx, AD_Client_ID).getAcctSchema();
    if (as == null) return "@NotFound@ @C_AcctSchema_ID@ for AD_Client_ID=" + AD_Client_ID;
    if (as.isAutoPeriodControl()) {
      if (as.isAutoPeriodControlOpen(DateAcct)) return null;
      else return "@PeriodClosed@ - @AutoPeriodControl@";
    }

    //	Get all Calendars in line with Organizations
    MClientInfo clientInfo = MClientInfo.get(ctx, AD_Client_ID, null);
    ArrayList<Integer> orgCalendars = new ArrayList<Integer>();
    ArrayList<Integer> calendars = new ArrayList<Integer>();
    for (int org : orgs) {
      MOrgInfo orgInfo = MOrgInfo.get(ctx, org, null);
      int C_Calendar_ID = orgInfo.getC_Calendar_ID();
      if (C_Calendar_ID == 0) C_Calendar_ID = clientInfo.getC_Calendar_ID();
      orgCalendars.add(C_Calendar_ID);
      if (!calendars.contains(C_Calendar_ID)) calendars.add(C_Calendar_ID);
    }
    //	Should not happen
    if (calendars.size() == 0) return "@NotFound@ @C_Calendar_ID@";

    //	For all Calendars get Periods
    for (int i = 0; i < calendars.size(); i++) {
      int C_Calendar_ID = calendars.get(i);
      MPeriod period = MPeriod.getOfCalendar(ctx, C_Calendar_ID, DateAcct);
      //	First Org for Calendar
      int AD_Org_ID = 0;
      for (int j = 0; j < orgCalendars.size(); j++) {
        if (orgCalendars.get(j) == C_Calendar_ID) {
          AD_Org_ID = orgs.get(j);
          break;
        }
      }
      if (period == null) {
        MCalendar cal = MCalendar.get(ctx, C_Calendar_ID);
        String date = DisplayType.getDateFormat(DisplayTypeConstants.Date).format(DateAcct);
        if (cal != null)
          return "@NotFound@ @C_Period_ID@: "
              + date
              + " - "
              + MOrg.get(ctx, AD_Org_ID).getName()
              + " -> "
              + cal.getName();
        else
          return "@NotFound@ @C_Period_ID@: "
              + date
              + " - "
              + MOrg.get(ctx, AD_Org_ID).getName()
              + " -> C_Calendar_ID="
              + C_Calendar_ID;
      }
      String error = period.isOpen(DocBaseType, DateAcct);
      if (error != null)
        return error
            + " - "
            + MOrg.get(ctx, AD_Org_ID).getName()
            + " -> "
            + MCalendar.get(ctx, C_Calendar_ID).getName();
    }
    return null; //	open
  } //	isOpen