Example usage for java.sql Connection isClosed

List of usage examples for java.sql Connection isClosed

Introduction

In this page you can find the example usage for java.sql Connection isClosed.

Prototype

boolean isClosed() throws SQLException;

Source Link

Document

Retrieves whether this Connection object has been closed.

Usage

From source file:nz.co.gregs.dbvolution.DBDatabase.java

/**
 * Retrieve the Connection used internally.
 *
 * <p>//  w w w  . j a va 2s  . c o  m
 * However you will not need a Connection to use DBvolution. Your path lies
 * elsewhere.
 *
 * @return the Connection to be used.
 * @throws java.sql.SQLException interacts with the database layer
 * @throws UnableToCreateDatabaseConnectionException thrown when there is an
 * issue connecting
 * @throws UnableToFindJDBCDriver may be thrown if the JDBCDriver is not on
 * the class path. DBvolution includes several JDBCDrivers already but Oracle
 * and MS SQLserver, in particular, need to be added to the path if you wish
 * to work with those databases.
 */
public Connection getConnection()
        throws UnableToCreateDatabaseConnectionException, UnableToFindJDBCDriver, SQLException {
    if (isInATransaction && !this.transactionConnection.isClosed()) {
        return this.transactionConnection;
    }
    Connection conn = null;
    while (conn == null) {
        if (supportsPooledConnections()) {
            synchronized (freeConnections) {
                if (freeConnections.isEmpty() || getConnectionList(freeConnections).isEmpty()) {
                    conn = getRawConnection();
                } else {
                    conn = getConnectionList(freeConnections).get(0);
                }
            }
        } else {
            conn = getRawConnection();
        }
        try {
            if (conn.isClosed()) {
                discardConnection(conn);
                conn = null;
            }
        } catch (SQLException ex) {
            Logger.getLogger(DBDatabase.class.getName()).log(Level.FINEST, null, ex);
        }
        if (connectionUsedForPersistentConnection(conn)) {
            conn = null;
        }
    }
    usedConnection(conn);
    return conn;
}

From source file:jdbc.pool.JDBCPoolOracleConnectionTest.java

/**
 * Test case for LIFO Algorithm with Maximum JDBC Usage parameter.
 */// ww  w .  j  av a 2 s  . com
public void testLIFOAlgorithm() {
    System.out.println("testLIFOAlgorithm with Maximum Usage Counter Start.");
    testGetInstanceNull();
    try {
        CConnectionPoolManager manager = create();
        Connection realCon = null;
        Connection con = manager.getConnection("LIFO"); //It has 3 iniital connections.
        if (con instanceof ConnectionWrapper) {
            ConnectionWrapper wrapper = (ConnectionWrapper) con;
            realCon = wrapper.realConnection();
        } else {
            fail("Connection returned is not an instance of ConnectionWrapper");
        }
        con.close();
        con = manager.getConnection("LIFO");
        con.close();
        assertFalse("Connection must be active", realCon.isClosed());
        con = manager.getConnection("LIFO");
        con.close();
        assertFalse("Connection must be active", realCon.isClosed());
        con = manager.getConnection("LIFO");
        con.close();
        assertTrue("Connection must be active", realCon.isClosed());
        manager.destroy(true);
    } catch (ConfigurationException e) {
        e.printStackTrace();
        fail("Caught ConfigurationException");
    } catch (ParseException e) {
        e.printStackTrace();
        fail("Caught ParseException");
    } catch (IOException e) {
        e.printStackTrace();
        fail("Caught IOException");
    } catch (SQLException e) {
        e.printStackTrace();
        fail("Caught SQLException");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        fail("Caught ClassNotFoundException");
    }
    System.out.println("testLIFOAlgorithm with Maximum Usage Counter End.");
}

From source file:cz.incad.vdkcommon.solr.Indexer.java

public void indexDocOffers(String uniqueCode)
        throws NamingException, SQLException, IOException, SolrServerException, Exception {
    Connection conn = DbUtils.getConnection();
    try {/*w w  w.  j  a v a2s.co  m*/
        String sql = "SELECT offer,datum, ZaznamOffer.zaznamoffer_id, ZaznamOffer.offer, "
                + "ZaznamOffer.uniqueCode, ZaznamOffer.zaznam, ZaznamOffer.exemplar, "
                + "ZaznamOffer.fields, ZaznamOffer.knihovna, ZaznamOffer.pr_knihovna, ZaznamOffer.pr_timestamp "
                + "FROM ZaznamOffer "
                + "JOIN offer ON offer.offer_id=ZaznamOffer.offer where offer.closed=? and ZaznamOffer.uniquecode=?";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setBoolean(1, true);
        ps.setString(2, uniqueCode);
        try (ResultSet rs = ps.executeQuery()) {
            while (rs.next()) {
                if (jobData.isInterrupted()) {
                    LOGGER.log(Level.INFO, "INDEXER INTERRUPTED");
                    break;
                }
                server.add(offerDoc(rs.getInt("offer"), rs.getDate("datum"), rs.getString("uniquecode"),
                        rs.getInt("zaznamoffer_id"), rs.getString("zaznam"), rs.getString("knihovna"),
                        rs.getString("pr_knihovna"), rs.getString("exemplar"), rs.getString("fields")));

                offerIndexed++;

            }
        }
        server.commit();
    } finally {
        if (conn != null && !conn.isClosed()) {
            conn.close();
        }
    }
}

