Java Code Examples for java.sql.Connection.isClosed()

The following are Jave code examples for showing how to use isClosed() of the java.sql.Connection class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: jetfuel   File: Database.java   View Source Code Vote up 6 votes
/**
 * Pops a connection from the pool and checks if it is open and the last
 * used time is below 19 minutes. If those things are false, it attempts to
 * close the connection. Otherwise it returns the connection or simply
 * instantiates a new one;
 * 
 * @return
 * @throws SQLException
 */
public synchronized Connection popConnection() throws SQLException {
	if (this.transaction_connection != null)
		return this.transaction_connection;

	else if (!connection_pool.isEmpty()) {
		Connection conn = connection_pool.removeFirst();
		Date conn_used = connection_last_used.removeFirst();
		if (!conn.isClosed()) {
			// 19 minutes threshold
			if (new Date().getTime() - conn_used.getTime() <= 1140000)
				return conn;

			// just close it and do nothing
			try {
				conn.close();
			} catch (Exception e) {
			}
		} // try to pop another one;
		return popConnection();
	}

	return properties == null
			? DriverManager.getConnection(url)
			: DriverManager.getConnection(url, properties);
}
 
Example 2
Project: elastic-db-tools-for-java   File: MultiShardTestUtils.java   View Source Code Vote up 6 votes
/**
 * Helper method that alters the column name on one of our test tables in one of our test databases. Useful for inducing a schema mismatch to test
 * our failure handling.
 *
 * @param database
 *            The 0-based index of the test database to change the schema in.
 * @param oldColName
 *            The current name of the column to change.
 * @param newColName
 *            The desired new name of the column.
 */
