コード例 #1
0
ファイル: SubSystemView.java プロジェクト: jackrain/framework
  /**
   * @param request
   * @param subSystemId
   * @return
   */
  private boolean containsViewableActions(HttpServletRequest request, SubSystem ss) {
    List<WebAction> list = ss.getWebActions();
    Connection conn = null;
    try {
      UserWebImpl userWeb =
          ((UserWebImpl)
              WebUtils.getSessionContextManager(request.getSession())
                  .getActor(nds.util.WebKeys.USER));
      conn = QueryEngine.getInstance().getConnection();
      HashMap webActionEnv = new HashMap();
      webActionEnv.put("connection", conn);
      webActionEnv.put("httpservletrequest", request);
      webActionEnv.put("userweb", userWeb);

      for (int i = 0; i < list.size(); i++) {
        WebAction wa = list.get(i);
        if (wa.canDisplay(webActionEnv)) {
          return true;
        }
      }
    } catch (Throwable t) {
      logger.error("Fail to load subsystem webaction", t);
    } finally {
      try {
        if (conn != null) conn.close();
      } catch (Throwable te) {
      }
    }
    return false;
  }
コード例 #2
0
ファイル: Scriptlet.java プロジェクト: WilkerDiaz/Compiere
 /**
  * Set Environment key to value
  *
  * @param key variable name ('#' will be vonverted to '_')
  * @param value
  */
 public void setEnvironment(String key, Object value) {
   if (key != null && key.length() > 0) {
     //	log.fine( "Scriptlet.setEnvironment " + key, value);
     if (value == null) m_ctx.remove(key);
     else m_ctx.put(convertKey(key), value);
   }
 } //  SetEnvironment
コード例 #3
0
  public String updateModifiedOnlySql(ValueObject obj, String[] fields) throws SQLException {

    if ((obj instanceof PT_KICA_ERR_LOGEntity) == false) {
      throw new SQLException("DAO 에러(1): PT_KICA_ERR_LOG : updateModifiedOnly() ");
    }
    PT_KICA_ERR_LOGEntity entity = (PT_KICA_ERR_LOGEntity) obj;

    HashMap clobs = new HashMap();

    if (fields == null) throw new SQLException("Field Name can not be Null");

    StringBuffer setString = new StringBuffer();
    boolean flag = false;
    for (int i = 0; i < fields.length; i++) {
      if (fields[i] == null) throw new SQLException("Field Name can not be Null");
      if (default_update_field.containsKey(fields[i]) == false) {
        if (flag) setString.append(",");
        flag = true;
        if (clobs.containsKey(fields[i])) {
          setString.append(fields[i]).append("=?");
        } else {
          setString.append(fields[i]).append("=").append(toDB(entity.getByName(fields[i])));
        }
      }
    }
    if (flag = false) throw new SQLException("Nothing to update");

    StringBuffer sb = new StringBuffer();
    sb.append("update PT_KICA_ERR_LOG  set ").append(setString.toString()).append(" where  1=1 ");

    sb.append(" and SEQ = ").append(toDB(entity.getSEQ()));

    return sb.toString();
  }
コード例 #4
0
ファイル: LongObject.java プロジェクト: exss/replicatoros
  /**
   * puts the value for the column aginst the column Name
   *
   * @param os
   * @param rows
   * @param oldResultSet
   * @param index
   * @param modifiedColumns
   * @param columnName
   * @throws SQLException
   * @throws IOException
   */
  public void writeUpdate(
      Writer os,
      ResultSet rows,
      ResultSet oldResultSet,
      int index,
      HashMap modifiedColumns,
      String columnName,
      ArrayList encodedCols)
      throws SQLException, IOException {
    Object newObject = rows.getObject(index);
    Object oldObject = oldResultSet.getObject(index);

    if (newObject == null) {
      write(os, "NULL", encodedCols, columnName);
      if (oldObject != null) {
        modifiedColumns.put(columnName, "NULL");
      }
    } else {
      write(os, newObject, encodedCols, columnName);
      if (oldObject != null) {
        if (!(newObject.equals(oldObject))) {
          modifiedColumns.put(columnName, newObject);
        }
      } else {
        modifiedColumns.put(columnName, newObject);
      }
    }
  }
コード例 #5
0
  /** Looks up the local database, creating if necessary. */
  private DataSource findDatabaseImpl(String url, String driverName) throws SQLException {
    try {
      synchronized (_databaseMap) {
        DBPool db = _databaseMap.get(url);

        if (db == null) {
          db = new DBPool();

          db.setVar(url + "-" + _gId++);

          DriverConfig driver = db.createDriver();

          ClassLoader loader = Thread.currentThread().getContextClassLoader();

          Class driverClass = Class.forName(driverName, false, loader);

          driver.setType(driverClass);
          driver.setURL(url);

          db.init();

          _databaseMap.put(url, db);
        }

        return db;
      }
    } catch (RuntimeException e) {
      throw e;
    } catch (SQLException e) {
      throw e;
    } catch (Exception e) {
      throw ConfigException.create(e);
    }
  }
コード例 #6
0
ファイル: SubSystemView.java プロジェクト: jackrain/framework
  /**
   * @param request
   * @param tableCategoryId
   * @paqram includeAction if true, will load webactions also
   * @return elements are Table or WebAction
   */
  public List getChildrenOfTableCategory(
      HttpServletRequest request, int tableCategoryId, boolean includeAction) {
    TableManager manager = TableManager.getInstance();

    WebAction action;
    ArrayList cats = new ArrayList();
    Connection conn = null;
    HashMap webActionEnv = null;
    Table table;
    UserWebImpl userWeb =
        ((UserWebImpl)
            WebUtils.getSessionContextManager(request.getSession())
                .getActor(nds.util.WebKeys.USER));

    TableCategory tc = manager.getTableCategory(tableCategoryId);
    List children = tc.children();
    ArrayList catschild = new ArrayList();
    try {
      if (includeAction) {
        conn = QueryEngine.getInstance().getConnection();
        webActionEnv = new HashMap();
        webActionEnv.put("connection", conn);
        webActionEnv.put("httpservletrequest", request);
        webActionEnv.put("userweb", userWeb);
      }
      for (int j = 0; j < children.size(); j++) {
        if (children.get(j) instanceof Table) {
          table = (Table) children.get(j);
          if (!table.isMenuObject()) {
            continue;
          }
          try {
            WebUtils.checkTableQueryPermission(table.getName(), request);
          } catch (NDSSecurityException e) {
            continue;
          }
          // table is ok for current user to list
          catschild.add(table);
        } else if (children.get(j) instanceof WebAction) {
          if (includeAction) {
            action = (WebAction) children.get(j);
            if (action.canDisplay(webActionEnv)) catschild.add(action);
          }
        } else {
          throw new NDSRuntimeException(
              "Unsupported element in TableCategory children:" + children.get(j).getClass());
        }
      }
    } catch (Throwable t) {
      logger.error("Fail to load subsystem tree", t);
    } finally {
      try {
        if (conn != null) conn.close();
      } catch (Throwable e) {
      }
    }
    return catschild;
  }
