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

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

Introduction

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

Prototype

public synchronized int getNumIdle() 

Source Link

Document

[Read Only] The current number of idle connections that are waiting to be allocated from this data source.

Usage

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/*  www. j  a va2 s.c o  m*/
        public void run() {
            synchronized (pool) {
                cnt.set(true, pool.getNumActive());
                cnt.set(false, pool.getNumIdle());
            }
        }
    });
}

From source file:fr.cnes.sitools.datasource.jdbc.DataSourceMonitoringResource.java

/**
 * Trace informations for a sitoolsDataSource
 * //  w  ww  . j a v  a  2  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:net.risesoft.soa.asf.web.controller.SystemController.java

private List<SysInfo> getDBInfo() {
    List list = new ArrayList();
    String group = "4. ??";
    try {/*from  w w w .  j av  a 2  s .c o  m*/
        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   ww w.  j  av a2 s.c  om*/
    return dataSourceInfo;
}

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

/**
 * Query data source status//from  ww w .  j  a v a 2  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  www .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/*from ww w . j  a  va  2 s  . com*/
 * @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   www  .  j ava 2  s . co m
 */
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./*  ww w.jav a 2s  .c  o m*/
 */
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.gvsig.fmap.dal.store.jdbc.JDBCResource.java

private void debugPoolStatus(String src) {
    if (logger.isDebugEnabled() && dataSource instanceof BasicDataSource) {
        BasicDataSource ds = (BasicDataSource) dataSource;
        logger.debug(src + "  actives:" + ds.getNumActive() + "(" + ds.getMaxActive() + ") idle:"
                + ds.getNumIdle() + "(" + ds.getMaxIdle() + ")");
    }/* w  w w .j av  a 2  s. c o m*/

}