org.apache.tomcat.jdbc.pool.PooledConnection Java Examples

The following examples show how to use org.apache.tomcat.jdbc.pool.PooledConnection. 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: TomEEDataSourceCreator.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Override
protected PooledConnection create(final boolean incrementCounter) {
    final PooledConnection con = super.create(incrementCounter);
    if (getPoolProperties().getDataSource() == null) { // using driver
        // init driver with TCCL
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        if (cl == null) {
            cl = TomEEConnectionPool.class.getClassLoader();
        }
        try {
            Reflections.set(con, "driver", Class.forName(getPoolProperties().getDriverClassName(), true, cl).newInstance());
        } catch (final ClassNotFoundException cnfe) {
            try { // custom resource classloader
                Reflections.set(con, "driver", Class.forName(getPoolProperties().getDriverClassName(), true, creationLoader).newInstance());
            } catch (final Exception e) {
                // will fail later, no worry
            }
        } catch (final Exception cn) {
            // will fail later, no worry
        }
    }
    return con;
}
 
Example #2
Source File: ResetAbandonedTimer.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
public void reset(ConnectionPool parent, PooledConnection con) {
    super.reset(parent, con);
    if (con == null) {
        this.pcon = null;
        if (oname != null) {
            JmxUtil.unregisterJmx(oname);
            oname = null;
        }
    } else {
        this.pcon = con;
        if (oname == null) {
            String keyprop = ",JdbcInterceptor=" + getClass().getSimpleName();
            oname = JmxUtil.registerJmx(pcon.getObjectName(), keyprop, this);
        }
    }
}
 
Example #3
Source File: StatementCache.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
public void reset(ConnectionPool parent, PooledConnection con) {
    super.reset(parent, con);
    if (parent==null) {
        cacheSize = null;
        this.pcon = null;
        if (oname != null) {
            JmxUtil.unregisterJmx(oname);
            oname = null;
        }
    } else {
        cacheSize = cacheSizeMap.get(parent);
        this.pcon = con;
        if (!pcon.getAttributes().containsKey(STATEMENT_CACHE_ATTR)) {
            ConcurrentHashMap<CacheKey,CachedStatement> cache =
                    new ConcurrentHashMap<>();
            pcon.getAttributes().put(STATEMENT_CACHE_ATTR,cache);
        }
        if (oname == null) {
            String keyprop = ",JdbcInterceptor=" + getClass().getSimpleName();
            oname = JmxUtil.registerJmx(pcon.getObjectName(), keyprop, this);
        }
    }
}
 
Example #4
Source File: TestSuspectTimeout.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testSuspect() throws Exception {
    this.datasource.setMaxActive(100);
    this.datasource.setMaxIdle(100);
    this.datasource.setInitialSize(0);
    this.datasource.getPoolProperties().setAbandonWhenPercentageFull(0);
    this.datasource.getPoolProperties().setTimeBetweenEvictionRunsMillis(100);
    this.datasource.getPoolProperties().setRemoveAbandoned(true);
    this.datasource.getPoolProperties().setRemoveAbandonedTimeout(100);
    this.datasource.getPoolProperties().setSuspectTimeout(1);
    this.datasource.getPoolProperties().setLogAbandoned(true);
    Connection con = datasource.getConnection();
    Assert.assertEquals("Number of connections active/busy should be 1",1,datasource.getPool().getActive());
    Thread.sleep(3000);
    PooledConnection pcon = con.unwrap(PooledConnection.class);
    Assert.assertTrue("Connection should be marked suspect",pcon.isSuspect());
    con.close();
}
 
Example #5
Source File: ConnectionRollbackOnReturnInterceptor.java    From micro-integrator with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("finally")
@Override
   public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
       PooledConnection pc = this.connection;
       try {
           if (compare(CLOSE_VAL, method)) {
               this.connection = null;
               if (pc != null && pc.getXAConnection() == null && !pc.getConnection().getAutoCommit()) {
                   pc.getConnection().rollback();
               }
           }
       } catch (Exception e) {
           throw e;
       } finally {
           return super.invoke(proxy, method, args);
       }

   }
 
Example #6
Source File: ResetAbandonedTimer.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
public boolean resetTimer() {
    boolean result = false;
    JdbcInterceptor interceptor = this.getNext();
    while (interceptor!=null && result==false) {
        if (interceptor instanceof ProxyConnection) {
            PooledConnection con = ((ProxyConnection)interceptor).getConnection();
            if (con!=null) {
                con.setTimestamp(System.currentTimeMillis());
                result = true;
            } else {
                break;
            }
        }
        interceptor = interceptor.getNext();
    }
    return result;
}
 
