public static boolean deleteLumberLog(LumberLog lumberLog) {
    Logger logger = Logger.getLogger("dao");
    boolean status = false;
    StringBuilder delete =
        new StringBuilder("delete from lumberlog where id = " + lumberLog.getId());

    Connection con = null;
    Statement stm = null;

    try {
      con = DataAccess.getInstance().getDatabaseConnection();
      con.setAutoCommit(true);
      stm = con.createStatement();
      logger.info(delete.toString());
      int rez = stm.executeUpdate(delete.toString());
      if (rez > 0) {
        status = true;
        IDPlateManager.addAvailablePlate(lumberLog.getPlate());
      }
    } catch (Exception e) {
      logger.warning(e.getMessage());
      logger.log(Level.INFO, "Error", e);
    } finally {
      if (stm != null)
        try {
          stm.close();
        } catch (Exception e) {
        }
    }

    return status;
  }
  public static void refreshLumberLog(LumberLog lumberLog) {
    Logger logger = Logger.getLogger("dao");
    StringBuilder lumberLogData =
        new StringBuilder("select diameter, metric from lumberlog_diameter where lumberlog_id = ")
            .append(lumberLog.getId());

    Connection con = null;
    Statement stm = null;
    ResultSet rs = null;
    try {
      con = DataAccess.getInstance().getDatabaseConnection();
      con.setAutoCommit(true);
      stm = con.createStatement();
      logger.info(lumberLogData.toString());
      rs = stm.executeQuery(lumberLogData.toString());
      lumberLog.setMediumRadius(new ArrayList<Double>());
      while (rs.next()) {
        lumberLog.getMediumRadius().add(rs.getDouble(1));
      }
    } catch (Exception e) {
      logger.warning(e.getMessage());
      logger.log(Level.INFO, "Error", e);
    } finally {
      if (rs != null)
        try {
          rs.close();
        } catch (Exception e) {
        }
      if (stm != null)
        try {
          stm.close();
        } catch (Exception e) {
        }
    }
  }
Example #3
1
  @Override
  public Map<String, Object> saveMap(Map<String, Object> object, Class clazz) throws Exception {

    StringBuilder sql = new StringBuilder();
    EntityInfo entityInfo = ClassUtils.getEntityInfoByClazz(clazz);

    sql.append("INSERT INTO ");
    sql.append(entityInfo.getTableName());
    sql.append("(");

    List<String> columns = new ArrayList<String>();
    List<Object> values = new ArrayList<Object>();
    Map<String, String> ptcMap = ClassUtils.propToColumnMap.get(entityInfo.getClazzName());
    for (Map.Entry<String, Object> entry : object.entrySet()) {
      columns.add(ptcMap.get(entry.getKey()));
      values.add(entry.getValue());
    }
    sql.append(StringUtils.join(columns, ","));
    sql.append(") VALUES(");
    String[] params = new String[values.size()];
    Arrays.fill(params, "?");
    sql.append(StringUtils.join(params, ","));
    sql.append(")");
    if (entityInfo.getStrategy().equals(GenerationType.IDENTITY)) {
      Long id = addReutrnId(sql.toString(), values);
      if (id != null) {
        object.put(entityInfo.getPkName(), id);
      }
    } else {
      add(sql.toString(), values);
    }
    return object;
  }
  public static String reformatQuery(String query, String matchingSensors, String unionElement) {

    String lower_query = query.toLowerCase();

    String listSensors[] = matchingSensors.split(",");
    for (int i = 0; i < listSensors.length; i++) logger.warn(i + " : " + listSensors[i]);

    // replace "sensors"
    String ref_query =
        new StringBuilder(lower_query.replaceAll(LIST_SENSORS_RESERVED_WORD_REGEX, matchingSensors))
            .toString();

    // check for aggregates, containing reserved word $union
    if (ref_query.indexOf(UNION_RESERVED_WORD) > 0) {
      StringBuilder unionOfAll = new StringBuilder();
      if (unionElement != "") {
        System.out.println("what_to_repeat => " + unionElement);
        for (int i = 0; i < listSensors.length; i++) {
          unionOfAll.append(unionElement.replaceAll(SENSOR_RESERVED_WORD_REGEX, listSensors[i]));
          if (i < listSensors.length - 1) unionOfAll.append("\n union \n");
        }
      }
      System.out.println("unionofAll => " + unionOfAll);
      ref_query = ref_query.replaceAll(UNION_RESERVED_WORD_REGEX, unionOfAll.toString());
    }

    return ref_query;
  }