コード例 #7
0
 /**
  * The main program for the DictCachService class
  *
  * @param args The command line arguments
  */
 public static void main(String[] args) {
   HashMap h = DictCachService.getInstance().getDictSql("select * from tab");
   HashMap h2 = DictCachService.getInstance().getDictSql("select * from tab");
   HashMap hash = DictCachService.getInstance().getDictSql("select code ,name from t_kouan");
   Iterator itor1 = hash.keySet().iterator();
   while (itor1.hasNext()) {
     String code = (String) itor1.next();
     String text = (String) hash.get(code);
     System.out.println(code + "  " + text);
   }
 }
コード例 #8
0
  /**
   * Creates a NamedParameterStatement. Wraps a call to c.{@link
   * Connection#prepareStatement(java.lang.String) prepareStatement}.
   *
   * @param conn the database connection
   * @param sql the parameterized sql
   * @throws SQLException if the statement could not be created
   */
  public NamedParameterStatement(Connection conn, String sql) throws SQLException {
    if (nameIndexCache.containsKey(sql)) {
      nameIndexMap = nameIndexCache.get(sql);
      parsedSql = parsedSqlCache.get(sql);
    } else {
      nameIndexMap = new HashMap<String, List<Integer>>();
      parsedSql = parseNamedSql(sql, nameIndexMap);

      nameIndexCache.put(sql, nameIndexMap);
      parsedSqlCache.put(sql, parsedSql);
    }
    ps = conn.prepareStatement(parsedSql);
  }
コード例 #9
0
ファイル: SqlConnect.java プロジェクト: fpapai/basex
 /**
  * Parses connection options.
  *
  * @param options options
  * @return connection properties
  */
 private static Properties connProps(final HashMap<String, String> options) {
   final Properties props = new Properties();
   for (final Entry<String, String> entry : options.entrySet()) {
     props.setProperty(entry.getKey(), entry.getValue());
   }
   return props;
 }
コード例 #10
0
ファイル: Scriptlet.java プロジェクト: WilkerDiaz/Compiere
 /**
  * Set Environment for Interpreter
  *
  * @param i Interpreter
  */
 private void loadEnvironment(Interpreter i) {
   if (m_ctx == null) return;
   Iterator<String> it = m_ctx.keySet().iterator();
   while (it.hasNext()) {
     String key = it.next();
     Object value = m_ctx.get(key);
     try {
       if (value instanceof Boolean) i.set(key, ((Boolean) value).booleanValue());
       else if (value instanceof Integer) i.set(key, ((Integer) value).intValue());
       else if (value instanceof Double) i.set(key, ((Double) value).doubleValue());
       else i.set(key, value);
     } catch (EvalError ee) {
       log.log(Level.SEVERE, "", ee);
     }
   }
 } //  setEnvironment
コード例 #11
0
ファイル: DBUtils.java プロジェクト: GayashanNA/carbon-data
 /** Converts from XML schema types to DS SQL types, e.g. "string" -> "STRING". */
 public static String getSQLTypeFromXsdType(String xsdType) {
   String sqlType = xsdSqlTypeMap.get(xsdType);
   if (sqlType == null) {
     sqlType = DBConstants.DataTypes.STRING;
   }
   return sqlType;
 }
コード例 #12
0
ファイル: Scriptlet.java プロジェクト: WilkerDiaz/Compiere
  /**
   * Set Environment key to value
   *
   * @param key variable name ('#' will be converted to '_')
   * @param stringValue try to convert to Object
   */
  public void setEnvironment(String key, String stringValue) {
    if (key == null || key.length() == 0) return;
    //	log.fine( "Scriptlet.setEnvironment " + key, stringValue);
    if (stringValue == null) {
      m_ctx.remove(key);
      return;
    }

    //  Boolean
    if (stringValue.equals("Y")) {
      m_ctx.put(convertKey(key), Boolean.valueOf(true));
      return;
    }
    if (stringValue.equals("N")) {
      m_ctx.put(convertKey(key), Boolean.valueOf(false));
      return;
    }

    //  Timestamp
    Timestamp timeValue = null;
    try {
      timeValue = Timestamp.valueOf(stringValue);
      m_ctx.put(convertKey(key), timeValue);
      return;
    } catch (Exception e) {
    }

    //  Numeric
    Integer intValue = null;
    try {
      intValue = Integer.valueOf(stringValue);
    } catch (NumberFormatException e) {
    }
    Double doubleValue = null;
    try {
      doubleValue = Double.valueOf(stringValue);
    } catch (NumberFormatException e) {
    }
    if (doubleValue != null) {
      if (intValue != null) {
        double di = Double.parseDouble(intValue.toString());
        //  the numbers are the same -> integer
        if (Double.compare(di, doubleValue.doubleValue()) == 0) {
          m_ctx.put(convertKey(key), intValue);
          return;
        }
      }
      m_ctx.put(convertKey(key), doubleValue);
      return;
    }
    if (intValue != null) {
      m_ctx.put(convertKey(key), intValue);
      return;
    }
    m_ctx.put(convertKey(key), stringValue);
  } //  SetEnvironment
コード例 #13
0
 public String getTextOfDic(String strSql) {
   String returnValue = "";
   Debug.getAppErrLogger().debug("get select text's sql is:" + strSql);
   if (strSql != null && !strSql.equals("")) {
     HashMap hp = getDictSql(strSql);
     Iterator it = hp.keySet().iterator();
     String sText = "";
     while (it.hasNext()) {
       sText = (String) it.next() + ",";
     }
     if (sText.length() > 0 && sText.lastIndexOf(",") == (sText.length() - 1)) {
       sText = sText.substring(0, sText.lastIndexOf(","));
     }
     returnValue = sText;
   }
   return returnValue;
 }
コード例 #14
0
ファイル: Sql2oTest.java プロジェクト: 22221cjp/sql2o
  public Sql2oTest(Driver driverToRegister, String url, String user, String pass, String testName) {

    if (driverToRegister != null) {
      try {
        DriverManager.registerDriver(driverToRegister);
      } catch (SQLException e) {
        throw new RuntimeException(
            "could not register driver '" + driverToRegister.getClass().getName() + "'", e);
      }
    }

    this.sql2o = new Sql2o(url, user, pass);

    HashMap<String, String> defaultColumnMap = new HashMap<String, String>();
    defaultColumnMap.put("ID", "id");
    defaultColumnMap.put("NAME", "name");
    defaultColumnMap.put("EMAIL", "email");
    defaultColumnMap.put("TEXT", "text");
    defaultColumnMap.put("ANUMBER", "aNumber");
    defaultColumnMap.put("ALONGNUMBER", "aLongNumber");
    sql2o.setDefaultColumnMappings(defaultColumnMap);

    this.url = url;
    this.user = user;
    this.pass = pass;

    if ("HyperSQL DB test".equals(testName)) {
      sql2o.createQuery("set database sql syntax MSS true").executeUpdate();
    }
  }
