public boolean updateStatus(List<Long> lumberLogIds) {
    Logger logger = Logger.getLogger("dao");
    StringBuilder updateSql = new StringBuilder(" update lumberlog set Status = 0 ");
    updateSql.append(" where id in(");
    for (Long id : lumberLogIds) {
      updateSql.append(id).append(",");
    }
    updateSql.deleteCharAt(updateSql.length() - 1);
    updateSql.append(")");

    boolean status = true;

    Connection con = null;
    Statement stm = null;
    try {
      con = DataAccess.getInstance().getDatabaseConnection();
      con.setAutoCommit(true);
      stm = con.createStatement();
      logger.info(updateSql.toString());
      int count = stm.executeUpdate(updateSql.toString());

    } catch (Exception e) {
      status = false;
      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) {
        }
    }
  }
示例#3
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;
  }
示例#4
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 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 List<LumberLog> findAll(LumberLogFilterDTO filter) {
    Logger logger = Logger.getLogger("dao");
    StringBuilder selectSql =
        new StringBuilder(
            " select l.*,i.label as plateName,st.name as stackName from lumberlog l left join idplate i on l.idplate = i.id left join lumberstack st on l.stack = st.id join lumberentry_to_lumberlog le on l.id = le.lumberlogid join lumberentry stoe on le.entryid = stoe.id join user u on stoe.user = u.ID");
    if (filter != null) {
      selectSql.append(" where ");
      String operator = "";
      if (filter.getStatus() != null) {
        selectSql.append(operator).append(" l.Status=").append(filter.getStatus());
        operator = " and ";
      }
      if (filter.getTransportEntryId() != null) {
        selectSql
            .append(operator)
            .append(" l.TransportEntryId=")
            .append(filter.getTransportEntryId());
        operator = " and ";
      }
    }
    List<LumberLog> result = new ArrayList<>();

    Connection con = null;
    Statement stm = null;
    ResultSet rs = null;
    try {
      con = DataAccess.getInstance().getDatabaseConnection();
      con.setAutoCommit(true);
      stm = con.createStatement();
      logger.info(selectSql.toString());
      rs = stm.executeQuery(selectSql.toString());
      while (rs.next()) {
        result.add(fromResultSet(rs));
      }
    } 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) {
        }
    }

    return result;
  }
示例#7
1
  /**
   * Returns orders with given identifiers.
   *
   * @param ids Orders identifiers.
   * @return List of order entities.
   */
  public List<Order> findOrders(String[] ids) throws DBException {
    List<Order> ordersList = new ArrayList<Order>();
    Statement stmt = null;
    ResultSet rs = null;
    Connection con = null;
    try {
      con = getConnection();

      // create SQL query like "... id IN (1, 2, 7)"
      StringBuilder query = new StringBuilder("SELECT * FROM orders WHERE id IN (");
      for (String idAsString : ids) {
        query.append(idAsString).append(',');
      }
      query.deleteCharAt(query.length() - 1);
      query.append(')');

      stmt = con.createStatement();
      rs = stmt.executeQuery(query.toString());
      while (rs.next()) {
        ordersList.add(extractOrder(rs));
      }
      con.commit();
    } catch (SQLException ex) {
      rollback(con);
      throw new DBException(Messages.ERR_CANNOT_OBTAIN_ORDERS_BY_IDENTIFIERS, ex);
    } finally {
      close(con, stmt, rs);
    }
    return ordersList;
  }
  /*
   * 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();
  }
示例#9
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;
  }
  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;
  }
示例#11
0
  private static String buildInsertStatement(String table, String[] columns, String[] values) {
    if (columns.length != values.length) {
      throw new RuntimeException("insert statement incorrect");
    }
    StringBuilder sb = new StringBuilder();
    sb.append("insert into ");
    sb.append(table);
    sb.append(" (");
    for (int i = 0; i < columns.length; i++) {
      sb.append("");
      sb.append(columns[i]);
      if (i == columns.length - 1) {
        sb.append(") ");
      } else {
        sb.append(",");
      }
    }
    sb.append("value (");
    for (int i = 0; i < values.length; i++) {
      sb.append("'");
      sb.append(values[i]);
      if (i == values.length - 1) {
        sb.append("');");
      } else {
        sb.append("',");
      }
    }

    return sb.toString();
  }
示例#12
0
  /*
   * 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();
  }
示例#13
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();
  }
  /**
   * 生成特定数据库的分页语句
   *
   * @param sql
   * @param page
   * @return
   */
  private String buildPageSql(String sql, Page<?> page) {
    if (page == null || dialect == null || dialect.equals("")) {
      return sql;
    }
    StringBuilder sb = new StringBuilder();
    int startRow = page.getOffset();

    if ("mysql".equals(dialect)) {
      sb.append(sql);
      sb.append(" limit ").append(startRow).append(",").append(page.getLimit());
    } else if ("hsqldb".equals(dialect)) {
      sb.append("select limit ");
      sb.append(startRow);
      sb.append(" ");
      sb.append(page.getLimit());
      sb.append(" ");
      sb.append(sql.substring(6));
    } else if ("oracle".equals(dialect)) {
      sb.append("select * from (select tmp_tb.*,ROWNUM row_id from (");
      sb.append(sql);
      sb.append(")  tmp_tb where ROWNUM<=");
      sb.append(startRow + page.getLimit());
      sb.append(") where row_id>");
      sb.append(startRow);
    } else {
      throw new IllegalArgumentException("SelectInterceptor error:does not support " + dialect);
    }
    return sb.toString();
  }
