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

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

Introduction

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

Prototype

public void setDefaultQueryTimeout(Integer defaultQueryTimeout) 

Source Link

Document

Set the default query timeout that will be used for java.sql.Statement Statement s created from this connection.

Usage

From source file:com.github.akiraly.db4j.pool.DbcpUtils.java

public static BasicDataSource newDefaultDS() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDefaultAutoCommit(false);

    dataSource.setDefaultQueryTimeout(1);
    dataSource.setValidationQueryTimeout(1);
    dataSource.setMaxWaitMillis(5000);//ww w  . j a v  a2s .  c o m

    dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);

    dataSource.setInitialSize(4);
    dataSource.setMinIdle(4);
    dataSource.setMaxIdle(8);
    dataSource.setMaxTotal(16);
    dataSource.setPoolPreparedStatements(true);
    dataSource.setMaxOpenPreparedStatements(128);
    return dataSource;
}

From source file:no.kantega.publishing.common.util.database.dbConnectionFactory.java

public static void loadConfiguration() {
    try {//ww w . j  av  a  2 s.  c  o  m

        setConfiguration();

        verifyCompleteDatabaseConfiguration();

        DriverManagerDataSource rawDataSource = new DriverManagerDataSource();
        rawDataSource.setDriverClassName(dbDriver);
        rawDataSource.setUrl(dbUrl);

        if (!dbNTMLAuthentication) {
            rawDataSource.setUsername(dbUsername);
            rawDataSource.setPassword(dbPassword);
        }

        if (dbEnablePooling) {
            // Enable DBCP pooling
            BasicDataSource bds = new BasicDataSource();
            bds.setMaxTotal(dbMaxConnections);
            bds.setMaxIdle(dbMaxIdleConnections);
            bds.setMinIdle(dbMinIdleConnections);
            if (dbMaxWait != -1) {
                bds.setMaxWaitMillis(1000 * dbMaxWait);
            }

            if (dbDefaultQueryTimeout != -1) {
                bds.setDefaultQueryTimeout(dbDefaultQueryTimeout);
            }

            bds.setDriverClassName(dbDriver);
            if (!dbNTMLAuthentication) {
                bds.setUsername(dbUsername);
                bds.setPassword(dbPassword);
            }
            bds.setUrl(dbUrl);

            if (dbUseTransactions) {
                bds.setDefaultTransactionIsolation(dbTransactionIsolationLevel);
            }

            if (dbCheckConnections) {
                // Gjr at connections frigjres ved lukking fra database/brannmur
                bds.setValidationQuery("SELECT max(ContentId) from content");
                bds.setTimeBetweenEvictionRunsMillis(1000 * 60 * 2);
                bds.setMinEvictableIdleTimeMillis(1000 * 60 * 5);
                bds.setNumTestsPerEvictionRun(dbMaxConnections);
                if (dbRemoveAbandonedTimeout > 0) {
                    bds.setRemoveAbandonedTimeout(dbRemoveAbandonedTimeout);
                    bds.setLogAbandoned(true);
                }
            }

            ds = bds;
        } else {
            ds = rawDataSource;
        }

        // Use non-pooled datasource for table creation since validation query might fail
        ensureDatabaseExists(rawDataSource);
        if (shouldMigrateDatabase) {
            migrateDatabase(servletContext, rawDataSource);
        }

        if (dbUseTransactions) {
            log.info("Using transactions, database transaction isolation level set to "
                    + dbTransactionIsolationLevel);
        } else {
            log.info("Not using transactions");
        }

        if (debugConnections) {
            proxyDs = (DataSource) Proxy.newProxyInstance(DataSource.class.getClassLoader(),
                    new Class[] { DataSource.class }, new DataSourceWrapper(ds));
        }

    } catch (Exception e) {
        log.error("********* could not read aksess.conf **********", e);
    }

}

From source file:org.lib4j.dbcp.DataSources.java

/**
 * Create a <code>BasicDataSource</code> given a dbcp JAXB binding.
 *
 * @param dbcp JAXB dbcp binding./*ww  w  .  j a v  a 2 s  .c  o m*/
 * @param driverClassLoader Class loader to be used to load the JDBC driver.
 * @return the <code>BasicDataSource</code> instance.
 * @throws SQLException If a database access error occurs.
 */
