Example usage for org.apache.commons.dbcp2 BasicDataSource getNumActive

List of usage examples for org.apache.commons.dbcp2 BasicDataSource getNumActive

Introduction

In this page you can find the example usage for org.apache.commons.dbcp2 BasicDataSource getNumActive.

Prototype

@Override
public int getNumActive() 

Source Link

Document

[Read Only] The current number of active connections that have been allocated from this data source.

Usage

From source file:BasicDataSourceExample.java

public static void printDataSourceStats(DataSource ds) {
    BasicDataSource bds = (BasicDataSource) ds;
    System.out.println("NumActive: " + bds.getNumActive());
    System.out.println("NumIdle: " + bds.getNumIdle());
}

From source file:dgw.mt940.db.util.DGWBasicDataSource.java

public static void printDataSourceStats(DataSource ds) {
    BasicDataSource bds = (BasicDataSource) ds;
    logger4j.debug("NumActive: " + bds.getNumActive());
    logger4j.debug("NumIdle: " + bds.getNumIdle());
}

From source file:i5.las2peer.services.mobsos.SurveyService.java

/**
 * TODO: write documentation//from   w  w  w  . j av  a  2 s.c  o  m
 * 
 * @param ds
 */
private static void printDataSourceStats(DataSource ds) {
    System.out.println("Data Source Stats: ");
    BasicDataSource bds = (BasicDataSource) ds;
    System.out.println("  Num Active: " + bds.getNumActive());
    System.out.println("  Num Idle: " + bds.getNumIdle());
    System.out.println("  Max Idle: " + bds.getMaxIdle());
    System.out.println("  Max Total: " + bds.getMaxTotal());
    System.out.println("  Max Conn Lifetime Millis: " + bds.getMaxConnLifetimeMillis());
    System.out.println("  Min Idle: " + bds.getMinIdle());
    System.out.println("  Min Evictable Idletime Millis: " + bds.getMinEvictableIdleTimeMillis());
    System.out.println("  Validation Query: " + bds.getValidationQuery());
}

From source file:org.apache.openejb.resource.jdbc.XAPoolTest.java

@Test
public void check() throws SQLException {
    assertNotNull(ds);/*from w ww .  j  ava  2s.  co  m*/
    final BasicDataSource tds = ManagedDataSourceWithRecovery.class.cast(ds);

    assertEquals(0, tds.getNumIdle()); // db not yet used so no connection at all (dbcp behavior)

    try (final Connection c = ds.getConnection()) {
        assertNotNull(c);

        final Connection connection = c.getMetaData().getConnection(); // just to do something and force the connection init
        assertThat(connection, instanceOf(ManagedConnection.class));
        assertTrue(connection.toString()
                .contains("URL=jdbc:hsqldb:mem:dbcpxa, UserName=SA, HSQL Database Engine Driver"));
    } // here we close the connection so we are back in the initial state

    assertEquals(0, tds.getNumActive());
    assertEquals(3, tds.getNumIdle());

    for (int it = 0; it < 5; it++) { // ensures it always works and not only the first time
        final Collection<Connection> connections = new ArrayList<>(25);
        for (int i = 0; i < 25; i++) {
            final Connection connection = ds.getConnection();
            connections.add(connection);
            connection.getMetaData(); // trigger connection retrieving otherwise nothing is done (pool is not used)
        }
        assertEquals(25, tds.getNumActive());
        assertEquals(0, tds.getNumIdle());
        for (final Connection toClose : connections) {
            toClose.close();
        }
        assertEquals(0, tds.getNumActive());
        assertEquals(25, tds.getNumIdle());
    }
}

From source file:org.mot.common.db.DatabaseConnectionFactory.java

