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

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

Introduction

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

Prototype

public synchronized void setPoolPreparedStatements(boolean poolingStatements) 

Source Link

Document

Sets whether to pool statements or not.

Note: this method currently has no effect once the pool has been initialized.

Usage

From source file:cn.cuizuoli.gotour.config.DataSourceConfig.java

@Bean
public DataSource slaveDataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(env.getRequiredProperty("gotour.slave.jdbc.driverClassName"));
    dataSource.setUrl(env.getRequiredProperty("gotour.slave.jdbc.url"));
    dataSource.setUsername(env.getRequiredProperty("gotour.slave.jdbc.username"));
    dataSource.setPassword(env.getRequiredProperty("gotour.slave.jdbc.password"));
    dataSource.setInitialSize(env.getRequiredProperty("jdbc.initialSize", Integer.class));
    dataSource.setMaxActive(env.getRequiredProperty("jdbc.maxActive", Integer.class));
    dataSource.setMaxIdle(env.getRequiredProperty("jdbc.maxIdle", Integer.class));
    dataSource.setMinIdle(env.getRequiredProperty("jdbc.minIdle", Integer.class));
    dataSource.setDefaultAutoCommit(env.getRequiredProperty("jdbc.defaultAutoCommit", Boolean.class));
    dataSource.setPoolPreparedStatements(env.getRequiredProperty("jdbc.poolPreparedStatements", Boolean.class));
    dataSource.setValidationQuery(env.getRequiredProperty("jdbc.validationQuery"));
    dataSource.setTestOnBorrow(env.getRequiredProperty("jdbc.testOnBorrow", Boolean.class));
    dataSource.setTestOnReturn(env.getRequiredProperty("jdbc.testOnReturn", Boolean.class));
    dataSource.setTestWhileIdle(env.getRequiredProperty("jdbc.testWhileIdle", Boolean.class));
    dataSource.setTimeBetweenEvictionRunsMillis(
            env.getRequiredProperty("jdbc.timeBetweenEvictionRunsMillis", Long.class));
    dataSource.setNumTestsPerEvictionRun(env.getRequiredProperty("jdbc.numTestsPerEvictionRun", Integer.class));
    dataSource.setMinEvictableIdleTimeMillis(
            env.getRequiredProperty("jdbc.minEvictableIdleTimeMillis", Long.class));
    return dataSource;
}

From source file:com.jolbox.benchmark.BenchmarkTests.java

/**
 * Benchmarks PreparedStatement functionality (single thread) 
 * @return result//w  ww .ja  v a 2s. c om
 * 
 * @throws PropertyVetoException
 * @throws SQLException
 */
private long testPreparedStatementSingleThreadDBCP() throws PropertyVetoException, SQLException {
    BasicDataSource cpds = new BasicDataSource();
    cpds.setDriverClassName("com.jolbox.bonecp.MockJDBCDriver");
    cpds.setUrl(url);
    cpds.setUsername(username);
    cpds.setPassword(password);
    cpds.setMaxIdle(-1);
    cpds.setMinIdle(-1);
    cpds.setPoolPreparedStatements(true);
    cpds.setMaxOpenPreparedStatements(30);
    cpds.setInitialSize(pool_size);
    cpds.setMaxActive(pool_size);
    Connection conn = cpds.getConnection();

    long start = System.currentTimeMillis();
    for (int i = 0; i < MAX_CONNECTIONS; i++) {
        Statement st = conn.prepareStatement(TEST_QUERY);
        st.close();
    }
    conn.close();

    long end = (System.currentTimeMillis() - start);
    System.out.println("DBCP PreparedStatement Single thread benchmark: " + end);
    results.add("DBCP, " + end);
    // dispose of pool
    cpds.close();
    return end;
}

From source file:com.jolbox.benchmark.BenchmarkTests.java

/**
 * // w  w  w . jav a  2 s.c  o m
 *
 * @param doPreparedStatement 
 * @return time taken
 * @throws PropertyVetoException 
 * @throws InterruptedException 
 * @throws SQLException 
 */
