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:edu.uga.cs.fluxbuster.db.PostgresDBInterface.java

/**
 * @see edu.uga.cs.fluxbuster.db.DBInterface#storeClusterClasses(java.util.Date, java.util.Map, boolean)
 *///from   www  .  jav a2 s  . c om
@Override
public void storeClusterClasses(Date logdate, Map<ClusterClass, List<StoredDomainCluster>> clusterClasses,
        boolean validated) {
    String logDateTable = dateFormatTable.format(logdate);

    Connection con = null;
    PreparedStatement clusterClassesInsertStmt = null;
    try {
        con = this.getConnection();
        clusterClassesInsertStmt = con.prepareStatement(
                "INSERT INTO cluster_classes_" + logDateTable + " VALUES (?, 'SIE', ?, ?, ?)");
        for (ClusterClass clusclass : clusterClasses.keySet()) {
            for (StoredDomainCluster cluster : clusterClasses.get(clusclass)) {
                clusterClassesInsertStmt.setInt(1, cluster.getClusterId());
                clusterClassesInsertStmt.setDate(2, new java.sql.Date(logdate.getTime()));
                clusterClassesInsertStmt.setString(3, clusclass.toString());
                clusterClassesInsertStmt.setBoolean(4, validated);
                this.executePreparedStatementNoResult(con, clusterClassesInsertStmt);
            }
        }
    } catch (SQLException e) {
        if (log.isErrorEnabled()) {
            log.error("Error storing cluster classes.", e);
        }
    } finally {
        try {
            if (clusterClassesInsertStmt != null && !clusterClassesInsertStmt.isClosed()) {
                clusterClassesInsertStmt.close();
            }
        } catch (SQLException e) {
            if (log.isErrorEnabled()) {
                log.error("e");
            }
        }
        try {
            if (con != null && !con.isClosed()) {
                con.close();
            }
        } catch (SQLException e) {
            if (log.isErrorEnabled()) {
                log.error("e");
            }
        }
    }
}

From source file:jdbc.pool.JDBCPoolMySQLTest.java

/**
 * Test case for LIFO Algorithm with Maximum JDBC Usage parameter.
 *//*from w w w  .j  av  a  2 s.  com*/
public void testLIFOAlgorithm() {
    testGetInstanceNull();

    logger.debug("testLIFOAlgorithm with Maximum Usage Counter Start.");
    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");
    }
    logger.debug("testLIFOAlgorithm with Maximum Usage Counter End.");
}

From source file:jdbc.pool.JDBCPoolTestCase.java

/**
 * Tests Inactive time out closing of the JDBC Connection.
 * /*from  www .j  a  v  a 2  s.c  om*/
 * Check whether the connection returns back to the pool.
 */
public void testInactiveTimeout() {
    System.out.println("testInactiveTimeout Start.");
    CConnectionPoolManager manager = null;
    try {
        manager = create();
        Connection conOra1 = manager.getConnection("ORACLE");
        Connection realCon = null;
        Connection conOra2 = manager.getConnection("ORACLE");
        if (conOra2 instanceof ConnectionWrapper) {
            ConnectionWrapper wrapper = (ConnectionWrapper) conOra2;
            realCon = wrapper.realConnection();
        } else {
            fail("Connection returned is not an instance of ConnectionWrapper");
        }
        conOra2.close();
        try {
            // 4 = 1 + 3 + (1) As the maximum time in which the con will be
            // closed is 4 have an additional 1 minute extra
            Thread.sleep(5 * 60 * 1000); // Shrink Pool Interval 1 minute + Inactive timeout 3 mins.
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
        assertTrue("Real Connection is closed", realCon.isClosed());
        conOra1.close();
        CPoolStatisticsBean bean = manager.getPoolStatistics("ORACLE");
        assertEquals("Pool Name", "ORACLE", bean.getPoolName());
        System.out.println("********************************************************");
        ArrayList al = manager.getPoolStatisticsHistory("ORACLE");
        assertTrue("Statistics History Count", 5 >= al.size());
        for (Iterator iter = al.iterator(); iter.hasNext();) {
            CPoolStatisticsBean element = (CPoolStatisticsBean) iter.next();
            System.out.println(element.toString());
        }
        System.out.println("********************************************************");
    } 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);
    }
    System.out.println("testInactiveTimeout end.");
}