Example #5
1
  @Override
  public int size(final DatabaseTable table) throws DatabaseException {
    preOperationCheck();

    final StringBuilder sb = new StringBuilder();
    sb.append("SELECT COUNT(" + KEY_COLUMN + ") FROM ").append(table.toString());

    PreparedStatement statement = null;
    ResultSet resultSet = null;
    try {
      statement = connection.prepareStatement(sb.toString());
      resultSet = statement.executeQuery();
      if (resultSet.next()) {
        return resultSet.getInt(1);
      }
    } catch (SQLException e) {
      final ErrorInformation errorInformation =
          new ErrorInformation(
              PwmError.ERROR_DB_UNAVAILABLE, "size operation failed: " + e.getMessage());
      lastError = errorInformation;
      throw new DatabaseException(errorInformation);
    } finally {
      close(statement);
      close(resultSet);
    }

    updateStats(true, false);
    return 0;
  }
  /*
   * Returns list of sensors currently loaded in the system
   * */
  public static String getListOfSensors() {
    StringBuilder s = new StringBuilder();
    Iterator iter = Mappings.getAllVSensorConfigs();

    sensors.clear();
    coordinates.clear();

    while (iter.hasNext()) {
      VSensorConfig sensorConfig = (VSensorConfig) iter.next();
      Double longitude = sensorConfig.getLongitude();
      Double latitude = sensorConfig.getLatitude();
      Double altitude = sensorConfig.getAltitude();
      String sensor = sensorConfig.getName();

      if ((latitude != null) && (longitude != null) && (altitude != null)) {
        Point point = new Point(latitude, longitude, altitude);
        coordinates.add(point);
        sensors.add(sensor);
        s.append(sensor)
            .append(" => ")
            .append(longitude)
            .append(" : ")
            .append(latitude)
            .append("\n");
      }
    }
    return s.toString();
  }
Example #7
1
 public String tableColumns(String tableName, String columnPrefix) throws SQLException {
   ResultSet columns = executeQuery(driver.getQueries().getColumns(tableName));
   StringBuilder columnsBuilder = new StringBuilder();
   while (columns.next()) {
     if (columnsBuilder.length() > 0) columnsBuilder.append(',');
     columnsBuilder.append(columnPrefix).append(columns.getString("property.name"));
   }
   return columnsBuilder.toString();
 }
Example #8
1
  @Override
  public <T> Page<T> searchPage(String sql, Class<T> clazz, List<Object> params, Page<T> page)
      throws Exception {
    if (StringUtils.isBlank(sql)) {
      List<T> list = new ArrayList<>();
      page.setTotalCount(0);
      page.setResult(list);
      return page;
    }
    if (params == null) {
      params = new ArrayList<>();
    }
    StringBuilder sb = new StringBuilder(sql);
    int count = getCount(sb.toString(), params);
    page.setTotalCount(count);
    if (!StringUtils.isBlank(page.getOrder())) {
      sb.append(" ORDER BY ").append(page.getOrder());
      if (!StringUtils.isBlank(page.getSort())) {
        sb.append(" ").append(page.getSort());
      }
    }
    sb.append(" LIMIT ");
    sb.append(String.valueOf(page.getFirstResult()));
    sb.append(",");
    sb.append(String.valueOf(page.getPageSize()));
    List<T> list = searchForList(sb.toString(), clazz, params);
    page.setResult(list);

    return page;
  }
  /*
   * Returns list of sensors currently loaded in the system
   * */
  public static String getListOfSensors() {
    StringBuilder s = new StringBuilder();
    Iterator iter = Mappings.getAllVSensorConfigs();
    while (iter.hasNext()) {
      VSensorConfig sensorConfig = (VSensorConfig) iter.next();
      Double longitude = sensorConfig.getLongitude();
      Double latitude = sensorConfig.getLatitude();
      String sensor = sensorConfig.getName();

      if ((latitude != null) && (longitude != null)) {
        Point point =
            geometryFactory.createPoint(
                new Coordinate(longitude.doubleValue(), latitude.doubleValue()));
        coordinates.add(point);
        sensors.add(sensor);
        s.append(sensor)
            .append(" => ")
            .append(longitude)
            .append(" : ")
            .append(latitude)
            .append(NEWLINE);
      }
    }
    return s.toString();
  }
 @Override
 public String toString() {
   final StringBuilder sb = new StringBuilder();
   sb.append("User : "******"\n");
   sb.append("Info").append("\n").append(info.toString());
   return sb.toString();
 }