private DataSource multiThreadedDBCP(boolean doPreparedStatement)
        throws PropertyVetoException, InterruptedException, SQLException {
    BasicDataSource cpds = new BasicDataSource();
    cpds.setDriverClassName("com.jolbox.bonecp.MockJDBCDriver");
    cpds.setUrl(url);
    cpds.setUsername(username);
    cpds.setPassword(password);
    cpds.setMaxIdle(-1);
    cpds.setMinIdle(-1);
    if (doPreparedStatement) {
        cpds.setPoolPreparedStatements(true);
        cpds.setMaxOpenPreparedStatements(max_statement);
    }
    cpds.setInitialSize(pool_size);
    cpds.setMaxActive(pool_size);
    return cpds;
}

From source file:org.apache.drill.exec.store.http.InsertTestData.java

public static DataSource createDataSource(String driver, String url, String userName, String password) {

    BasicDataSource source = new BasicDataSource();
    source.setDriverClassName(driver);//from  w w  w .j  a  v a2s. c  o  m
    source.setUrl(url);

    if (userName != null) {
        source.setUsername(userName);
    }

    if (password != null) {
        source.setPassword(password);
    }
    source.setInitialSize(1);
    source.setPoolPreparedStatements(true);
    try {
        // initial a connection
        source.getConnection();
    } catch (SQLException sqlE) {

        logger.error("db connection error: ", sqlE);
    }
    return source;

}

From source file:org.apache.drill.exec.store.http.util.DBUtil.java

public static DataSource createDataSource(String driver, String url, String userName, String password) {

    BasicDataSource source = new BasicDataSource();
    source.setDriverClassName(driver);//from  w w w . jav  a  2s  .c  om
    source.setUrl(url);

    if (userName != null) {
        source.setUsername(userName);
    }

    if (password != null) {
        source.setPassword(password);
    }

    source.setPoolPreparedStatements(true);
    source.setInitialSize(1);
    try {
        // initial a connection
        Connection conn = source.getConnection();
        conn.close();
    } catch (SQLException sqlE) {

        logger.error("db connection error: ", sqlE);
    }
    return source;

}

From source file:org.apache.jackrabbit.core.util.db.ConnectionFactory.java

/**
 * Creates and returns a pooling JDBC {@link DataSource} for accessing
 * the database identified by the given driver class and JDBC
 * connection URL. The driver class can be <code>null</code> if
 * a specific driver has not been configured.
 *
 * @param driverClass the JDBC driver class, or <code>null</code>
 * @param url the JDBC connection URL/* w ww.j a  v  a 2  s  .  co  m*/
 * @return pooling DataSource for accessing the specified database
 */
private BasicDataSource getDriverDataSource(Class<?> driverClass, String url, String user, String password) {
    BasicDataSource ds = new BasicDataSource();
    created.add(ds);

    if (driverClass != null) {
        Driver instance = null;
        try {
            // Workaround for Apache Derby:
            // The JDBC specification recommends the Class.forName
            // method without the .newInstance() method call,
            // but it is required after a Derby 'shutdown'
            instance = (Driver) driverClass.newInstance();
        } catch (Throwable e) {
            // Ignore exceptions as there's no requirement for
            // a JDBC driver class to have a public default constructor
        }
        if (instance != null) {
            if (instance.jdbcCompliant()) {
                // JCR-3445 At the moment the PostgreSQL isn't compliant because it doesn't implement this method...                   
                ds.setValidationQueryTimeout(3);
            }
        }
        ds.setDriverClassName(driverClass.getName());
    }

    ds.setUrl(url);
    ds.setUsername(user);
    ds.setPassword(password);
    ds.setDefaultAutoCommit(true);
    ds.setTestOnBorrow(false);
    ds.setTestWhileIdle(true);
    ds.setTimeBetweenEvictionRunsMillis(600000); // 10 Minutes
    ds.setMinEvictableIdleTimeMillis(60000); // 1 Minute
    ds.setMaxActive(-1); // unlimited
    ds.setMaxIdle(GenericObjectPool.DEFAULT_MAX_IDLE + 10);
    ds.setValidationQuery(guessValidationQuery(url));
    ds.setAccessToUnderlyingConnectionAllowed(true);
    ds.setPoolPreparedStatements(true);
    ds.setMaxOpenPreparedStatements(-1); // unlimited
    return ds;
}