コード例 #15
0
  private void loadNewDict(String sql) {
    Debug.getAppErrLogger().debug("------------------------------------------------load:" + sql);

    HashMap htemp = new HashMap();
    Statement state = null;
    ResultSet rs_dic = null;
    try {
      if (conn != null) {
        conn.close();
        conn = null;
      }
      getConnection();
      state = conn.createStatement();
      rs_dic = state.executeQuery(sql);
      while (rs_dic.next()) {
        String text = rs_dic.getString(1);
        String value = rs_dic.getString(2);
        if (null != text && value != null) {
          htemp.put(text.trim(), value.trim());
        }
      }
      hashCache.put(sql, htemp);
      rs_dic.close();
      state.close();
    } catch (Exception e) {
      e.printStackTrace();
      Debug.getAppErrLogger().error(e);
    } finally {
      try {
        if (rs_dic != null) {
          rs_dic.close();
          rs_dic = null;
        }
        if (state != null) {
          state.close();
          state = null;
        }
      } catch (Exception e) {
        Debug.getAppErrLogger().error("Inside DictCachService::loadNewDict() - 关闭时出错!\n" + e);
      }
      close();
    }
  }
コード例 #16
0
 /**
  * Builds the HashSet which will be used to test whether the given methods can be exempted or not
  */
 void buildHashSet() {
   Class<Clob> iface = Clob.class;
   for (int i = 0; i < emd.length; i++) {
     try {
       Method m = iface.getMethod(emd[i].getMethodName(), emd[i].getParams());
       excludedMethodSet.put(m, emd[i]);
     } catch (NoSuchMethodException nsme) {
       fail("The method could not be found in the interface");
     }
   }
 }
コード例 #17
0
    public int compare(Object path1, Object path2) {
      long date1 = hmTimestamps.get((Path) path1).longValue();
      long date2 = hmTimestamps.get((Path) path2).longValue();

      if (date1 > date2) {
        return 1;
      } else if (date1 < date2) {
        return -1;
      } else {
        return 0;
      }
    }
コード例 #18
0
ファイル: SqlConnect.java プロジェクト: fpapai/basex
  @Override
  public Item item(final QueryContext qc, final InputInfo ii) throws QueryException {
    checkCreate(qc);
    // URL to relational database
    final String url = string(toToken(exprs[0], qc));
    final JDBCConnections jdbc = jdbc(qc);
    try {
      if (exprs.length > 2) {
        // credentials
        final String user = string(toToken(exprs[1], qc));
        final String pass = string(toToken(exprs[2], qc));
        if (exprs.length == 4) {
          // connection options
          final Options opts = toOptions(3, Q_OPTIONS, new Options(), qc);
          // extract auto-commit mode from options
          boolean ac = true;
          final HashMap<String, String> options = opts.free();
          final String commit = options.get(AUTO_COMM);
          if (commit != null) {
            ac = Strings.yes(commit);
            options.remove(AUTO_COMM);
          }
          // connection properties
          final Properties props = connProps(options);
          props.setProperty(USER, user);
          props.setProperty(PASS, pass);

          // open connection
          final Connection conn = getConnection(url, props);
          // set auto/commit mode
          conn.setAutoCommit(ac);
          return Int.get(jdbc.add(conn));
        }
        return Int.get(jdbc.add(getConnection(url, user, pass)));
      }
      return Int.get(jdbc.add(getConnection(url)));
    } catch (final SQLException ex) {
      throw BXSQ_ERROR_X.get(info, ex);
    }
  }
コード例 #19
0
 public void renderTable(HashMap<String, String> tipeKolom) {
   // tipeKolom = 1#Z#HCODE
   // tipeKolom = 1#D#NONE
   // tipeKolom = 1#N#FORMAT
   for (int i = 0; i < tipeKolom.size(); i++) {
     String temp = tipeKolom.get(i + "");
     String data[] = temp.split("#");
     int no = 0;
     try {
       no = Integer.parseInt(data[0].trim());
     } catch (Exception e) {
       no = 0;
     }
     if (data[1].trim().equals("Z")) {
       Function.setColumnRender(this, data[2], no);
     } else if (data[1].trim().equals("D")) {
       Function.setColumnRenderDate(this, data[2], no);
     } else if (data[1].trim().equals("N")) {
       Function.setColumnRenderNumeric(this, no);
     }
   }
 }
コード例 #20
0
 /**
  * Checks if the method is to be exempted from testing or not.
  *
  * @param m the method to check for exemption
  * @return <code>false</code> if the method shall be tested, <code>true</code> if the method is
  *     exempted and shall not be tested.
  */
 boolean checkIfExempted(Method m) {
   ExemptClobMD md = excludedMethodSet.get(m);
   boolean isExempted = false;
   if (md != null) {
     if (usingDerbyNetClient()) {
       isExempted = md.getIfClientFramework();
     } else if (usingEmbedded()) {
       isExempted = md.getIfEmbeddedFramework();
     } else {
       fail("Unknown test environment/framework");
     }
   }
   return isExempted;
 }
コード例 #21
0
  public LoadItemVariantsBean() {
    productVariants.put("ITM11_VARIANTS_1", "ITM16_PRODUCT_VARIANTS_1");
    productVariants.put("ITM12_VARIANTS_2", "ITM17_PRODUCT_VARIANTS_2");
    productVariants.put("ITM13_VARIANTS_3", "ITM18_PRODUCT_VARIANTS_3");
    productVariants.put("ITM14_VARIANTS_4", "ITM19_PRODUCT_VARIANTS_4");
    productVariants.put("ITM15_VARIANTS_5", "ITM20_PRODUCT_VARIANTS_5");

    variantTypes.put("ITM11_VARIANTS_1", "ITM06_VARIANT_TYPES_1");
    variantTypes.put("ITM12_VARIANTS_2", "ITM07_VARIANT_TYPES_2");
    variantTypes.put("ITM13_VARIANTS_3", "ITM08_VARIANT_TYPES_3");
    variantTypes.put("ITM14_VARIANTS_4", "ITM09_VARIANT_TYPES_4");
    variantTypes.put("ITM15_VARIANTS_5", "ITM10_VARIANT_TYPES_5");

    variantTypeJoins.put("ITM11_VARIANTS_1", "VARIANT_TYPE_ITM06");
    variantTypeJoins.put("ITM12_VARIANTS_2", "VARIANT_TYPE_ITM07");
    variantTypeJoins.put("ITM13_VARIANTS_3", "VARIANT_TYPE_ITM08");
    variantTypeJoins.put("ITM14_VARIANTS_4", "VARIANT_TYPE_ITM09");
    variantTypeJoins.put("ITM15_VARIANTS_5", "VARIANT_TYPE_ITM10");

    variantCodeJoins.put("ITM11_VARIANTS_1", "VARIANT_CODE_ITM11");
    variantCodeJoins.put("ITM12_VARIANTS_2", "VARIANT_CODE_ITM12");
    variantCodeJoins.put("ITM13_VARIANTS_3", "VARIANT_CODE_ITM13");
    variantCodeJoins.put("ITM14_VARIANTS_4", "VARIANT_CODE_ITM14");
    variantCodeJoins.put("ITM15_VARIANTS_5", "VARIANT_CODE_ITM15");
  }