Example #11
0
  /**
   * Test that <code>Clob.getCharacterStream(long,long)</code> works on CLOBs that are streamed from
   * store. (DERBY-2891)
   */
  public void testGetCharacterStreamLongOnLargeClob() throws Exception {
    getConnection().setAutoCommit(false);

    // create large (>32k) clob that can be read from store
    final int size = 33000;
    StringBuilder sb = new StringBuilder(size);
    for (int i = 0; i < size; i += 10) {
      sb.append("1234567890");
    }

    final int id = BlobClobTestSetup.getID();
    PreparedStatement ps =
        prepareStatement("insert into blobclob(id, clobdata) values (?,cast(? as clob))");
    ps.setInt(1, id);
    ps.setString(2, sb.toString());
    ps.executeUpdate();
    ps.close();

    Statement s = createStatement();
    ResultSet rs = s.executeQuery("select clobdata from blobclob where id = " + id);
    assertTrue(rs.next());
    Clob c = rs.getClob(1);

    // request a small region of the clob
    BufferedReader r = new BufferedReader(c.getCharacterStream(4L, 3L));
    assertEquals("456", r.readLine());

    r.close();
    c.free();
    rs.close();
    s.close();
    rollback();
  }
Example #12
0
	/**
	 * 创建更新激活码
	 * 
	 * @param model 
	 *        激活码
	 * @return 激活码编号
	 */
	public int createUpdate(wh.game.model.ActiveCode model) throws Exception{
		Map<String, Object> inParameters = new HashMap<String, Object>();
		inParameters.put("ActiveCodeId", model.getActiveCodeId());
		inParameters.put("GameId", model.getGameId());
		inParameters.put("ServerId", model.getServerId());
		inParameters.put("Name", model.getName());
		inParameters.put("Code", model.getCode());
		inParameters.put("ActiveCodeType", model.getActiveCodeType());
		inParameters.put("CreateDate", Utility.getSqlDate(model.getCreateDate()));
		inParameters.put("ModifyDate", Utility.getSqlDate(model.getModifyDate()));
		inParameters.put("Status", model.getStatus());
		inParameters.put("UsedType", model.getUsedType());
		
		OutParameters outParameters = new OutParameters();
		outParameters.putOutParmType("ErrNo", java.sql.Types.INTEGER);
		outParameters.putOutParmType("ErrMsg", java.sql.Types.NVARCHAR);
		int parasCount = inParameters.size() + outParameters.getOutParmTypes().size();
		StringBuilder sbBuilder = new StringBuilder();
		for (int i = 0; i < parasCount; i++) {
			if (0 == i) {
				sbBuilder.append("?");
			} else {
				sbBuilder.append(",?");
			}
		}
		
		int retValue = SQLHelper.runProcedureNonQuery(Config.CONNECTION_STRING_ULD,
			"{? = call WH_Game_ActiveCode_CreateUpdate(" + sbBuilder.toString() + ")}", inParameters, outParameters);		
		
		int errNo = Integer.valueOf(outParameters.getOutParmValue("ErrNo").toString());
		String errMsg = outParameters.getOutParmValue("ErrMsg").toString();
		MyErr.checkErr(errNo, errMsg);
		
		return retValue;
	}
Example #13
0
  @Override
  public String getScanListingOfAllMessages() {

    StringBuilder scanListing = new StringBuilder();
    String query = "SELECT txMailContent FROM m_Mail WHERE iMaildropID=" + seissionUserID;

    try (Statement statement = conn.createStatement()) {

      ResultSet rs = statement.executeQuery(query);

      int numberOfMails = getNumberOfMailsInMaildrop();

      while (rs.next()) {

        int messageNumber = rs.getRow();
        int sizeInOctets = getNumberOfOctetsInString(rs.getString("txMailContent"));

        if (messageNumber == numberOfMails) {
          // For Nice Formatting
          scanListing.append(messageNumber + " " + sizeInOctets);
        } else {
          scanListing.append(messageNumber + " " + sizeInOctets + "\n");
        }
      }

    } catch (SQLException e) {
      printSQLException(e);
    }

    return scanListing.toString();
  }
Example #14
0
  public Collection<Exchange> findByFilter(Filter iFilter)
      throws StockPlayException, FilterException {
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try {
      try {
        conn = OracleConnection.getConnection();

        StringBuilder tQuery = new StringBuilder(SELECT_EXCHANGES);
        if (!iFilter.empty()) tQuery.append(" WHERE " + (String) iFilter.compile("sql"));
        stmt = conn.prepareStatement(tQuery.toString());

        rs = stmt.executeQuery();
        ArrayList<Exchange> list = new ArrayList<Exchange>();
        while (rs.next()) {
          Exchange tExchange = new Exchange(rs.getString(1));
          tExchange.setName(rs.getString(2));
          tExchange.setLocation(rs.getString(3));
          list.add(tExchange);
        }
        return list;
      } finally {
        if (rs != null) rs.close();
        if (stmt != null) stmt.close();
        if (conn != null) conn.close();
      }
    } catch (SQLException ex) {
      throw new SubsystemException(SubsystemException.Type.DATABASE_FAILURE, ex.getCause());
    }
  }
