List of usage examples for org.apache.commons.dbcp BasicDataSource setMaxOpenPreparedStatements
public synchronized void setMaxOpenPreparedStatements(int maxOpenStatements)
Sets the value of the #maxOpenPreparedStatements property.
Note: this method currently has no effect once the pool has been initialized.
From source file:com.headstrong.fusion.services.dbpool.impl.DbPool.java
/** * package level constructor to create new dbpool instance. * //from w ww . ja va2 s. c o m * @param props * properties that needs to be set for creating the pool. * @throws FusionException * Error initializing dbpool */ /* package */ DbPool(Map<String, String> props, String dbcp) throws FusionException { BasicDataSource basicDataSource = new BasicDataSource(); if (dbProps == null) { dbProps = new HashMap<String, String>(props); } if (checkMandatoryProperties(props)) { basicDataSource.setDriverClassName(props.get(FusionConstants.DATABASE_CLASSNAME)); basicDataSource.setUsername(props.get(FusionConstants.DATABASE_USERNAME)); basicDataSource.setPassword(props.get(FusionConstants.DATABASE_PASSWORD)); basicDataSource.setUrl(props.get(FusionConstants.DATABASE_URL)); basicDataSource.setMinEvictableIdleTimeMillis(this.MINEVICTABLEIDLETIMEMILLIS); basicDataSource.setTimeBetweenEvictionRunsMillis(this.TIMEBETWEENEVICTIONRUNSMILLIS); String JDBCINITIALSIZE = props.get(FusionConstants.JDBCINITIALSIZE) != null ? props.get(FusionConstants.JDBCINITIALSIZE) : dbProps.get(FusionConstants.JDBCINITIALSIZE); basicDataSource.setInitialSize(Integer.parseInt(JDBCINITIALSIZE)); String JDBCMAXACTIVE = props.get(FusionConstants.JDBCMAXACTIVE) != null ? props.get(FusionConstants.JDBCMAXACTIVE) : dbProps.get(FusionConstants.JDBCMAXACTIVE); basicDataSource.setMaxActive(Integer.parseInt(JDBCMAXACTIVE)); String JDBCMAXOPENACTIVEPREP = props.get(FusionConstants.JDBCMAXOPENACTIVEPREP) != null ? props.get(FusionConstants.JDBCMAXOPENACTIVEPREP) : dbProps.get(FusionConstants.JDBCMAXOPENACTIVEPREP); basicDataSource.setMaxOpenPreparedStatements(Integer.parseInt(JDBCMAXOPENACTIVEPREP)); String MINEVICTABLEIDLETIMEMILLIS = props.get(FusionConstants.MINEVICTABLEIDLETIMEMILLIS) != null ? props.get(FusionConstants.MINEVICTABLEIDLETIMEMILLIS) : dbProps.get(FusionConstants.MINEVICTABLEIDLETIMEMILLIS); basicDataSource.setMinEvictableIdleTimeMillis(Integer.parseInt(MINEVICTABLEIDLETIMEMILLIS)); String TIMEBETWEENEVICTIONRUNSMILLIS = props.get(FusionConstants.TIMEBETWEENEVICTIONRUNSMILLIS) != null ? props.get(FusionConstants.TIMEBETWEENEVICTIONRUNSMILLIS) : dbProps.get(FusionConstants.TIMEBETWEENEVICTIONRUNSMILLIS); basicDataSource.setTimeBetweenEvictionRunsMillis(Long.parseLong(TIMEBETWEENEVICTIONRUNSMILLIS)); /* * if (props.get(FusionConstants.JDBCINITIALSIZE) == null) { * basicDataSource.setInitialSize(Integer.parseInt(dbProps * .get(FusionConstants.JDBCINITIALSIZE))); } else { * basicDataSource.setInitialSize(Integer.parseInt(props * .get(FusionConstants.JDBCINITIALSIZE))); } if * (props.get(FusionConstants.JDBCMAXACTIVE) == null) { * basicDataSource.setInitialSize(Integer.parseInt(dbProps * .get(FusionConstants.JDBCMAXACTIVE))); } else { * basicDataSource.setInitialSize(Integer.parseInt(props * .get(FusionConstants.JDBCMAXACTIVE))); } if * (props.get(FusionConstants.JDBCMAXOPENACTIVEPREP) == null) { * basicDataSource.setInitialSize(Integer.parseInt(dbProps * .get(FusionConstants.JDBCMAXOPENACTIVEPREP))); } else { * basicDataSource.setInitialSize(Integer.parseInt(props * .get(FusionConstants.JDBCMAXOPENACTIVEPREP))); } * * if (props.get(FusionConstants.MINEVICTABLEIDLETIMEMILLIS) == * null) { basicDataSource.setInitialSize(Integer.parseInt(dbProps * .get(FusionConstants.MINEVICTABLEIDLETIMEMILLIS))); } else { * basicDataSource.setInitialSize(Integer.parseInt(props * .get(FusionConstants.MINEVICTABLEIDLETIMEMILLIS))); } if * (props.get(FusionConstants.TIMEBETWEENEVICTIONRUNSMILLIS) == * null) { basicDataSource.setInitialSize(Integer.parseInt(dbProps * .get(FusionConstants.TIMEBETWEENEVICTIONRUNSMILLIS))); } else { * basicDataSource.setInitialSize(Integer.parseInt(props * .get(FusionConstants.TIMEBETWEENEVICTIONRUNSMILLIS))); } */ dataSource = basicDataSource; } else { throw new FusionException("Error initializing dbpool"); } }
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/*from ww w . java 2 s . c o 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 w w .ja va 2s . c om*/ */ 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 w w. j a v a2 s . c om 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.apache.wookie.server.Start.java
private static void configureServer() throws Exception { // create embedded jetty instance logger.info("Configuring Jetty server"); server = new Server(port); // configure embedded jetty to handle wookie web application WebAppContext context = new WebAppContext(); context.setServer(server);//from w w w. j a v a2s .c o m context.setContextPath("/wookie"); context.setWar("build/webapp/wookie"); // enable and configure JNDI container resources context.setConfigurationClasses(new String[] { "org.mortbay.jetty.webapp.WebInfConfiguration", "org.mortbay.jetty.plus.webapp.EnvConfiguration", "org.mortbay.jetty.plus.webapp.Configuration", "org.mortbay.jetty.webapp.JettyWebXmlConfiguration", "org.mortbay.jetty.webapp.TagLibConfiguration" }); if (persistenceManagerType.equals(PERSISTENCE_MANAGER_TYPE_JPA)) { logger.info("Configuring JPA persistence manager"); // setup derby database directory and logging properties if (dbType.equals("derby") && dbUri.startsWith("jdbc:derby:")) { int dbUriArgsIndex = dbUri.indexOf(";", 11); if (dbUriArgsIndex == -1) { dbUriArgsIndex = dbUri.length(); } String databasePath = dbUri.substring(11, dbUriArgsIndex); int databaseDirIndex = databasePath.lastIndexOf(File.separatorChar); if ((databaseDirIndex == -1) && (File.separatorChar != '/')) { databaseDirIndex = databasePath.lastIndexOf('/'); } if (databaseDirIndex != -1) { String databaseDir = databasePath.substring(0, databaseDirIndex); File databaseDirFile = new File(databaseDir); if (!databaseDirFile.exists()) { databaseDirFile.mkdirs(); } String derbyLog = databaseDirFile.getAbsolutePath() + File.separator + "derby.log"; System.setProperty("derby.stream.error.file", derbyLog); } } // Setup a database connection resource using DBCP BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(dbDriver); dataSource.setUrl(dbUri); dataSource.setUsername(dbUser); dataSource.setPassword(dbPassword); dataSource.setMaxActive(80); dataSource.setMaxIdle(80); dataSource.setInitialSize(5); dataSource.setMaxOpenPreparedStatements(0); // Set up connection pool GenericObjectPool pool = new GenericObjectPool(); // setup factory and pooling DataSource DataSourceConnectionFactory factory = new DataSourceConnectionFactory(dataSource); @SuppressWarnings("unused") PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(factory, pool, null, null, false, true); DataSource poolingDataSource = new PoolingDataSource(pool); new Resource(JPAPersistenceManager.WIDGET_DATABASE_JNDI_DATASOURCE_NAME, poolingDataSource); } else if (persistenceManagerType.equals(PERSISTENCE_MANAGER_TYPE_JCR)) { logger.info("Configuring JCR persistence manager"); // setup repository directory and derby logging properties File repositoryDirFile = new File("widgetRepository"); if (!repositoryDirFile.exists()) { repositoryDirFile.mkdirs(); } String derbyLog = repositoryDirFile.getAbsolutePath() + File.separator + "derby.log"; System.setProperty("derby.stream.error.file", derbyLog); // setup Jackrabbit JCR repository JNDI resource String repositoryConfig = repositoryDirFile.getAbsolutePath() + File.separator + "repository.xml"; Repository repository = new TransientRepository(repositoryConfig, repositoryDirFile.getAbsolutePath()); new Resource(JCRPersistenceManager.WIDGET_REPOSITORY_JNDI_REPOSITORY_NAME, repository); } // configure embedded jetty web application handler server.addHandler(context); // configure embedded jetty authentication realm HashUserRealm authedRealm = new HashUserRealm("Authentication Required", "etc/jetty-realm.properties"); server.setUserRealms(new UserRealm[] { authedRealm }); logger.info("Configured Jetty server"); }
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 w w w . j a v a 2s . c om*/ 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.geosde.core.jdbc.data.datasource.DataSourceUtil.java
/** * Builds up a default DBCP DataSource that easy to use connection factories * can use to setup a connection pool.// ww w . ja va 2s. c o m * * @param url * the jdbc url * @param driverName * the jdbc driver full qualified class name * @param username * @param password * @param maxActive maximum number of concurrent connections in the pool * @param minIdle minimum number of concurrent connections in the pool * @param validationQuery * the validation query to be used for connection liveliness on * borrow, or null, if no check is to be performed * @param cachePreparedStatements * wheter to cache prepared statements or not * @return * @throws DataSourceException */ public static ManageableDataSource buildDefaultDataSource(String url, String driverName, String username, String password, int maxActive, int minIdle, String validationQuery, boolean cachePreparedStatements, int removeAbandonedTimeout) throws DataSourceException { // basics BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(driverName); dataSource.setUrl(url); dataSource.setUsername(username); dataSource.setPassword(password); dataSource.setAccessToUnderlyingConnectionAllowed(true); // pool size dataSource.setMaxActive(maxActive); dataSource.setMinIdle(minIdle); // pool eviction settings dataSource.setMinEvictableIdleTimeMillis(1000 * 20); dataSource.setTimeBetweenEvictionRunsMillis(1000 * 10); // connection validation if (validationQuery != null) { dataSource.setTestOnBorrow(true); dataSource.setValidationQuery(validationQuery); } // prepared statement cache if (cachePreparedStatements) { dataSource.setPoolPreparedStatements(true); dataSource.setMaxOpenPreparedStatements(10); } // remove abandoned connections (I know it's deprecated, but we do want // something shaving off lost connections. Let's give them 5 minutes of // continuous usage if (removeAbandonedTimeout > 0) { dataSource.setRemoveAbandoned(true); dataSource.setRemoveAbandonedTimeout(removeAbandonedTimeout); dataSource.setLogAbandoned(true); } Connection conn = null; try { conn = dataSource.getConnection(); } catch (Exception e) { throw new DataSourceException("Connection test failed ", e); } finally { if (conn != null) try { conn.close(); } catch (SQLException e) { } } return new DBCPDataSource(dataSource); }
From source file:org.geosde.core.jdbc.JDBCDataStoreFactory.java
/** * Creates the datasource for the data store. * <p>/*from ww w .j ava 2 s . c o m*/ * This method creates a {@link BasicDataSource} instance and populates it * as follows: * <ul> * <li>poolPreparedStatements -> false * <li>driverClassName -> {@link #getDriverClassName()} * <li>url -> 'jdbc:<{@link #getDatabaseID()}>://<{@link #HOST}>/<{@link #DATABASE}>' * <li>username -> <{@link #USER}> * <li>password -> <{@link #PASSWD}> * </ul> * If different behaviour is needed, this method should be extended or * overridden. * </p> */ protected DataSource createDataSource(Map params, SQLDialect dialect) throws IOException { BasicDataSource dataSource = createDataSource(params); // some default data source behaviour if (dialect instanceof PreparedStatementSQLDialect) { dataSource.setPoolPreparedStatements(true); // check if the dialect exposes the max prepared statements param Map<String, Serializable> testMap = new HashMap<String, Serializable>(); setupParameters(testMap); if (testMap.containsKey(MAX_OPEN_PREPARED_STATEMENTS.key)) { Integer maxPreparedStatements = (Integer) MAX_OPEN_PREPARED_STATEMENTS.lookUp(params); // limit prepared statements if (maxPreparedStatements != null && maxPreparedStatements > 0) dataSource.setMaxOpenPreparedStatements(maxPreparedStatements); // disable statement caching fully if necessary if (maxPreparedStatements != null && maxPreparedStatements < 0) dataSource.setPoolPreparedStatements(false); } } return new DBCPDataSource(dataSource); }
From source file:org.geowebcache.diskquota.jdbc.JDBCQuotaStoreFactory.java
private DataSource getDataSource(JDBCConfiguration config) throws ConfigurationException { try {// w w w .j a va 2s . c om DataSource ds = null; if (config.getJNDISource() != null) { InitialContext context = new InitialContext(); ds = (DataSource) context.lookup(config.getJNDISource()); } else if (config.getConnectionPool() != null) { ConnectionPoolConfiguration cp = config.getConnectionPool(); BasicDataSource bds = new BasicDataSource(); bds.setDriverClassName(cp.getDriver()); bds.setUrl(cp.getUrl()); bds.setUsername(cp.getUsername()); bds.setPassword(cp.getPassword()); bds.setPoolPreparedStatements(true); bds.setMaxOpenPreparedStatements(cp.getMaxOpenPreparedStatements()); bds.setMinIdle(cp.getMinConnections()); bds.setMaxActive(cp.getMaxConnections()); bds.setMaxWait(cp.getConnectionTimeout() * 1000); bds.setValidationQuery(cp.getValidationQuery()); ds = bds; } // verify the datasource works Connection c = null; try { c = ds.getConnection(); } catch (SQLException e) { throw new ConfigurationException("Failed to get a database connection: " + e.getMessage(), e); } finally { if (c != null) { try { c.close(); } catch (SQLException e) { // nothing we can do about it, but at least let the admin know log.debug("An error occurred while closing the test JDBC connection: " + e.getMessage(), e); } } } return ds; } catch (NamingException e) { throw new ConfigurationException("Failed to locate the data source in JNDI", e); } }
From source file:org.ngrinder.infra.config.Database.java
/** * Setup the database common features.//from ww w .j av a2 s . co m * * @param dataSource datasource */ protected void setupCommon(BasicDataSource dataSource) { dataSource.setDriverClassName(getJdbcDriverName()); dataSource.setInitialSize(DB_INITIAL_SIZE); dataSource.setMaxActive(DB_MAX_ACTIVE); dataSource.setMinIdle(DB_MIN_IDLE); dataSource.setMaxWait(DB_MAX_WAIT); dataSource.setPoolPreparedStatements(true); dataSource.setMaxOpenPreparedStatements(DB_MAX_OPEN_PREPARED_STATEMENTS); dataSource.setTestWhileIdle(true); dataSource.setTestOnBorrow(true); dataSource.setTestOnReturn(true); dataSource.setValidationQuery("SELECT 1"); }