示例#15
0
 // 创建新表
 public boolean createTable(String tableName) {
   try {
     Connection conn = getConn();
     if (conn != null) {
       StringBuilder sql = new StringBuilder("CREATE TABLE ");
       sql.append(tableName);
       sql.append(" (");
       sql.append("serialno int(11) NOT NULL AUTO_INCREMENT,");
       sql.append("title varchar(128) NOT NULL,");
       sql.append("smalldesc varchar(512) NOT NULL,");
       sql.append("smallurl varchar(256) DEFAULT NULL,");
       sql.append("source varchar(32) NOT NULL,");
       sql.append("releasetime bigint(20) NOT NULL,");
       sql.append("content varchar(128) NOT NULL,");
       sql.append("classify varchar(16) NOT NULL,");
       sql.append("curl varchar(256) NOT NULL,");
       sql.append("createtime varchar(14) NOT NULL,");
       sql.append("PRIMARY KEY (serialno)");
       sql.append(") ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=gbk");
       PreparedStatement stat = conn.prepareStatement(sql.toString());
       stat.executeUpdate();
       conn.close();
     }
   } catch (SQLException e) {
     e.printStackTrace();
   }
   return true;
 }
示例#16
0
  public void createNewPlayer(String player) {
    if (!checkConnection()) {
      return;
    }

    PreparedStatement preparedStatement = null;

    try {
      StringBuilder queryBuilder = new StringBuilder();
      queryBuilder.append("INSERT INTO `skywars_player` ");
      queryBuilder.append("(`player_id`, `player_name`, `first_seen`, `last_seen`) ");
      queryBuilder.append("VALUES ");
      queryBuilder.append("(NULL, ?, NOW(), NOW());");

      preparedStatement = connection.prepareStatement(queryBuilder.toString());
      preparedStatement.setString(1, player);
      preparedStatement.executeUpdate();

    } catch (final SQLException sqlException) {
      sqlException.printStackTrace();

    } finally {
      if (preparedStatement != null) {
        try {
          preparedStatement.close();
        } catch (final SQLException ignored) {
        }
      }
    }
  }
 @Override
 public String toString() {
   final StringBuilder sb = new StringBuilder();
   sb.append("User : "******"\n");
   sb.append("Info").append("\n").append(info.toString());
   return sb.toString();
 }
示例#18
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();
  }
示例#19
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();
  }
示例#20
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;
	}
示例#21
0
 private String buildSql(final List<Column> columns, final String tableName) {
   StringBuilder builder = new StringBuilder();
   builder.append("upsert into ");
   builder.append(tableName);
   builder.append(" (");
   int count = 1;
   for (Column column : columns) {
     builder.append(column.getName());
     if (count < columns.size()) {
       builder.append(",");
     } else {
       builder.append(")");
     }
     count++;
   }
   builder.append(" VALUES (");
   for (int i = 0; i < columns.size(); i++) {
     if (i < columns.size() - 1) {
       builder.append("?,");
     } else {
       builder.append("?)");
     }
   }
   return builder.toString();
 }
示例#22
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());
    }
  }
示例#23
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();
 }