Example #15
0
 public String getSubject(int len) {
   StringBuilder tmp = new StringBuilder();
   for (int i = 0; i < this.lev; i++) {
     tmp.append("&nbsp;");
   }
   return CommonUtil.showHtml(tmp + CommonUtil.cropByte(this.subject, len, "..."));
 }
Example #16
0
  @Override
  public String getUniqueIDListingOfAllMessages() {

    StringBuilder uidlListing = new StringBuilder();
    String query = "SELECT iMailID, vchUIDL FROM m_Mail WHERE iMaildropID=" + seissionUserID;

    try (Statement statement = conn.createStatement()) {

      ResultSet rs = statement.executeQuery(query);

      int numberOfMails = getNumberOfMailsInMaildrop();

      while (rs.next()) {

        int messageNumber = rs.getRow();
        String uidl = rs.getString("vchUIDL");

        if (messageNumber == numberOfMails) {
          // For Nice Formatting
          uidlListing.append(messageNumber + " " + uidl);
        } else {
          uidlListing.append(messageNumber + " " + uidl + "\n");
        }
      }

    } catch (SQLException e) {
      printSQLException(e);
    }

    return uidlListing.toString();
  }
Example #17
0
 @Override
 public String toString() {
   StringBuilder sb = new StringBuilder();
   sb.append("materias_ID").append(getMaterias_ID()).append("], ");
   sb.append("des_Materias").append(getDes_Materias()).append("], ");
   sb.append("departamento").append(getDepartamento()).append("], ");
   return sb.toString();
 }
 /*
  * Searches for the list of sensors which are located at the given point (comma separated)
  * */
 public static String searchForSensors_String(Point p) {
   StringBuilder s = new StringBuilder("");
   for (int i = 0; i < coordinates.size(); i++) {
     if (coordinates.get(i) == p) {
       s.append(sensors.get(i)).append(" ");
     }
   }
   return s.toString().trim().replace(" ", SEPARATOR);
 }
Example #19
0
  /** @param userPath */
  public static String formatUrl(String userPath) {

    ManagementContainer mc = ManagementContainer.getInstance();
    String prefix = mc.getClientSupportManager().getUrlPrefix();
    StringBuilder sb = new StringBuilder(80);
    sb.append(prefix);
    sb.append(userPath);
    return sb.toString();
  }
Example #20
0
 /**
  * Gets the current stacktrace as a String.
  *
  * @return the stacktrace
  */
 private static String getStackTrace() {
   final StringBuilder stack = new StringBuilder();
   for (final StackTraceElement elem : Thread.currentThread().getStackTrace()) {
     stack.append("\tat ");
     stack.append(elem);
     stack.append(SystemUtils.LINE_SEPARATOR);
   }
   return stack.toString();
 }
Example #21
0
 public static void logmex(String t, int lvl, String msg, Object o, Exception ex) {
   StringBuilder sb = new StringBuilder();
   StackTraceElement se[] = ex.getStackTrace();
   for (int i = 0; i < se.length; i++) {
     sb.append(se[i].getMethodName() + "@" + se[i].getFileName() + "@" + se[i].getLineNumber());
     sb.append(" > ");
   }
   logm(t, lvl, msg + " EXCEPTION " + ex + " " + sb.toString(), o);
 }
Example #22
0
 @Override
 public int getCount(String sql, List<Object> values) throws Exception {
   if (StringUtils.isEmpty(sql)) return 0;
   if (values == null) values = new ArrayList<Object>();
   StringBuilder sb = new StringBuilder("SELECT COUNT(*) FROM (");
   sb.append(sql);
   sb.append(") AS _TN");
   return this.getInt(sb.toString(), values);
 }