From source file:jdbc.pool.JDBCPoolOracleConnectionTest.java

/**
 * Tests Inactive time out closing of the JDBC Connection.
 * /* ww w .  j ava  2 s  .co m*/
 * Check whether the connection returns back to the pool.
 */
public void testInactiveTimeout() {
    System.out.println("testInactiveTimeout Start.");
    testGetInstanceNull();
    CConnectionPoolManager manager = null;
    try {
        manager = create();
        Connection conOra1 = manager.getConnection("ORACLE");
        Connection realCon = null;
        Connection conOra2 = manager.getConnection("ORACLE");
        if (conOra2 instanceof ConnectionWrapper) {
            ConnectionWrapper wrapper = (ConnectionWrapper) conOra2;
            realCon = wrapper.realConnection();
        } else {
            fail("Connection returned is not an instance of ConnectionWrapper");
        }
        conOra2.close();
        try {
            // 4 = 1 + 3 + (1) As the maximum time in which the con will be
            // closed is 4 have an additional 1 minute extra
            Thread.sleep(5 * 60 * 1000); // Shrink Pool Interval 1 minute + Inactive timeout 3 mins.
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
        assertTrue("Real Connection is closed", realCon.isClosed());
        conOra1.close();
        CPoolStatisticsBean bean = manager.getPoolStatistics("ORACLE");
        assertEquals("Pool Name", "ORACLE", bean.getPoolName());
        System.out.println("********************************************************");
        ArrayList al = manager.getPoolStatisticsHistory("ORACLE");
        assertTrue("Statistics History Count", 5 >= al.size());
        for (Iterator iter = al.iterator(); iter.hasNext();) {
            CPoolStatisticsBean element = (CPoolStatisticsBean) iter.next();
            System.out.println(element.toString());
        }
        System.out.println("********************************************************");
    } 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);
    }
    System.out.println("testInactiveTimeout end.");
}

From source file:jdbc.pool.JDBCPoolMySQLTest.java

/**
 * Test case for FIFO Algorithm with Maximum JDBC Usage parameter.
 *///w ww .  java2 s.  co  m
public void testFIFOAlgorithm() {
    testGetInstanceNull();

    logger.debug("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");
    }
    logger.debug("testFIFOAlgorithm with Maximum Usage Counter End.");
}

From source file:jdbc.pool.JDBCPoolOracleConnectionTest.java

public void testUpdatePoolAttributesCPoolAttribute() {
    testGetInstanceNull();/*from   w  w w.  ja v a2s  .  com*/
    System.out.println("testUpdatePoolAttributesCPoolAttribute Started");
    try {
        CConnectionPoolManager manager = null;
        manager = create();
        CPoolAttribute attribMySQL = manager.getPoolAttributes("MYSQL");
        Connection con = manager.getConnection("MYSQL");
        int iOriginalInitialPoolSize = attribMySQL.getInitialPoolSize();
        attribMySQL.setPassword("root");
        attribMySQL.setInitialPoolSize(10);
        try {
            manager.updatePoolAttributes(attribMySQL, false);
        } catch (InvalidPoolAttributeException e) {
            e.printStackTrace();
        }
        CPoolAttribute attributes = manager.getPoolAttributes("MYSQL");
        assertFalse("Initial Pool size should not be same as the updated ones",
                (attributes.getInitialPoolSize() == 10));
        assertTrue("Initial pool size should be same as the original ones",
                (attributes.getInitialPoolSize() == iOriginalInitialPoolSize));
        assertFalse("Connection is not closed ", con.isClosed());
        manager.destroy(true);
        testGetInstanceNull();
        manager = create();
        con = manager.getConnection("MYSQL");
        attribMySQL = manager.getPoolAttributes("MYSQL");
        assertEquals("Initial Size should be same as the updated ones", 10, attribMySQL.getInitialPoolSize());
        assertFalse("Initial pool size should not be same as the original ones",
                (attribMySQL.getInitialPoolSize() == iOriginalInitialPoolSize));
        attribMySQL.setPassword("root");
        attribMySQL.setInitialPoolSize(iOriginalInitialPoolSize);
        try {
            manager.updatePoolAttributes(attribMySQL, true);
            attributes = manager.getPoolAttributes("MYSQL");
            assertEquals("Initial Pool size should be same as the updated ones", iOriginalInitialPoolSize,
                    attributes.getInitialPoolSize());
            assertTrue("Connection is closed ", ((ConnectionWrapper) con).realConnection().isClosed());
        } catch (InvalidPoolAttributeException e) {
            e.printStackTrace();
        }
        con = manager.getConnection("MYSQL");
        assertNotNull(con);
        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");
    }

    try {
        CConnectionPoolManager manager = null;
        manager = create();
        CPoolAttribute attribMySQL = manager.getPoolAttributes("MYSQL");
        attribMySQL.setPoolName("NOTEXISTANT");
        attribMySQL.setPassword("root");
        attribMySQL.setInitialPoolSize(10);
        try {
            manager.updatePoolAttributes(attribMySQL, true); // Raises
            // configuration
            // exception.
            fail("did not throw Configuration Exception");
        } catch (ConfigurationException e) {
            e.printStackTrace();
            assertTrue("Caught ConfigurationException", true);
        } catch (InvalidPoolAttributeException e) {
            e.printStackTrace();
            fail("Invalid Pool Attribute Exception caught");
        }
        manager.destroy(true);
        testGetInstanceNull();
    } 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("testUpdatePoolAttributesCPoolAttribute ended");
}