示例#24
0
  public Collection<User> findUsers(Set<String> fields, String query)
      throws UnsupportedOperationException {
    if (fields.isEmpty()) {
      return Collections.emptyList();
    }
    if (!getSearchFields().containsAll(fields)) {
      throw new IllegalArgumentException("Search fields " + fields + " are not valid.");
    }
    if (query == null || "".equals(query)) {
      return Collections.emptyList();
    }
    // SQL LIKE queries don't map directly into a keyword/wildcard search like we want.
    // Therefore, we do a best approximiation by replacing '*' with '%' and then
    // surrounding the whole query with two '%'. This will return more data than desired,
    // but is better than returning less data than desired.
    query = "%" + query.replace('*', '%') + "%";
    if (query.endsWith("%%")) {
      query = query.substring(0, query.length() - 1);
    }

    List<String> usernames = new ArrayList<String>(50);
    Connection con = null;
    Statement stmt = null;
    ResultSet rs = null;
    try {
      con = DbConnectionManager.getConnection();
      stmt = con.createStatement();
      StringBuilder sql = new StringBuilder();
      sql.append("SELECT username FROM jiveUser WHERE");
      boolean first = true;
      if (fields.contains("Username")) {
        sql.append(" username LIKE '").append(StringUtils.escapeForSQL(query)).append("'");
        first = false;
      }
      if (fields.contains("Name")) {
        if (!first) {
          sql.append(" AND");
        }
        sql.append(" name LIKE '").append(StringUtils.escapeForSQL(query)).append("'");
        first = false;
      }
      if (fields.contains("Email")) {
        if (!first) {
          sql.append(" AND");
        }
        sql.append(" email LIKE '").append(StringUtils.escapeForSQL(query)).append("'");
      }
      rs = stmt.executeQuery(sql.toString());
      while (rs.next()) {
        usernames.add(rs.getString(1));
      }
    } catch (SQLException e) {
      Log.error(e);
    } finally {
      DbConnectionManager.closeConnection(rs, stmt, con);
    }
    return new UserCollection(usernames.toArray(new String[usernames.size()]));
  }
示例#25
0
  /*
   * Execute query against a list of sensors
   *
   * */
  public static String executeQuery(
      String envelope, String query, String matchingSensors, String format) throws ParseException {

    // String matchingSensors = getListOfSensorsAsString(envelope);

    String reformattedQuery = reformatQuery(query, matchingSensors);
    StringBuilder sb = new StringBuilder();
    Connection connection = null;

    try {
      connection = Main.getDefaultStorage().getConnection();
      Statement statement =
          connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
      ResultSet results = statement.executeQuery(reformattedQuery);
      ResultSetMetaData metaData; // Additional information about the results
      int numCols, numRows; // How many rows and columns in the table
      metaData = results.getMetaData(); // Get metadata on them
      numCols = metaData.getColumnCount(); // How many columns?
      results.last(); // Move to last row
      numRows = results.getRow(); // How many rows?

      String s;

      // System.out.println("* Executing query *\n" + reformattedQuery + "\n***");

      // headers
      // sb.append("# Query: " + query + NEWLINE);
      sb.append("# Query: " + reformattedQuery.replaceAll("\n", "\n# ") + NEWLINE);

      sb.append("# ");
      // System.out.println("ncols: " + numCols);
      // System.out.println("nrows: " + numRows);
      for (int col = 0; col < numCols; col++) {
        sb.append(metaData.getColumnLabel(col + 1));
        if (col < numCols - 1) sb.append(SEPARATOR);
      }
      sb.append(NEWLINE);

      for (int row = 0; row < numRows; row++) {
        results.absolute(row + 1); // Go to the specified row
        for (int col = 0; col < numCols; col++) {
          Object o = results.getObject(col + 1); // Get value of the column
          // logger.warn(row + " , "+col+" : "+ o.toString());
          if (o == null) s = "null";
          else s = o.toString();
          if (col < numCols - 1) sb.append(s).append(SEPARATOR);
          else sb.append(s);
        }
        sb.append(NEWLINE);
      }
    } catch (SQLException e) {
      sb.append("ERROR in execution of query: " + e.getMessage());
    } finally {
      Main.getDefaultStorage().close(connection);
    }

    return sb.toString();
  }
示例#26
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();
  }
示例#27
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();
 }
 /*
  * 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);
 }
示例#29
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);
 }
示例#30
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);
 }