// execute and get results
  private void execute(Connection conn, String text, Writer writer, boolean commaSeparator)
      throws SQLException {

    BufferedWriter buffer = new BufferedWriter(writer);
    Statement stmt = conn.createStatement();
    stmt.execute(text);
    ResultSet rs = stmt.getResultSet();
    ResultSetMetaData metadata = rs.getMetaData();
    int nbCols = metadata.getColumnCount();
    String[] labels = new String[nbCols];
    int[] colwidths = new int[nbCols];
    int[] colpos = new int[nbCols];
    int linewidth = 1;

    // read each occurrence
    try {
      while (rs.next()) {
        for (int i = 0; i < nbCols; i++) {
          Object value = rs.getObject(i + 1);
          if (value != null) {
            buffer.write(value.toString());
            if (commaSeparator) buffer.write(",");
          }
        }
      }
      buffer.flush();
      rs.close();
    } catch (IOException ex) {
      if (Debug.isDebug()) ex.printStackTrace();
      // ok, exit from the loop
    } catch (SQLException ex) {
      if (Debug.isDebug()) ex.printStackTrace();
    }
  }
 public static void init() throws Exception {
   Properties props = new Properties();
   int pid = OSProcess.getId();
   String path = File.createTempFile("dunit-cachejta_", ".xml").getAbsolutePath();
   /** * Return file as string and then modify the string accordingly ** */
   String file_as_str = readFile(TestUtil.getResourcePath(CacheUtils.class, "cachejta.xml"));
   file_as_str = file_as_str.replaceAll("newDB", "newDB_" + pid);
   String modified_file_str = modifyFile(file_as_str);
   FileOutputStream fos = new FileOutputStream(path);
   BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(fos));
   wr.write(modified_file_str);
   wr.flush();
   wr.close();
   props.setProperty("cache-xml-file", path);
   //    String tableName = "";
   //		  props.setProperty("mcast-port", "10339");
   try {
     //			   ds = DistributedSystem.connect(props);
     ds = (new ExceptionsDUnitTest("temp")).getSystem(props);
     cache = CacheFactory.create(ds);
   } catch (Exception e) {
     e.printStackTrace(System.err);
     throw new Exception("" + e);
   }
 }
Exemplo n.º 3
0
  static void task1() throws FileNotFoundException, IOException, SQLException {
    // Read Input
    System.out.println("Task1 Started...");
    BufferedReader br = new BufferedReader(new FileReader(inputFile));
    br.readLine();
    String task1Input = br.readLine();
    br.close();
    double supportPercent =
        Double.parseDouble(task1Input.split(":")[1].split("=")[1].split("%")[0].trim());
    if (supportPercent >= 0) {
      System.out.println("Task1 Support Percent :" + supportPercent);
      // Prepare query
      String task1Sql =
          "select  temp.iname,(temp.counttrans/temp2.uniquetrans)*100 as percent"
              + " from (select i.itemname iname,count(t.transid) counttrans from trans t, items i"
              + " where i.itemid = t.itemid group by i.itemname having count(t.transid)>=(select count(distinct transid)*"
              + supportPercent / 100
              + " from trans)"
              + ") temp , (select count(distinct transid) uniquetrans from trans) temp2 order by percent";

      PreparedStatement selTask1 = con.prepareStatement(task1Sql);
      ResultSet rsTask1 = selTask1.executeQuery();

      BufferedWriter bw = new BufferedWriter(new FileWriter("system.out.1"));
      while (rsTask1.next()) {
        bw.write("{" + rsTask1.getString(1) + "}, s=" + rsTask1.getDouble(2) + "%");
        bw.newLine();
      }
      rsTask1.close();
      bw.close();
      System.out.println("Task1 Completed...\n");
    } else System.out.println("Support percent should be a positive number");
  }
Exemplo n.º 4
0
 public void ChangeData(String trans, String type) throws IOException {
   try {
     Statement stmt = conn.createStatement();
     int result = stmt.executeUpdate(trans);
     if (result != 0) {
       log.write(type + " SUCCESSFUL\n");
     }
   } catch (Exception ex) {
     log.write("\r\nERROR " + type + " not done\r\n");
     log.write(ex.toString() + "\r\n");
   }
 }