From source file:jdbc.pool.JDBCPoolMySQLTest.java

/**
 * Tests Inactive Timeout for -1 or 0 value.
 * This pool has different set of parameters as compared to MYSQL pool and this forces the behaviour changes
 * in the pool. The connections will not be pooled and therefore the connections will be closed upon release.
 *///from   ww w. j a va  2  s  .  c  om
public void testTIT() {
    testGetInstanceNull();

    logger.debug("testTIT Start.");
    CConnectionPoolManager manager = null;
    try {
        manager = create();
        CPoolAttribute attrib = manager.getPoolAttributes("TIT");
        assertEquals("Driver", "com.mysql.jdbc.Driver", attrib.getDriver());
        assertEquals("Vendor", "MySQL", attrib.getVendor());
        assertEquals("URL", "jdbc:mysql://localhost/pre", attrib.getURL());
        assertEquals("User", "root", attrib.getUser());
        //            assertEquals("Password", "=?UTF-8?B?cm9vdA==?=", attrib.getPassword());
        assertEquals("Initial Pool Size", 3, attrib.getInitialPoolSize());
        assertEquals("Capacity Increament", 2, attrib.getCapacityIncreament());
        assertEquals("Maximum Capacity", 50, attrib.getMaximumCapacity());
        assertEquals("Connection Idle Timeout", -1, attrib.getConnectionIdleTimeout());
        assertEquals("Shrink Pool Interval", 1, attrib.getShrinkPoolInterval());
        assertEquals("Critical Operation Timelimit", 10000, attrib.getCriticalOperationTimeLimit());
        assertEquals("In Use wait time", 10, attrib.getInUseWaitTime());
        assertFalse("load-on-startup", attrib.isLoadOnStartup());

        Connection conOra1 = manager.getConnection("TIT");
        Connection realCon = null;
        if (conOra1 instanceof ConnectionWrapper) {
            ConnectionWrapper wrapper = (ConnectionWrapper) conOra1;
            realCon = wrapper.realConnection();
        } else {
            fail("Connection returned is not an instance of ConnectionWrapper");
        }
        conOra1.close();
        assertTrue("Connection must get closed as the inactive-time-out <= 0", realCon.isClosed());
        attrib = manager.getPoolAttributes("TIT");
        assertEquals("Driver", "com.mysql.jdbc.Driver", attrib.getDriver());
        assertEquals("Vendor", "MySQL", attrib.getVendor());
        assertEquals("URL", "jdbc:mysql://localhost/pre", attrib.getURL());
        assertEquals("User", "root", attrib.getUser());
        //            assertEquals("Password", "gPa8lK4P+Bk=", attrib.getPassword());
        assertEquals("Initial Pool Size", 0, attrib.getInitialPoolSize());
        assertEquals("Capacity Increament", 1, attrib.getCapacityIncreament());
        assertEquals("Maximum Capacity", 50, attrib.getMaximumCapacity());
        assertEquals("Connection Idle Timeout", -1, attrib.getConnectionIdleTimeout());
        assertEquals("Shrink Pool Interval", -1, attrib.getShrinkPoolInterval());
        assertEquals("Critical Operation Timelimit", 10000, attrib.getCriticalOperationTimeLimit());
        assertEquals("In Use wait time", 10, attrib.getInUseWaitTime());
        assertFalse("load-on-startup", attrib.isLoadOnStartup());
    } catch (ConfigurationException e) {
        e.printStackTrace();
        fail("Caught ConfigurationException");
    } catch (ParseException e) {
        e.printStackTrace();
        fail("Caught ParseException");
    } catch (IOException e) {
        e.printStackTrace();
        fail("Caught IOException");
    } catch (SQLException e) {
        e.printStackTrace();
        fail("Caught SQLException");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        fail("Caught ClassNotFoundException");
    } finally {
        manager.destroy(true);
    }
    logger.debug("testTIT end.");
}

From source file:jdbc.pool.JDBCPoolMySQLTest.java

/**
 * Test if JDBC connection is getting closed after crossing the maximum
 * usage per JDBC connection./* www  .ja v  a  2s  .c  om*/
 * 
 */