From source file:org.apache.synapse.commons.datasource.factory.DataSourceFactory.java

/**
 * Factory method to create a DataSource based on provided information
 * which is encapsulated in the DataSourceInformation object.
 *
 * @param dataSourceInformation Information about DataSource
 * @return DataSource Instance if one can be created ,
 *         otherwise null or exception if provided details are not valid or enough to create
 *         a DataSource//from  w  ww. ja va  2  s .  com
 */
public static DataSource createDataSource(DataSourceInformation dataSourceInformation) {

    String dsType = dataSourceInformation.getType();
    String driver = dataSourceInformation.getDriver();

    if (driver == null || "".equals(driver)) {
        handleException("Database driver class name cannot be found.");
    }

    String url = dataSourceInformation.getUrl();

    if (url == null || "".equals(url)) {
        handleException("Database connection URL cannot be found.");
    }

    String user = dataSourceInformation.getSecretInformation().getUser();
    String password = dataSourceInformation.getSecretInformation().getResolvedSecret();

    int defaultTransactionIsolation = dataSourceInformation.getDefaultTransactionIsolation();

    if (DataSourceInformation.BASIC_DATA_SOURCE.equals(dsType)) {

        BasicDataSource basicDataSource = new BasicDataSource();
        basicDataSource.setDriverClassName(driver);
        basicDataSource.setUrl(url);

        if (user != null && !"".equals(user)) {
            basicDataSource.setUsername(user);
        }

        if (password != null && !"".equals(password)) {
            basicDataSource.setPassword(password);
        }

        basicDataSource.setMaxActive(dataSourceInformation.getMaxActive());
        basicDataSource.setMaxIdle(dataSourceInformation.getMaxIdle());
        basicDataSource.setMaxWait(dataSourceInformation.getMaxWait());
        basicDataSource.setMinIdle(dataSourceInformation.getMinIdle());
        basicDataSource.setDefaultAutoCommit(dataSourceInformation.isDefaultAutoCommit());
        basicDataSource.setDefaultReadOnly(dataSourceInformation.isDefaultReadOnly());
        basicDataSource.setTestOnBorrow(dataSourceInformation.isTestOnBorrow());
        basicDataSource.setTestOnReturn(dataSourceInformation.isTestOnReturn());
        basicDataSource.setTestWhileIdle(dataSourceInformation.isTestWhileIdle());
        basicDataSource.setMinEvictableIdleTimeMillis(dataSourceInformation.getMinEvictableIdleTimeMillis());
        basicDataSource
                .setTimeBetweenEvictionRunsMillis(dataSourceInformation.getTimeBetweenEvictionRunsMillis());
        basicDataSource.setNumTestsPerEvictionRun(dataSourceInformation.getNumTestsPerEvictionRun());
        basicDataSource.setMaxOpenPreparedStatements(dataSourceInformation.getMaxOpenPreparedStatements());
        basicDataSource.setAccessToUnderlyingConnectionAllowed(
                dataSourceInformation.isAccessToUnderlyingConnectionAllowed());
        basicDataSource.setInitialSize(dataSourceInformation.getInitialSize());
        basicDataSource.setPoolPreparedStatements(dataSourceInformation.isPoolPreparedStatements());

        if (defaultTransactionIsolation != -1) {
            basicDataSource.setDefaultTransactionIsolation(defaultTransactionIsolation);
        }

        String defaultCatalog = dataSourceInformation.getDefaultCatalog();
        if (defaultCatalog != null && !"".equals(defaultCatalog)) {
            basicDataSource.setDefaultCatalog(defaultCatalog);
        }

        String validationQuery = dataSourceInformation.getValidationQuery();

        if (validationQuery != null && !"".equals(validationQuery)) {
            basicDataSource.setValidationQuery(validationQuery);
        }

        return basicDataSource;

    } else if (DataSourceInformation.PER_USER_POOL_DATA_SOURCE.equals(dsType)) {

        DriverAdapterCPDS adapterCPDS = new DriverAdapterCPDS();

        try {
            adapterCPDS.setDriver(driver);
        } catch (ClassNotFoundException e) {
            handleException("Error setting driver : " + driver + " in DriverAdapterCPDS", e);
        }

        adapterCPDS.setUrl(url);

        if (user != null && !"".equals(user)) {
            adapterCPDS.setUser(user);
        }

        if (password != null && !"".equals(password)) {
            adapterCPDS.setPassword(password);
        }

        adapterCPDS.setPoolPreparedStatements(dataSourceInformation.isPoolPreparedStatements());
        adapterCPDS.setMaxIdle(dataSourceInformation.getMaxIdle());

        PerUserPoolDataSource perUserPoolDataSource = new PerUserPoolDataSource();
        perUserPoolDataSource.setConnectionPoolDataSource(adapterCPDS);

        perUserPoolDataSource.setDefaultMaxActive(dataSourceInformation.getMaxActive());
        perUserPoolDataSource.setDefaultMaxIdle(dataSourceInformation.getMaxIdle());
        perUserPoolDataSource.setDefaultMaxWait((int) dataSourceInformation.getMaxWait());
        perUserPoolDataSource.setDefaultAutoCommit(dataSourceInformation.isDefaultAutoCommit());
        perUserPoolDataSource.setDefaultReadOnly(dataSourceInformation.isDefaultReadOnly());
        perUserPoolDataSource.setTestOnBorrow(dataSourceInformation.isTestOnBorrow());
        perUserPoolDataSource.setTestOnReturn(dataSourceInformation.isTestOnReturn());
        perUserPoolDataSource.setTestWhileIdle(dataSourceInformation.isTestWhileIdle());
        perUserPoolDataSource
                .setMinEvictableIdleTimeMillis((int) dataSourceInformation.getMinEvictableIdleTimeMillis());
        perUserPoolDataSource.setTimeBetweenEvictionRunsMillis(
                (int) dataSourceInformation.getTimeBetweenEvictionRunsMillis());
        perUserPoolDataSource.setNumTestsPerEvictionRun(dataSourceInformation.getNumTestsPerEvictionRun());

        if (defaultTransactionIsolation != -1) {
            perUserPoolDataSource.setDefaultTransactionIsolation(defaultTransactionIsolation);
        }

        String validationQuery = dataSourceInformation.getValidationQuery();

        if (validationQuery != null && !"".equals(validationQuery)) {
            perUserPoolDataSource.setValidationQuery(validationQuery);
        }

        return perUserPoolDataSource;

    } else {
        handleException("Unsupported DataSource : " + dsType);
    }
    return null;
}