Exemplo n.º 5
0
  public static void main(String[] args) {
    BD bd = new BD();
    String lsTable = "pays";
    String lsContenu = "";
    lsContenu += "<?xml version='1.0' encoding='utf-8'?>\n";
    lsContenu += "<!-- " + lsTable + "Document.xml -->\n";
    lsContenu += "<" + lsTable + ">\n";

    String lsEnfant = lsTable.substring(0, lsTable.length() - 1);

    try {
      bd.seConnecter("cours", "root", "alonso");
      Connection lcn = bd.getConnexion();
      PreparedStatement lpst =
          lcn.prepareStatement("SELECT * FROM pays"); // paysSelect() ou villesSelect()
      ResultSet lrs = lpst.executeQuery();

      ResultSetMetaData lrsmd = lrs.getMetaData();

      int liCols = lrsmd.getColumnCount();

      while (lrs.next()) {
        lsContenu += "\t<" + lsEnfant + " ";

        for (int i = 1; i <= liCols; i++) {
          lsContenu += lrsmd.getColumnName(i) + "='" + lrs.getString(i) + "' ";
        }

        lsContenu += "/>\n";
      }

      lsContenu += "</" + lsTable + ">";

      System.out.println(lsContenu);

      FileWriter lfwFichier = new FileWriter(lsTable + ".xml"); // pays.csv ou villes.csv
      BufferedWriter lbwBuffer = new BufferedWriter(lfwFichier);
      lbwBuffer.write(lsContenu);
      lbwBuffer.close();
      lfwFichier.close();

      bd.seDeconnecter();

    } catch (Exception e) {
      System.out.println("Erreor : ");
    }
  }
Exemplo n.º 6
0
  public void RetrieveData(String trans) throws IOException {
    try {
      // create a Statement object
      Statement stmt = conn.createStatement();
      // Send the statement to the DBMS
      ResultSet rs = stmt.executeQuery(trans);
      ResultSetMetaData rsmd = rs.getMetaData();
      int numberOfColumns = rsmd.getColumnCount();

      while (rs.next()) {
        for (int i = 1; i <= numberOfColumns; i++) {
          log.write(rs.getString(i) + " ");
        }
        log.write("\n");
      }
      stmt.close();
    } catch (Exception ex) {
      log.write("\r\nERROR QUERY not done\r\n");
      log.write(ex.toString() + "\r\n");
    }
  }