public void testMaxUsagePerJDBCConnection() {
    testGetInstanceNull();

    logger.debug("testMaxUsagePerJDBCConnection start.");
    CConnectionPoolManager manager = null;
    try {
        manager = create();
        Connection realCon = null;
        Connection con = manager.getConnection("MYSQL2");
        if (con instanceof ConnectionWrapper) {
            ConnectionWrapper wrapper = (ConnectionWrapper) con;
            realCon = wrapper.realConnection();
        } else {
            fail("Connection returned is not an instance of ConnectionWrapper");
        }
        con.close();
        assertFalse("Connection must be active", realCon.isClosed());
        // 2
        con = manager.getConnection("MYSQL2");
        con.close();
        assertFalse("Connection must be active", realCon.isClosed());
        // 3
        con = manager.getConnection("MYSQL2");
        assertFalse("Connection must be active", realCon.isClosed());
        con.close();
        assertFalse("Connection must be active", realCon.isClosed());
        // 4
        con = manager.getConnection("MYSQL2");
        con.close();
        assertTrue("Connection must be closed", realCon.isClosed());
    } catch (ConfigurationException e) {
        e.printStackTrace();
        fail("Caught ConfigurationException");
    } catch (ParseException e) {
        e.printStackTrace();
        fail("Caught ParseException");
    } catch (IOException e) {
        e.printStackTrace();
        fail("Caught IOException");
    } catch (SQLException e) {
        e.printStackTrace();
        fail("Caught SQLException");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        fail("Caught ClassNotFoundException");
    } finally {
        if (manager != null) {
            manager.destroy(true);
        }
    }
    logger.debug("testMaxUsagePerJDBCConnection end.");
}

From source file:org.sakaiproject.event.impl.ClusterEventTracking.java

/**
 * Write a batch of events to the db//from www . jav  a  2 s.  co  m
 * 
 * @param events
 *        The collection of event to write.
 */
protected void writeBatchEvents(Collection events) {
    // get a connection
    Connection conn = null;
    boolean wasCommit = true;
    try {
        conn = sqlService().borrowConnection();
        wasCommit = conn.getAutoCommit();
        if (wasCommit) {
            conn.setAutoCommit(false);
        }

        // Note: investigate batch writing via the jdbc driver: make sure we can still use prepared statements (check out host arrays, too)
        // -ggolden

        // common preparation for each insert
        String statement = insertStatement();
        Object fields[] = new Object[6];

        // write all events
        for (Iterator i = events.iterator(); i.hasNext();) {
            Event event = (Event) i.next();
            bindValues(event, fields);

            // process the insert
            if (cachingEnabled) {
                conn = sqlService().borrowConnection();
                if (conn.getAutoCommit()) {
                    conn.setAutoCommit(false);
                }
                Long eventId = sqlService().dbInsert(conn, statement, fields, "EVENT_ID");
                if (eventId != null) {
                    // write event to cache
                    writeEventToCluster(event, eventId);
                }
            } else {
                boolean ok = sqlService().dbWrite(conn, statement, fields);
                if (!ok) {
                    M_log.warn(this + ".writeBatchEvents(): dbWrite failed: session: " + fields[3] + " event: "
                            + event.toString());
                }
            }
        }

        // commit
        if (!conn.isClosed()) {
            conn.commit();
        }
    } catch (Exception e) {
        if (conn != null) {
            try {
                conn.rollback();
            } catch (Exception ee) {
                M_log.warn(this + ".writeBatchEvents, while rolling back: " + ee);
            }
        }
        M_log.warn(this + ".writeBatchEvents: " + e, e);
    } finally {
        if (conn != null) {
            try {
                if (!conn.isClosed() && conn.getAutoCommit() != wasCommit) {
                    conn.setAutoCommit(wasCommit);
                }
            } catch (Exception e) {
                M_log.warn(this + ".writeBatchEvents, while setting auto commit: " + e, e);
            }
            sqlService().returnConnection(conn);
        }
    }
}

From source file:jdbc.pool.JDBCPoolTestCase.java

/**
 * Test case for FIFO Algorithm with Maximum JDBC Usage parameter.
 *//*from w w w  .j a v a 2 s  .com*/
