Exemple #1
0
 /** 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;
 }
  /** 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);
    }
  }
 /**
  * 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);
   }
 }
    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;
      }
    }
  /**
   * 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);
  }
 /**
  * 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;
 }
Exemple #7
0
 /**
  * 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
Exemple #8
0
  @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);
    }
  }
 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);
     }
   }
 }
  /** 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) {
      }
    }
  }
 /**
  * Parses the files passed into the <CODE>setTemplateFiles</CODE> method. The data extracted from
  * the template files is returned.
  */
 public void parse() {
   setMessage("Parsing Files");
   templates.clear();
   importedFieldCount = 0;
   importedMacroCount = 0;
   File[] templateFiles = getTemplateFiles();
   resetParseCanceled();
   int totalFileSize = 0;
   for (int i = 0; i < templateFiles.length; i++)
     if (templateFiles[i].exists()) totalFileSize += (int) templateFiles[i].length();
   setProgressMaximum(totalFileSize);
   int progress = 0;
   setProgressValue(0);
   setProgressIndeterminate(false);
   for (int i = 0; i < templateFiles.length; i++) {
     String currentFilePath = templateFiles[i].getAbsolutePath();
     Timestamp modifiedDate = new Timestamp(templateFiles[i].lastModified());
     Template currentTemplate = new Template(currentFilePath, modifiedDate);
     String[] nameParts = templateFiles[i].getName().split("\\.");
     if (nameParts != null && nameParts.length > 0) currentTemplate.setID(nameParts[0]);
     templates.add(currentTemplate);
     try {
       BufferedReader iStream = new BufferedReader(new FileReader(templateFiles[i]));
       try {
         String currentLine = iStream.readLine();
         Signal currentSignal = null, archiveTag = null;
         ArchiveRequest request = null;
         ArchiveGroup group = null;
         HashMap archiveSignals = new HashMap();
         int lineNumber = 0;
         int braceCount = 0;
         while (currentLine != null) // null indicates EOF
         {
           lineNumber++;
           if (currentLine.trim().startsWith("#")) // Comments start with #
           {
             // Comments start with #. Archive information is embedded in comments.
             ArchiveGroup newGroup = parseArchiveGroupTag(currentLine, currentTemplate);
             if (newGroup != null) group = newGroup;
             else {
               ArchiveRequest newRequest =
                   parseArchiveRequestTag(currentLine, group, currentTemplate);
               if (newRequest != null) request = newRequest;
               else {
                 Signal newArchiveTag = parseArchiveTag(currentLine);
                 if (newArchiveTag != null) {
                   if (archiveTag != null) // Tag was not used in request. Use for defaults.
                   archiveSignals.put(archiveTag.getID(), archiveTag);
                   archiveTag = newArchiveTag;
                 }
               }
             }
           } else {
             Matcher macroMatcher = macroPattern.matcher(currentLine);
             if (macroMatcher.find()) {
               String macro = macroMatcher.group(1);
               if (!currentTemplate.containsMacro(macro)) {
                 importedMacroCount++;
                 currentTemplate.addMacro(macro);
               }
             }
             int linePosition = 0;
             int lineLength = currentLine.length();
             while (linePosition < lineLength) {
               int openBracePosition = currentLine.indexOf('{', linePosition);
               int closeBracePosition = currentLine.indexOf('}', linePosition);
               if (currentSignal == null || braceCount == 0) {
                 // Got no signal or the brace was never opened...
                 Matcher recordMatcher = recordPattern.matcher(currentLine);
                 if (recordMatcher.find(linePosition))
                   if (openBracePosition < 0 || recordMatcher.start() < openBracePosition) {
                     linePosition = recordMatcher.end();
                     SignalType currentSignalType = new SignalType();
                     String recordType = recordMatcher.group(1);
                     currentSignalType.setRecordType(new EpicsRecordType(recordType));
                     String signalID = recordMatcher.group(2);
                     currentSignal = new Signal(signalID);
                     currentSignal.setType(currentSignalType);
                     if (archiveTag != null)
                       archiveSignals.put(archiveTag.getID(), archiveTag); // Use as defaults.
                     archiveTag = (Signal) archiveSignals.get(signalID);
                     if (archiveTag != null) {
                       currentSignal.setArchiveIndicator("Y");
                       currentSignal.setArchiveType(archiveTag.getArchiveType());
                       currentSignal.setArchiveFrequency(archiveTag.getArchiveFrequency());
                       // Must use a new instance of signal since each request has different
                       // values for type, frequency, etc.
                       if (request != null && request.getSignal(signalID) == null)
                         request.addSignal(new Signal(signalID));
                       currentSignal.setArchiveIndicator("Y");
                       currentSignal.setArchiveType(archiveTag.getArchiveType());
                       currentSignal.setArchiveFrequency(archiveTag.getArchiveFrequency());
                     }
                     currentTemplate.addSignal(currentSignal);
                     archiveTag = null; // Reset so is not used twice.
                     continue; // Go back and check the line position against length.
                   }
               }
               if (braceCount == 0 && currentSignal != null && openBracePosition >= linePosition) {
                 // Got the signal, need the open brace.
                 linePosition = openBracePosition + 1;
                 braceCount++;
                 continue; // Go back and check the line position against length.
               }
               if (braceCount > 0) {
                 // Looking for fields or the close brace.
                 Matcher fieldMatcher = fieldPattern.matcher(currentLine);
                 if (fieldMatcher.find(linePosition))
                   if (closeBracePosition < 0 || fieldMatcher.start() < closeBracePosition) {
                     // Found a field...
                     linePosition = fieldMatcher.end();
                     SignalField currentField = new SignalField();
                     String currentFieldID = fieldMatcher.group(1);
                     currentField.setType(new SignalFieldType(currentFieldID));
                     currentField.setValue(fieldMatcher.group(2));
                     currentSignal.addField(currentField);
                     importedFieldCount++;
                     continue;
                   }
                 if (closeBracePosition >= 0) {
                   // Found end of current signal.
                   braceCount--;
                   linePosition = closeBracePosition + 1;
                   currentSignal = null;
                   continue;
                 }
               }
               linePosition = lineLength;
               if (isParseCanceled()) break;
             }
           }
           progress += currentLine.length() + 1;
           setProgressValue(progress);
           currentLine = iStream.readLine();
           if (isParseCanceled()) break;
         }
       } finally {
         iStream.close();
       }
     } catch (java.io.FileNotFoundException ex) {
       StringBuffer errorMessage = new StringBuffer("<HTML><FONT COLOR=RED>Unable to open file '");
       errorMessage.append(templateFiles[i].getAbsoluteFile());
       errorMessage.append("'.</FONT></HTML>");
       addMessage(errorMessage.toString());
     } catch (java.io.IOException ex) {
       ex.printStackTrace();
       StringBuffer errorMessage = new StringBuffer("<HTML><FONT COLOR=RED>IO Error: ");
       errorMessage.append(ex.getMessage());
       errorMessage.append("</FONT></HTML>");
       addMessage(errorMessage.toString());
     }
     if (isParseCanceled()) break;
   }
 }
  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();
      }
    }
  }
  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();
      }
    }
  }
  // </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();
    }
  }
