/** * @param connection a connection to the DB (won't be closed by this method) * @param version the version to set for all servers * @throws SQLException */ public int setVersionForAllServers(Connection connection, String version) throws SQLException { PreparedStatement preparedStatement = null; try { preparedStatement = connection.prepareStatement("UPDATE RHQ_SERVER SET VERSION = ?"); preparedStatement.setString(1, version); return preparedStatement.executeUpdate(); } finally { JDBCUtil.safeClose(null, preparedStatement, null); } } }
/** * @param connection a connection to the DB (won't be closed by this method) * @param version the version to set for all nodes * @throws SQLException */ public int setVersionForAllNodes(Connection connection, String version) throws SQLException { PreparedStatement preparedStatement = null; try { preparedStatement = connection.prepareStatement("UPDATE RHQ_STORAGE_NODE SET VERSION = ?"); preparedStatement.setString(1, version); return preparedStatement.executeUpdate(); } finally { JDBCUtil.safeClose(null, preparedStatement, null); } } }
@PostConstruct public void init() { Connection conn = null; try { conn = rhqDs.getConnection(); databaseType = DatabaseTypeFactory.getDatabaseType(conn); } catch (Exception e) { throw new RuntimeException(e); } finally { JDBCUtil.safeClose(conn); } }
/** * @param connection a connection to the DB (won't be closed by this method) * @param version the version to set for server with the specified <code>name</code> * @param name server name * @throws java.sql.SQLException */ public int setVersionForServerWithName(Connection connection, String version, String name) throws SQLException { PreparedStatement preparedStatement = null; try { preparedStatement = connection.prepareStatement("UPDATE RHQ_SERVER SET VERSION = ? WHERE NAME = ?"); preparedStatement.setString(1, version); preparedStatement.setString(2, name); return preparedStatement.executeUpdate(); } finally { JDBCUtil.safeClose(null, preparedStatement, null); } }
/** * @param connection a connection to the DB (won't be closed by this method) * @param version the version to set for node with the specified <code>address</code> * @param address storage node address * @throws SQLException */ public int setVersionForNodeWithAddress(Connection connection, String version, String address) throws SQLException { PreparedStatement preparedStatement = null; try { preparedStatement = connection .prepareStatement("UPDATE RHQ_STORAGE_NODE SET VERSION = ? WHERE ADDRESS = ?"); preparedStatement.setString(1, version); preparedStatement.setString(2, address); return preparedStatement.executeUpdate(); } finally { JDBCUtil.safeClose(null, preparedStatement, null); } }
private void clearImplicitResources(int resourceGroupId) throws ResourceGroupUpdateException { Connection conn = null; PreparedStatement removeImplicitStatement = null; try { conn = rhqDs.getConnection(); removeImplicitStatement = conn.prepareStatement(ResourceGroup.QUERY_UPDATE_REMOVE_IMPLICIT); removeImplicitStatement.setInt(1, resourceGroupId); removeImplicitStatement.executeUpdate(); } catch (SQLException sqle) { log.error("Error removing implicit resources from group[id=" + resourceGroupId + "]: ", sqle); throw new ResourceGroupUpdateException("Error removing implicit resources from group[id=" + resourceGroupId + "]: " + sqle.getMessage()); } finally { JDBCUtil.safeClose(removeImplicitStatement); JDBCUtil.safeClose(conn); } }
/** * Get the most recent measurement. */ private long getMaxTimestamp(String dataTable) throws SQLException { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { conn = dataSource.getConnection(); String sql = "SELECT MAX(time_stamp) FROM " + dataTable; // returns null rows if nothing exists stmt = conn.createStatement(); rs = stmt.executeQuery(sql); // We'll have a single result if (rs.next()) { return rs.getLong(1); } else { // New installation return 0L; } } finally { JDBCUtil.safeClose(conn, stmt, rs); } }
private void makeImplicitMirrorExplicit(int resourceGroupId) throws ResourceGroupUpdateException { Connection conn = null; PreparedStatement updateImplicitMirrorExplicitStatement = null; try { conn = rhqDs.getConnection(); updateImplicitMirrorExplicitStatement = conn .prepareStatement(ResourceGroup.QUERY_UPDATE_IMPLICIT_MIRROR_EXPLICIT); updateImplicitMirrorExplicitStatement.setInt(1, resourceGroupId); updateImplicitMirrorExplicitStatement.executeUpdate(); } catch (SQLException sqle) { log.error("Error making implicit resources mirror explicit resources for group[id=" + resourceGroupId + "]: ", sqle); throw new ResourceGroupUpdateException( "Error making implicit resources mirror explicit resources for group[id=" + resourceGroupId + "]: " + sqle.getMessage()); } finally { JDBCUtil.safeClose(updateImplicitMirrorExplicitStatement); JDBCUtil.safeClose(conn); } }
/** * Get the oldest timestamp in the database. Getting the minimum time is expensive, so this is only called once when * the compression routine runs for the first time. After the first call, the range is cached. */ private long getMinTimestamp(String dataTable) throws SQLException { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { conn = dataSource.getConnection(); String sql = "SELECT MIN(time_stamp) FROM " + dataTable; // returns null rows if nothing exists stmt = conn.createStatement(); rs = stmt.executeQuery(sql); // We'll have a single result if (rs.next()) { return rs.getLong(1); } else { throw new SQLException("Unable to determine oldest measurement"); } } finally { JDBCUtil.safeClose(conn, stmt, rs); } }
public static void main(String[] args) throws ClassNotFoundException, SQLException { String driver = System.getProperty("driver", "org.postgresql.Driver"); String url = System.getProperty("url", "jdbc:postgresql://127.0.0.1:5432"); String username = System.getProperty("username", "jon"); String password = System.getProperty("password", "jon"); int numSchedules = Integer.parseInt(System.getProperty("numSchedules", "5")); System.out.println("driver=" + driver); System.out.println("url=" + url); System.out.println("username=" + username); System.out.println("password=" + password); System.out.println("numSchedules=" + numSchedules); System.out.println("(to override these, set system properties of the same names as above)"); Class.forName(driver); c = DriverManager.getConnection(url, username, password); try { long time = System.currentTimeMillis() - (7L * 24 * HOUR); time = time - (time % HOUR); for (int i = 0; i < (7 * 24); i++) { long bucket = time + (i * HOUR); insert(bucket, numSchedules); } } finally { JDBCUtil.safeClose(c, null, null); } } }
private void deactivateCacheIfNecessary(Date mostRecent24HourTimeSlice) { Connection connection = null; Statement statement = null; try { DateTime current24HourTimeSlice = get24HourTimeSlice(new Date()); if (current24HourTimeSlice.isAfter(mostRecent24HourTimeSlice.getTime())) { log.info("The metrics cache will not be deactivated since the most recent raw data is from before today - " + mostRecent24HourTimeSlice); } else { DateTime next24HourTimeSlice = current24HourTimeSlice.plusDays(1); log.info("The metrics cache will be come active at " + next24HourTimeSlice); connection = dbConnectionFactory.newConnection(); statement = connection.createStatement(); statement.executeUpdate("UPDATE rhq_system_config SET property_value = '" + next24HourTimeSlice.getMillis() + "' WHERE property_key = 'METRICS_CACHE_ACTIVATION_TIME'"); } } catch (SQLException e) { throw new RuntimeException("Failed to deactivate metrics cache", e); } finally { JDBCUtil.safeClose(statement); JDBCUtil.safeClose(connection); } }
@RequiredPermission(Permission.MANAGE_INVENTORY) @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public void removeAllResourcesFromGroup(Subject subject, int groupId) throws ResourceGroupDeleteException { Connection conn = null; PreparedStatement explicitStatement = null; PreparedStatement implicitStatement = null; try { conn = rhqDs.getConnection(); explicitStatement = conn .prepareStatement("delete from rhq_resource_group_res_exp_map where resource_group_id = ?"); implicitStatement = conn .prepareStatement("delete from rhq_resource_group_res_imp_map where resource_group_id = ?"); explicitStatement.setInt(1, groupId); implicitStatement.setInt(1, groupId); explicitStatement.executeUpdate(); implicitStatement.executeUpdate(); } catch (SQLException sqle) { log.error("Error removing group resources", sqle); throw new ResourceGroupDeleteException("Error removing group resources: " + sqle.getMessage()); } finally { JDBCUtil.safeClose(explicitStatement); JDBCUtil.safeClose(implicitStatement); JDBCUtil.safeClose(conn); } }
private Set<String> findForeignKeys(String query, String tableParam, String columnParam) { Set<String> foreignKeys = new HashSet<String>(); PreparedStatement statement = null; ResultSet resultSet = null; try { statement = getConnection().prepareStatement(query); statement.setString(1, tableParam); statement.setString(2, columnParam); resultSet = statement.executeQuery(); while (resultSet.next()) { foreignKeys.add(resultSet.getString(1)); } } catch (SQLException e) { if (!isIgnoreError()) { log(ThrowableUtil.getAllSqlExceptionMessages(e), MSG_WARN); } else { throw new BuildException(e); } } finally { safeClose(statement, resultSet); } return foreignKeys; }
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public void truncateMeasurements(String tableName) throws SQLException { // Make sure we only truncate the dead table... other tables may have live data in them if (tableName.equals(MeasurementDataManagerUtility.getDeadTable(System.currentTimeMillis()))) { Connection conn = null; Statement stmt = null; StopWatch watch = new StopWatch(); try { conn = dataSource.getConnection(); stmt = conn.createStatement(); long startTime = System.currentTimeMillis(); stmt.executeUpdate("TRUNCATE TABLE " + tableName); MeasurementMonitor.getMBean().incrementPurgeTime(System.currentTimeMillis() - startTime); } finally { JDBCUtil.safeClose(conn, stmt, null); log.info("Truncated table [" + tableName + "] in [" + (watch.getElapsed() / SECOND) + "] seconds"); } } } }
public MeasurementAggregate getAggregateByScheduleId(long beginTime, long endTime, long scheduleId) throws MeasurementNotFoundException { Connection connection = null; PreparedStatement ps = null; ResultSet rs = null; try { connection = datasource.getConnection(); String condition = " AND d.schedule_id = ? \n"; ps = getFullQuery("getAggregateByScheduleId", connection, beginTime, endTime, 1, condition, scheduleId); rs = ps.executeQuery(); if (rs.next()) { MeasurementAggregate measurementAggregate = fillAggregateFromResultSet(rs); return measurementAggregate; } throw new MeasurementNotFoundException("Data not found"); } catch (SQLException e) { throw new MeasurementNotFoundException(e); } finally { JDBCUtil.safeClose(connection, ps, rs); } }
private void dropForeignKey(String foreignKey) { Statement statement = null; try { String sql = "ALTER TABLE " + table + " DROP CONSTRAINT " + foreignKey; log(sql, MSG_INFO); statement = getConnection().createStatement(); statement.executeUpdate(sql); } catch (SQLException e) { if (!isIgnoreError()) { log(ThrowableUtil.getAllSqlExceptionMessages(e), MSG_WARN); } else { throw new BuildException(e); } } finally { safeClose(statement); } }
private int deleteRows(List<KEY> selectedKeys) throws Exception { Connection connection = null; PreparedStatement preparedStatement = null; try { userTransaction.begin(); String deleteRowByKeyQuery = getDeleteRowByKeyQuery(databaseType); connection = dataSource.getConnection(); preparedStatement = connection.prepareStatement(deleteRowByKeyQuery); for (KEY key : selectedKeys) { setDeleteRowByKeyQueryParams(preparedStatement, key); preparedStatement.addBatch(); } int[] batchResults = preparedStatement.executeBatch(); userTransaction.commit(); return evalDeletedRows(batchResults); } finally { JDBCUtil.safeClose(connection, preparedStatement, null); rollbackIfTransactionActive(); } }
public MeasurementAggregate getAggregateByDefinitionAndContext(long beginTime, long endTime, int definitionId, EntityContext context) throws MeasurementNotFoundException { Connection connection = null; PreparedStatement ps = null; ResultSet rs = null; try { String conditions = getQueryConditionsByDefinitionAndContext(definitionId, context); Object[] bindParams = getBindParamsByDefinitionAndContext(definitionId, context); connection = datasource.getConnection(); ps = getFullQuery("getAggregateByContext", connection, beginTime, endTime, 1, conditions, bindParams); rs = ps.executeQuery(); if (rs.next()) { MeasurementAggregate measurementAggregate = fillAggregateFromResultSet(rs); return measurementAggregate; } throw new MeasurementNotFoundException("Data not found"); } catch (SQLException e) { throw new MeasurementNotFoundException(e); } finally { JDBCUtil.safeClose(connection, ps, rs); } }