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

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

Introduction

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

Prototype

@Override
public synchronized int getMaxTotal() 

Source Link

Document

Returns the maximum number of active connections that can be allocated at the same time.

Usage

From source file:com.thoughtworks.go.server.database.H2DatabaseTest.java

@Test
void shouldUseParamterizedActiveAndIdleConnections() {
    BasicDataSource dataSource = h2Database.createDataSource();
    assertThat(dataSource.getMaxTotal(), is(20));
    assertThat(dataSource.getMaxIdle(), is(10));
}

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

/**
 * TODO: write documentation//from   w  ww .jav  a  2  s .co  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.ramadda.repository.database.DatabaseManager.java

/**
 * _more_//w  ww.j  a va  2s  .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.springframework.boot.docs.jdbc.SimpleTwoDataSourcesExampleTests.java

@Test
public void validateConfiguration() throws SQLException {
    assertThat(this.context.getBeansOfType(DataSource.class)).hasSize(2);
    DataSource dataSource = this.context.getBean(DataSource.class);
    assertThat(this.context.getBean("firstDataSource")).isSameAs(dataSource);
    assertThat(dataSource.getConnection().getMetaData().getURL()).startsWith("jdbc:h2:mem:");
    BasicDataSource secondDataSource = this.context.getBean("secondDataSource", BasicDataSource.class);
    assertThat(secondDataSource.getUrl()).isEqualTo("jdbc:h2:mem:bar;DB_CLOSE_DELAY=-1");
    assertThat(secondDataSource.getMaxTotal()).isEqualTo(42);
}

From source file:org.springframework.boot.jdbc.SimpleTwoDataSourcesExampleTests.java

@Test
public void validateConfiguration() throws SQLException {
    assertThat(this.context.getBeansOfType(DataSource.class)).hasSize(2);
    DataSource dataSource = this.context.getBean(DataSource.class);
    assertThat(this.context.getBean("fooDataSource")).isSameAs(dataSource);
    assertThat(dataSource.getConnection().getMetaData().getURL()).startsWith("jdbc:h2:mem:");
    BasicDataSource barDataSource = this.context.getBean("barDataSource", BasicDataSource.class);
    assertThat(barDataSource.getUrl()).isEqualTo("jdbc:h2:mem:bar;DB_CLOSE_DELAY=-1");
    assertThat(barDataSource.getMaxTotal()).isEqualTo(42);
}

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  www.  j  a va 2  s  .co  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");
    }//from w  ww . j  a  v a2  s  . co  m
    return dataSourceInfo;
}

From source file:tilda.db.ConnectionPool.java

public static void init(String Id, String Driver, String DB, String User, String Pswd, int InitialSize,
        int MaxSize) {
    if (_DataSourcesById.get(Id) == null)
        synchronized (_DataSourcesById) {
            if (_DataSourcesById.get(Id) == null) // Definitely no connection pool by that name
            {//from ww  w  . ja  v a  2 s . com
                String Sig = DB + "``" + User;
                BasicDataSource BDS = _DataSourcesBySig.get(Sig); // Let's see if that DB definition is already there
                if (BDS == null) {
                    LOG.info("Initializing a fresh pool for Id=" + Id + ", DB=" + DB + ", User=" + User
                            + ", and Pswd=Shhhhhhh!");
                    BDS = new BasicDataSource();
                    BDS.setDriverClassName(Driver);
                    BDS.setUrl(DB);
                    if (TextUtil.isNullOrEmpty(Pswd) == false && TextUtil.isNullOrEmpty(User) == false) {
                        BDS.setUsername(User);
                        BDS.setPassword(Pswd);
                    }
                    BDS.setInitialSize(InitialSize);
                    BDS.setMaxTotal(MaxSize);
                    BDS.setDefaultAutoCommit(false);
                    BDS.setDefaultTransactionIsolation(java.sql.Connection.TRANSACTION_READ_COMMITTED);
                    BDS.setDefaultQueryTimeout(20000);
                    _DataSourcesBySig.put(Sig, BDS);
                } else {
                    LOG.info("Merging pool with ID " + Id + " into prexisting pool " + Sig);
                    if (BDS.getInitialSize() < InitialSize)
                        BDS.setInitialSize(InitialSize);
                    if (BDS.getMaxTotal() < MaxSize)
                        BDS.setMaxTotal(MaxSize);

                }
                _DataSourcesById.put(Id, BDS);
            }
        }
}

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;//ww w .  java2s . c  o m
}

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

private void init() {

    List<DatabaseCredentials> databases = properties.getDatabases();
    for (DatabaseCredentials credentials : databases) {

        String name = "";
        String driver = "";
        String userName = "";
        String password = "";
        String url = "";
        try {/*from ww w .jav  a  2  s.  c om*/
            name = credentials.getName();
            logger.log("ConnectionBroker initialising database " + name);
            driver = credentials.getDriver();
            url = credentials.getUrl();
            userName = credentials.getUsername();
            password = credentials.getPassword();
            logger.log("ConnectionBroker credentials for " + name + " are " + driver + " " + url + " "
                    + userName + " " + password);

        } catch (Exception e) {
            logger.log("ConnectionBroker had a problem getting credentials for " + name, e);
        }
        /* try{
            //although we only use postgresql, there's no reason we couldn't use a different sql rdbms with a different driver for each
            //database.
        Class.forName(driver);
         }catch(ClassNotFoundException e){
        logger.log("ConnectionBroker couldn't load database driver", e);
         }*/
        try {
            /*connFac = new DriverManagerConnectionFactory(url, userName, password);
            PoolableConnectionFactory poolableConFac = new PoolableConnectionFactory(connFac, null);
            GenericObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<PoolableConnection>(poolableConFac);
            pools.put(name, connectionPool);
            poolableConFac.setPool(connectionPool);
            PoolingDataSource<PoolableConnection> dataSource = new PoolingDataSource<PoolableConnection>(connectionPool);*/
            BasicDataSource dataSource = new BasicDataSource();
            dataSource.setDriverClassName(driver);
            dataSource.setUsername(userName);
            dataSource.setPassword(password);
            dataSource.setUrl(url);
            dataSource.setMinIdle(2);
            dataSource.setMaxTotal(MAX_ACTIVE);
            logger.log(5, "ConnectionBroker has made BasicDataSource " + dataSource.toString());
            logger.log("Datasource " + name + " has " + dataSource.getMaxTotal() + " maxConnections");
            try {
                Connection connection = dataSource.getConnection();
                connection.close();
                dataSources.put(name, dataSource);
                dataSet.add(dataSource);
                logger.log(5, "ConnectionBroker has initialised database " + name);
            } catch (PSQLException psqe) {
                logger.log("could not make a test connection to database: " + name, psqe);
            }
        } catch (Exception e) {
            logger.log("ConnectionBroker had a problem configuring the pool with " + name, e);
        }
    }
    done = true;
}