public static BasicDataSource createDataSource(final Dbcp dbcp, final ClassLoader driverClassLoader)
        throws SQLException {
    final BasicDataSource dataSource = new BasicDataSource();

    final Dbcp.Jdbc jdbc = dbcp.getJdbc();
    dataSource.setDriverClassName(jdbc.getDriverClassName());
    dataSource.setDriverClassLoader(driverClassLoader);

    dataSource.setUrl(jdbc.getUrl());

    dataSource.setUsername(jdbc.getUsername());
    dataSource.setPassword(jdbc.getPassword());

    final Dbcp.Default _default = dbcp.getDefault();
    if (_default != null && _default.getCatalog() != null)
        dataSource.setDefaultCatalog(_default.getCatalog());

    dataSource.setDefaultAutoCommit(
            _default == null || _default.getAutoCommit() == null || _default.getAutoCommit());
    dataSource.setDefaultReadOnly(_default != null && _default.getReadOnly() != null && _default.getReadOnly());
    if (_default != null && _default.getQueryTimeout() != null)
        dataSource.setDefaultQueryTimeout(_default.getQueryTimeout());

    if (_default != null && _default.getTransactionIsolation() != null) {
        if ("NONE".equals(_default.getTransactionIsolation()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_NONE);
        else if ("READ_COMMITTED".equals(_default.getTransactionIsolation()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
        else if ("READ_UNCOMMITTED".equals(_default.getTransactionIsolation()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
        else if ("REPEATABLE_READ".equals(_default.getTransactionIsolation()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
        else if ("SERIALIZABLE".equals(_default.getTransactionIsolation()))
            dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
        else
            throw new UnsupportedOperationException(
                    "Unsupported transaction isolation: " + _default.getTransactionIsolation());
    }

    final Dbcp.Connection connection = dbcp.getConnection();
    if (connection != null) {
        if (connection.getProperties() != null)
            for (final Dbcp.Connection.Properties.Property property : connection.getProperties().getProperty())
                if (property.getName() != null && property.getValue() != null)
                    dataSource.addConnectionProperty(property.getName(), property.getValue());

        if (connection.getInitSqls() != null) {
            final List<String> initSqls = new ArrayList<>();
            for (final String initSql : connection.getInitSqls().getInitSql())
                initSqls.add(initSql);

            dataSource.setConnectionInitSqls(initSqls);
        }
    }

    final Dbcp.Size size = dbcp.getSize();
    dataSource.setInitialSize(size == null || size.getInitialSize() == null ? 0 : size.getInitialSize());
    dataSource.setMaxTotal(size == null || size.getMaxTotal() == null ? 8
            : INDEFINITE.equals(size.getMaxTotal()) ? -1 : Integer.parseInt(size.getMaxTotal()));
    dataSource.setMaxIdle(size == null || size.getMaxIdle() == null ? 8
            : INDEFINITE.equals(size.getMaxIdle()) ? -1 : Integer.parseInt(size.getMaxIdle()));
    dataSource.setMinIdle(size == null || size.getMinIdle() == null ? 9 : size.getMinIdle());
    if (size == null || size.getMaxOpenPreparedStatements() == null
            || INDEFINITE.equals(size.getMaxOpenPreparedStatements())) {
        dataSource.setPoolPreparedStatements(false);
    } else {
        dataSource.setPoolPreparedStatements(true);
        dataSource.setMaxOpenPreparedStatements(Integer.parseInt(size.getMaxOpenPreparedStatements()));
    }

    final Dbcp.Pool pool = dbcp.getPool();
    if (pool == null || pool.getQueue() == null || "lifo".equals(pool.getQueue()))
        dataSource.setLifo(true);
    else if ("fifo".equals(pool.getQueue()))
        dataSource.setLifo(false);
    else
        throw new UnsupportedOperationException("Unsupported queue spec: " + pool.getQueue());

    dataSource.setCacheState(pool != null && pool.getCacheState() != null && pool.getCacheState());
    dataSource.setMaxWaitMillis(
            pool == null || pool.getMaxWait() != null || INDEFINITE.equals(pool.getMaxWait()) ? -1
                    : Long.parseLong(pool.getMaxWait()));
    dataSource.setMaxConnLifetimeMillis(pool == null || pool.getMaxConnectionLifetime() == null
            || INDEFINITE.equals(pool.getMaxConnectionLifetime()) ? 0
                    : Long.parseLong(pool.getMaxConnectionLifetime()));
    dataSource.setEnableAutoCommitOnReturn(_default == null || pool.getEnableAutoCommitOnReturn() == null
            || pool.getEnableAutoCommitOnReturn());
    dataSource.setRollbackOnReturn(
            pool == null || pool.getRollbackOnReturn() == null || pool.getRollbackOnReturn());
    if (pool != null && pool.getRemoveAbandoned() != null) {
        if ("borrow".equals(pool.getRemoveAbandoned().getOn()))
            dataSource.setRemoveAbandonedOnBorrow(true);
        else if ("maintenance".equals(pool.getRemoveAbandoned().getOn()))
            dataSource.setRemoveAbandonedOnMaintenance(true);
        else
            throw new UnsupportedOperationException(
                    "Unsupported remove abandoned spec: " + pool.getRemoveAbandoned().getOn());

        dataSource.setRemoveAbandonedTimeout(pool.getRemoveAbandoned().getTimeout());
    }

    dataSource.setAbandonedUsageTracking(
            pool != null && pool.getAbandonedUsageTracking() != null && pool.getAbandonedUsageTracking());
    dataSource.setAccessToUnderlyingConnectionAllowed(
            pool != null && pool.getAllowAccessToUnderlyingConnection() != null
                    && pool.getAllowAccessToUnderlyingConnection());

    final Dbcp.Pool.Eviction evictor = pool != null && pool.getEviction() != null ? pool.getEviction() : null;
    if (evictor != null) {
        dataSource.setTimeBetweenEvictionRunsMillis(evictor.getTimeBetweenRuns());
        dataSource.setNumTestsPerEvictionRun(evictor.getNumTestsPerRun());
        dataSource.setMinEvictableIdleTimeMillis(
                evictor.getMinIdleTime() == null ? 1800000 : evictor.getMinIdleTime());
        dataSource.setSoftMinEvictableIdleTimeMillis(
                evictor.getSoftMinIdleTime() == null || INDEFINITE.equals(evictor.getSoftMinIdleTime()) ? -1
                        : Long.parseLong(evictor.getSoftMinIdleTime()));
        if (evictor.getPolicyClassName() != null)
            dataSource.setEvictionPolicyClassName(evictor.getPolicyClassName());
    }

    final Dbcp.Validation validation = dbcp.getValidation();
    if (validation != null && validation.getQuery() != null)
        dataSource.setValidationQuery(validation.getQuery());

    dataSource.setTestOnBorrow(
            validation == null || validation.getTestOnBorrow() == null || validation.getTestOnBorrow());
    dataSource.setTestOnReturn(
            validation != null && validation.getTestOnReturn() != null && validation.getTestOnReturn());
    dataSource.setTestWhileIdle(
            validation != null && validation.getTestWhileIdle() != null && validation.getTestWhileIdle());
    if (validation != null && validation.getFastFail() != null) {
        dataSource.setFastFailValidation(true);
        if (validation.getFastFail().getDisconnectionSqlCodes() != null)
            dataSource.setDisconnectionSqlCodes(
                    Arrays.asList(validation.getFastFail().getDisconnectionSqlCodes().split(" ")));
    }

    final Dbcp.Logging logging = dbcp.getLogging();
    if (logging != null) {
        final Logger logger = LoggerFactory.getLogger(DataSources.class);
        final LoggerPrintWriter loggerPrintWriter = new LoggerPrintWriter(logger,
                Level.valueOf(logging.getLevel().toString()));
        dataSource.setLogWriter(loggerPrintWriter);
        dataSource.setLogExpiredConnections(logging.isLogExpiredConnections());
        if (logging.isLogAbandoned()) {
            dataSource.setAbandonedLogWriter(loggerPrintWriter);
            dataSource.setLogAbandoned(true);
        }
    }

    return dataSource;
}

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 w  w  w  .  j  a va2 s .c o m
                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);
            }
        }
}