Ejemplo n.º 1
1
  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;
  }
Ejemplo n.º 2
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;
  }
  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;
  }
Ejemplo n.º 4
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();
 }
Ejemplo n.º 5
1
  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;
  }
  /*
   * 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();
  }
Ejemplo n.º 7
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;
  }
Ejemplo n.º 8
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();
  }
Ejemplo n.º 9
0
 @Override
 public String toString() {
   final StringBuilder sb = new StringBuilder();
   sb.append("User : "******"\n");
   sb.append("Info").append("\n").append(info.toString());
   return sb.toString();
 }
Ejemplo n.º 10
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) {
        }
      }
    }
  }
Ejemplo n.º 11
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;
	}
Ejemplo n.º 12
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();
  }
Ejemplo n.º 13
0
 protected void executeQuery(Statement stmt, String q) throws SQLException {
   q = q.replace("$PREFIX", getPrefix());
   LOG.info(" Executing " + q);
   ResultSet rs = stmt.executeQuery(q);
   StringBuilder header = new StringBuilder();
   for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
     if (i > 1) {
       header.append("|");
     }
     header.append(rs.getMetaData().getColumnName(i));
   }
   LOG.info(header);
   int seq = 0;
   while (true) {
     boolean valid = rs.next();
     if (!valid) break;
     seq++;
     StringBuilder line = new StringBuilder();
     for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
       if (i > 1) {
         line.append("|");
       }
       line.append(rs.getString(i));
     }
     LOG.info(seq + ":" + line);
   }
 }
Ejemplo n.º 14
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();
 }
Ejemplo n.º 15
0
  /** 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();
      }
    }
  }
Ejemplo n.º 16
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();
  }
Ejemplo n.º 17
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]);
     }
   }
 }
Ejemplo n.º 18
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);
 }
Ejemplo n.º 19
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();
 }
Ejemplo n.º 20
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);
 }
Ejemplo n.º 21
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();
 }
 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();
 }
Ejemplo n.º 23
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();
 }
Ejemplo n.º 24
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();
 }
Ejemplo n.º 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();
  }
Ejemplo n.º 26
0
  private static String array2String(int[] a) {
    if (a == null) return "null";
    int iMax = a.length - 1;
    if (iMax == -1) return "[]";

    StringBuilder b = new StringBuilder();
    b.append('[');
    for (int i = 0; ; i++) {
      b.append(a[i]);
      if (i == iMax) return b.append(']').toString();
      b.append(", ");
    }
  }
  private String buildClobString(int clobsize) {
    int iterations = clobsize / BUILDSTRING.length();
    int substrsize = clobsize % BUILDSTRING.length();
    StringBuilder sb = new StringBuilder(clobsize);

    for (int i = 0; i < iterations; i++) {
      sb.append(BUILDSTRING);
    }

    if (substrsize > 0) {
      sb.append(BUILDSTRING.substring(0, substrsize));
    }

    return sb.toString();
  }
Ejemplo n.º 28
0
  private void setParamExtra(EqlParamPlaceholder placeHolder, int index, Object value)
      throws SQLException {
    if (value instanceof Date) {
      Timestamp date = new Timestamp(((Date) value).getTime());
      ps.setTimestamp(index + 1, date);
      boundParams.append('[').append(EqlUtils.toDateTimeStr(date)).append(']');
    } else {
      Object paramValue = value;
      if (placeHolder != null && placeHolder.getOption().contains("LOB") && value instanceof String)
        paramValue = EqlUtils.toBytes((String) value);

      ps.setObject(index + 1, paramValue);
      boundParams.append('[').append(value).append(']');
    }
  }
Ejemplo n.º 29
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();
  }
Ejemplo n.º 30
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, "..."));
 }