Java Code Examples for java.sql.Statement#setQueryTimeout()

The following examples show how to use java.sql.Statement#setQueryTimeout() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DalStatementCreator.java    From das with Apache License 2.0 8 votes vote down vote up
private void applyHints(Statement statement, Hints hints) throws SQLException {
	Integer fetchSize = (Integer)hints.get(HintEnum.fetchSize);
	
	if(fetchSize != null && fetchSize > 0) {
           statement.setFetchSize(fetchSize);
       }

	Integer maxRows = (Integer)hints.get(HintEnum.maxRows);
	if (maxRows != null && maxRows > 0) {
           statement.setMaxRows(maxRows);
       }

       Integer timeout = (Integer)hints.get(HintEnum.timeout);
       if (timeout == null || timeout < 0) {
           timeout = StatusManager.getTimeoutMarkdown().getTimeoutThreshold();
       }

	statement.setQueryTimeout(timeout);
}
 
Example 2
Source File: TGroupStatement.java    From tddl with Apache License 2.0 6 votes vote down vote up
/**
 * 会调用setBaseStatement以关闭已有的Statement
 */
private Statement createStatementInternal(Connection conn, String sql, boolean isBatch) throws SQLException {
    Statement stmt;
    if (isBatch) {
        stmt = conn.createStatement();
    } else {
        int resultSetHoldability = this.resultSetHoldability;
        if (resultSetHoldability == -1) {// 未调用过setResultSetHoldability
            resultSetHoldability = conn.getHoldability();
        }
        stmt = conn.createStatement(this.resultSetType, this.resultSetConcurrency, resultSetHoldability);
    }

    setBaseStatement(stmt); // 会关闭已有的Statement
    stmt.setQueryTimeout(queryTimeout); // 这句也有可能抛出异常,放在最后
    stmt.setFetchSize(fetchSize);
    stmt.setMaxRows(maxRows);
    // 填充sql元信息
    fillSqlMetaData(stmt, sql);
    return stmt;
}
 
Example 3
Source File: ResultSetEnumerable.java    From Quicksql with MIT License 6 votes vote down vote up
private void setTimeoutIfPossible(Statement statement) throws SQLException {
  if (timeout == 0) {
    return;
  }
  long now = System.currentTimeMillis();
  long secondsLeft = (queryStart + timeout - now) / 1000;
  if (secondsLeft <= 0) {
    throw Static.RESOURCE.queryExecutionTimeoutReached(
        String.valueOf(timeout),
        String.valueOf(Instant.ofEpochMilli(queryStart))).ex();
  }
  if (secondsLeft > Integer.MAX_VALUE) {
    // Just ignore the timeout if it happens to be too big, we can't squeeze it into int
    return;
  }
  try {
    statement.setQueryTimeout((int) secondsLeft);
  } catch (SQLFeatureNotSupportedException e) {
    if (!timeoutSetFailed && LOGGER.isDebugEnabled()) {
      // We don't really want to print this again and again if enumerable is used multiple times
      LOGGER.debug("Failed to set query timeout " + secondsLeft + " seconds", e);
      timeoutSetFailed = true;
    }
  }
}
 
Example 4
Source File: RDB.java    From tuffylite with Apache License 2.0 6 votes vote down vote up
public Statement createStatementWithTimeout(int resultSetType, int resultSetConcurrency) throws SQLException  {
	Statement stm = con.createStatement(resultSetType, resultSetConcurrency);
	if (Config.timeout > 0 && !Config.mcsatTimedOut && !Config.exiting_mode) {
		int secondsLeft;
		if (Config.inGroundingPhase) {
			secondsLeft = Timer.secondsToGroundingTimeOut();
			if (secondsLeft <= 0) {
				ExceptionMan.die("Timeout during grounding");
			}
		} else {
			secondsLeft = Timer.secondsToTimeOut();
		}			
		if (secondsLeft <= 0) {
			ExceptionMan.die("Trying to set query timeout to value <= 0");
		}
		stm.setQueryTimeout(secondsLeft);
	}
	return stm;
}
 