public Connection getConnection() {

    Connection conn = null;//from   w ww  .j  a  v a 2  s.c  o m

    try {
        logger.trace("Getting new connection from database ...");

        BasicDataSource bds = (BasicDataSource) ds;
        logger.trace("DBConnections - NumActive: " + bds.getNumActive());
        logger.trace("DBConnections - NumIdle: " + bds.getNumIdle());

        conn = ds.getConnection();

    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return conn;

}

From source file:org.ramadda.repository.database.DatabaseManager.java

/**
 * _more_//w ww  . jav  a2s  . co  m
 *
 * @param request _more_
 * @param dbSB _more_
 *
 * @throws Exception _more_
 */
public void addStatistics(Request request, StringBuffer dbSB) throws Exception {

    BasicDataSource bds = (BasicDataSource) dataSource;

    StringBuffer poolSB = new StringBuffer();
    poolSB.append("&nbsp;&nbsp;#active:" + bds.getNumActive() + "<br>&nbsp;&nbsp;#idle:" + bds.getNumIdle()
    //                      + "<br>&nbsp;&nbsp;max active: " + bds.getMaxActive()
    //                      + "<br>&nbsp;&nbsp;max idle:" + bds.getMaxIdle());
            + "<br>&nbsp;&nbsp;max active: " + bds.getMaxTotal());

    poolSB.append("<br># of open selects:" + numberOfSelects.getCount());
    poolSB.append("<br>");

    long time = System.currentTimeMillis();
    StringBuffer openConnections = new StringBuffer();
    List<ConnectionInfo> infos = getConnectionInfos();
    for (ConnectionInfo info : infos) {
        openConnections
                .append(HtmlUtils.makeShowHideBlock("Open for:" + ((time - info.time) / 1000) + " seconds",
                        HtmlUtils.pre(info.msg + "\nStack:" + info.where), false));
    }
    if (infos.size() > 0) {
        poolSB.append(HtmlUtils.br());
        poolSB.append(msgLabel("Open connections"));
        poolSB.append(openConnections);
    }

    StringBuffer msgb = new StringBuffer();
    synchronized (scourMessages) {
        if (totalScours > 0) {
            msgb.append("Total scours:" + totalScours + HtmlUtils.p());
        }
        for (String msg : scourMessages) {
            msgb.append("<pre>" + msg + "</pre>");
            msgb.append("<hr>");
        }
        if (scourMessages.size() > 0) {
            poolSB.append(HtmlUtils.insetLeft(
                    HtmlUtils.makeShowHideBlock(msg("Scoured Connections"), msgb.toString(), false), 20));
        }
    }

    dbSB.append(HtmlUtils
            .insetLeft(HtmlUtils.makeShowHideBlock(msg("Connection Pool"), poolSB.toString(), false), 20));

    /**
     * Don't show the entry break down as it can be kind of slow
     * dbSB.append(HtmlUtils.br());
     * dbSB.append("<table>\n");
     * String[] names = { msg("Users"), msg("Associations"),
     *                  msg("Metadata Items") };
     * String[] tables = { Tables.USERS.NAME, Tables.ASSOCIATIONS.NAME,
     *                   Tables.METADATA.NAME };
     * for (int i = 0; i < tables.length; i++) {
     *   dbSB.append(HtmlUtils.row(HtmlUtils.cols(""
     *           + getDatabaseManager().getCount(tables[i].toLowerCase(),
     *               new Clause()), names[i])));
     * }
     *
     *
     * dbSB.append(
     *   HtmlUtils.row(
     *       HtmlUtils.colspan(HtmlUtils.bold(msgLabel("Types")), 2)));
     * int total = 0;
     * dbSB.append(HtmlUtils.row(HtmlUtils.cols(""
     *       + getDatabaseManager().getCount(Tables.ENTRIES.NAME,
     *           new Clause()), msg("Total entries"))));
     * for (TypeHandler typeHandler : getRepository().getTypeHandlers()) {
     *   if (typeHandler.isType(TypeHandler.TYPE_ANY)) {
     *       continue;
     *   }
     *   int cnt = getCount(Tables.ENTRIES.NAME,
     *                      Clause.eq(Tables.ENTRIES.COL_TYPE,
     *                                typeHandler.getType()));
     *
     *   String url =
     *       HtmlUtils.href(
     *           request.makeUrl(
     *               getRepository().getSearchManager().URL_SEARCH_FORM,
     *               ARG_TYPE,
     *               typeHandler.getType()), typeHandler.getLabel());
     *   dbSB.append(HtmlUtils.row(HtmlUtils.cols("" + cnt, url)));
     * }
     *
     *
     * dbSB.append("</table>\n");
     */
}

From source file:org.yx.db.conn.ConnectionFactory.java

public Map<String, Map<String, Integer>> status() {
    Set<DataSource> set = new HashSet<>();
    set.addAll(this.read.allDataSource());
    set.addAll(this.write.allDataSource());
    Map<String, Map<String, Integer>> statusMap = new HashMap<>();
    for (DataSource datasource : set) {
        if (!BasicDataSource.class.isInstance(datasource)) {
            Log.get(this.getClass(), 25345).info("ds.class({}) is not instance form BasicDataSource",
                    datasource.getClass().getName());
            continue;
        }/*from w ww  . jav  a  2s . c o  m*/
        @SuppressWarnings("resource")
        BasicDataSource ds = (BasicDataSource) datasource;
        Map<String, Integer> map = new HashMap<>();
        map.put("active", ds.getNumActive());
        map.put("idle", ds.getNumIdle());
        map.put("minIdle", ds.getMinIdle());
        map.put("maxIdle", ds.getMaxIdle());
        map.put("maxTotal", ds.getMaxTotal());
        statusMap.put(ds.toString(), map);
    }
    return statusMap;
}

From source file:psiprobe.beans.Dbcp2DatasourceAccessor.java

@Override
public DataSourceInfo getInfo(Object resource) throws Exception {
    DataSourceInfo dataSourceInfo = null;
    if (canMap(resource)) {
        BasicDataSource source = (BasicDataSource) resource;
        dataSourceInfo = new DataSourceInfo();
        dataSourceInfo.setBusyConnections(source.getNumActive());
        dataSourceInfo.setEstablishedConnections(source.getNumIdle() + source.getNumActive());
        dataSourceInfo.setMaxConnections(source.getMaxTotal());
        dataSourceInfo.setJdbcUrl(source.getUrl());
        dataSourceInfo.setUsername(source.getUsername());
        dataSourceInfo.setResettable(false);
        dataSourceInfo.setType("commons-dbcp2");
    }// ww w .ja v a2s . co  m
    return dataSourceInfo;
}

From source file:tilda.db.ConnectionPool.java

public static Connection get(String Id) throws Exception {
    BasicDataSource BDS = _DataSourcesById.get(Id);
    if (BDS == null)
        throw new Exception("Cannot find a connection pool for " + Id);
    long T0 = System.nanoTime();
    java.sql.Connection C = BDS.getConnection();
    Connection Conn = new Connection(C, Id);
    PerfTracker.add(TransactionType.CONNECTION_GET, System.nanoTime() - T0);
    LOG.info("-------- O B T A I N E D   C O N N E C T I O N --------- " + Conn._PoolId + " ---- ("
            + BDS.getNumActive() + "/" + BDS.getNumIdle() + "/" + BDS.getMaxTotal() + ")   ----------");
    return Conn;/*w ww .  j a v  a 2 s . c o m*/
}

From source file:uk.co.platosys.db.jdbc.ConnectionBroker.java

protected Connection getConnection(String databaseName) throws PlatosysDBException {
    Connection connect;/*w  w w  .  j a v  a2s.  com*/
    while (!done) {
    } //wait for databases to be set up.
    try {
        if (dataSources.containsKey(databaseName)) {
            BasicDataSource dataSource = dataSources.get(databaseName);

            /* GenericObjectPool<PoolableConnection> pool = pools.get(databaseName);*/
            //logger.log("1 "+databaseName+" has "+dataSource.getNumIdle()+"  idle plus "+dataSource.getNumActive()+" borrowed");
            Connection connection = dataSource.getConnection();
            if (connection != null) {
                //logger.log("2 "+databaseName+" has "+dataSource.getNumIdle()+"  idle plus "+dataSource.getNumActive()+" borrowed");
                connect = connection;
            } else {
                logger.log("dataSource returned a null connection");
                return null;
            }
        } else {
            logger.log("not found first time, reloading datasources");
            done = false;
            init();
            while (!done) {
            } //
            if (dataSources.containsKey(databaseName)) {
                BasicDataSource dataSource = dataSources.get(databaseName);
                /*GenericObjectPool<PoolableConnection> pool = pools.get(databaseName);*/
                //logger.log("3 "+databaseName+" has "+dataSource.getNumIdle()+"  idle plus "+dataSource.getNumActive()+" borrowed");
                Connection connection = dataSource.getConnection();
                if (connection != null) {
                    // logger.log("4 "+databaseName+" has "+dataSource.getNumIdle()+"  idle plus "+dataSource.getNumActive()+" borrowed");
                    connect = connection;
                } else {
                    logger.log("dataSource returned a null connection");
                    return null;
                }
            } else {
                logger.log(2, "CB - Database " + databaseName + " is not known ");
                throw new PlatosysDBException("CB says Database " + databaseName + " is not known");
            }
        }
        //refresh connection counters:
        int idleConnections = 0;
        int activeConnections = 0;
        int totalConnections = 0;
        int maxTotal = 0;
        for (BasicDataSource bds : dataSet) {
            idleConnections = idleConnections + bds.getNumIdle();
            activeConnections = activeConnections + bds.getNumActive();
            maxTotal = maxTotal + bds.getMaxTotal();
        }
        totalConnections = idleConnections + activeConnections;
        logger.log("CB has " + totalConnections + "; of which " + activeConnections + " active and "
                + idleConnections + " idle");
        return connect;
    } catch (Exception e) {
        throw new PlatosysDBException("ConnectionBroker issues", e);
    }
}