Exemplo n.º 7
0
  private static void generateKML(boolean isHighway) {
    System.out.println("generate link kml...");
    try {
      FileWriter fstream =
          new FileWriter(root + "/" + (isHighway ? highwayKmlFile : arterialKmlFile));
      BufferedWriter out = new BufferedWriter(fstream);
      out.write("<kml><Document>");
      ArrayList<LinkInfo> linkList = isHighway ? highwayLinkList : arterialLinkList;
      for (int i = 0; i < linkList.size(); i++) {
        LinkInfo link = linkList.get(i);
        int linkId = link.getLinkId();
        int funcClass = link.getFuncClass();
        String streetName = link.getStreetName();
        if (streetName.contains("&")) streetName = streetName.replaceAll("&", " and ");
        ArrayList<PairInfo> nodeList = link.getNodeList();

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

        out.write(kmlStr);
      }
      out.write("</Document></kml>");
      out.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
    System.out.println("generate link kml finish!");
  }
  private void executeParsedFile(NameListMessage nameListMessage, ArrayList cmds) {
    BufferedWriter buffer = null;
    int connectionId = nameListMessage.connectionId;
    boolean commaSeparated = nameListMessage.commaSeparated;

    // get java.sql.Connection from connectionId
    Connection connection = ConnectionService.getConnection(connectionId);

    if (connection == null) {
      nameListMessage.errorMessage = kConnectionClosed;
    } else {

      try {
        Thread th = null;
        buffer = new BufferedWriter(writer);

        // if reader exists, create reading thread
        if (reader != null) {
          final ObjectNameReader objectReader = new ObjectNameReader(nameListMessage.nameList);

          // This thread will read stream until meets EOL (ie. when
          // writer is closed)
          th =
              new Thread() {
                public void run() {
                  objectReader.readInputFile(reader);
                }
              };
        } // end if

        // if no reader (offline reverse), never start the reading
        // thread
        // (because output is written down directly to the disk without
        // processing in counterpart).
        if (reader != null) th.start();

        // execute each SQL statement
        // we skip objects that don't need to be reversed
        Iterator iter = cmds.iterator();
        int index = -1;
        while (iter.hasNext()) {
          String cmd = (String) iter.next();
          index++;
          // check if this statement id is marked as <to skip>
          if (nameListMessage.ignoredStatementIds != null
              && nameListMessage.ignoredStatementIds.contains(new Integer(index))) {
            if (commaSeparated) {
              buffer.flush();
              buffer.newLine();
            }
            continue;
          }
          if (writer != null) {
            if (cmd != null) {
              try {
                execute(connection, cmd, buffer, commaSeparated);
              } catch (SQLException e) {
                if (Debug.isDebug()) e.printStackTrace();
                nameListMessage.errorMessage =
                    nameListMessage.errorMessage == null
                        ? e.toString()
                        : nameListMessage.errorMessage.concat("\n" + e.toString()); // NOT
                // LOCALIZABLE,
                // escape
                // code
              }
            }
            if (commaSeparated) {
              buffer.flush();
              buffer.newLine();
            }
          }
        }
      }
      /*
       * catch (SQLException ex) { if (Debug.isDebug()) ex.printStackTrace();
       * nameListMessage.errorMessage = nameListMessage.errorMessage == null ? ex.toString() :
       * nameListMessage.errorMessage.concat("\n" + ex.toString()); //NOT LOCALIZABLE, escape
       * code }
       */
      catch (IOException ex) {
        if (Debug.isDebug()) ex.printStackTrace();
        nameListMessage.errorMessage =
            nameListMessage.errorMessage == null
                ? ex.toString()
                : nameListMessage.errorMessage.concat(
                    "\n" + ex.toString()); // NOT LOCALIZABLE, escape
        // code
      }

      // close writer: the reading thread terminates.
      try {
        // WARNING: we must make a pause after closing the buffer
        // otherwise
        // the nameList variable won't be well initialized...strange!
        // [FG]
        buffer.close();
        Thread.sleep(400);
      } catch (IOException ex) {
      } catch (InterruptedException ex) {
      }
    } // end if
  } // end parseSqlFile()
Exemplo n.º 9
0
  static void task2() throws FileNotFoundException, IOException, SQLException {
    System.out.println("Task2 Started...");
    BufferedReader br = new BufferedReader(new FileReader(inputFile));
    br.readLine();
    br.readLine();
    String task2Input = br.readLine();
    br.close();
    double supportPercent =
        Double.parseDouble(task2Input.split(":")[1].split("=")[1].split("%")[0].trim());
    if (supportPercent >= 0) {
      System.out.println("Task2 Support percent:" + supportPercent);
      try {
        PreparedStatement dropView = con.prepareStatement("drop materialized view trans1");
        dropView.executeUpdate();
      } catch (SQLException e) {
      }
      // Creating materilalized view to filter out transactions as per apriori rule
      String sqlTransView =
          "create materialized view trans1(transid,itemid) as select * from trans where itemid in"
              + " (select itemid from trans group by itemid having count(*)>=(select count(distinct(transid))*"
              + supportPercent / 100
              + " from trans))";

      PreparedStatement createView = con.prepareStatement(sqlTransView);

      createView.executeUpdate();
      createView.close();
      // Using SQL from task1 to retrieve item sets of size 1.
      String task1Sql =
          "select  temp.iname,(temp.counttrans/temp2.uniquetrans)*100 as percent"
              + " from (select i.itemname iname,count(t.transid) counttrans from trans t, items i"
              + " where i.itemid = t.itemid group by i.itemname having count(t.transid)>=(select count(distinct transid)*"
              + supportPercent / 100
              + " from trans)"
              + ") temp , (select count(distinct transid) uniquetrans from trans) temp2 order by percent";

      PreparedStatement selTask1 = con.prepareStatement(task1Sql);
      ResultSet rsTask1 = selTask1.executeQuery();

      BufferedWriter bw = new BufferedWriter(new FileWriter("system.out.2"));
      while (rsTask1.next()) {
        bw.write("{" + rsTask1.getString(1) + "}, s=" + rsTask1.getDouble(2) + "%");
        bw.newLine();
      }
      rsTask1.close();
      selTask1.close();

      String task2Sql =
          "select  temp.iname1,temp.iname2,(temp.counttrans/temp2.uniquetrans)*100 as percent"
              + " from(select t1.itemid,t2.itemid,i1.itemname iname1,i2.itemname iname2,count(*) counttrans"
              + " from trans1 t1,trans1 t2,items i1,items i2 where t1.transid = t2.transid and t1.itemid = i1.itemid"
              + " and t2.itemid = i2.itemid and t1.itemid < t2.itemid group by t1.itemid,t2.itemid,i1.itemname,i2.itemname"
              + " having count(*)>=(select count(distinct transid)*"
              + supportPercent / 100
              + " from trans))  temp , (select count(distinct transid) uniquetrans from trans) temp2 order by percent";

      PreparedStatement selTask2 = con.prepareStatement(task2Sql);
      ResultSet rsTask2 = selTask2.executeQuery();

      while (rsTask2.next()) {
        bw.write(
            "{"
                + rsTask2.getString(1)
                + ", "
                + rsTask2.getString(2)
                + "}, s="
                + rsTask2.getDouble(3)
                + "%");
        bw.newLine();
      }
      rsTask2.close();
      selTask2.close();
      bw.close();
      System.out.println("Task2 Completed...\n");
    } else System.out.println("Support percent should be a positive number");
  }
Exemplo n.º 10
0
 public static void writeTransControlFile() throws IOException {
   BufferedWriter bw = new BufferedWriter(new FileWriter("trans.ctl"));
   bw.write("LOAD DATA");
   bw.newLine();
   bw.write("INFILE trans.dat");
   bw.newLine();
   bw.write("INTO TABLE trans");
   bw.newLine();
   bw.write("FIELDS TERMINATED BY ','");
   bw.newLine();
   bw.write("(transid,itemid)");
   bw.close();
 }
Exemplo n.º 11
0
 public static void writeItemsControlFile() throws IOException {
   BufferedWriter bw = new BufferedWriter(new FileWriter("items.ctl"));
   bw.write("LOAD DATA");
   bw.newLine();
   bw.write("INFILE items.dat");
   bw.newLine();
   bw.write("INTO TABLE items");
   bw.newLine();
   bw.write("FIELDS TERMINATED BY ',' optionally enclosed by X'27'");
   bw.newLine();
   bw.write("(itemid,itemname)");
   bw.close();
 }
Exemplo n.º 12
0
  static void task4()
      throws FileNotFoundException, IOException, InterruptedException, SQLException {
    System.out.println("Task4 Started...");
    BufferedReader br = new BufferedReader(new FileReader(inputFile));
    br.readLine();
    br.readLine();
    br.readLine();
    br.readLine();
    String task4Input = br.readLine();
    br.close();
    double supportPercent =
        Double.parseDouble(
            task4Input.split(":")[1].split(",")[0].split("=")[1].split("%")[0].trim());
    double confidence =
        Double.parseDouble(
            task4Input.split(":")[1].split(",")[1].split("=")[1].split("%")[0].trim());
    int size = Integer.parseInt(task4Input.split(":")[1].split(",")[2].split("=")[1].trim());
    if (supportPercent >= 0 && size >= 2 && confidence >= 0) {
      System.out.println("Task4 Confidence Percent: " + confidence);
      System.out.println("Task4 Support Percent: " + supportPercent);
      System.out.println("Task4 Size : " + size);

      BufferedWriter bw = new BufferedWriter(new FileWriter("system.out.4"));
      for (int i = 2; i <= size; i++) {
        CallableStatement cstmt = con.prepareCall("{CALL GenerateAR(?,?,?)}");
        cstmt.setDouble(1, confidence / 100);
        cstmt.setInt(2, i);
        cstmt.setDouble(3, supportPercent / 100);
        cstmt.executeQuery();

        String sqlTask4 = "select * from artable order by ruleid,confidence";
        PreparedStatement selTask4 = con.prepareStatement(sqlTask4);
        ResultSet rsTask4 = selTask4.executeQuery(sqlTask4);

        String leftSet = "";
        String rightSet = "";
        Boolean resultSetExhausted = false;
        String itemName;
        String isLeft;
        Double support;
        Double conf;
        if (rsTask4.next()) {
          while (true && !resultSetExhausted) {

            leftSet = "{";
            rightSet = "{";
            for (int j = 0; j < i; j++) {
              itemName = rsTask4.getString(3);
              isLeft = rsTask4.getString(5);
              // support = rsTask4.getBigDecimal(6);
              // conf = rsTask4.getBigDecimal(4);
              if (j == 0) {

                if (isLeft.equals("Y")) leftSet = leftSet + itemName;
                else rightSet = rightSet + itemName;
                if (!rsTask4.next()) {
                  resultSetExhausted = true;
                  break;
                }
              }
              if (j == i - 1) {
                if (isLeft.equals("Y")) {
                  if (leftSet.equals("{")) leftSet = leftSet + itemName;
                  else leftSet = leftSet + "," + itemName;
                } else {
                  if (rightSet.equals("{")) rightSet = rightSet + itemName;
                  else rightSet = rightSet + ", " + itemName;
                }

                leftSet = leftSet + "}";
                rightSet = rightSet + "}";
                String resultString =
                    "{"
                        + leftSet
                        + " - > "
                        + rightSet
                        + "} s="
                        + rsTask4.getDouble(6)
                        + "%, c="
                        + rsTask4.getDouble(4)
                        + "%";
                bw.write(resultString);
                bw.newLine();
                leftSet = "{";
                rightSet = "{";
                if (!rsTask4.next()) {
                  resultSetExhausted = true;
                  break;
                }
              }

              if (j > 0 && j < i - 1) {

                if (isLeft.equals("Y")) {
                  if (leftSet.equals("{")) leftSet = leftSet + itemName;
                  else leftSet = leftSet + ", " + itemName;
                } else {
                  if (rightSet.equals("{")) rightSet = rightSet + itemName;
                  else rightSet = rightSet + ", " + itemName;
                }
                if (!rsTask4.next()) {
                  resultSetExhausted = true;
                  break;
                }
              }
            }
          }
        }
      }
      bw.close();
      System.out.println("Task4 Completed...\n");
    } else
      System.out.println(
          "For Task4, supportPercent and confidence should be a positive numbers and size should be greater than or equal to 2");
  }
Exemplo n.º 13
0
  static void task3()
      throws FileNotFoundException, IOException, InterruptedException, SQLException {
    System.out.println("Task3 Started..");
    BufferedReader br = new BufferedReader(new FileReader(inputFile));
    br.readLine();
    br.readLine();
    br.readLine();
    String task3Input = br.readLine();
    br.close();
    double supportPercent =
        Double.parseDouble(
            task3Input.split(":")[1].split(",")[0].split("=")[1].split("%")[0].trim());
    int size = Integer.parseInt(task3Input.split(":")[1].split(",")[1].split("=")[1].trim());
    if (supportPercent >= 0 && size > 0) {
      System.out.println("Task3 Size : " + size);
      System.out.println("Task3 Support Percent: " + supportPercent);
      BufferedWriter bw = new BufferedWriter(new FileWriter("system.out.3"));
      for (int i = 1; i <= size; i++) {
        CallableStatement cstmt = con.prepareCall("{CALL GenerateFI(?,?)}");
        cstmt.setInt(1, i);
        cstmt.setDouble(2, supportPercent / 100);
        cstmt.executeQuery();

        String sqlTask3 =
            "select i.itemname,f.percent from FISet f ,items i where f.itemid = i.itemid order by f.percent,f.isetid";
        // String sqlTask3 = "select i.itemname,f.percent from FISet f ,items i where f.itemid =
        // i.itemid order by f.isetid";
        PreparedStatement selTask3 = con.prepareStatement(sqlTask3);
        ResultSet rsTask3 = selTask3.executeQuery(sqlTask3);

        int j = 1;
        String res = "";
        j = 1;
        while (rsTask3.next()) {

          if (j == 1) {

            res += "{";
          }
          res = res + rsTask3.getString(1);
          if (j == i) {
            res += "}, s=" + rsTask3.getDouble(2) + "%";
            bw.write(res);
            bw.newLine();
            j = 1;
            res = "";
          } else {
            res += ", ";
            j++;
          }
        }
        rsTask3.close();
        selTask3.close();
      }
      bw.close();
      System.out.println("Task3 Completed...\n");
    } else {
      System.out.println(
          "Support percent should a postive number and size should be a positive integer.");
    }
  }
Exemplo n.º 14
0
  /**
   * Convert an existing data object to the specified JDBC type.
   *
   * @param callerReference an object reference to the caller of this method; must be a <code>
   *     Connection</code>, <code>Statement</code> or <code>ResultSet</code>
   * @param x the data object to convert
   * @param jdbcType the required type constant from <code>java.sql.Types</code>
   * @return the converted data object
   * @throws SQLException if the conversion is not supported or fails
   */
  static Object convert(Object callerReference, Object x, int jdbcType, String charSet)
      throws SQLException {
    // handle null value
    if (x == null) {
      switch (jdbcType) {
        case java.sql.Types.BIT:
        case JtdsStatement.BOOLEAN:
          return Boolean.FALSE;

        case java.sql.Types.TINYINT:
        case java.sql.Types.SMALLINT:
        case java.sql.Types.INTEGER:
          return INTEGER_ZERO;

        case java.sql.Types.BIGINT:
          return LONG_ZERO;

        case java.sql.Types.REAL:
          return FLOAT_ZERO;

        case java.sql.Types.FLOAT:
        case java.sql.Types.DOUBLE:
          return DOUBLE_ZERO;

        default:
          return null;
      }
    }

    try {
      switch (jdbcType) {
        case java.sql.Types.TINYINT:
          if (x instanceof Boolean) {
            return ((Boolean) x).booleanValue() ? INTEGER_ONE : INTEGER_ZERO;
          } else if (x instanceof Byte) {
            return new Integer(((Byte) x).byteValue() & 0xFF);
          } else {
            long val;
            if (x instanceof Number) {
              val = ((Number) x).longValue();
            } else if (x instanceof String) {
              val = new Long(((String) x).trim()).longValue();
            } else {
              break;
            }
            if (val < Byte.MIN_VALUE || val > Byte.MAX_VALUE) {
              throw new SQLException(
                  Messages.get("error.convert.numericoverflow", x, getJdbcTypeName(jdbcType)),
                  "22003");
            } else {
              return new Integer(new Long(val).intValue());
            }
          }

        case java.sql.Types.SMALLINT:
          if (x instanceof Boolean) {
            return ((Boolean) x).booleanValue() ? INTEGER_ONE : INTEGER_ZERO;
          } else if (x instanceof Short) {
            return new Integer(((Short) x).shortValue());
          } else if (x instanceof Byte) {
            return new Integer(((Byte) x).byteValue() & 0xFF);
          } else {
            long val;
            if (x instanceof Number) {
              val = ((Number) x).longValue();
            } else if (x instanceof String) {
              val = new Long(((String) x).trim()).longValue();
            } else {
              break;
            }
            if (val < Short.MIN_VALUE || val > Short.MAX_VALUE) {
              throw new SQLException(
                  Messages.get("error.convert.numericoverflow", x, getJdbcTypeName(jdbcType)),
                  "22003");
            } else {
              return new Integer(new Long(val).intValue());
            }
          }

        case java.sql.Types.INTEGER:
          if (x instanceof Integer) {
            return x;
          } else if (x instanceof Boolean) {
            return ((Boolean) x).booleanValue() ? INTEGER_ONE : INTEGER_ZERO;
          } else if (x instanceof Short) {
            return new Integer(((Short) x).shortValue());
          } else if (x instanceof Byte) {
            return new Integer(((Byte) x).byteValue() & 0xFF);
          } else {
            long val;
            if (x instanceof Number) {
              val = ((Number) x).longValue();
            } else if (x instanceof String) {
              val = new Long(((String) x).trim()).longValue();
            } else {
              break;
            }
            if (val < Integer.MIN_VALUE || val > Integer.MAX_VALUE) {
              throw new SQLException(
                  Messages.get("error.convert.numericoverflow", x, getJdbcTypeName(jdbcType)),
                  "22003");
            } else {
              return new Integer(new Long(val).intValue());
            }
          }

        case java.sql.Types.BIGINT:
          if (x instanceof BigDecimal) {
            BigDecimal val = (BigDecimal) x;
            if (val.compareTo(MIN_VALUE_LONG_BD) < 0 || val.compareTo(MAX_VALUE_LONG_BD) > 0) {
              throw new SQLException(
                  Messages.get("error.convert.numericoverflow", x, getJdbcTypeName(jdbcType)),
                  "22003");
            } else {
              return new Long(val.longValue());
            }
          } else if (x instanceof Long) {
            return x;
          } else if (x instanceof Boolean) {
            return ((Boolean) x).booleanValue() ? LONG_ONE : LONG_ZERO;
          } else if (x instanceof Byte) {
            return new Long(((Byte) x).byteValue() & 0xFF);
          } else if (x instanceof BigInteger) {
            BigInteger val = (BigInteger) x;
            if (val.compareTo(MIN_VALUE_LONG_BI) < 0 || val.compareTo(MAX_VALUE_LONG_BI) > 0) {
              throw new SQLException(
                  Messages.get("error.convert.numericoverflow", x, getJdbcTypeName(jdbcType)),
                  "22003");
            } else {
              return new Long(val.longValue());
            }
          } else if (x instanceof Number) {
            return new Long(((Number) x).longValue());
          } else if (x instanceof String) {
            return new Long(((String) x).trim());
          } else {
            break;
          }

        case java.sql.Types.REAL:
          if (x instanceof Float) {
            return x;
          } else if (x instanceof Byte) {
            return new Float(((Byte) x).byteValue() & 0xFF);
          } else if (x instanceof Number) {
            return new Float(((Number) x).floatValue());
          } else if (x instanceof String) {
            return new Float(((String) x).trim());
          } else if (x instanceof Boolean) {
            return ((Boolean) x).booleanValue() ? FLOAT_ONE : FLOAT_ZERO;
          }

          break;

        case java.sql.Types.FLOAT:
        case java.sql.Types.DOUBLE:
          if (x instanceof Double) {
            return x;
          } else if (x instanceof Byte) {
            return new Double(((Byte) x).byteValue() & 0xFF);
          } else if (x instanceof Number) {
            return new Double(((Number) x).doubleValue());
          } else if (x instanceof String) {
            return new Double(((String) x).trim());
          } else if (x instanceof Boolean) {
            return ((Boolean) x).booleanValue() ? DOUBLE_ONE : DOUBLE_ZERO;
          }

          break;

        case java.sql.Types.NUMERIC:
        case java.sql.Types.DECIMAL:
          if (x instanceof BigDecimal) {
            return x;
          } else if (x instanceof Number) {
            return new BigDecimal(x.toString());
          } else if (x instanceof String) {
            return new BigDecimal((String) x);
          } else if (x instanceof Boolean) {
            return ((Boolean) x).booleanValue() ? BIG_DECIMAL_ONE : BIG_DECIMAL_ZERO;
          }

          break;

        case java.sql.Types.VARCHAR:
        case java.sql.Types.CHAR:
          if (x instanceof String) {
            return x;
          } else if (x instanceof Number) {
            return x.toString();
          } else if (x instanceof Boolean) {
            return ((Boolean) x).booleanValue() ? "1" : "0";
          } else if (x instanceof Clob) {
            Clob clob = (Clob) x;
            long length = clob.length();

            if (length > Integer.MAX_VALUE) {
              throw new SQLException(Messages.get("error.normalize.lobtoobig"), "22000");
            }

            return clob.getSubString(1, (int) length);
          } else if (x instanceof Blob) {
            Blob blob = (Blob) x;
            long length = blob.length();

            if (length > Integer.MAX_VALUE) {
              throw new SQLException(Messages.get("error.normalize.lobtoobig"), "22000");
            }

            x = blob.getBytes(1, (int) length);
          }

          if (x instanceof byte[]) {
            return toHex((byte[]) x);
          }

          return x.toString(); // Last hope!

        case java.sql.Types.BIT:
        case JtdsStatement.BOOLEAN:
          if (x instanceof Boolean) {
            return x;
          } else if (x instanceof Number) {
            return (((Number) x).intValue() == 0) ? Boolean.FALSE : Boolean.TRUE;
          } else if (x instanceof String) {
            String tmp = ((String) x).trim();

            return ("1".equals(tmp) || "true".equalsIgnoreCase(tmp)) ? Boolean.TRUE : Boolean.FALSE;
          }

          break;

        case java.sql.Types.VARBINARY:
        case java.sql.Types.BINARY:
          if (x instanceof byte[]) {
            return x;
          } else if (x instanceof Blob) {
            Blob blob = (Blob) x;

            return blob.getBytes(1, (int) blob.length());
          } else if (x instanceof Clob) {
            Clob clob = (Clob) x;
            long length = clob.length();

            if (length > Integer.MAX_VALUE) {
              throw new SQLException(Messages.get("error.normalize.lobtoobig"), "22000");
            }

            x = clob.getSubString(1, (int) length);
          }

          if (x instanceof String) {
            //
            // Strictly speaking this conversion is not required by
            // the JDBC standard but jTDS has always supported it.
            //
            if (charSet == null) {
              charSet = "ISO-8859-1";
            }

            try {
              return ((String) x).getBytes(charSet);
            } catch (UnsupportedEncodingException e) {
              return ((String) x).getBytes();
            }
          } else if (x instanceof UniqueIdentifier) {
            return ((UniqueIdentifier) x).getBytes();
          }

          break;

        case java.sql.Types.TIMESTAMP:
          if (x instanceof DateTime) {
            return ((DateTime) x).toTimestamp();
          } else if (x instanceof java.sql.Timestamp) {
            return x;
          } else if (x instanceof java.sql.Date) {
            return new java.sql.Timestamp(((java.sql.Date) x).getTime());
          } else if (x instanceof java.sql.Time) {
            return new java.sql.Timestamp(((java.sql.Time) x).getTime());
          } else if (x instanceof java.lang.String) {
            return java.sql.Timestamp.valueOf(((String) x).trim());
          }

          break;

        case java.sql.Types.DATE:
          if (x instanceof DateTime) {
            return ((DateTime) x).toDate();
          } else if (x instanceof java.sql.Date) {
            return x;
          } else if (x instanceof java.sql.Time) {
            return DATE_ZERO;
          } else if (x instanceof java.sql.Timestamp) {
            GregorianCalendar cal = (GregorianCalendar) calendar.get();
            cal.setTime((java.util.Date) x);
            cal.set(Calendar.HOUR_OF_DAY, 0);
            cal.set(Calendar.MINUTE, 0);
            cal.set(Calendar.SECOND, 0);
            cal.set(Calendar.MILLISECOND, 0);
            // VM1.4+ only              return new java.sql.Date(cal.getTimeInMillis());
            return new java.sql.Date(cal.getTime().getTime());
          } else if (x instanceof java.lang.String) {
            return java.sql.Date.valueOf(((String) x).trim());
          }

          break;

        case java.sql.Types.TIME:
          if (x instanceof DateTime) {
            return ((DateTime) x).toTime();
          } else if (x instanceof java.sql.Time) {
            return x;
          } else if (x instanceof java.sql.Date) {
            return TIME_ZERO;
          } else if (x instanceof java.sql.Timestamp) {
            GregorianCalendar cal = (GregorianCalendar) calendar.get();
            // VM 1.4+ only             cal.setTimeInMillis(((java.sql.Timestamp)x).getTime());
            cal.setTime((java.util.Date) x);
            cal.set(Calendar.YEAR, 1970);
            cal.set(Calendar.MONTH, 0);
            cal.set(Calendar.DAY_OF_MONTH, 1);
            // VM 1.4+ only             return new java.sql.Time(cal.getTimeInMillis());*/
            return new java.sql.Time(cal.getTime().getTime());
          } else if (x instanceof java.lang.String) {
            return java.sql.Time.valueOf(((String) x).trim());
          }

          break;

        case java.sql.Types.OTHER:
          return x;

        case java.sql.Types.JAVA_OBJECT:
          throw new SQLException(
              Messages.get(
                  "error.convert.badtypes", x.getClass().getName(), getJdbcTypeName(jdbcType)),
              "22005");

        case java.sql.Types.LONGVARBINARY:
        case java.sql.Types.BLOB:
          if (x instanceof Blob) {
            return x;
          } else if (x instanceof byte[]) {
            return new BlobImpl(getConnection(callerReference), (byte[]) x);
          } else if (x instanceof Clob) {
            //
            // Convert CLOB to BLOB. Not required by the standard but we will
            // do it anyway.
            //
            Clob clob = (Clob) x;
            try {
              if (charSet == null) {
                charSet = "ISO-8859-1";
              }
              Reader rdr = clob.getCharacterStream();
              BlobImpl blob = new BlobImpl(getConnection(callerReference));
              BufferedWriter out =
                  new BufferedWriter(new OutputStreamWriter(blob.setBinaryStream(1), charSet));
              // TODO Use a buffer to improve performance
              int c;
              while ((c = rdr.read()) >= 0) {
                out.write(c);
              }
              out.close();
              rdr.close();
              return blob;
            } catch (UnsupportedEncodingException e) {
              // Unlikely to happen but fall back on in memory copy
              x = clob.getSubString(1, (int) clob.length());
            } catch (IOException e) {
              throw new SQLException(
                  Messages.get("error.generic.ioerror", e.getMessage()), "HY000");
            }
          }

          if (x instanceof String) {
            //
            // Strictly speaking this conversion is also not required by
            // the JDBC standard but jTDS has always supported it.
            //
            BlobImpl blob = new BlobImpl(getConnection(callerReference));
            String data = (String) x;

            if (charSet == null) {
              charSet = "ISO-8859-1";
            }

            try {
              blob.setBytes(1, data.getBytes(charSet));
            } catch (UnsupportedEncodingException e) {
              blob.setBytes(1, data.getBytes());
            }

            return blob;
          }

          break;

        case java.sql.Types.LONGVARCHAR:
        case java.sql.Types.CLOB:
          if (x instanceof Clob) {
            return x;
          } else if (x instanceof Blob) {
            //
            // Convert BLOB to CLOB
            //
            Blob blob = (Blob) x;
            try {
              InputStream is = blob.getBinaryStream();
              ClobImpl clob = new ClobImpl(getConnection(callerReference));
              Writer out = clob.setCharacterStream(1);
              // TODO Use a buffer to improve performance
              int b;
              // These reads/writes are buffered by the underlying blob buffers
              while ((b = is.read()) >= 0) {
                out.write(hex[b >> 4]);
                out.write(hex[b & 0x0F]);
              }
              out.close();
              is.close();
              return clob;
            } catch (IOException e) {
              throw new SQLException(
                  Messages.get("error.generic.ioerror", e.getMessage()), "HY000");
            }
          } else if (x instanceof Boolean) {
            x = ((Boolean) x).booleanValue() ? "1" : "0";
          } else if (!(x instanceof byte[])) {
            x = x.toString();
          }

          if (x instanceof byte[]) {
            ClobImpl clob = new ClobImpl(getConnection(callerReference));
            clob.setString(1, toHex((byte[]) x));

            return clob;
          } else if (x instanceof String) {
            return new ClobImpl(getConnection(callerReference), (String) x);
          }

          break;

        default:
          throw new SQLException(
              Messages.get("error.convert.badtypeconst", getJdbcTypeName(jdbcType)), "HY004");
      }

      throw new SQLException(
          Messages.get("error.convert.badtypes", x.getClass().getName(), getJdbcTypeName(jdbcType)),
          "22005");
    } catch (NumberFormatException nfe) {
      throw new SQLException(
          Messages.get("error.convert.badnumber", getJdbcTypeName(jdbcType)), "22000");
    }
  }
Exemplo n.º 15
0
  public static void loadSettings() {

    if (!new File("/plugins/config/WorldTools/MySQL.properties").exists()) {
      try {
        File f = new File("plugins/config/WorldTools/MySQL.properties");
        BufferedWriter out = new BufferedWriter(new FileWriter(f));
        out.write("############################");
        out.newLine();
        out.write("# THIS IS CURRENTLY UNUSED #");
        out.newLine();
        out.write("############################");
        out.newLine();
        out.write("useCanarySQL=true");
        out.newLine();
        out.newLine();
        out.write("SQLdriver=com.mysql.jdbc.Driver");
        out.newLine();
        out.newLine();
        out.write("SQLuser=root");
        out.newLine();
        out.newLine();
        out.write("SQLpass=root");
        out.newLine();
        out.newLine();
        out.write("SQLdb=jdbc:mysql://localhost:3306/minecraft");
        out.newLine();
        out.newLine();
      } catch (IOException e) {
        log.info("[WorldTools] - Error during creating SQL propertiesfile!");
        e.printStackTrace();
      }
    }
    PropertiesFile properties = new PropertiesFile("/plugins/config/WorldTools/MySQL.properties");
    try {
      SQLdriver = properties.getProperty("SQLdriver");
      SQLusername = properties.getProperty("SQLuser");
      SQLpassword = properties.getProperty("SQLpass");
      SQLdb = properties.getProperty("SQLdb");
      useSql = Boolean.parseBoolean(properties.getProperty("UseCanarySQL"));
    } catch (Exception e) {
      log.log(Level.SEVERE, "Exception while reading from the mysql properties", e);
    }
    getConnection();
  }