Example 5
Source File: SetQueryTimeoutTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/** Test that a statement remembers its timeout value when executed
 * multiple times. */
private static void testStatementRemembersTimeout(Statement stmt)
    throws SQLException, TestFailedException
{
    System.out.println("Testing that Statement remembers timeout.");
    stmt.setQueryTimeout(1);
    for (int i = 0; i < 3; i++) {
        try {
            ResultSet rs = stmt.executeQuery(getFetchQuery("t"));
            while (rs.next());
            throw new TestFailedException("Should have timed out.");
        } catch (SQLException sqle) {
            expectException("XCL52", sqle, "Should have timed out.");
        }
    }
    stmt.close();
}
 
Example 6
Source File: SetQueryTimeoutTest.java    From spliceengine with GNU Affero General Public License v3.0 6 votes vote down vote up
/** Test that a statement remembers its timeout value when executed
 * multiple times. */
private static void testStatementRemembersTimeout(Statement stmt)
    throws SQLException, TestFailedException
{
    System.out.println("Testing that Statement remembers timeout.");
    stmt.setQueryTimeout(1);
    for (int i = 0; i < 3; i++) {
        try {
            ResultSet rs = stmt.executeQuery(getFetchQuery("t"));
            while (rs.next());
            throw new TestFailedException("Should have timed out.");
        } catch (SQLException sqle) {
            expectException("XCL52", sqle, "Should have timed out.");
        }
    }
    stmt.close();
}
 
Example 7
Source File: DataSource.java    From glowroot with Apache License 2.0 6 votes vote down vote up
public void execute(@Untainted String sql) throws SQLException {
    debug(sql);
    synchronized (lock) {
        if (closed) {
            return;
        }
        checkConnectionUnderLock();
        Statement statement = connection.createStatement();
        StatementCloser closer = new StatementCloser(statement);
        try {
            // setQueryTimeout() affects all statements of this connection (at least with h2)
            statement.setQueryTimeout(0);
            statement.execute(sql);
        } catch (Throwable t) {
            throw closer.rethrow(t);
        } finally {
            closer.close();
        }
    }
}
 
Example 8
Source File: TGroupStatement.java    From tddl5 with Apache License 2.0 6 votes vote down vote up
/**
 * 会调用setBaseStatement以关闭已有的Statement
 */
private Statement createStatementInternal(Connection conn, String sql, boolean isBatch) throws SQLException {
    Statement stmt;
    if (isBatch) {
        stmt = conn.createStatement();
    } else {
        int resultSetHoldability = this.resultSetHoldability;
        if (resultSetHoldability == -1) {// 未调用过setResultSetHoldability
            resultSetHoldability = conn.getHoldability();
        }
        stmt = conn.createStatement(this.resultSetType, this.resultSetConcurrency, resultSetHoldability);
    }

    setBaseStatement(stmt); // 会关闭已有的Statement
    stmt.setQueryTimeout(queryTimeout); // 这句也有可能抛出异常,放在最后
    stmt.setFetchSize(fetchSize);
    stmt.setMaxRows(maxRows);
    // 填充sql元信息
    if (stmt instanceof DataChannel) {
        ((DataChannel) stmt).fillMetaData(sqlMetaData);
    }
    return stmt;
}
 
Example 9
Source File: QueryTimeoutInterceptor.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
public Object createStatement(Object proxy, Method method, Object[] args, Object statement, long time) {
    if (statement instanceof Statement && timeout > 0) {
        Statement s = (Statement)statement;
        try {
            s.setQueryTimeout(timeout);
        }catch (SQLException x) {
            log.warn("[QueryTimeoutInterceptor] Unable to set query timeout:"+x.getMessage(),x);
        }
    }
    return statement;
}
 