From source file:com.mysql.stresstool.RunnableQueryInsertPartRange.java

public void run() {

    BufferedReader d = null;//from   w w w. j  a v  a  2  s  .c om
    Connection conn = null;

    try {
        if (stikyconnection && jdbcUrlMap.get("dbType") != null
                && !((String) jdbcUrlMap.get("dbType")).equals("MySQL")) {
            conn = DriverManager.getConnection((String) jdbcUrlMap.get("dbType"), "test", "test");
        } else if (stikyconnection)
            conn = DriverManager.getConnection((String) jdbcUrlMap.get("jdbcUrl"));

    } catch (SQLException ex) {
        ex.printStackTrace();
    }

    try {

        long execTime = 0;
        int pkStart = 0;
        int pkEnds = 0;
        int intDeleteInterval = 0;
        int intBlobInterval = 0;
        int intBlobIntervalLimit = StressTool.getNumberFromRandom(4).intValue();
        ThreadInfo thInfo;

        long threadTimeStart = System.currentTimeMillis();
        active = true;

        thInfo = new ThreadInfo();
        thInfo.setId(this.ID);
        thInfo.setType("insert");
        thInfo.setStatusActive(this.isActive());

        StressTool.setInfo(this.ID, thInfo);
        boolean lazy = false;
        int lazyInterval = 0;

        for (int repeat = 0; repeat <= repeatNumber; repeat++) {
            if (!stikyconnection) {
                try {
                    if (conn != null && !conn.isClosed()) {
                        conn.close();
                    }
                    SoftReference sf = new SoftReference(
                            DriverManager.getConnection((String) jdbcUrlMap.get("jdbcUrl")));
                    conn = (Connection) sf.get();
                } catch (SQLException ex) {
                    for (int icon = 0; icon <= 3; icon++) {
                        try {
                            Thread.sleep(10000);
                            SoftReference sf = new SoftReference(
                                    DriverManager.getConnection((String) jdbcUrlMap.get("jdbcUrl")));
                            conn = (Connection) sf.get();
                        } catch (SQLException ex2) {
                            ex2.printStackTrace();
                        }
                    }
                    //ex.printStackTrace();
                }

            }
            if (conn != null) {
                Statement stmt = null;
                //                ResultSet rs = null;
                //                ResultSet rs2 = null;

                conn.setAutoCommit(false);
                stmt = conn.createStatement();
                stmt.execute("SET AUTOCOMMIT=0");

                String query = null;
                ArrayList insert1 = null;
                ArrayList insert2 = null;
                int pk = 0;

                if (repeat > 0 && lazyInterval < 500) {
                    lazy = true;
                    ++lazyInterval;
                } else {
                    lazy = false;
                    lazyInterval = 0;
                }

                intBlobInterval++;
                //IMPLEMENTING lazy
                Vector v = this.getTablesValues(lazy);

                insert1 = (ArrayList<String>) v.get(0);
                insert2 = (ArrayList<String>) v.get(1);

                //                    System.out.println(insert1);
                //                    System.out.println(insert2);

                //                    pk = ((Integer) v.get(2)).intValue();

                int[] iLine = { 0, 0 };

                //                    pkStart = StressTool.getNumberFromRandom(2147483647).intValue();
                //                    pkEnds = StressTool.getNumberFromRandom(2147483647).intValue();

                try {

                    long timeStart = System.currentTimeMillis();

                    if (this.ignoreBinlog)
                        stmt.execute("SET sql_log_bin=0");
                    //stmt.execute("SET GLOBAL max_allowed_packet=1073741824");

                    if (dbType.equals("MySQL") && !engine.toUpperCase().equals("BRIGHTHOUSE"))
                        stmt.execute("BEGIN");
                    else
                        stmt.execute("COMMIT");
                    //                                stmt.execute("SET TRANSACTION NAME 'TEST'");
                    {
                        Iterator<String> it = insert1.iterator();
                        while (it.hasNext()) {
                            stmt.addBatch(it.next());
                        }
                    }

                    if (!this.doSimplePk) {
                        if (intBlobInterval > intBlobIntervalLimit) {
                            Iterator<String> it = insert2.iterator();
                            while (it.hasNext()) {
                                stmt.addBatch(it.next());
                            }
                            intBlobInterval = 0;

                        }
                    }
                    if (debug) {
                        System.out.println("Thread " + thInfo.getId() + " Executing loop "
                                + thInfo.getExecutedLoops() + " QUERY1==" + insert1);
                        System.out.println("Thread " + thInfo.getId() + " Executing loop "
                                + thInfo.getExecutedLoops() + " QUERY2==" + insert2);

                    }

                    iLine = executeSQL(stmt);
                    //                            System.out.println("Query1 = " + insert1);
                    //                            System.out.println("Query2 = " + insert2);
                    //                            stmt.execute("START TRANSACTION");
                    //                            stmt.execute(insert1);
                    //                            iLine = stmt.executeBatch();
                    //                            conn.commit();
                    long timeEnds = System.currentTimeMillis();
                    execTime = (timeEnds - timeStart);

                } catch (SQLException sqle) {

                    conn.rollback();
                    System.out.println("FAILED QUERY1==" + insert1);
                    System.out.println("FAILED QUERY2==" + insert2);
                    sqle.printStackTrace();
                    System.exit(1);
                    //conn.close();
                    //this.setJdbcUrl(jdbcUrl);
                    //System.out.println("Query Insert TH RE-INIZIALIZING");

                } finally {
                    //                           conn.commit();
                    if (conn != null && !conn.isClosed()) {
                        try {
                            stmt.addBatch("COMMIT");
                            executeSQL(stmt);
                        } catch (SQLException sqle) {
                            System.out.println(
                                    "#####################\n[Warning] Cannot explicitly commit given error\n#################");
                            conn.close();
                            continue;
                        }
                    } else {
                        System.out.println(
                                "#####################\n[Warning] Cannot explicitly commit given connection was interrupted unexpectedly\n#################");
                    }
                    //                            intDeleteInterval++;
                    if (doLog) {

                        System.out.println("Query Insert TH = " + this.getID() + " Loop N = " + repeat + " "
                                + iLine[0] + "|" + ((iLine.length > 1) ? iLine[1] : 0) + " Exec Time(ms) ="
                                + execTime + " Running = " + repeat + " of " + repeatNumber + " to go ="
                                + (repeatNumber - repeat) + " Using Lazy=" + lazy);
                    }
                }
                thInfo.setExecutedLoops(repeat);
                if (sleepFor > 0 || this.getSleepWrite() > 0) {
                    if (this.getSleepWrite() > 0) {
                        Thread.sleep(getSleepWrite());
                    } else
                        Thread.sleep(sleepFor);
                }

            }
        }

        long threadTimeEnd = System.currentTimeMillis();
        this.executionTime = (threadTimeEnd - threadTimeStart);
        //                this.setExecutionTime(executionTime);
        active = false;
        //                System.out.println("Query Insert TH = " + this.getID() + " COMPLETED!  TOTAL TIME = " + execTime + "(ms) Sec =" + (execTime/1000));

        thInfo.setExecutionTime(executionTime);
        thInfo.setStatusActive(false);
        StressTool.setInfo(this.ID, thInfo);
        return;

    } catch (Exception ex) {
        ex.printStackTrace();
        try {
            conn.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

From source file:jdbc.pool.JDBCPoolTestCase.java

public void testUpdatePoolAttributesCPoolAttribute() {
    System.out.println("testUpdatePoolAttributesCPoolAttribute Started.");
    try {//from  w w  w.  j a  va2 s  . co  m
        CConnectionPoolManager manager = null;
        manager = create();
        Connection con = manager.getConnection("MYSQL");
        CPoolAttribute attribMySQL = manager.getPoolAttributes("MYSQL");
        int iOriginalInitialPoolSize = attribMySQL.getInitialPoolSize();
        attribMySQL.setPassword("root");
        attribMySQL.setInitialPoolSize(10);
        try {
            manager.updatePoolAttributes(attribMySQL, false);
        } catch (InvalidPoolAttributeException e) {
            e.printStackTrace();
        }
        CPoolAttribute attributes = manager.getPoolAttributes("MYSQL");
        assertFalse("Initial Pool size should not be same as the updated ones",
                (attributes.getInitialPoolSize() == 10));
        assertTrue("Initial Pool size should be same as the original ones",
                (attributes.getInitialPoolSize() == iOriginalInitialPoolSize));
        assertTrue("Connection is not closed ", !con.isClosed());
        manager.destroy(true);
        testGetInstanceNull();
        manager = create();
        attribMySQL = manager.getPoolAttributes("MYSQL");
        con = manager.getConnection("MYSQL");
        assertEquals("Initial Size ", 10, attribMySQL.getInitialPoolSize());
        attribMySQL.setPassword("root");
        attribMySQL.setInitialPoolSize(iOriginalInitialPoolSize);
        try {
            manager.updatePoolAttributes(attribMySQL, true);
            attributes = manager.getPoolAttributes("MYSQL");
            assertTrue("Connection is closed ", con.isClosed());
            assertTrue("Initial Pool size should not be same as the updated ones",
                    (attributes.getInitialPoolSize() == iOriginalInitialPoolSize));
        } catch (InvalidPoolAttributeException e) {
            e.printStackTrace();
        }
        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");
    }

    try {
        CConnectionPoolManager manager = null;
        manager = create();
        CPoolAttribute attribMySQL = manager.getPoolAttributes("MYSQL");
        attribMySQL.setPoolName("NOTEXISTANT");
        attribMySQL.setPassword("root");
        attribMySQL.setInitialPoolSize(10);
        try {
            manager.updatePoolAttributes(attribMySQL, true); // Raises
            // configuration
            // exception.
            fail("did not throw Configuration Exception");
        } catch (ConfigurationException e) {
            e.printStackTrace();
            assertTrue("Caught ConfigurationException", true);
        } catch (InvalidPoolAttributeException e) {
            e.printStackTrace();
            fail("Invalid Pool Attribute Exception caught");
        }
        manager.destroy(true);
        testGetInstanceNull();
    } 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("testUpdatePoolAttributesCPoolAttribute end.");
}

From source file:org.openanzo.datasource.nodecentric.internal.NodeCentricDatasource.java

/**
 * Abort database transaction/* w w w . j  a  v  a 2  s.c  o  m*/
 * 
 * Note:Database already in transaction
 * 
 * @param connection
 *            {@link Connection} to underlying database
 * @param needsWrite
 *            if true, tables will be locked if needed
 * @param needsTransaction
 *            TODO
 * @throws AnzoException
 *             {@link ExceptionConstants.RDB#DIDNT_START_RDB_TRANSACTION} if this thread didn't start the transaction
 * @throws AnzoException
 *             {@link ExceptionConstants.RDB#FAILED_ROLLBACK_RDB_TRANSACTION} if there was a problem rolling back the connection
 */
protected void abort(Connection connection, boolean needsWrite, boolean needsTransaction) throws AnzoException {
    long start = 0;
    if (stats.isEnabled()) {
        start = System.currentTimeMillis();
        stats.getAbortUse().increment();
    }
    try {
        ReentrantLock lock = connectionLocks.get(connection);
        if (lock == null) {
            lock = new ReentrantLock();
            connectionLocks.put(connection, lock);
        }
        if (lock.isLocked()) {
            if (lock.isHeldByCurrentThread()) {
                try {
                    if (needsTransaction) {
                        ArrayList<AnzoException> exceptions = null;
                        try {
                            if (!connection.isClosed()) {
                                try {
                                    connection.rollback();
                                    connection.setAutoCommit(true);
                                } catch (SQLException e) {
                                    log.error(LogUtils.RDB_MARKER, "Error rolling back transaction", e);
                                    exceptions = new ArrayList<AnzoException>();
                                    exceptions.add(new AnzoException(
                                            ExceptionConstants.RDB.FAILED_ROLLBACK_RDB_TRANSACTION, e));
                                }
                                try {
                                    unlockTable(connection, needsWrite);
                                } catch (AnzoException ae) {
                                    log.error(LogUtils.RDB_MARKER, "Error unlocking table", ae);
                                    if (exceptions == null) {
                                        exceptions = new ArrayList<AnzoException>();
                                    }
                                    exceptions.add(ae);
                                }
                            }
                        } catch (SQLException e) {
                            log.error(LogUtils.RDB_MARKER, "Error rollingback jdbc transaction", e);
                            exceptions = new ArrayList<AnzoException>();
                            exceptions.add(new AnzoException(
                                    ExceptionConstants.RDB.FAILED_ROLLBACK_RDB_TRANSACTION, e));
                        }

                        if (exceptions != null && exceptions.size() > 0) {
                            throw new CompoundAnzoException(exceptions,
                                    ExceptionConstants.RDB.FAILED_ROLLBACK_RDB_TRANSACTION);
                        }
                    }
                } finally {
                    lock.unlock();
                    nodeLayout.clearUncommittedCache();
                }
            } else {
                throw new AnzoException(ExceptionConstants.RDB.DIDNT_START_RDB_TRANSACTION);
            }
        }
    } finally {
        if (stats.isEnabled()) {
            stats.getAbortDuration().addTime((System.currentTimeMillis() - start));
        }
    }
}

From source file:jdbc.pool.JDBCPoolMySQLTest.java

/**
 * Tests Inactive time out closing of the JDBC Connection.
 * // w  w w .  ja  v a2  s  .  c  o  m
 * Check whether the connection returns back to the pool.
 */
public void testInactiveTimeout() {
    testGetInstanceNull();
    logger.debug("testInactiveTimeout Start.");
    CConnectionPoolManager manager = null;
    try {
        manager = create();
        Connection conOra1 = manager.getConnection("MYSQL2");
        Connection realCon = null;
        Connection conOra2 = manager.getConnection("MYSQL2");
        if (conOra2 instanceof ConnectionWrapper) {
            ConnectionWrapper wrapper = (ConnectionWrapper) conOra2;
            realCon = wrapper.realConnection();
        } else {
            fail("Connection returned is not an instance of ConnectionWrapper");
        }
        conOra2.close();
        try {
            // 4 = 1 + 3 + (1) As the maximum time in which the con will be
            // closed is 4 have an additional 1 minute extra
            Thread.sleep(5 * 60 * 1000, 999999); // Shrink Pool Interval 1 minute + Inactive timeout 3 mins.
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
        assertTrue("Real Connection is closed", realCon.isClosed());
        conOra1.close();
        CPoolStatisticsBean bean = manager.getPoolStatistics("MYSQL2");
        assertEquals("Pool Name", "MYSQL2", bean.getPoolName());
        logger.debug("********************************************************");
        ArrayList<CPoolStatisticsBean> al = manager.getPoolStatisticsHistory("MYSQL2");
        assertTrue("Statistics History Count", 5 >= al.size());
        for (CPoolStatisticsBean element : al) {
            logger.debug(element.toString());
        }
        logger.debug("********************************************************");
    } 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("testInactiveTimeout end.");
}