コード例 #22
0
  /**
   * Method to go though the HDFS filesystem in a DFS to find all files
   *
   * <p>fs:FileSystem object from HDFS minDate: Oldest date for files to be backed up maxDate:Newest
   * date for files to be backed up p:Path in HDFS to look for files pathList:Will be filled with
   * all files in p hmTimestamps: hashmap of timestamps for later sorting
   */
  public void checkDir(
      FileSystem fs,
      long minDate,
      long maxDate,
      Path p,
      ArrayList<Path> pathList,
      HashMap<Path, Long> hmTimestamps) {
    long tmpDate;
    FileStatus[] fStat;

    try {
      String sPath = p.toUri().getPath();

      // If this is a directory
      if (fs.getFileStatus(p).isDir()) {
        // ignore certain directories
        if ("dfstmp".equals(p.getName())
            || "tmp".equals(p.getName())
            || "jobtracker".equals(p.getName())
            || sPath.startsWith("/mapred")
            || "ops".equals(p.getName())
            || p.getName().startsWith("_distcp_logs")) {
          return;
        }

        // dump the mkdir and chmod commands for this
        // directory -- skip root directory only
        {
          FileStatus stat = fs.getFileStatus(p);

          if (!sPath.equals("/")) {
            m_wrMkdirs.println("hadoop fs -mkdir " + sPath);
          }

          m_wrChmods.println(
              "hadoop fs -chown " + stat.getOwner() + ":" + stat.getGroup() + " " + sPath);

          Short sh = new Short(stat.getPermission().toShort());
          m_wrChmods.println(
              "hadoop fs -chmod " + Long.toOctalString(sh.longValue()) + " " + sPath);
        }

        fStat = fs.listStatus(p);

        // Do a recursive call to all elements
        for (int i = 0; i < fStat.length; i++) {
          checkDir(fs, minDate, maxDate, fStat[i].getPath(), pathList, hmTimestamps);
        }
      } else {
        // If not a directory then we've found a file

        // ignore crc files
        if (p.getName().endsWith(".crc")) {
          return;
        }

        // ignore other files
        if (sPath.startsWith("/user/oozie/etl/workflows/")) {
          return;
        }

        // try to get the table name from the path. There are
        // various types of tables, from those replicated from
        // another database to regular hive tables to
        // partitioned hive tables.  We use table names to
        // both exclude some from the backup, and for the rest
        // to dump out the schema and partition name.
        if (m_ignoreTables != null && m_ignoreTables.doIgnoreFile(sPath)) {
          m_nIgnoredTables++;

          if (m_nIgnoredTables < 5) {
            System.out.println("Skipping ignore-table file: " + sPath);
          } else if (m_nIgnoredTables == 5) {
            System.out.println("(...not showing other skipped tables...)");
          }
          return;
        }

        FileStatus stat = fs.getFileStatus(p);

        tmpDate = stat.getModificationTime() / 1000;

        // store the chmods/chowns for all files
        m_wrChmods.println(
            "hadoop fs -chown " + stat.getOwner() + ":" + stat.getGroup() + " " + sPath);

        m_wrChmods.println("hadoop fs -chmod " + stat.getPermission().toShort() + " " + sPath);

        // check dates.  is it too young?
        if (tmpDate < minDate) {
          return;
        }

        // is the file too recent?
        if (tmpDate > maxDate) {
          // System.out.println("file too recent: " + sPath);
          return;
        }

        // file timestamp is ok
        pathList.add(p);

        hmTimestamps.put(p, new Long(tmpDate));

        // store info about total bytes neeed to backup
        m_nTotalBytes += fs.getContentSummary(p).getLength();
      }
    } catch (IOException e) {
      System.err.println("ERROR: could not open " + p + ": " + e);

      // System.exit(1) ;
    }
  }