From source file:org.apache.synapse.config.xml.AbstractDBMediatorFactory.java

/**
 * Create a custom DataSource using the specified properties and Apache DBCP
 * @param pool the toplevel 'pool' element that holds DataSource information
 * @param mediator the mediator to store properties for serialization
 * @return a DataSource created using specified properties
 *//*from w  ww.jav  a 2 s .com*/
private DataSource createCustomDataSource(OMElement pool, AbstractDBMediator mediator) {

    BasicDataSource ds = new BasicDataSource();

    // load the minimum required properties
    ds.setDriverClassName(getValue(pool, DRIVER_Q));
    ds.setUsername(getValue(pool, USER_Q));
    ds.setPassword(getValue(pool, PASS_Q));
    ds.setUrl(getValue(pool, URL_Q));

    //save loaded properties for later
    mediator.addDataSourceProperty(DRIVER_Q, getValue(pool, DRIVER_Q));
    mediator.addDataSourceProperty(URL_Q, getValue(pool, URL_Q));
    mediator.addDataSourceProperty(USER_Q, getValue(pool, USER_Q));
    mediator.addDataSourceProperty(PASS_Q, getValue(pool, PASS_Q));

    Iterator props = pool.getChildrenWithName(PROP_Q);
    while (props.hasNext()) {

        OMElement prop = (OMElement) props.next();
        String name = prop.getAttribute(ATT_NAME).getAttributeValue();
        String value = prop.getAttribute(ATT_VALUE).getAttributeValue();
        // save property for later
        mediator.addDataSourceProperty(name, value);

        if ("autocommit".equals(name)) {
            if ("true".equals(value)) {
                ds.setDefaultAutoCommit(true);
            } else if ("false".equals(value)) {
                ds.setDefaultAutoCommit(false);
            }
        } else if ("isolation".equals(name)) {
            try {
                if ("Connection.TRANSACTION_NONE".equals(value)) {
                    ds.setDefaultTransactionIsolation(Connection.TRANSACTION_NONE);
                } else if ("Connection.TRANSACTION_READ_COMMITTED".equals(value)) {
                    ds.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
                } else if ("Connection.TRANSACTION_READ_UNCOMMITTED".equals(value)) {
                    ds.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
                } else if ("Connection.TRANSACTION_REPEATABLE_READ".equals(value)) {
                    ds.setDefaultTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
                } else if ("Connection.TRANSACTION_SERIALIZABLE".equals(value)) {
                    ds.setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
                }
            } catch (NumberFormatException ignore) {
            }
        } else if ("initialsize".equals(name)) {
            try {
                ds.setInitialSize(Integer.parseInt(value));
            } catch (NumberFormatException ignore) {
            }
        } else if ("maxactive".equals(name)) {
            try {
                ds.setMaxActive(Integer.parseInt(value));
            } catch (NumberFormatException ignore) {
            }
        } else if ("maxidle".equals(name)) {
            try {
                ds.setMaxIdle(Integer.parseInt(value));
            } catch (NumberFormatException ignore) {
            }
        } else if ("maxopenstatements".equals(name)) {
            try {
                ds.setMaxOpenPreparedStatements(Integer.parseInt(value));
            } catch (NumberFormatException ignore) {
            }
        } else if ("maxwait".equals(name)) {
            try {
                ds.setMaxWait(Long.parseLong(value));
            } catch (NumberFormatException ignore) {
            }
        } else if ("minidle".equals(name)) {
            try {
                ds.setMinIdle(Integer.parseInt(value));
            } catch (NumberFormatException ignore) {
            }
        } else if ("poolstatements".equals(name)) {
            if ("true".equals(value)) {
                ds.setPoolPreparedStatements(true);
            } else if ("false".equals(value)) {
                ds.setPoolPreparedStatements(false);
            }
        } else if ("testonborrow".equals(name)) {
            if ("true".equals(value)) {
                ds.setTestOnBorrow(true);
            } else if ("false".equals(value)) {
                ds.setTestOnBorrow(false);
            }
        } else if ("testonreturn".equals(name)) {
            if ("true".equals(value)) {
                ds.setTestOnReturn(true);
            } else if ("false".equals(value)) {
                ds.setTestOnReturn(false);
            }
        } else if ("testwhileidle".equals(name)) {
            if ("true".equals(value)) {
                ds.setTestWhileIdle(true);
            } else if ("false".equals(value)) {
                ds.setTestWhileIdle(false);
            }
        } else if ("validationquery".equals(name)) {
            ds.setValidationQuery(value);
        }
    }
    return ds;
}