Exemple #15
0
  /** Create data. */
  private void createData() {
    try {
      String[] categories = new String[] {"Hardware", "Software"};
      String[][] subCategories =
          new String[][] {
            {"PC", "Monitor", "Printer"},
            {"O.S.", "IDEs", "Office Appl.", "Database", "Games", "Other SW"}
          };
      String[] agents = new String[] {"Agent 1", "Agent 2", "Agent 3"};
      String[] countries = new String[] {"Italy", "France", "Germany", "Other"};
      String[][] zones =
          new String[][] {
            {"North Italy", "Center Italy", "South Italy"},
            {"Paris", "Outside Paris"},
            {"East", "West"},
            {"Iberica Peninsula", "U.K. & Ireland", "Be.Ne.Lux.", "East Europe"}
          };
      HashMap items = new HashMap();
      items.put("PC", new String[] {"Dell", "HP"});
      items.put("Monitor", new String[] {"LG", "Sony", "Philips"});
      items.put("Printer", new String[] {"HP", "Epson"});
      items.put("O.S.", new String[] {"Windows", "Linux", "Mac"});
      items.put("IDEs", new String[] {"JBuilder", "IBM RAD", "MS Visual Studio .NET"});
      items.put("Office Appl.", new String[] {"MS Office 2007", "Open Office"});
      items.put("Database", new String[] {"Oracle", "MS SQLServer", "Sybase", "IBM DB2"});
      items.put("Games", new String[] {"Need4Speed", "Fifa"});
      items.put("Other SW", new String[] {"Norton AV", "Photoshop"});

      FileOutputStream out = new FileOutputStream("orders.txt");
      String line = null;
      int i = 0;
      Calendar cal = Calendar.getInstance();
      cal.set(cal.YEAR, 2007);
      cal.set(cal.MONTH, 0);
      cal.set(cal.DAY_OF_MONTH, 1);
      cal.set(cal.HOUR_OF_DAY, 0);
      cal.set(cal.MINUTE, 0);
      cal.set(cal.SECOND, 0);
      cal.set(cal.MILLISECOND, 0);
      long t = cal.getTimeInMillis();
      SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
      String date = null;
      int maxRows = 2000000;
      String[] ii = null;
      String[] sub = null;
      String[] z = null;
      do {
        date = sdf.format(new java.util.Date(t));
        for (int k1 = 0; k1 < categories.length; k1++) {
          sub = subCategories[k1];
          for (int k2 = 0; k2 < sub.length; k2++) {
            if (i >= maxRows) break;
            for (int k3 = 0; k3 < countries.length; k3++) {
              z = zones[k3];
              for (int k4 = 0; k4 < z.length; k4++)
                for (int k5 = 0; k5 < agents.length; k5++) {
                  if (i >= maxRows) break;
                  ii = (String[]) items.get(sub[k2]);
                  for (int k6 = 0; k6 < ii.length; k6++) {
                    if (i >= maxRows) break;

                    line =
                        date
                            + ";"
                            + categories[k1]
                            + ";"
                            + sub[k2]
                            + ";"
                            + countries[k3]
                            + ";"
                            + z[k4]
                            + ";"
                            + agents[k5]
                            + ";"
                            + ii[k6]
                            + ";"
                            + new BigDecimal(Math.random() * 10)
                                .setScale(0, BigDecimal.ROUND_HALF_UP)
                            + ";"
                            + new BigDecimal(Math.random() * 1000)
                                .setScale(2, BigDecimal.ROUND_HALF_UP)
                            + ";"
                            + "\n";
                    out.write(line.getBytes());
                    out.flush();
                    i++;
                  }
                }
            }
          }
        }
        t += 86400000;
      } while (i < maxRows);
      out.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
Exemple #16
0
  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());
  }
Exemple #17
0
 /** Converts from DS SQL types to Java types, e.g. "STRING" -> "java.lang.String". */
 public static String getJavaTypeFromSQLType(String sqlType) {
   return conversionTypes.get(sqlType);
 }