Example 10
Source File: QuarkQueryExecutor.java    From quark with Apache License 2.0 5 votes vote down vote up
public Object execute(ParserResult parserResult) throws Exception {
  Object object = null;
  final DataSourceSchema dataSourceSchema =
      ((SqlQueryParser.SqlQueryParserResult) parserResult).getDataSource();

  if (dataSourceSchema != null) {
    Connection conn;
    final String id = dataSourceSchema.getName();
    Executor executor = (Executor) dataSourceSchema.getDataSource();
    String parsedSql = parserResult.getParsedSql();

    LOG.info("Execute query[" + parsedSql + "]");

    if (executor instanceof JdbcDB) {
      conn = getExecutorConnection(id, executor);
      Statement statement = conn.createStatement();
      try {
        statement.setQueryTimeout(QUERY_TIMEOUT);
      } catch (Exception e) {
        LOG.warn("Couldnot set Query Timeout to " + QUERY_TIMEOUT + " seconds", e);
      }
      object = statement.executeQuery(parsedSql);
    } else {
      object = executor.executeQuery(parsedSql);
    }
  }
  return object;
}
 
Example 11
Source File: StatementJdbc30Test.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * DERBY-3198: Verify that a statement can be executed
 * more than 32000 times, even when query timeout is enabled.
 */
public void xtestMultiExecWithQueryTimeout() throws SQLException {
    Statement stmt = createStatement();
    stmt.setQueryTimeout(10);
    for (int i = 0; i < 33000; ++i) {
        ResultSet rs = stmt.executeQuery("VALUES(1)");
        rs.close();
    }
}
 
Example 12
Source File: TestValidationQueryTimeout.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Test
public void testLongValidationQueryTime() throws Exception {
    // use our mock driver
    this.datasource.setDriverClassName("org.h2.Driver");
    this.datasource.setUrl("jdbc:h2:~/.h2/test;QUERY_TIMEOUT=0;DB_CLOSE_ON_EXIT=FALSE");
    Connection con = this.datasource.getConnection();
    Statement stmt = null;
    long start = 0, end = 0;
    try {
        stmt = con.createStatement();
        // set the query timeout to 2 sec
        //  this keeps this test from slowing things down too much
        stmt.setQueryTimeout(2);
        // assert that our long query takes longer than one second to run
        //  this is a requirement for other tests to run properly
        start = System.currentTimeMillis();
        stmt.execute(longQuery);
    } catch (SQLException ex) {}
    finally {
        end = System.currentTimeMillis();

        if (stmt != null) { stmt.close(); }
        if (con != null) { con.close(); }

        Assert.assertTrue(start != 0 && end != 0);
        Assert.assertTrue((end - start) > 1000);
    }
}
 
Example 13
Source File: PGValidConnectionChecker_t.java    From coming with MIT License 5 votes vote down vote up
public boolean isValidConnection(Connection conn, String validateQuery, int validationQueryTimeout) throws Exception {
    if (validateQuery == null || validateQuery.isEmpty()) {
        validateQuery = this.defaultValidateQuery;
    }

    if (conn.isClosed()) {
        return false;
    }

    if (conn instanceof DruidPooledConnection) {
        conn = ((DruidPooledConnection) conn).getConnection();
    }

    if (conn instanceof ConnectionProxy) {
        conn = ((ConnectionProxy) conn).getRawObject();
    }

    int queryTimeout = validationQueryTimeout <= 0 ? defaultQueryTimeout : validationQueryTimeout;

    Statement stmt = null;
    ResultSet rs = null;
    try {
        stmt = conn.createStatement();
        if(queryTimeout>=0){
            //pgsql Driver 9.0以及以下版本不支持setQueryTimeout,可通过设置queryTimeout<0兼容低版本
            stmt.setQueryTimeout(queryTimeout);
        }
        rs = stmt.executeQuery(validateQuery);
        return true;
    } finally {
        JdbcUtils.close(rs);
        JdbcUtils.close(stmt);
    }
}
 