public void testFIFOAlgorithm() {
    System.out.println("testFIFOAlgorithm with Maximum Usage Counter Start.");
    try {
        CConnectionPoolManager manager = create();
        Connection realCon = null;
        Connection con = manager.getConnection("FIFO"); //It has 3 iniital connections.
        if (con instanceof ConnectionWrapper) {
            ConnectionWrapper wrapper = (ConnectionWrapper) con;
            realCon = wrapper.realConnection();
        } else {
            fail("Connection returned is not an instance of ConnectionWrapper");
        }
        con.close();
        for (int i = 2; i <= (3 * 4) - 3; i++) { // 3 (no. of con) * 4 (max jdbc usage) - 2 (to bring the original on top.)
            con = manager.getConnection("FIFO");
            con.close();
            assertFalse("Connection must be active #" + i, realCon.isClosed());
        }
        con = manager.getConnection("FIFO");
        con.close();
        assertTrue("Connection must be active", realCon.isClosed());
        manager.destroy(true);
    } catch (ConfigurationException e) {
        e.printStackTrace();
        fail("Caught ConfigurationException");
    } catch (ParseException e) {
        e.printStackTrace();
        fail("Caught ParseException");
    } catch (IOException e) {
        e.printStackTrace();
        fail("Caught IOException");
    } catch (SQLException e) {
        e.printStackTrace();
        fail("Caught SQLException");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        fail("Caught ClassNotFoundException");
    }
    System.out.println("testFIFOAlgorithm with Maximum Usage Counter End.");
}

From source file:cz.incad.vdkcommon.solr.Indexer.java

private String getDocOffers(String uniqueCode)
        throws NamingException, SQLException, IOException, SolrServerException, Exception {
    Connection conn = DbUtils.getConnection();
    try {//  w w w . ja  v  a  2 s.c  o  m
        String sql = "SELECT offer,datum, ZaznamOffer.zaznamoffer_id, ZaznamOffer.offer, "
                + "ZaznamOffer.uniqueCode, ZaznamOffer.zaznam, ZaznamOffer.exemplar, "
                + "ZaznamOffer.fields, ZaznamOffer.knihovna, ZaznamOffer.pr_knihovna, ZaznamOffer.pr_timestamp "
                + "FROM ZaznamOffer "
                + "JOIN offer ON offer.offer_id=ZaznamOffer.offer where offer.closed=? and ZaznamOffer.uniquecode=?";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setBoolean(1, true);
        ps.setString(2, uniqueCode);
        StringBuilder sb = new StringBuilder();
        try (ResultSet rs = ps.executeQuery()) {
            while (rs.next()) {
                if (jobData.isInterrupted()) {
                    LOGGER.log(Level.INFO, "INDEXER INTERRUPTED");
                    break;
                }
                sb.append(offerXml(rs.getInt("offer"), rs.getDate("datum"), rs.getString("uniquecode"),
                        rs.getInt("zaznamoffer_id"), rs.getString("zaznam"), rs.getString("knihovna"),
                        rs.getString("pr_knihovna"), rs.getString("exemplar"), rs.getString("fields")));

                offerIndexed++;

            }
        }
        return sb.toString();
    } finally {
        if (conn != null && !conn.isClosed()) {
            conn.close();
        }
    }
}

From source file:jdbc.pool.JDBCPoolOracleConnectionTest.java

/**
 * Test case for FIFO Algorithm with Maximum JDBC Usage parameter.
 *//* ww  w  .  j  a v  a  2s  .c om*/
public void testFIFOAlgorithm() {
    System.out.println("testFIFOAlgorithm with Maximum Usage Counter Start.");
    testGetInstanceNull();
    try {
        CConnectionPoolManager manager = create();
        Connection realCon = null;
        Connection con = manager.getConnection("FIFO"); //It has 3 iniital connections.
        if (con instanceof ConnectionWrapper) {
            ConnectionWrapper wrapper = (ConnectionWrapper) con;
            realCon = wrapper.realConnection();
        } else {
            fail("Connection returned is not an instance of ConnectionWrapper");
        }
        con.close();
        for (int i = 2; i <= (3 * 4) - 3; i++) { // 3 (no. of con) * 4 (max jdbc usage) - 2 (to bring the original on top.)
            con = manager.getConnection("FIFO");
            con.close();
            assertFalse("Connection must be active #" + i, realCon.isClosed());
        }
        con = manager.getConnection("FIFO");
        con.close();
        assertTrue("Connection must be active", realCon.isClosed());
        manager.destroy(true);
    } catch (ConfigurationException e) {
        e.printStackTrace();
        fail("Caught ConfigurationException");
    } catch (ParseException e) {
        e.printStackTrace();
        fail("Caught ParseException");
    } catch (IOException e) {
        e.printStackTrace();
        fail("Caught IOException");
    } catch (SQLException e) {
        e.printStackTrace();
        fail("Caught SQLException");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        fail("Caught ClassNotFoundException");
    }
    System.out.println("testFIFOAlgorithm with Maximum Usage Counter End.");
}

From source file:com.glaf.jbpm.container.ProcessContainer.java

public JbpmContext createJbpmContext() {
    JbpmContext jbpmContext = getJbpmConfiguration().createJbpmContext();
    java.sql.Connection conn = null;
    try {//from w  w w. java 2 s  .  c  om
        conn = jbpmContext.getConnection();
        if (conn == null || conn.isClosed()) {
            jbpmContext = null;
        }
    } catch (SQLException ex) {
        ex.printStackTrace();
    }
    return jbpmContext;
}