Example #23
0
 private static void byteArrayToString(byte[] barray, StringBuilder strbuf) {
   if (barray == null) {
     strbuf.append("null");
   } else {
     for (int i = 0; i < barray.length; i++) {
       strbuf.append(barray[i]);
     }
   }
 }
  /** Creates tables if they do not exist. */
  private void initializeTables() {
    Connection conn = null;
    Statement statement = null;
    try {
      conn = retrieveConnection();
      statement = conn.createStatement();
      statement.setQueryTimeout(30);

      // One table holding the playername id relation
      String playerQuery =
          String.format(
              "CREATE TABLE IF NOT EXISTS %s (id INTEGER PRIMARY KEY AUTOINCREMENT, %s STRING)",
              playerTable, "name");
      statement.executeUpdate(playerQuery);

      // One column for every message
      StringBuilder columns = new StringBuilder();
      for (MessageNode node : MessageNode.getMessageNodes()) {
        MsgCategory cat = messages.getCat(node);
        if (node.getColumnName() != null
            && (cat == MsgCategory.TUTORIAL || cat == MsgCategory.ONE_TIME)) {
          columns.append(',');
          columns.append(node.getColumnName());
        }
      }

      String msgQuery =
          String.format(
              "CREATE TABLE IF NOT EXISTS %s (id INTEGER PRIMARY KEY UNIQUE %s)",
              msgTable, columns);
      statement.executeUpdate(msgQuery);

      // Check if all columns are present
      DatabaseMetaData dmd = conn.getMetaData();
      // Add missing columns
      for (MessageNode node : MessageNode.getMessageNodes()) {
        MsgCategory cat = messages.getCat(node);
        if (cat == MsgCategory.TUTORIAL || cat == MsgCategory.ONE_TIME) {
          ResultSet set = dmd.getColumns(null, null, msgTable, node.getColumnName());
          if (!set.next()) {
            String updateQuery =
                String.format("ALTER TABLE %s ADD COLUMN %s", msgTable, node.getColumnName());
            statement.executeUpdate(updateQuery);
          }
        }
      }
    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      try {
        if (conn != null) conn.close();
        if (statement != null) statement.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
  }
 String makeStringFromList(List l) {
   StringBuilder sb = new StringBuilder();
   for (int i = 0; i < l.size(); i++) {
     Object o = l.get(i);
     if (o == null) sb.append("null");
     else sb.append(o.toString());
     if (i < l.size() - 1) sb.append(SEPARATOR);
   }
   return sb.toString();
 }
 private static String read(Clob c) throws SQLException, IOException {
   StringBuilder sb = new StringBuilder((int) c.length());
   Reader r = c.getCharacterStream();
   char[] cbuf = new char[CLOBBUFFERSIZE];
   int n;
   while ((n = r.read(cbuf, 0, cbuf.length)) != -1) {
     sb.append(cbuf, 0, n);
   }
   return sb.toString();
 }
Example #27
0
 private static String join(List<String> list, String conjunction) {
   StringBuilder sb = new StringBuilder();
   boolean first = true;
   for (String item : list) {
     if (first) first = false;
     else sb.append(conjunction);
     sb.append(item);
   }
   return sb.toString();
 }
Example #28
0
 // Hàm hỗ trợ DELETE trong CSDL
 // DELETE FROM TableName WHERE Condition.
 public boolean Delete(String TableName, String Condition) throws Exception {
   // Khai báo biến StringBuilder để tạo chuỗi Select.
   StringBuilder query = new StringBuilder("DELETE FROM " + TableName);
   // Đưa câu lệnh điều kiện vào trong câu query
   this.AddCondition(query, Condition);
   // Chèn ký tự ';' vào cuối dòng lệnh của để cách các câu lệnh.
   query.append(";");
   // Thực thi câu query và trả kết quả ra ngoài
   return this._connect.executeUpdate(query.toString()) > 0;
 }
 private String getTweetPadding(int tweetIdx) { // copiado do Utils.java
   int MaxNTweets = 10000;
   StringBuilder strBuild = new StringBuilder();
   int current = (int) Math.floor(Math.log10(tweetIdx)) + 1;
   int expected = (int) Math.floor(Math.log10(MaxNTweets));
   if (tweetIdx == 0) current = 1;
   for (int i = 0; i < (expected - current); i++) strBuild.append(0);
   strBuild.append(tweetIdx);
   return strBuild.toString();
 }
Example #30
0
 // Hàm hỗ trợ Select CSDL
 // SELECT * FORM TableName WHERE Condition ORDER BY OrderBy;
 public ResultSet Select(String TableName, String Condition, String OrderBy) throws Exception {
   // Khai báo biến StringBuilder để tạo chuỗi Select.
   StringBuilder query = new StringBuilder("SELECT * FROM " + TableName);
   // Đưa câu lệnh điều kiện vào trong câu query
   this.AddCondition(query, Condition);
   // Đưa câu lệnh Order vào câu query
   this.AddOrderBy(query, OrderBy);
   // Chèn ký tự ';' vào cuối dòng lệnh của để cách các câu lệnh.
   query.append(";");
   // Thực thi câu query và trả kết quả ra ngoài
   return _connect.excuteQuery(query.toString());
 }