Example 14
Source File: QueryTimeOutDUnit.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
   * @param timOutOnCallableStmt - time out (in seconds) set on the outer 
   * callable stmt
   */
  public static void myProc2(int timOutOnCallableStmt, 
      int[] count, ResultSet[] resultSet1,
      ResultSet[] resultSet2,
      ProcedureExecutionContext ctx) 
          throws SQLException, InterruptedException {
    Connection conn = ctx.getConnection();
//    Connection conn = DriverManager.getConnection("jdbc:default:connection");
    
    Statement stmt = conn.createStatement();
    
    // make sure that by default the timeout for statement in proc is same as 
    // that of outer callable statement's time out
    assertEquals(timOutOnCallableStmt, stmt.getQueryTimeout());
    
    // timeout cannot be more than the outer callable stmt's timeout, so the 
    // time out will be set to outer statement's timeout
    stmt.setQueryTimeout(timOutOnCallableStmt + 1);
    SQLWarning sw = stmt.getWarnings();
    if (sw != null) {
      if (!sw.getSQLState().equals("01509")) {
//        fail("Expected warning state 01509. Received warning:" + sw.getSQLState());
        throw sw;
      } // else ignore
    }
    else {
      fail("This test should have thrown a warning(01509) as query time out "
          + "for statement in stored procedure can not be more "
          + "than outer callable statement's time out");
    }
    assertEquals(timOutOnCallableStmt, stmt.getQueryTimeout());

    // set different(lesser) timeout for stmt in sproc
    stmt.setQueryTimeout(1); 
    assertEquals(1, stmt.getQueryTimeout());
    
    stmt.execute("select * from mytable");
    resultSet1[0] = stmt.getResultSet();
    
    Statement stmt3 = conn.createStatement();
    stmt3 .execute("select count(*) from mytable");
    stmt3.getResultSet().next();
    Integer cnt = stmt3.getResultSet().getInt(1);
    count[0] = cnt;
    
    Statement stmt2 = conn.createStatement();
    stmt2.execute("select count(*) from mytable");
    resultSet2[0] = stmt2.getResultSet();
  }
 
Example 15
Source File: SQLQueryService.java    From cs-actions with Apache License 2.0 4 votes vote down vote up
public static void executeSqlQuery(@NotNull final SQLInputs sqlInputs) throws Exception {
    if (StringUtils.isEmpty(sqlInputs.getSqlCommand())) {
        throw new Exception("command input is empty.");
    }
    ConnectionService connectionService = new ConnectionService();
    try (final Connection connection = connectionService.setUpConnection(sqlInputs)) {

        connection.setReadOnly(true);
        Statement statement = connection.createStatement(sqlInputs.getResultSetType(), sqlInputs.getResultSetConcurrency());
        statement.setQueryTimeout(sqlInputs.getTimeout());
        final ResultSet results = statement.executeQuery(sqlInputs.getSqlCommand());

        final ResultSetMetaData mtd = results.getMetaData();

        int iNumCols = mtd.getColumnCount();

        final StringBuilder strColumns = new StringBuilder(sqlInputs.getStrColumns());

        for (int i = 1; i <= iNumCols; i++) {
            if (i > 1) {
                strColumns.append(sqlInputs.getStrDelim());
            }
            strColumns.append(mtd.getColumnLabel(i));
        }
        sqlInputs.setStrColumns(strColumns.toString());

        while (results.next()) {
            final StringBuilder strRowHolder = new StringBuilder();
            for (int i = 1; i <= iNumCols; i++) {
                if (i > 1) strRowHolder.append(sqlInputs.getStrDelim());
                if (results.getString(i) != null) {
                    String value = results.getString(i).trim();
                    if (sqlInputs.isNetcool())
                        value = SQLUtils.processNullTerminatedString(value);

                    strRowHolder.append(value);
                }
            }
            sqlInputs.getLRows().add(strRowHolder.toString());
        }
    }
}
 