static void changeColumnNameOnShardedTable(int database,
        String oldColName,
        String newColName) throws SQLException {
    Connection conn = null;
    try {
        conn = DriverManager.getConnection(getTestConnectionString(testDatabaseNames.get(database)));
        try (Statement stmt = conn.createStatement()) {

            String tsql = String.format("EXEC sp_rename '[%1$s].[%2$s]', '%3$s', 'COLUMN';", TABLE_NAME, oldColName, newColName);

            stmt.executeUpdate(tsql);
        }
        catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
    catch (Exception e) {
        System.out.printf("Failed to connect to SQL database: " + e.getMessage());
    }
    finally {
        if (conn != null && !conn.isClosed()) {
            conn.close();
        }
    }
}
 
Example 3
Project: DBus   File: OracleManager.java   View Source Code Vote up 6 votes
/**
 * @return a Connection instance that can be used to connect to the
 * given database, if a previously-opened connection is available in
 * the cache. Returns null if none is available in the map.
 */
public synchronized Connection getConnection(String connectStr,
    String username) throws SQLException {
  CacheKey key = new CacheKey(connectStr, username);
  Connection cached = connectionMap.get(key);
  if (null != cached) {
    connectionMap.remove(key);
    if (cached.isReadOnly()) {
      // Read-only mode? Don't want it.
      cached.close();
    }

    if (cached.isClosed()) {
      // This connection isn't usable.
      return null;
    }

    cached.rollback(); // Reset any transaction state.
    cached.clearWarnings();

    LOG.debug("Got cached connection for " + key);
  }

  return cached;
}
 
Example 4
Project: my-diploma-work   File: QueriesImpl.java   View Source Code Vote up 6 votes
@Override
public List<Eat> getInfoAboutEatWith(int eatId) throws SQLException {
    Connection c = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    String sql = util.createSqlInfoEatWith(eatId);
    System.out.println(sql);
    List<Eat> eatList = new ArrayList<>();
    c = connectionDB.getConnection();
    if (!c.isClosed()) {
        ps = c.prepareStatement(sql);
        rs = ps.executeQuery();
        while (rs.next()) {
            eatList.add(new Eat(rs.getString(1), rs.getString(2), rs.getString(3)));
        }
    }
    connectionDB.closeConnection(c, ps, rs);
    return eatList;
}
 
Example 5
Project: my-diploma-work   File: QueriesImpl.java   View Source Code Vote up 6 votes
@Override
public List<Eat> getEatList() throws SQLException {
    Connection c = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    String sql = "select id,name from eat_name";
    System.out.println(sql);
    List<Eat> eatList = new ArrayList<>();
    try {
        c = connectionDB.getConnection();
        if (c.isClosed() == false) {
            ps = c.prepareStatement(sql);
            rs = ps.executeQuery();
            while (rs.next()) {
                eatList.add(new Eat(rs.getInt("id"), rs.getString("name")));
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        connectionDB.closeConnection(c, ps, rs);
    }
    return eatList;
}
 
Example 6
Project: apache-tomcat-7.0.73-with-comment   File: AbandonPercentageTest.java   View Source Code Vote up 6 votes
@Test
public void testResetConnection() throws Exception {
    int size = 1;
    this.datasource.setMaxActive(size);
    this.datasource.setMaxIdle(size);
    this.datasource.setInitialSize(0);
    this.datasource.getPoolProperties().setAbandonWhenPercentageFull(100);
    this.datasource.getPoolProperties().setTimeBetweenEvictionRunsMillis(100);
    this.datasource.getPoolProperties().setRemoveAbandoned(true);
    this.datasource.getPoolProperties().setRemoveAbandonedTimeout(1);
    this.datasource.getPoolProperties().setJdbcInterceptors(ResetAbandonedTimer.class.getName());
    Connection con = datasource.getConnection();
    Assert.assertEquals("Number of connections active/busy should be 1",1,datasource.getPool().getActive());
    for (int i=0; i<20; i++) {
        Thread.sleep(200);
        con.isClosed();
    }
    Assert.assertEquals("Number of connections active/busy should be 1",1,datasource.getPool().getActive());
    con.close();
}
 
Example 7
Project: apache-tomcat-7.0.73-with-comment   File: JDBCStore.java   View Source Code Vote up 6 votes
/**
 * Check the connection associated with this store, if it's
 * <code>null</code> or closed try to reopen it.
 * Returns <code>null</code> if the connection could not be established.
 *
 * @return <code>Connection</code> if the connection succeeded
 */
protected Connection getConnection() {
    Connection conn = null;
    try {
        conn = open();
        if (conn == null || conn.isClosed()) {
            manager.getContainer().getLogger().info(sm.getString(getStoreName() + ".checkConnectionDBClosed"));
            conn = open();
            if (conn == null || conn.isClosed()) {
                manager.getContainer().getLogger().info(sm.getString(getStoreName() + ".checkConnectionDBReOpenFail"));
            }
        }
    } catch (SQLException ex) {
        manager.getContainer().getLogger().error(sm.getString(getStoreName() + ".checkConnectionSQLException",
                ex.toString()));
    }

    return conn;
}
 
Example 8
Project: eXperDB-DB2PG   File: ExecuteQuery.java   View Source Code Vote up 5 votes
protected static void CloseConn(Connection conn, PreparedStatement pStmt) {
	try{
		if(pStmt != null) {
			pStmt.close();
		}
		if (conn != null && !conn.isClosed()) {
			conn.commit();
			conn.close();
			conn = null;
		}	
	}catch(Exception e){
		LogUtils.error(e.getMessage(),ExecuteQuery.class,e);
	}
}
 
Example 9
Project: elastic-db-tools-for-java   File: MultiShardResultSetTests.java   View Source Code Vote up 5 votes
/**
 * Gets a ResultSet by executing the passed in t-sql over the passed in connection.
 *
 * @param conn
 *            Connection to the database we wish to execute the t-sql against.
 * @param tsql
 *            The t-sql to execute.
 * @return The ResultSet obtained by executing the passed in t-sql over the passed in connection.
 */
private LabeledResultSet getReader(Connection conn,
        String tsql,
        String dbName) throws SQLException {
    String connStr = conn.getMetaData().getURL();
    SqlConnectionStringBuilder connStrBldr = new SqlConnectionStringBuilder(connStr);
    if (conn.isClosed()) {
        conn = DriverManager.getConnection(connStr);
    }
    Statement cmd = conn.createStatement();
    ResultSet sdr = cmd.executeQuery(tsql);

    return new LabeledResultSet(sdr, new ShardLocation(connStrBldr.getDataSource(), dbName), cmd);
}
 
Example 10
Project: ralasafe   File: DBUtil.java   View Source Code Vote up 5 votes
public static void close(Connection conn) {
	if (conn != null) {
		try {
			if (!conn.isClosed()) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			conn = null;
		}
	}
}
 
Example 11
Project: dble   File: TravelRecordInsertJob.java   View Source Code Vote up 5 votes
@Override
public void run() {
    Connection con = null;
    try {

        List<Map<String, String>> batch = getNextBatch();
        while (!batch.isEmpty()) {
            try {
                if (con == null || con.isClosed()) {
                    con = conPool.getConnection();
                    con.setAutoCommit(false);
                }

                insert(con, batch);
                finshiedCount.addAndGet(batch.size());
            } catch (Exception e) {
                e.printStackTrace();
                try {
                    con.rollback();
                } catch (SQLException e1) {
                    e1.printStackTrace();
                    e1.printStackTrace();
                }
                failedCount.addAndGet(batch.size());
            }
            batch = getNextBatch();
        }
    } finally {
        if (con != null) {
            this.conPool.returnCon(con);
        }
    }

}
 
Example 12
Project: my-diploma-work   File: QueriesImpl.java   View Source Code Vote up 5 votes
@Override
public int insertEat(String eatName) {
    int id = 0;
    Connection c = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    String sql = "insert into eat_name(name)values(?)";
    System.out.println(sql);
    c = connectionDB.getConnection();
    try {
        if (!c.isClosed()) {
            ps = c.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
            ps.setString(1, eatName);
            ps.executeUpdate();
            rs = ps.getGeneratedKeys();
            if (rs.next()) {
                id = rs.getInt(1);
            }
        } else {
            System.out.println("Connection is null");
        }
    } catch (SQLException ex) {
        ex.printStackTrace();
    } finally {
        try {
            connectionDB.closeConnection(c, ps, null);
        } catch (Exception e) {
        }
    }
    return id;
}
 
Example 13
Project: elastic-db-tools-for-java   File: SqlDatabaseUtils.java   View Source Code Vote up 5 votes
private static void connFinally(Connection conn) {
    try {
        if (conn != null && !conn.isClosed()) {
            conn.close();
        }
        else {
            ConsoleUtils.writeWarning("Returned Connection was either null or already closed.");
        }
    }
    catch (SQLException ex) {
        ex.printStackTrace();
    }
}
 
Example 14
Project: elastic-db-tools-for-java   File: ShardMapperTests.java   View Source Code Vote up 5 votes
private boolean tryOpenConnectionForKey(ListShardMap lsm,
        boolean openAsync) {
    boolean failed = false;
    Connection conn = null;
    try {
        if (openAsync) {
            conn = lsm.openConnectionForKeyAsync(2, Globals.SHARD_USER_CONN_STRING).call();
        }
        else {
            conn = lsm.openConnectionForKey(2, Globals.SHARD_USER_CONN_STRING);
        }
    }
    catch (Exception ex) {
        if (ex.getCause() != null && ex.getCause() instanceof SQLException) {
            failed = true;
        }
    }
    finally {
        try {
            if (conn != null && !conn.isClosed()) {
                conn.close();
            }
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
    }
    return failed;
}
 
Example 15
Project: elastic-db-tools-for-java   File: ShardMapManagerFactoryTests.java   View Source Code Vote up 5 votes
/**
 * Initializes common state for tests in this class.
 */
@BeforeClass
public static void shardMapManagerFactoryTestsInitialize() throws SQLException {
    Connection conn = null;
    try {
        conn = DriverManager.getConnection(Globals.SHARD_MAP_MANAGER_TEST_CONN_STRING);
        // Create ShardMapManager database
        try (Statement stmt = conn.createStatement()) {
            String query = String.format(Globals.CREATE_DATABASE_QUERY, Globals.SHARD_MAP_MANAGER_DATABASE_NAME);
            stmt.executeUpdate(query);
        }
        catch (SQLException ex) {
            ex.printStackTrace();
        }

        /*
         * Testing TryGetSqlShardMapManager failure case here instead of in TryGetShardMapManager_Fail() There is no method to cleanup GSM
         * objects, so if some other test runs in lab before TryGetShardMapManager_Fail, then this call will actually succeed as it will find
         * earlier SMM structures. Calling it just after creating database makes sure that GSM does not exist. Other options were to recreate SMM
         * database in tests (this will increase test duration) or delete storage structures (t-sql delete) in the test which is not very clean
         * solution.
         */

        ShardMapManager smm = null;
        ReferenceObjectHelper<ShardMapManager> smmref = new ReferenceObjectHelper<>(smm);
        boolean lookupSmm = ShardMapManagerFactory.tryGetSqlShardMapManager(Globals.SHARD_MAP_MANAGER_CONN_STRING,
                ShardMapManagerLoadPolicy.Eager, RetryBehavior.getDefaultRetryBehavior(), smmref);
        assertFalse(lookupSmm);
    }
    catch (Exception e) {
        System.out.printf("Failed to connect to SQL database with connection string: " + e.getMessage());
    }
    finally {
        if (conn != null && !conn.isClosed()) {
            conn.close();
        }
    }
}
 
Example 16
Project: monarch   File: AbstractDataSource.java   View Source Code Vote up 5 votes
/**
 * @param conn
 * @return boolean
 */
protected boolean validateConnection(Connection conn) {
  try {
    return (!conn.isClosed());
  } catch (SQLException e) {
    if (logger.isDebugEnabled()) {
      logger.debug("AbstractDataSource::validateConnection:exception in validating connection",
          e);
    }
    return false;
  }
}
 
Example 17
Project: message-broker   File: RdbmsCoordinationDaoImpl.java   View Source Code Vote up 5 votes
/**
 * Closes the provided connection, on failure logs the error.
 *
 * @param connection the Connection
 * @param task       the task that was done before closing
 */
protected void close(Connection connection, String task) {
    try {
        if (connection != null && !connection.isClosed()) {
            connection.close();
        }
    } catch (SQLException e) {
        logger.error("Failed to close connection after " + task, e);
    }
}
 
Example 18
Project: dubbo-transaction   File: DBTransaction.java   View Source Code Vote up 5 votes
public boolean prepare(){
    try {
        if (status.getTransaction() instanceof JdbcTransactionObjectSupport) {
            JdbcTransactionObjectSupport support = (JdbcTransactionObjectSupport) status.getTransaction();
            ConnectionHolder holder = support.getConnectionHolder();
            Connection con = holder.getConnection();
            return !con.isClosed() && !con.isReadOnly();
        }
    }catch (Exception e){
    }
    return false;
}
 
Example 19
Project: lams   File: JdbcMigrationLauncher.java   View Source Code Vote up 4 votes
/**
 * Performs the application rollbacks
 *
 * @param context       the database context to run the patches in
 * @param rollbackLevel the level the system should rollback to
 * @param forceRollback is a boolean indicating if the application should ignore a check to see if all patches are rollbackable
 * @return the number of patches applied
 * @throws SQLException       if an unrecoverable database error occurs while working with the patches table.
 * @throws MigrationException if an unrecoverable error occurs during the migration
 */
public int doRollbacks(JdbcMigrationContext context, int[] rollbackLevel, boolean forceRollback)
        throws SQLException, MigrationException
{
    PatchInfoStore patchTable = createPatchStore(context);

    lockPatchStore(context);

    // Now apply the patches
    int executedPatchCount = 0;
    try
    {

        // remember the auto-commit state, and turn auto-commit off
        Connection conn = context.getConnection();
        boolean commitState = conn.getAutoCommit();
        conn.setAutoCommit(false);

        // run the rollbacks
        try
        {
            executedPatchCount = migrationProcess.doRollbacks(patchTable, rollbackLevel, context, forceRollback);
        }

        // restore autocommit state
        finally
        {
            if ((conn != null) && !conn.isClosed())
            {
                conn.setAutoCommit(commitState);
            }
        }
    }
    catch (MigrationException me)
    {
        // If there was any kind of error, we don't want to eat it, but we do
        // want to unlock the patch store. So do that, then re-throw.
        patchTable.unlockPatchStore();
        throw me;
    }

    // Do any post-patch tasks
    try
    {
        migrationProcess.doPostPatchMigrations(context);
        return executedPatchCount;
    }
    finally
    {
        try
        {
            patchTable.unlockPatchStore();
        }
        catch (MigrationException e)
        {
            log.error("Error unlocking patch table: ", e);
        }
    }
}
 
Example 20
Project: connectors   File: SqlStoredCommon.java   View Source Code Vote up 4 votes
public void closeConnection(Connection connection) throws SQLException {
    if (connection!=null && !connection.isClosed()) {
        connection.close();
    }
}