Example #7
Source File: DataSourceValidator.java    From dal with Apache License 2.0 6 votes vote down vote up
private QueryParameter getQueryParameter(int validateAction) {
    QueryParameter parameter = null;
    if (validateAction != PooledConnection.VALIDATE_INIT)
        return parameter;

    PoolProperties poolProperties = getPoolProperties();
    if (poolProperties == null)
        return parameter;

    String query = poolProperties.getInitSQL();
    int validationQueryTimeout = poolProperties.getValidationQueryTimeout();
    if (validationQueryTimeout <= 0) {
        validationQueryTimeout = DEFAULT_VALIDATE_TIMEOUT_IN_SECONDS;
    }

    parameter = new QueryParameter();
    parameter.setQuery(query);
    parameter.setValidationQueryTimeout(validationQueryTimeout);
    return parameter;
}
 
Example #8
Source File: ConnectionActionTest.java    From dal with Apache License 2.0 6 votes vote down vote up
@Test
public void testCleanupCloseConnectionNegative() {
    try {
        TestConnectionAction test = new TestConnectionAction();
        DalConnection connHolder = getDalConnection();
        test.connHolder = connHolder;
        test.statement = test.connHolder.getConn().createStatement();
        test.rs = test.statement.executeQuery("select * from " + SqlServerTestInitializer.TABLE_NAME);
        test.rs.next();
        PooledConnection c = (PooledConnection) connHolder.getConn().unwrap(PooledConnection.class);
        connHolder.error(new NullPointerException("0800"));

        test.cleanup();
        assertTrue(!c.isDiscarded());
        assertTrue(!c.isReleased());
        assertNotNull(test);
        assertTrue(test.conn == null);
        assertTrue(test.statement == null);
        assertTrue(test.rs == null);
        assertTrue(test.connHolder == null);
    } catch (Exception ex) {
        ex.printStackTrace();
        fail("There should be no exception here");
    }
}
 
Example #9
Source File: ResetAbandonedTimer.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
public boolean resetTimer() {
    boolean result = false;
    JdbcInterceptor interceptor = this.getNext();
    while (interceptor!=null && result==false) {
        if (interceptor instanceof ProxyConnection) {
            PooledConnection con = ((ProxyConnection)interceptor).getConnection();
            if (con!=null) {
                con.setTimestamp(System.currentTimeMillis());
                result = true;
            } else {
                break;
            }
        }
        interceptor = interceptor.getNext();
    }
    return result;
}
 
Example #10
Source File: TestSuspectTimeout.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuspect() throws Exception {
    this.datasource.setMaxActive(100);
    this.datasource.setMaxIdle(100);
    this.datasource.setInitialSize(0);
    this.datasource.getPoolProperties().setAbandonWhenPercentageFull(0);
    this.datasource.getPoolProperties().setTimeBetweenEvictionRunsMillis(100);
    this.datasource.getPoolProperties().setRemoveAbandoned(true);
    this.datasource.getPoolProperties().setRemoveAbandonedTimeout(100);
    this.datasource.getPoolProperties().setSuspectTimeout(1);
    this.datasource.getPoolProperties().setLogAbandoned(true);
    Connection con = datasource.getConnection();
    Assert.assertEquals("Number of connections active/busy should be 1",1,datasource.getPool().getActive());
    Thread.sleep(3000);
    PooledConnection pcon = con.unwrap(PooledConnection.class);
    Assert.assertTrue("Connection should be marked suspect",pcon.isSuspect());
    con.close();
}
 
Example #11
Source File: DefaultConnectionState.java    From dal with Apache License 2.0 6 votes vote down vote up
@Override
public void reset(ConnectionPool parent, PooledConnection con) {
    if (parent == null || con == null)
        return;

    try {
        boolean firstTime = isFirstTime.get();
        if (!firstTime)
            return;

        isFirstTime.set(false);
        String connectionName = con.toString();
        String url = con.getPoolProperties().getUrl();
        String poolName = parent.getName();
        String info = String.format("%s of url %s has been created for the first time,connection pool name:%s.",
                connectionName, url, poolName);
        logger.info(info);
    } catch (Throwable e) {
    }
}
 