Example 16
Source File: ACS.java    From freeacs with MIT License 4 votes vote down vote up
private void readGroups(Unittypes unittypes) throws SQLException {
  Statement s = null;
  ResultSet rs = null;
  String sql;
  boolean wasAutoCommit = false;
  Connection connection = null;
  try {
    Map<String, Group> nameMap = null;
    Map<Integer, Group> idMap = null;
    Unittype lastUnittype = null;
    sql = "SELECT * FROM group_ ORDER BY unit_type_id ASC";
    connection = getDataSource().getConnection();
    wasAutoCommit = connection.getAutoCommit();
    connection.setAutoCommit(false);
    s = connection.createStatement();
    s.setQueryTimeout(60);
    rs = s.executeQuery(sql);
    int counter = 0;
    while (rs.next()) {
      counter++;

      // Read row data
      Unittype unittype = unittypes.getById(rs.getInt("unit_type_id"));
      Integer groupId = rs.getInt("group_id");
      String groupName = rs.getString("group_name");
      String description = rs.getString("description");
      String parentIdStr = rs.getString("parent_group_id");
      String profileIdStr = rs.getString("profile_id");
      Integer count;
      count = rs.getInt("count");

      // Make maps
      if (lastUnittype == null || lastUnittype != unittype) {
        nameMap = new MapWrapper<Group>(isStrictOrder()).getMap();
        idMap = new HashMap<>();
        unittype.setGroups(new Groups(idMap, nameMap, unittype));
        lastUnittype = unittype;
      }

      // Populate group object, make empty parent object if necessary
      // Populate maps
      Group parent = null;
      if (parentIdStr != null) {
        Integer parentId = Integer.valueOf(parentIdStr);
        parent = idMap.get(parentId);
        if (parent == null) {
          parent = new Group(parentId);
          idMap.put(parentId, parent);
        }
      }
      Group thisGroup = idMap.get(groupId);
      if (thisGroup == null) {
        thisGroup = new Group(groupId);
        idMap.put(groupId, thisGroup);
      }
      thisGroup.setUnittype(unittype);
      thisGroup.setName(groupName);
      thisGroup.setDescription(description);
      thisGroup.setCount(count);
      if (profileIdStr != null) {
        Integer profileId = Integer.parseInt(profileIdStr);
        thisGroup.setProfile(unittype.getProfiles().getById(profileId));
      }
      thisGroup.setParent(parent);
      if (parent != null) {
        parent.addChild(thisGroup);
      }

      nameMap.put(groupName, thisGroup);
    }
    if (logger.isDebugEnabled()) {
      logger.debug("Read " + counter + " groups");
    }
  } finally {
    if (rs != null) {
      rs.close();
    }
    if (s != null) {
      s.close();
    }
    if (connection != null) {
      connection.setAutoCommit(wasAutoCommit);
      connection.close();
    }
  }
}
 
Example 17
Source File: SWStatementTest.java    From skywalking with Apache License 2.0 4 votes vote down vote up
@Test
public void testPreparedStatementConfig() throws SQLException {
    Statement statement = swConnection.createStatement();
    statement.cancel();
    statement.getUpdateCount();
    statement.setFetchDirection(1);
    statement.getFetchDirection();
    statement.getResultSetConcurrency();
    statement.getResultSetType();
    statement.isClosed();
    statement.setPoolable(false);
    statement.isPoolable();
    statement.getWarnings();
    statement.clearWarnings();
    statement.setCursorName("test");
    statement.setMaxFieldSize(11);
    statement.getMaxFieldSize();
    statement.setMaxRows(10);
    statement.getMaxRows();
    statement.setEscapeProcessing(true);
    statement.setFetchSize(1);
    statement.getFetchSize();
    statement.setQueryTimeout(1);
    statement.getQueryTimeout();
    Connection connection = statement.getConnection();

    statement.execute("SELECT * FROM test");
    statement.getMoreResults();
    statement.getMoreResults(1);
    statement.getResultSetHoldability();
    statement.getResultSet();

    statement.close();
    verify(mysqlStatement).getUpdateCount();
    verify(mysqlStatement).getMoreResults();
    verify(mysqlStatement).setFetchDirection(anyInt());
    verify(mysqlStatement).getFetchDirection();
    verify(mysqlStatement).getResultSetType();
    verify(mysqlStatement).isClosed();
    verify(mysqlStatement).setPoolable(anyBoolean());
    verify(mysqlStatement).getWarnings();
    verify(mysqlStatement).clearWarnings();
    verify(mysqlStatement).setCursorName(anyString());
    verify(mysqlStatement).setMaxFieldSize(anyInt());
    verify(mysqlStatement).getMaxFieldSize();
    verify(mysqlStatement).setMaxRows(anyInt());
    verify(mysqlStatement).getMaxRows();
    verify(mysqlStatement).setEscapeProcessing(anyBoolean());
    verify(mysqlStatement).getResultSetConcurrency();
    verify(mysqlStatement).getResultSetConcurrency();
    verify(mysqlStatement).getResultSetType();
    verify(mysqlStatement).getMoreResults(anyInt());
    verify(mysqlStatement).setFetchSize(anyInt());
    verify(mysqlStatement).getFetchSize();
    verify(mysqlStatement).getQueryTimeout();
    verify(mysqlStatement).setQueryTimeout(anyInt());
    verify(mysqlStatement).getResultSet();
    assertThat(connection, CoreMatchers.<Connection>is(swConnection));

    TraceSegment traceSegment = segmentStorage.getTraceSegments().get(0);
    List<AbstractTracingSpan> spans = SegmentHelper.getSpans(traceSegment);
    assertThat(spans.size(), is(1));
    assertDBSpan(spans.get(0), "Mysql/JDBI/Statement/execute", "SELECT * FROM test");
}
 