From source file:org.compass.core.lucene.engine.store.jdbc.DbcpDataSourceProvider.java

protected DataSource doCreateDataSource(String url, CompassSettings settings) throws CompassException {
    BasicDataSource dataSource = new BasicDataSource();
    if (!externalAutoCommit) {
        dataSource.setDefaultAutoCommit(autoCommit);
    }/*from www  .j a  va  2  s  .c o m*/
    dataSource.setDriverClassName(driverClass);
    dataSource.setUrl(url);
    dataSource.setUsername(username);
    dataSource.setPassword(password);

    if (settings.getSetting(
            LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.DEFAULT_TRANSACTION_ISOLATION) != null) {
        dataSource.setDefaultTransactionIsolation(settings.getSettingAsInt(
                LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.DEFAULT_TRANSACTION_ISOLATION, 0));
    }

    if (settings.getSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.INITIAL_SIZE) != null) {
        dataSource.setInitialSize(
                settings.getSettingAsInt(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.INITIAL_SIZE, 0));
    }

    if (settings.getSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.MAX_ACTIVE) != null) {
        dataSource.setMaxActive(
                settings.getSettingAsInt(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.MAX_ACTIVE, 0));
    }

    if (settings.getSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.MAX_IDLE) != null) {
        dataSource.setMaxIdle(
                settings.getSettingAsInt(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.MAX_IDLE, 0));
    }

    if (settings.getSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.MIN_IDLE) != null) {
        dataSource.setMinIdle(
                settings.getSettingAsInt(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.MIN_IDLE, 0));
    }

    if (settings.getSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.MAX_WAIT) != null) {
        dataSource.setMaxWait(
                settings.getSettingAsLong(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.MAX_WAIT, 0));
    }

    if (settings.getSetting(
            LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.MAX_OPEN_PREPARED_STATEMENTS) != null) {
        dataSource.setMaxOpenPreparedStatements(settings.getSettingAsInt(
                LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.MAX_OPEN_PREPARED_STATEMENTS, 0));
    }

    if (settings
            .getSetting(LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.POOL_PREPARED_STATEMENTS) != null) {
        dataSource.setPoolPreparedStatements(settings.getSettingAsBoolean(
                LuceneEnvironment.JdbcStore.DataSourceProvider.Dbcp.POOL_PREPARED_STATEMENTS, false));
    }

    return dataSource;
}