コード例 #23
0
  /** 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) {
      }
    }
  }
コード例 #24
0
  public void InsertDataTable() {
    for (int i = 0; i < dataBaru.size(); i++) {
      try {
        rowSet.moveToInsertRow();
        for (int ii = 0; ii < insertKolom.size(); ii++) {
          String temp = insertKolom.get(ii + "");
          String data[] = temp.split("#");
          int no = 0;
          boolean constanta = false;
          if (data[1].trim().toLowerCase().equals("c")) {
            constanta = true;
          } else {
            try {
              no = Integer.parseInt(data[1].trim());
            } catch (Exception e) {
              no = 0;
            }
          }
          if (data[0].trim().toLowerCase().contains("i")) {
            if (data[2].trim().toLowerCase().equals("boolean")) {
              String value = "";
              if (data[4].trim().toLowerCase().equals("int")) {
                if (getValueAt(
                        new Integer(dataBaru.get(i).toString()), Integer.parseInt(data[1].trim()))
                    .toString()
                    .equals("true")) {
                  if (data[5].trim().equals("1") || data[5].trim().equals("0")) {
                    value = "1";
                  } else {
                    value = "Y";
                  }
                } else {
                  if (data[5].trim().equals("1") || data[5].trim().equals("0")) {
                    value = "0";
                  } else {
                    value = "N";
                  }
                }
                try {
                  rowSet.updateInt(data[3].trim().toString(), Integer.parseInt(value));
                } catch (Exception e) {
                  e.printStackTrace();
                }
              } else {
                if (getValueAt(
                        new Integer(dataBaru.get(i).toString()), Integer.parseInt(data[1].trim()))
                    .toString()
                    .equals("true")) {
                  if (data[5].trim().equals("1") || data[5].trim().equals("0")) {
                    value = "1";
                  } else {
                    value = "Y";
                  }
                } else {
                  if (data[5].trim().equals("1") || data[5].trim().equals("0")) {
                    value = "0";
                  } else {
                    value = "N";
                  }
                }
                try {
                  rowSet.updateString(data[3].trim().toString(), value.trim());
                } catch (Exception e) {
                  e.printStackTrace();
                }
              }

            } else if (data[2].trim().toLowerCase().equals("date")) {
              String value = "";
              java.util.Date dd =
                  (java.util.Date) getValueAt(new Integer(dataBaru.get(i).toString()), no);
              if (data[4].equals("dd-MM-yyyy")) {
                value = Function.dateToString(dd);
              } else if (data[4].equals("MM-yyyy")) {
                value = Function.monthToString(dd).trim();
              } else if (data[4].equals("yyyy")) {
                //                                    value = Function.yearToDate(sql);
                JOptionPane.showMessageDialog(null, "Belom Support");
              }
              //                            JOptionPane.showMessageDialog(null, value.length());
              try {
                rowSet.updateString(data[3].trim().toString(), value.trim());
              } catch (Exception e) {
                e.printStackTrace();
              }
            } else if (data[2].trim().toLowerCase().equals("string")
                || data[2].trim().toLowerCase().equals("numeric")) {
              String value = "";
              if (constanta) {
                value = data[6].trim();
              } else {
                try {
                  value = getValueAt(new Integer(dataBaru.get(i).toString()), no).toString();
                } catch (Exception e) {
                  try {
                    value = getValueAt(new Integer(dataBaru.get(i).toString()), no).toString();
                  } catch (Exception ee) {
                    value = "";
                  }
                }
              }
              if (data[4].trim().toLowerCase().equals("int")) {
                try {
                  if (value.trim().equals("")) {
                    value = "0";
                  }
                  rowSet.updateLong(data[3].trim().toString(), Long.parseLong(value.trim()));
                } catch (Exception e) {
                  e.printStackTrace();
                }
              } else {
                try {
                  rowSet.updateString(data[3].trim().toString(), value.trim());
                } catch (Exception e) {
                  e.printStackTrace();
                }
              }
            } else if (data[2].trim().toLowerCase().equals("combo")) {
              String value = "";
              String valueKolom = "";
              try {
                valueKolom =
                    getValueAt(new Integer(dataBaru.get(i).toString()), no).toString().trim();
              } catch (Exception e) {
                valueKolom = "";
              }
              try {
                value = Function.getValueFromCell(data[5].trim(), valueKolom);
              } catch (Exception e) {
                value = "";
              }
              if (data[4].trim().toLowerCase().equals("int")) {
                try {
                  rowSet.updateString(data[3].trim().toString(), value.trim());
                } catch (Exception e) {
                  e.printStackTrace();
                }
              } else {
                try {
                  rowSet.updateString(data[3].trim().toString(), value.trim());
                } catch (Exception e) {
                  e.printStackTrace();
                }
              }
            }
          }
        }
        //                JOptionPane.showMessageDialog(null, rowSet.getCommand());
        rowSet.insertRow();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
コード例 #25
0
  public void updateDataTable() {
    for (int i = 0; i < dataAsli.size(); i++) {
      try {
        rowSet.absolute(new Integer(dataAsli.elementAt(i).toString()));
        if (rowSet.next()) {
          for (int ii = 0; ii < updateKolom.size(); ii++) {
            String temp = updateKolom.get(ii + "");
            String data[] = temp.split("#");
            int no = 0;
            try {
              no = Integer.parseInt(data[1].trim());
            } catch (Exception e) {
              no = 0;
            }
            if (data[0].trim().toLowerCase().contains("u")) {
              if (data[2].trim().toLowerCase().equals("boolean")) {
                String value = "";
                if (data[4].trim().toLowerCase().equals("int")) {
                  if (getValueAt(
                          new Integer(dataAsli.get(i).toString()), Integer.parseInt(data[1].trim()))
                      .toString()
                      .equals("true")) {
                    if (data[5].trim().equals("1") || data[5].trim().equals("0")) {
                      value = "1";
                    } else {
                      value = "Y";
                    }
                  } else {
                    if (data[5].trim().equals("1") || data[5].trim().equals("0")) {
                      value = "0";
                    } else {
                      value = "N";
                    }
                  }
                  try {
                    rowSet.updateInt(data[3].trim().toString(), Integer.parseInt(value));
                  } catch (Exception e) {
                    e.printStackTrace();
                  }
                } else {
                  if (getValueAt(
                          new Integer(dataAsli.get(i).toString()), Integer.parseInt(data[1].trim()))
                      .toString()
                      .equals("true")) {
                    if (data[5].trim().equals("1") || data[5].trim().equals("0")) {
                      value = "1";
                    } else {
                      value = "Y";
                    }
                  } else {
                    if (data[5].trim().equals("1") || data[5].trim().equals("0")) {
                      value = "0";
                    } else {
                      value = "N";
                    }
                  }
                  try {
                    rowSet.updateString(data[3].trim().toString(), value.trim());
                  } catch (Exception e) {
                    e.printStackTrace();
                  }
                }

              } else if (data[2].trim().toLowerCase().equals("date")) {
                String value = "";
                java.util.Date dd =
                    (java.util.Date) getValueAt(new Integer(dataAsli.get(i).toString()), no);
                if (data[4].equals("dd-MM-yyyy")) {
                  value = Function.dateToString(dd);
                } else if (data[4].equals("MM-yyyy")) {
                  value = Function.monthToString(dd);
                } else if (data[4].equals("yyyy")) {
                  //                                    value = Function.yearToDate(sql);
                  JOptionPane.showMessageDialog(null, "Belom Support");
                }
                try {
                  rowSet.updateString(data[3].trim().toString(), value.trim());
                } catch (Exception e) {
                  e.printStackTrace();
                }
              } else if (data[2].trim().toLowerCase().equals("string")
                  || data[2].trim().toLowerCase().equals("numeric")) {
                String value = "";
                String data1 = data[1].trim();
                if (data1 == null || data1.equals("")) {
                  data1 = "0";
                }
                try {
                  value = getValueAt(new Integer(dataAsli.get(i).toString()), no).toString();
                } catch (Exception e) {
                  //                                    e.printStackTrace();
                  try {
                    value = getValueAt(new Integer(dataAsli.get(i).toString()), no).toString();
                  } catch (Exception ee) {
                    value = "";
                    //                                        e.printStackTrace();
                  }
                }
                if (data[4].trim().toLowerCase().equals("int")) {
                  try {
                    if (value.trim().equals("")) {
                      value = "0";
                    }
                    rowSet.updateLong(data[3].trim().toString(), Long.parseLong(value.trim()));
                  } catch (Exception e) {
                    e.printStackTrace();
                  }
                } else {
                  try {
                    rowSet.updateString(data[3].trim().toString(), value.trim());
                  } catch (Exception e) {
                    e.printStackTrace();
                  }
                }
              } else if (data[2].trim().toLowerCase().equals("combo")) {
                String value = "";
                value =
                    Function.getValueFromCell(
                        data[5].trim(),
                        getValueAt(new Integer(dataAsli.get(i).toString()), no).toString().trim());
                if (data[4].trim().toLowerCase().equals("int")) {
                  try {
                    rowSet.updateString(data[3].trim().toString(), value.trim());
                  } catch (Exception e) {
                    e.printStackTrace();
                  }
                } else {
                  try {
                    rowSet.updateString(data[3].trim().toString(), value.trim());
                  } catch (Exception e) {
                    e.printStackTrace();
                  }
                }
              }
            }
          }
          rowSet.updateRow();
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
コード例 #26
0
  // </editor-fold>
  // <editor-fold defaultstate="collapsed" desc="Select Table">
  public void selectTabel(DefaultTableModel tableM) {
    setModelTable(tableM);
    try {
      dataAsli = new Vector();
      rowSet.setCommand(sql);
      rowSet.execute();
      DefaultTableModel dtm = (DefaultTableModel) getModel();
      int i = 0;

      // tipeKolom =
      // untukASIU#noKolomJtable#tipeKolomJTable#namaKolomDB#tipeKolom#atributKolom#nilaiKolom
      // tipeKolom = boolean, Date, String, combo, Int, Numeric
      while (rowSet.next()) {
        Object[] dede = new Object[selectKolom.size()];
        for (int ii = 0; ii < selectKolom.size(); ii++) {
          String temp = selectKolom.get(ii + "");
          String data[] = temp.split("#");
          int no = 0;
          try {
            no = Integer.parseInt(data[1].trim());
          } catch (Exception e) {
            no = 0;
          }
          if (data[0].trim().toLowerCase().contains("s")) {
            if (data[2].trim().toLowerCase().equals("boolean")) {
              boolean value = false;
              if (data[4].trim().toLowerCase().equals("int")) {
                if (rowSet.getInt(data[3].trim()) == Integer.parseInt(data[5].trim())) {
                  value = true;
                } else {
                  value = false;
                }
              } else {
                if (rowSet.getString(data[3].trim()).equals(data[5].trim())) {
                  value = true;
                } else {
                  value = false;
                }
              }
              dede[no] = value;
            } else if (data[2].trim().toLowerCase().equals("date")) {
              java.util.Date value = new java.util.Date();
              if (data[4].equals("dd-MM-yyyy")) {
                value = Function.dateStringToDate(rowSet.getString(data[3].trim()));
              } else if (data[4].equals("MM-yyyy")) {
                value = Function.stringToMonth(rowSet.getString(data[3].trim()));
              } else if (data[4].equals("yyyy")) {
                value = Function.yearToDate(rowSet.getString(data[3].trim()));
              }
              dede[no] = value;
            } else if (data[2].trim().toLowerCase().equals("string")
                || data[2].trim().toLowerCase().equals("combo")
                || data[2].trim().toLowerCase().equals("numeric")) {
              String value = "";
              if (data[4].trim().toLowerCase().equals("int")) {
                value = rowSet.getLong(data[3].trim()) + "";
              } else {
                value = rowSet.getString(data[3].trim());
              }
              dede[no] = value;
            }
          }
        }
        dtm.addRow(dede);
        dataAsli.add(i);
        i++;
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
コード例 #27
0
  /** Business logic to execute. */
  public VOListResponse loadItemVariants(GridParams pars, String serverLanguageId, String username)
      throws Throwable {

    PreparedStatement pstmt = null;

    Connection conn = null;
    try {
      if (this.conn == null) conn = getConn();
      else conn = this.conn;

      String tableName = (String) pars.getOtherGridParams().get(ApplicationConsts.TABLE_NAME);
      ItemPK pk = (ItemPK) pars.getOtherGridParams().get(ApplicationConsts.ITEM_PK);
      String productVariant = (String) productVariants.get(tableName);
      String variantType = (String) variantTypes.get(tableName);
      String variantTypeJoin = (String) variantTypeJoins.get(tableName);
      String variantCodeJoin = (String) variantCodeJoins.get(tableName);

      String sql =
          "select "
              + tableName
              + "."
              + variantTypeJoin
              + ","
              + tableName
              + ".VARIANT_CODE,A.DESCRIPTION,B.DESCRIPTION, "
              + tableName
              + ".PROGRESSIVE_SYS10,"
              + variantType
              + ".PROGRESSIVE_SYS10 "
              + "from "
              + tableName
              + ","
              + variantType
              + ",SYS10_COMPANY_TRANSLATIONS A,SYS10_COMPANY_TRANSLATIONS B "
              + "where "
              + tableName
              + ".COMPANY_CODE_SYS01=? and "
              + tableName
              + ".COMPANY_CODE_SYS01="
              + variantType
              + ".COMPANY_CODE_SYS01 and "
              + tableName
              + "."
              + variantTypeJoin
              + "="
              + variantType
              + ".VARIANT_TYPE and "
              + tableName
              + ".COMPANY_CODE_SYS01=A.COMPANY_CODE_SYS01 and "
              + tableName
              + ".PROGRESSIVE_SYS10=A.PROGRESSIVE and A.LANGUAGE_CODE=? and "
              + variantType
              + ".COMPANY_CODE_SYS01=B.COMPANY_CODE_SYS01 and "
              + variantType
              + ".PROGRESSIVE_SYS10=B.PROGRESSIVE and B.LANGUAGE_CODE=? and "
              + tableName
              + ".ENABLED='Y' and "
              + variantType
              + ".ENABLED='Y' and "
              + // and not "+tableName+"."+variantTypeJoin+"=? and "+
              "not "
              + tableName
              + ".VARIANT_CODE=? "
              + "order by "
              + tableName
              + "."
              + variantTypeJoin
              + ","
              + tableName
              + ".CODE_ORDER";

      Map attribute2dbField = new HashMap();
      attribute2dbField.put("variantType", tableName + "." + variantTypeJoin);
      attribute2dbField.put("variantCode", tableName + ".VARIANT_CODE");
      attribute2dbField.put("variantDesc", "A.DESCRIPTION");
      attribute2dbField.put("variantTypeDesc", "B.DESCRIPTION");
      attribute2dbField.put("variantProgressiveSys10", tableName + ".PROGRESSIVE_SYS10");
      attribute2dbField.put("variantTypeProgressiveSys10", variantType + ".PROGRESSIVE_SYS10");

      ArrayList values = new ArrayList();
      values.add(pk.getCompanyCodeSys01ITM01());
      values.add(serverLanguageId);
      values.add(serverLanguageId);
      // values.add(ApplicationConsts.JOLLY);
      values.add(ApplicationConsts.JOLLY);

      // read from ITMxxx table...
      Response answer =
          QueryUtil.getQuery(
              conn,
              new UserSessionParameters(username),
              sql,
              values,
              attribute2dbField,
              ItemVariantVO.class,
              "Y",
              "N",
              null,
              pars,
              50,
              true);

      if (!answer.isError()) {
        java.util.List vos = ((VOListResponse) answer).getRows();
        HashMap map = new HashMap();
        ItemVariantVO vo = null;
        for (int i = 0; i < vos.size(); i++) {
          vo = (ItemVariantVO) vos.get(i);
          vo.setCompanyCodeSys01(pk.getCompanyCodeSys01ITM01());
          vo.setItemCodeItm01(pk.getItemCodeITM01());
          vo.setTableName(tableName);
          map.put(vo.getVariantType() + "." + vo.getVariantCode(), vo);
        }

        pstmt =
            conn.prepareStatement(
                "select "
                    + productVariant
                    + "."
                    + variantTypeJoin
                    + ","
                    + productVariant
                    + "."
                    + variantCodeJoin
                    + " "
                    + "from "
                    + productVariant
                    + " "
                    + "where "
                    + productVariant
                    + ".COMPANY_CODE_SYS01=? and "
                    + productVariant
                    + ".ITEM_CODE_ITM01=? and "
                    + productVariant
                    + ".ENABLED='Y' ");
        pstmt.setString(1, pk.getCompanyCodeSys01ITM01());
        pstmt.setString(2, pk.getItemCodeITM01());
        ResultSet rset = pstmt.executeQuery();

        while (rset.next()) {
          vo = (ItemVariantVO) map.get(rset.getString(1) + "." + rset.getString(2));
          if (vo != null) vo.setSelected(Boolean.TRUE);
        }
        rset.close();
        pstmt.close();
      }

      if (answer.isError()) throw new Exception(answer.getErrorMessage());
      else return (VOListResponse) answer;

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

      } catch (Exception exx) {
      }
    }
  }