Example 18
Source File: QueryTimeOutDUnit.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
/**
   * @param timOutOnCallableStmt - time out (in seconds) set on the outer 
   * callable stmt
   */
  public static void myProc2(int timOutOnCallableStmt, 
      int[] count, ResultSet[] resultSet1,
      ResultSet[] resultSet2,
      ProcedureExecutionContext ctx) 
          throws SQLException, InterruptedException {
    Connection conn = ctx.getConnection();
//    Connection conn = DriverManager.getConnection("jdbc:default:connection");
    
    Statement stmt = conn.createStatement();
    
    // make sure that by default the timeout for statement in proc is same as 
    // that of outer callable statement's time out
    assertEquals(timOutOnCallableStmt, stmt.getQueryTimeout());
    
    // timeout cannot be more than the outer callable stmt's timeout, so the 
    // time out will be set to outer statement's timeout
    stmt.setQueryTimeout(timOutOnCallableStmt + 1);
    SQLWarning sw = stmt.getWarnings();
    if (sw != null) {
      if (!sw.getSQLState().equals("01509")) {
//        fail("Expected warning state 01509. Received warning:" + sw.getSQLState());
        throw sw;
      } // else ignore
    }
    else {
      fail("This test should have thrown a warning(01509) as query time out "
          + "for statement in stored procedure can not be more "
          + "than outer callable statement's time out");
    }
    assertEquals(timOutOnCallableStmt, stmt.getQueryTimeout());

    // set different(lesser) timeout for stmt in sproc
    stmt.setQueryTimeout(1); 
    assertEquals(1, stmt.getQueryTimeout());
    
    stmt.execute("select * from mytable");
    resultSet1[0] = stmt.getResultSet();
    
    Statement stmt3 = conn.createStatement();
    stmt3 .execute("select count(*) from mytable");
    stmt3.getResultSet().next();
    Integer cnt = stmt3.getResultSet().getInt(1);
    count[0] = cnt;
    
    Statement stmt2 = conn.createStatement();
    stmt2.execute("select count(*) from mytable");
    resultSet2[0] = stmt2.getResultSet();
  }
 
Example 19
Source File: Database.java    From burp-hash with MIT License 4 votes vote down vote up
/**
 * initialize the database
 */