From source file:org.danann.cernunnos.sql.BasicDataSourceTemplate.java

public final void perform(TaskRequest req, TaskResponse res) {
    //Get the JDBC properties
    final String driverClassName = (String) this.driverPhrase.evaluate(req, res);
    final String url = (String) this.urlPhrase.evaluate(req, res);
    final String username = (String) this.usernamePhrase.evaluate(req, res);
    final String password = (String) this.passwordPhrase.evaluate(req, res);

    final String dataSourceInfo = "driverClassName='" + driverClassName + "', url='" + url + "', username='"
            + username + "'";
    this.logger.debug("Creating DataSource for " + dataSourceInfo + ".");

    final BasicDataSource dataSource = new BasicDataSource();
    try {//from w w w . j  av a  2 s . co  m
        //Configure the pooling DataSource
        dataSource.setUrl(url);
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setPoolPreparedStatements(true);
        dataSource.setMaxActive(-1);
        dataSource.setMaxIdle(32);

        //Provide the DataSource on the response environment
        final String dataSourceAttrName = (String) this.attributeNamePhrase.evaluate(req, res);
        res.setAttribute(dataSourceAttrName, dataSource);
        this.logger.debug("Attached DataSource '" + dataSource + "' for " + dataSourceInfo
                + " to response under attribute '" + dataSourceAttrName + "'.");

        //Execute subtasks
        this.performWithDataSource(req, res, dataSource);
    } finally {
        try {
            //Cleanup after the subtasks
            dataSource.close();
            this.logger.debug("Closed DataSource '" + dataSource + "' for " + dataSourceInfo + ".");
        } catch (SQLException e) {
            throw new RuntimeException(
                    "Failed to close BasicDataSource '" + dataSource + "' for " + dataSourceInfo + ".", e);
        }
    }
}