Example #12
Source File: TestSuspectTimeout.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
@Test
public void testSuspect() throws Exception {
    this.datasource.setMaxActive(100);
    this.datasource.setMaxIdle(100);
    this.datasource.setInitialSize(0);
    this.datasource.getPoolProperties().setAbandonWhenPercentageFull(0);
    this.datasource.getPoolProperties().setTimeBetweenEvictionRunsMillis(100);
    this.datasource.getPoolProperties().setRemoveAbandoned(true);
    this.datasource.getPoolProperties().setRemoveAbandonedTimeout(100);
    this.datasource.getPoolProperties().setSuspectTimeout(1);
    this.datasource.getPoolProperties().setLogAbandoned(true);
    Connection con = datasource.getConnection();
    Assert.assertEquals("Number of connections active/busy should be 1",1,datasource.getPool().getActive());
    Thread.sleep(3000);
    PooledConnection pcon = con.unwrap(PooledConnection.class);
    Assert.assertTrue("Connection should be marked suspect",pcon.isSuspect());
    con.close();
}
 
Example #13
Source File: PayloadInterceptor.java    From jqm with Apache License 2.0 6 votes vote down vote up
@Override
public void reset(ConnectionPool parent, PooledConnection con)
{
    trackedConnPool = parent;
    trackedPooledCon = con;

    if (parent != null && con != null)
    {
        ConnPair cp = new ConnPair();
        cp.conn = con;
        cp.thread = Thread.currentThread();
        Set<ConnPair> pairs = conns.get(parent);
        if (pairs != null)
        {
            conns.get(parent).add(cp);
        }
    }
}
 
Example #14
Source File: DalConnectionPool.java    From das with Apache License 2.0 5 votes vote down vote up
@Override
protected PooledConnection createConnection(long now, PooledConnection notUsed, String username, String password)
        throws SQLException {

    PooledConnection pooledConnection = super.createConnection(now, notUsed, username, password);
    try {
        connectionListener.onCreateConnection(getName(),
                pooledConnection == null ? null : pooledConnection.getConnection());
    } catch (Exception e) {
        logger.error("[createConnection]" + this, e);

    }
    return pooledConnection;
}
 
Example #15
Source File: DalConnectionPool.java    From das with Apache License 2.0 5 votes vote down vote up
@Override
protected void release(PooledConnection con) {

    try {
        connectionListener.onReleaseConnection(getName(), con == null ? null : con.getConnection());
    } catch (Exception e) {
        logger.error("[release]" + this, e);
    }
    super.release(con);
}
 
Example #16
Source File: MockedTomcatJdbcConnection.java    From liquibase-percona with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a mocked SQL connection, that looks like a tomcat-jdbc pooled connection.
 * @param username the username to use
 * @param password the password to use
 * @return the connection
 * @throws SQLException
 */
public static Connection create(String username, String password) throws SQLException {
    PoolProperties poolProps = new PoolProperties();
    poolProps.setUsername(username);
    poolProps.setPassword(password);
    poolProps.setDataSource(new MockDataSource());
    ConnectionPool pool = new ConnectionPool(poolProps);
    PooledConnection pooledConnection = new PooledConnection(poolProps, pool);
    pooledConnection.connect();
    ProxyConnection proxyConnection = new ProxyConnection(null, pooledConnection, true) {};
    DisposableConnectionFacade invocationHandler = new DisposableConnectionFacade(proxyConnection) {};
    Connection connection = (Connection) Proxy.newProxyInstance(DisposableConnectionFacade.class.getClassLoader(), new Class[] {Connection.class}, invocationHandler);
    return connection;
}
 
Example #17
Source File: ConnectionState.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Override
public void disconnected(ConnectionPool parent, PooledConnection con, boolean finalizing) {
    //we are resetting, reset our defaults
    autoCommit = null;
    transactionIsolation = null;
    readOnly = null;
    catalog = null;
    super.disconnected(parent, con, finalizing);
}
 
Example #18
Source File: SlowQueryReport.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public void reset(ConnectionPool parent, PooledConnection con) {
    super.reset(parent, con);
    if (parent!=null)
        queries = SlowQueryReport.perPoolStats.get(parent.getName());
    else
        queries = null;
}
 
Example #19
Source File: DalConnectionPool.java    From dal with Apache License 2.0 5 votes vote down vote up
@Override
protected void abandon(PooledConnection con) {
    try {
        connectionListener.onAbandonConnection(getName(), getConnection(con));
    } catch (Exception e) {
        logger.error("[abandon]" + this, e);
    }

    super.abandon(con);
}
 
