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

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

Introduction

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

Prototype

public synchronized 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:fr.cnes.sitools.datasource.jdbc.DataSourceMonitoringResource.java

/**
 * Trace informations for a sitoolsDataSource
 * /*from  w  w w  .  j av  a2 s.  c o m*/
 * @param sitoolsDataSource
 *          SitoolsDataSource
 * @param messages
 *          ArrayList<String> messages
 */
private void traceStatus(SitoolsSQLDataSource sitoolsDataSource, ArrayList<String> messages) {
    DataSource concreteDs = sitoolsDataSource.getDs();
    if ((concreteDs != null) && (concreteDs instanceof BasicDataSource)) {
        BasicDataSource bds = (BasicDataSource) concreteDs;
        messages.add("--------------------------------------------------");
        messages.add("Url: " + bds.getUrl());
        messages.add("User: " + bds.getUsername());
        messages.add("DefaultCatalog: " + bds.getDefaultCatalog());
        messages.add("InitialSize: " + bds.getInitialSize());
        messages.add("NumActive: " + bds.getNumActive());
        messages.add("MaxActive: " + bds.getMaxActive());
        messages.add("MaxIdl: " + bds.getMaxIdle());
        messages.add("MinIdl: " + bds.getMinIdle());
        messages.add("NumIdle: " + bds.getNumIdle());
    }

}

From source file:com.googlesource.gerrit.plugins.ci.server.schema.CiDataSourceProvider.java

private void exportPoolMetrics(final BasicDataSource pool) {
    final CallbackMetric1<Boolean, Integer> cnt = metrics.newCallbackMetric("sql/connection_pool/connections",
            Integer.class, new Description("SQL database connections").setGauge().setUnit("connections"),
            Field.ofBoolean("active"));
    metrics.newTrigger(cnt, new Runnable() {
        @Override//from  w  ww .  j  ava 2s  .co  m
        public void run() {
            synchronized (pool) {
                cnt.set(true, pool.getNumActive());
                cnt.set(false, pool.getNumIdle());
            }
        }
    });
}

From source file:net.risesoft.soa.asf.web.controller.SystemController.java

private List<SysInfo> getDBInfo() {
    List list = new ArrayList();
    String group = "4. ??";
    try {//from   w ww  . j a  v a  2 s .com
        Connection conn = this.basicDataSource.getConnection();
        try {
            DatabaseMetaData dbmd = conn.getMetaData();
            list.add(new SysInfo("DatabaseProductName", dbmd.getDatabaseProductName(), group));
            list.add(new SysInfo("DatabaseProductVersion", dbmd.getDatabaseProductVersion(), group));
            list.add(new SysInfo("DatabaseMajorVersion", Integer.valueOf(dbmd.getDatabaseMajorVersion()),
                    group));
            list.add(new SysInfo("DatabaseMinorVersion", Integer.valueOf(dbmd.getDatabaseMinorVersion()),
                    group));
            list.add(new SysInfo("DriverName", dbmd.getDriverName(), group));
            list.add(new SysInfo("DriverVersion", dbmd.getDriverVersion(), group));
            list.add(new SysInfo("DriverMajorVersion", Integer.valueOf(dbmd.getDriverMajorVersion()), group));
            list.add(new SysInfo("DriverMinorVersion", Integer.valueOf(dbmd.getDriverMinorVersion()), group));
        } finally {
            conn.close();
        }
        group = "5. ?";
        BasicDataSource bds = this.basicDataSource;
        list.add(new SysInfo("InitialSize", Integer.valueOf(bds.getInitialSize()), group));
        list.add(new SysInfo("MaxActive", Integer.valueOf(bds.getMaxActive()), group));
        list.add(new SysInfo("MaxIdle", Integer.valueOf(bds.getMaxIdle()), group));
        list.add(new SysInfo("MinIdle", Integer.valueOf(bds.getMinIdle()), group));
        list.add(new SysInfo("MaxWait", Long.valueOf(bds.getMaxWait()), group));
        list.add(new SysInfo("NumActive", Integer.valueOf(bds.getNumActive()), group));
        list.add(new SysInfo("NumIdle", Integer.valueOf(bds.getNumIdle()), group));
        list.add(new SysInfo("DriverClass", bds.getDriverClassName(), group));
        list.add(new SysInfo("URL", bds.getUrl(), group));
        list.add(new SysInfo("Username", bds.getUsername(), group));
        list.add(new SysInfo("Password", "******", group));
    } catch (Exception ex) {
        log.warn("???: " + ex.getMessage(), ex);
    }
    return list;
}