コード例 #28
0
ファイル: ReplicateTables.java プロジェクト: kuznecc/javaz
 static {
   dbQuotes.put(TYPE_MYSQL, "`");
 }
コード例 #29
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) {
      }
    }
  }
コード例 #30
0
ファイル: ReplicateTables.java プロジェクト: kuznecc/javaz
  public void runReplicate() throws InterruptedException {
    if (verbose) log.append("Started at " + Calendar.getInstance().getTime() + "\r\n");
    Connection connectionFrom = null;
    Connection connectionTo = null;
    try {
      connectionFrom = providerI.getConnection(dbFrom);
      connectionTo = providerI.getConnection(dbTo);
      PreparedStatement preparedStatementFrom = null;
      PreparedStatement preparedStatementTo = null;
      ResultSet resultSet = null;

      for (Iterator<HashMap<String, String>> HashMapIterator = tables.iterator();
          HashMapIterator.hasNext(); ) {
        try {
          HashMap<String, String> h = HashMapIterator.next();
          String name = h.get("name");
          String name2 = h.get("name2");
          String where1 = h.get("where1");
          String where2 = h.get("where2");

          if (verbose)
            log.append("Replicating " + dbFrom + "/" + name + " to " + dbTo + "/" + name2 + "\r\n");

          preparedStatementFrom =
              connectionFrom.prepareStatement("select * from " + name + " WHERE 1=1 " + where1);
          boolean b = preparedStatementFrom.execute();
          HashMap meta = new HashMap();
          // 1. find all ids from DB1
          ArrayList db1 = new ArrayList();
          String nullMark = "____NULL";
          if (b) {
            resultSet = preparedStatementFrom.getResultSet();
            ResultSetMetaData setMetaData = resultSet.getMetaData();
            for (int i = 1; i <= setMetaData.getColumnCount(); i++) {
              meta.put(
                  setMetaData.getColumnLabel(i).toLowerCase(), setMetaData.getColumnClassName(i));
            }
            while (resultSet.next()) {
              HashMap results = new HashMap();
              for (int i = 1; i <= setMetaData.getColumnCount(); i++) {
                String columnName = setMetaData.getColumnLabel(i).toLowerCase();
                Object o = resultSet.getObject(i);
                if (o != null) {
                  results.put(columnName, o);
                } else {
                  results.put(columnName + nullMark, nullMark);
                }
              }
              db1.add(results);
            }
            resultSet.close();
          } else {
            log.append("Couldn't execute select from " + dbFrom + "/" + name + " /r/n");
            return;
          }

          StringBuffer allIds = new StringBuffer();
          HashMap records1 = new HashMap();
          HashMap toInsert = new HashMap();
          HashMap toUpdate = new HashMap();
          for (Iterator iterator = db1.iterator(); iterator.hasNext(); ) {
            HashMap record = (HashMap) iterator.next();
            if (allIds.length() != 0) {
              allIds.append(",");
            }
            allIds.append(record.get("id"));
            records1.put(record.get("id"), record);
          }

          toInsert.putAll(records1);

          // 2. find all ids to delete in DB2;
          if (allIds.length() > 0) {
            preparedStatementTo =
                connectionTo.prepareStatement(
                    "delete from "
                        + name2
                        + " where id not in ("
                        + allIds.toString()
                        + ")"
                        + where2);
            if (verbose)
              log.append(
                  "deleted from "
                      + dbTo
                      + "/"
                      + name2
                      + " "
                      + preparedStatementTo.executeUpdate()
                      + " records;\r\n");
          } else {
            if (verbose)
              log.append(
                  "No records in "
                      + dbFrom
                      + "/"
                      + name
                      + ", nothing to delete in "
                      + dbTo
                      + "/"
                      + name2
                      + " ;\r\n");
          }

          // 3. find all ids from DB2;
          preparedStatementTo =
              connectionTo.prepareStatement("select * from " + name2 + " WHERE 1=1 " + where2);
          b = preparedStatementTo.execute();
          HashMap meta2 = new HashMap();
          ArrayList db2 = new ArrayList();
          if (b) {
            resultSet = preparedStatementTo.getResultSet();
            ResultSetMetaData setMetaData = resultSet.getMetaData();
            for (int i = 1; i <= setMetaData.getColumnCount(); i++) {
              meta2.put(
                  setMetaData.getColumnLabel(i).toLowerCase(), setMetaData.getColumnClassName(i));
            }
            while (resultSet.next()) {
              HashMap results = new HashMap();
              for (int i = 1; i <= setMetaData.getColumnCount(); i++) {
                String columnName = setMetaData.getColumnLabel(i).toLowerCase();
                Object o = resultSet.getObject(i);
                if (o != null) {
                  results.put(columnName, o);
                } else {
                  results.put(columnName + nullMark, nullMark);
                }
              }
              db2.add(results);
            }
          } else {
            log.append("Couldn't execute select from " + dbTo + "/" + name2 + " /r/n");
            return;
          }

          // compare meta-data;
          {
            HashMap temp = new HashMap();
            {
              temp.putAll(meta);

              Set set = meta2.keySet();
              for (Iterator iteratorSet = set.iterator(); iteratorSet.hasNext(); ) {
                Object o = iteratorSet.next();
                if (meta.containsKey(o)) {
                  if (meta.get(o).equals(meta2.get(o))) {
                    temp.remove(o);
                  }
                } else {
                  log.append("ERROR: Meta data not equals! \r\n");
                  log.append(o + "\t" + temp.get(o) + " not present in table " + name + "\r\n");
                }
              }
            }
            if (!temp.isEmpty()) {
              log.append("ERROR: Meta data not equals! \r\n");
              Set set = temp.keySet();
              for (Iterator iteratorSet = set.iterator(); iteratorSet.hasNext(); ) {
                Object o = iteratorSet.next();
                log.append(o + "\t" + temp.get(o) + " != " + meta2.get(o) + "\r\n");
              }

              return;
            }
          }

          for (Iterator iterator = db2.iterator(); iterator.hasNext(); ) {
            HashMap db2Record = (HashMap) iterator.next();
            if (toInsert.containsKey(db2Record.get("id"))) {
              HashMap db1Record = (HashMap) toInsert.get(db2Record.get("id"));
              boolean equal = true;
              Set set = meta2.keySet();
              for (Iterator iteratorSet = set.iterator(); equal && iteratorSet.hasNext(); ) {
                String columnName2 = (String) iteratorSet.next();
                if (db2Record.containsKey(columnName2 + nullMark)
                    || db1Record.containsKey(columnName2 + nullMark)) {
                  equal =
                      db2Record.containsKey(columnName2 + nullMark)
                          && db1Record.containsKey(columnName2 + nullMark);
                } else {
                  // checking not-null;
                  equal = equalRecords(db1Record.get(columnName2), db2Record.get(columnName2));
                }
              }
              if (!equal) {
                toUpdate.put(db2Record.get("id"), toInsert.get(db2Record.get("id")));
              }
              toInsert.remove(db2Record.get("id"));
            } else {
              // this case shouldn't happen at all, since we've deleted all such records

            }
          }

          log.append(
              "Found "
                  + toUpdate.size()
                  + " to update, and "
                  + toInsert.size()
                  + " to insert.\r\n");
          int totalUpdated = 0;
          // 4. calculate all to update in DB2
          if (!toUpdate.isEmpty()) {
            Set set = toUpdate.keySet();
            for (Iterator iteratorSet = set.iterator(); iteratorSet.hasNext(); ) {
              StringBuffer sql = new StringBuffer();
              Object id = iteratorSet.next();
              HashMap r = (HashMap) toUpdate.get(id);
              sql.append("UPDATE " + name2 + " SET ");
              StringBuffer values = new StringBuffer();

              Set en = meta2.keySet();
              for (Iterator iteratorSetEn = en.iterator(); iteratorSetEn.hasNext(); ) {
                Object o = iteratorSetEn.next();
                if (!o.equals("id")) {
                  if (values.length() != 0) {
                    values.append(",");
                  }
                  Object quote = dbQuotes.get(dbToType);
                  if (quote == null) {
                    quote = "";
                  }
                  values.append(quote).append(o).append(quote);
                  values.append(" =  ? ");
                }
              }
              values.append(" WHERE id = '" + r.get("id") + "';");
              PreparedStatement statement =
                  connectionTo.prepareStatement(sql.toString() + values.toString());
              en = meta2.keySet();
              int i = 0;
              for (Iterator iteratorSetEn = en.iterator(); iteratorSetEn.hasNext(); ) {
                Object o = iteratorSetEn.next();
                if (!o.equals("id")) {
                  i++;
                  statement.setObject(i, r.get(o));
                }
              }
              try {
                totalUpdated += statement.executeUpdate();
              } catch (SQLException e) {
                e.printStackTrace();
                log.append("Error occured: " + e + "\r\n");
              }
            }
          }
          if (verbose) log.append("Updated " + totalUpdated + " records.\r\n");

          // 4. calculate all to insert to DB2
          if (!toInsert.isEmpty()) {
            StringBuffer header = new StringBuffer();
            if (header.length() == 0) {
              header.append(" INSERT INTO " + name2 + " (");
              StringBuffer columns = new StringBuffer();
              Set en = meta2.keySet();
              for (Iterator iteratorSetEn = en.iterator(); iteratorSetEn.hasNext(); ) {
                Object o = iteratorSetEn.next();
                if (columns.length() != 0) {
                  columns.append(",");
                }

                Object quote = dbQuotes.get(dbToType);
                if (quote == null) {
                  quote = "";
                }
                columns.append(quote).append(o).append(quote);
              }
              header.append(columns.toString());
              header.append(") VALUES ");
            }

            Set enumeration = toInsert.keySet();
            for (Iterator iteratorSetX = enumeration.iterator(); iteratorSetX.hasNext(); ) {
              Object id = iteratorSetX.next();
              HashMap r = (HashMap) toInsert.get(id);
              StringBuffer values = new StringBuffer();
              if (values.length() != 0) {
                values.append(",");
              }
              values.append("(");

              StringBuffer columns = new StringBuffer();
              Set en = meta2.keySet();
              for (Iterator iteratorSetEn = en.iterator(); iteratorSetEn.hasNext(); ) {
                Object o = iteratorSetEn.next();
                if (columns.length() != 0) {
                  columns.append(",");
                }
                columns.append(" ? ");
              }
              values.append(columns.toString());
              values.append(");");

              PreparedStatement statement =
                  connectionTo.prepareStatement(header.toString() + values.toString());
              en = meta2.keySet();
              int i = 0;
              for (Iterator iteratorSetEn = en.iterator(); iteratorSetEn.hasNext(); ) {
                Object o = iteratorSetEn.next();
                i++;
                statement.setObject(i, r.get(o));
              }
              statement.execute();
            }
          }

          if (verbose) log.append("Replication finished OK.\r\n");
        } catch (Exception e) {
          log.append("Some error occured: " + e + "\r\n");
          log.append(e.getMessage() + "\r\n");
          e.printStackTrace();
        }
      }
    } catch (Exception e) {
      log.append("Error with query = " + e);
      log.append(e.getMessage());
      return;
    } finally {
      try {
        if (connectionFrom != null && !connectionFrom.isClosed()) {
          connectionFrom.close();
        }
      } catch (SQLException e) {
        e.printStackTrace();
      }
      try {
        if (connectionTo != null && !connectionTo.isClosed()) {
          connectionTo.close();
        }
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
    if (verbose) log.append("Ended at " + Calendar.getInstance().getTime());
  }