boolean init() 
{
	Statement stmt = null;
	try 
	{
		if (conn == null) 
		{
			conn = getConnection();
		}
		stmt = conn.createStatement();
		stmt.setQueryTimeout(30);
		stdOut.println(" + Rebuilding all DB tables.");
		String sql_dropTables = "DROP TABLE IF EXISTS params; DROP TABLE IF EXISTS hashes; DROP TABLE IF EXISTS algorithms;";
		stmt.executeUpdate(sql_dropTables);
		String sql_createAlgoTable = "CREATE TABLE algorithms (ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, Name TEXT NOT NULL)";
		stmt.executeUpdate(sql_createAlgoTable);
		String sql_createParamTable = "CREATE TABLE params (ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, value TEXT NOT NULL)";
		stmt.executeUpdate(sql_createParamTable);
		String sql_createHashTable = "CREATE TABLE hashes (ID INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, algorithmID INTEGER NOT NULL, paramID INTEGER, value TEXT NOT NULL)";
		stmt.executeUpdate(sql_createHashTable);
		stdOut.println(" + Adding " + config.hashAlgorithms.size() + " hash algorithms to DB.");
		Collections.reverse(config.hashAlgorithms); //so the db has ascending order
		String sql_insertAlgo = "INSERT OR REPLACE INTO algorithms(name, ID) VALUES (?, ?)";
		for (HashAlgorithm algo : config.hashAlgorithms)
		{
			pstmt = conn.prepareStatement(sql_insertAlgo);
			pstmt.setString(1, algo.name.text);
			pstmt.setString(2, Integer.toString(algo.id));
			pstmt.executeUpdate();
			stdOut.println(" + Adding Hash Algorithm to DB: " + algo.name.text + ", " + algo.id);
		}
		Collections.reverse(config.hashAlgorithms); //back to descending order for hash searching
		stdOut.println(moduleName + ": Database initialized.");
		return true;
	} 
	catch (SQLException e) 
	{
		stdErr.println(e.getMessage());
		return false;
	}
	catch (Exception ex)
	{
		stdErr.println(ex);
		return false;
	}
}
 
Example 20
Source File: PooledConnection.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
/**
 * Validates a connection.
 * @param validateAction the action used. One of {@link #VALIDATE_BORROW}, {@link #VALIDATE_IDLE},
 * {@link #VALIDATE_INIT} or {@link #VALIDATE_RETURN}
 * @param sql the SQL to be used during validation. If the {@link PoolConfiguration#setInitSQL(String)} has been called with a non null
 * value and the action is {@link #VALIDATE_INIT} the init SQL will be used for validation.
 *
 * @return true if the connection was validated successfully. It returns true even if validation was not performed, such as when
 * {@link PoolConfiguration#setValidationInterval(long)} has been called with a positive value.
 * <p>
 * false if the validation failed. The caller should close the connection if false is returned since a session could have been left in
 * an unknown state during initialization.
 */
public boolean validate(int validateAction,String sql) {
    if (this.isDiscarded()) {
        return false;
    }

    if (!doValidate(validateAction)) {
        //no validation required, no init sql and props not set
        return true;
    }

    //Don't bother validating if already have recently enough
    long now = System.currentTimeMillis();
    if (validateAction!=VALIDATE_INIT &&
        poolProperties.getValidationInterval() > 0 &&
        (now - this.lastValidated) <
        poolProperties.getValidationInterval()) {
        return true;
    }

    if (poolProperties.getValidator() != null) {
        if (poolProperties.getValidator().validate(connection, validateAction)) {
            this.lastValidated = now;
            return true;
        } else {
            if (getPoolProperties().getLogValidationErrors()) {
                log.error("Custom validation through "+poolProperties.getValidator()+" failed.");
            }
            return false;
        }
    }

    String query = sql;

    if (validateAction == VALIDATE_INIT && poolProperties.getInitSQL() != null) {
        query = poolProperties.getInitSQL();
    }

    if (query == null) {
        query = poolProperties.getValidationQuery();
    }

    Statement stmt = null;
    try {
        stmt = connection.createStatement();

        int validationQueryTimeout = poolProperties.getValidationQueryTimeout();
        if (validationQueryTimeout > 0) {
            stmt.setQueryTimeout(validationQueryTimeout);
        }

        stmt.execute(query);
        stmt.close();
        this.lastValidated = now;
        return true;
    } catch (Exception ex) {
        if (getPoolProperties().getLogValidationErrors()) {
            log.warn("SQL Validation error", ex);
        } else if (log.isDebugEnabled()) {
            log.debug("Unable to validate object:",ex);
        }
        if (stmt!=null)
            try { stmt.close();} catch (Exception ignore2){/*NOOP*/}
    }
    return false;
}