From source file:net.testdriven.psiprobe.beans.DbcpDatasourceAccessor.java

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.getMaxActive());
        dataSourceInfo.setJdbcURL(source.getUrl());
        dataSourceInfo.setUsername(source.getUsername());
        dataSourceInfo.setResettable(false);
    }/*from w  ww .ja  v  a2s .c o m*/
    return dataSourceInfo;
}

From source file:onlinefrontlines.admin.web.ServerInfoAction.java

/**
 * Query data source status/*from ww w  .  j a  v a2 s .co m*/
 * 
 * @param dataSourceName Name of the data source
 */
private String getDataSourceStatus(String dataSourceName) {
    DataSource dataSource = (DataSource) DbConnectionPool.getInstance().getDataSources().get(dataSourceName);
    if (dataSource.getClass().getName().equals("org.apache.commons.dbcp.BasicDataSource")
            && dataSource instanceof org.apache.commons.dbcp.BasicDataSource) {
        org.apache.commons.dbcp.BasicDataSource s = (org.apache.commons.dbcp.BasicDataSource) dataSource;
        return "Busy: " + s.getNumActive() + " (" + (int) (s.getNumActive() * 100 / s.getMaxActive())
                + "%), Connections: " + (s.getNumIdle() + s.getNumActive()) + ", Max: " + s.getMaxActive();
    } else if (dataSource.getClass().getName().equals("org.apache.tomcat.dbcp.dbcp.BasicDataSource")
            && dataSource instanceof org.apache.tomcat.dbcp.dbcp.BasicDataSource) {
        org.apache.tomcat.dbcp.dbcp.BasicDataSource s = (org.apache.tomcat.dbcp.dbcp.BasicDataSource) dataSource;
        return "Busy: " + s.getNumActive() + " (" + (int) (s.getNumActive() * 100 / s.getMaxActive())
                + "%), Connections: " + (s.getNumIdle() + s.getNumActive()) + ", Max: " + s.getMaxActive();
    } else {
        return "Unknown datasource: " + dataSource.getClass().getName();
    }
}

From source file:org.apache.oozie.service.JPAService.java

@Override
public void instrument(Instrumentation instr) {
    this.instr = instr;

    final BasicDataSource dataSource = getBasicDataSource();
    if (dataSource != null) {
        instr.addSampler("jdbc", "connections.active", 60, 1, new Instrumentation.Variable<Long>() {
            @Override//from ww  w .j  av  a 2  s. c  o m
            public Long getValue() {
                return (long) dataSource.getNumActive();
            }
        });
        instr.addSampler("jdbc", "connections.idle", 60, 1, new Instrumentation.Variable<Long>() {
            @Override
            public Long getValue() {
                return (long) dataSource.getNumIdle();
            }
        });
    }
}

From source file:org.apache.synapse.mediators.db.AbstractDBMediator.java

/**
 * Return a Prepared statement for the given Statement object, which is ready to be executed
 *
 * @param stmnt  SQL stataement to be executed
 * @param con    The connection to be used
 * @param msgCtx Current message context
 * @return a PreparedStatement/*w  ww .j  a v a2  s .  co m*/
 * @throws SQLException on error
 */