Example #20
Source File: DalConnectionPool.java    From dal with Apache License 2.0 5 votes vote down vote up
@Override
protected void release(PooledConnection con) {
    try {
        connectionListener.onReleaseConnection(getName(), getConnection(con));
    } catch (Exception e) {
        logger.error("[release]" + this, e);
    }

    super.release(con);
}
 
Example #21
Source File: ConnectionState.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
public void disconnected(ConnectionPool parent, PooledConnection con, boolean finalizing) {
    //we are resetting, reset our defaults
    autoCommit = null;
    transactionIsolation = null;
    readOnly = null;
    catalog = null;
    super.disconnected(parent, con, finalizing);
}
 
Example #22
Source File: StatementCache.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
protected ConcurrentHashMap<CacheKey,CachedStatement> getCache() {
    PooledConnection pCon = this.pcon;
    if (pCon == null) {
        if (log.isWarnEnabled()) log.warn("Connection has already been closed or abandoned");
        return null;
    }
    @SuppressWarnings("unchecked")
    ConcurrentHashMap<CacheKey,CachedStatement> cache =
            (ConcurrentHashMap<CacheKey,CachedStatement>)pCon.getAttributes().get(STATEMENT_CACHE_ATTR);
    return cache;
}
 
Example #23
Source File: SlowQueryReportJmx.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public void reset(ConnectionPool parent, PooledConnection con) {
    super.reset(parent, con);
    if (parent!=null) {
        poolName = parent.getName();
        pool = parent;
        registerJmx();
    }
}
 
Example #24
Source File: SlowQueryReport.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
public void reset(ConnectionPool parent, PooledConnection con) {
    super.reset(parent, con);
    if (parent!=null)
        queries = SlowQueryReport.perPoolStats.get(parent.getName());
    else
        queries = null;
}
 
Example #25
Source File: StatementCache.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
public void disconnected(ConnectionPool parent, PooledConnection con, boolean finalizing) {
    @SuppressWarnings("unchecked")
    ConcurrentHashMap<CacheKey,CachedStatement> statements =
        (ConcurrentHashMap<CacheKey,CachedStatement>)con.getAttributes().get(STATEMENT_CACHE_ATTR);

    if (statements!=null) {
        for (Map.Entry<CacheKey, CachedStatement> p : statements.entrySet()) {
            closeStatement(p.getValue());
        }
        statements.clear();
    }

    super.disconnected(parent, con, finalizing);
}
 
Example #26
Source File: StatementCache.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
public void reset(ConnectionPool parent, PooledConnection con) {
    super.reset(parent, con);
    if (parent==null) {
        cacheSize = null;
        this.pcon = null;
    } else {
        cacheSize = cacheSizeMap.get(parent);
        this.pcon = con;
        if (!pcon.getAttributes().containsKey(STATEMENT_CACHE_ATTR)) {
            ConcurrentHashMap<CacheKey,CachedStatement> cache = new ConcurrentHashMap<CacheKey, CachedStatement>();
            pcon.getAttributes().put(STATEMENT_CACHE_ATTR,cache);
        }
    }
}
 
Example #27
Source File: DalConnectionPool.java    From dal with Apache License 2.0 5 votes vote down vote up
@Override
protected PooledConnection borrowConnection(long now, PooledConnection con, String username, String password) throws SQLException {
    try {
        long waitTime = System.currentTimeMillis() - poolWaitTime.get().longValue();
        if (waitTime > 1) {
            connectionListener.onWaitConnection(getName(), getConnection(con), poolWaitTime.get().longValue());
        }
    } catch (Exception e) {
        logger.error("[borrow]" + this, e);
    }

    return super.borrowConnection(now, con, username, password);
}
 
Example #28
Source File: SlowQueryReportJmx.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
public void reset(ConnectionPool parent, PooledConnection con) {
    super.reset(parent, con);
    if (parent!=null) {
        poolName = parent.getName();
        pool = parent;
        registerJmx();
    }
}
 
Example #29
Source File: ConnectionState.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public void disconnected(ConnectionPool parent, PooledConnection con, boolean finalizing) {
    //we are resetting, reset our defaults
    autoCommit = null;
    transactionIsolation = null;
    readOnly = null;
    catalog = null;
    super.disconnected(parent, con, finalizing);
}
 
Example #30
Source File: SlowQueryReport.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Override
public void reset(ConnectionPool parent, PooledConnection con) {
    super.reset(parent, con);
    if (parent!=null)
        queries = SlowQueryReport.perPoolStats.get(parent.getName());
    else
        queries = null;
}