protected PreparedStatement getPreparedStatement(Statement stmnt, Connection con, MessageContext msgCtx)
        throws SQLException {

    SynapseLog synLog = getLog(msgCtx);

    if (synLog.isTraceOrDebugEnabled()) {
        synLog.traceOrDebug("Getting a connection from DataSource " + getDSName()
                + " and preparing statement : " + stmnt.getRawStatement());
    }

    if (con == null) {
        String msg = "Connection from DataSource " + getDSName() + " is null.";
        log.error(msg);
        throw new SynapseException(msg);
    }

    if (dataSource instanceof BasicDataSource) {

        BasicDataSource basicDataSource = (BasicDataSource) dataSource;
        int numActive = basicDataSource.getNumActive();
        int numIdle = basicDataSource.getNumIdle();
        String connectionId = Integer.toHexString(con.hashCode());

        DBPoolView dbPoolView = getDbPoolView();
        if (dbPoolView != null) {
            dbPoolView.setNumActive(numActive);
            dbPoolView.setNumIdle(numIdle);
            dbPoolView.updateConnectionUsage(connectionId);
        }

        if (synLog.isTraceOrDebugEnabled()) {
            synLog.traceOrDebug("[ DB Connection : " + con + " ]");
            synLog.traceOrDebug("[ DB Connection instance identifier : " + connectionId + " ]");
            synLog.traceOrDebug("[ Number of Active Connection : " + numActive + " ]");
            synLog.traceOrDebug("[ Number of Idle Connection : " + numIdle + " ]");
        }
    }

    PreparedStatement ps = con.prepareStatement(stmnt.getRawStatement());

    // set parameters if any
    List<Statement.Parameter> params = stmnt.getParameters();
    int column = 1;

    for (Statement.Parameter param : params) {
        if (param == null) {
            continue;
        }
        String value = (param.getPropertyName() != null ? param.getPropertyName()
                : param.getXpath().stringValueOf(msgCtx));

        if (synLog.isTraceOrDebugEnabled()) {
            synLog.traceOrDebug("Setting as parameter : " + column + " value : " + value + " as JDBC Type : "
                    + param.getType() + "(see java.sql.Types for valid " + "types)");
        }

        switch (param.getType()) {
        // according to J2SE 1.5 /docs/guide/jdbc/getstart/mapping.html
        case Types.CHAR:
        case Types.VARCHAR:
        case Types.LONGVARCHAR: {
            if (value != null && value.length() != 0) {
                ps.setString(column++, value);
            } else {
                ps.setString(column++, null);
            }
            break;
        }
        case Types.NUMERIC:
        case Types.DECIMAL: {
            if (value != null && value.length() != 0) {
                ps.setBigDecimal(column++, new BigDecimal(value));
            } else {
                ps.setBigDecimal(column++, null);
            }
            break;
        }
        case Types.BIT: {
            if (value != null && value.length() != 0) {
                ps.setBoolean(column++, Boolean.parseBoolean(value));
            } else {
                ps.setNull(column++, Types.BIT);
            }
            break;
        }
        case Types.TINYINT: {
            if (value != null && value.length() != 0) {
                ps.setByte(column++, Byte.parseByte(value));
            } else {
                ps.setNull(column++, Types.TINYINT);
            }
            break;
        }
        case Types.SMALLINT: {
            if (value != null && value.length() != 0) {
                ps.setShort(column++, Short.parseShort(value));
            } else {
                ps.setNull(column++, Types.SMALLINT);
            }
            break;
        }
        case Types.INTEGER: {
            if (value != null && value.length() != 0) {
                ps.setInt(column++, Integer.parseInt(value));
            } else {
                ps.setNull(column++, Types.INTEGER);
            }
            break;
        }
        case Types.BIGINT: {
            if (value != null && value.length() != 0) {
                ps.setLong(column++, Long.parseLong(value));
            } else {
                ps.setNull(column++, Types.BIGINT);
            }
            break;
        }
        case Types.REAL: {
            if (value != null && value.length() != 0) {
                ps.setFloat(column++, Float.parseFloat(value));
            } else {
                ps.setNull(column++, Types.REAL);
            }
            break;
        }
        case Types.FLOAT: {
            if (value != null && value.length() != 0) {
                ps.setDouble(column++, Double.parseDouble(value));
            } else {
                ps.setNull(column++, Types.FLOAT);
            }
            break;
        }
        case Types.DOUBLE: {
            if (value != null && value.length() != 0) {
                ps.setDouble(column++, Double.parseDouble(value));
            } else {
                ps.setNull(column++, Types.DOUBLE);
            }
            break;
        }
        // skip BINARY, VARBINARY and LONGVARBINARY
        case Types.DATE: {
            if (value != null && value.length() != 0) {
                ps.setDate(column++, Date.valueOf(value));
            } else {
                ps.setNull(column++, Types.DATE);
            }
            break;
        }
        case Types.TIME: {
            if (value != null && value.length() != 0) {
                ps.setTime(column++, Time.valueOf(value));
            } else {
                ps.setNull(column++, Types.TIME);
            }
            break;
        }
        case Types.TIMESTAMP: {
            if (value != null && value.length() != 0) {
                ps.setTimestamp(column++, Timestamp.valueOf(value));
            } else {
                ps.setNull(column++, Types.TIMESTAMP);
            }
            break;
        }
        // skip CLOB, BLOB, ARRAY, DISTINCT, STRUCT, REF, JAVA_OBJECT
        default: {
            String msg = "Trying to set an un-supported JDBC Type : " + param.getType() + " against column : "
                    + column + " and statement : " + stmnt.getRawStatement()
                    + " used by a DB mediator against DataSource : " + getDSName()
                    + " (see java.sql.Types for valid type values)";
            handleException(msg, msgCtx);
        }
        }
    }

    if (synLog.isTraceOrDebugEnabled()) {
        synLog.traceOrDebug("Successfully prepared statement : " + stmnt.getRawStatement()
                + " against DataSource : " + getDSName());
    }
    return ps;
}

From source file:org.bzewdu.tools.perftrend.data.oracledalHelper.java

/**
 *
 * @param ds/*from   ww  w.  j av a  2 s.c om*/
 */
public static void printDataSourceStats(final DataSource ds) {
    final BasicDataSource bds = (BasicDataSource) ds;
    if (Config.debug) {
        System.out.println("NumActive: " + bds.getNumActive());
    }
    if (Config.debug) {
        System.out.println("NumIdle: " + bds.getNumIdle());
    }
}

From source file:org.fao.geonet.api.site.SiteInformation.java

/**
 * Compute information about database.// w  w w  .  j  a v  a2  s  .com
 */
private void loadDatabaseInfo(ServiceContext context) throws SQLException {
    String dbURL = null;

    Connection connection = null;
    try {
        connection = context.getBean(DataSource.class).getConnection();
        dbURL = connection.getMetaData().getURL();
        databaseProperties.put("db.openattempt", "Database Opened Successfully");

        if (connection instanceof BasicDataSource) {
            BasicDataSource basicDataSource = (BasicDataSource) connection;
            try {
                databaseProperties.put("db.numactive", "" + basicDataSource.getNumActive());
                databaseProperties.put("db.numidle", "" + basicDataSource.getNumIdle());
                databaseProperties.put("db.maxactive", "" + basicDataSource.getMaxActive());
            } catch (Exception e) {
                databaseProperties.put("db.statserror",
                        "Failed to get stats on database connections. Error is: " + e.getMessage());
            }
        }

    } catch (Exception e) {
        databaseProperties.put("db.openattempt",
                "Failed to open database connection, Check config.xml db file configuration. Error" + " is: "
                        + e.getMessage());
    } finally {
        if (connection != null) {
            connection.close();
        }
    }
    databaseProperties.put("db.url", dbURL);
}

From source file:org.geotools.jdbc.JDBCTestSetup.java

public void tearDown() throws Exception {
    final String leakMessage = "Expected no active connection, either there is a connection leak "
            + "or you forgot to close some object holding onto connections in the tests (e.g., a reader, an iterator)";
    if (dataSource instanceof BasicDataSource) {
        BasicDataSource bds = (BasicDataSource) dataSource;
        assertEquals(leakMessage, 0, bds.getNumActive());
    } else if (dataSource instanceof DBCPDataSource) {
        BasicDataSource bds = (BasicDataSource) ((DBCPDataSource) dataSource).getWrapped();
        assertEquals(leakMessage, 0, bds.getNumActive());
    }//from  w  w  w.  j  av a  2s .  co  m

    if (dataSource instanceof BasicDataSource) {
        BasicDataSource bds = (BasicDataSource) dataSource;
        bds.close();
    } else if (dataSource instanceof ManageableDataSource) {
        ((ManageableDataSource) dataSource).close();
    }
}