List of usage examples for org.apache.commons.dbcp PoolableConnectionFactory PoolableConnectionFactory
public PoolableConnectionFactory(ConnectionFactory connFactory, ObjectPool pool, KeyedObjectPoolFactory stmtPoolFactory, String validationQuery, boolean defaultReadOnly, boolean defaultAutoCommit)
From source file:org.monansrill.ConfluenceDBBasedUserInfoGetter.java
public static PoolingDataSource setupDataSource() { try {/*from w ww .java 2 s. com*/ Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } ObjectPool connectionPool = new GenericObjectPool(null); String connectionURI; Properties secretProperties = getSecretProperties(); if (secretProperties.getProperty("dbpass") == null) { System.err.println( "sorry you need to specifiby dbpass and dbuser as properties with $HOME/.ictask.properties"); System.exit(-1); } connectionURI = "jdbc:mysql://localhost/confluence?zeroDateTimeBehavior=convertToNull"; ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectionURI, secretProperties.getProperty("dbuser"), secretProperties.getProperty("dbpass")); PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true); PoolingDataSource dataSource = new PoolingDataSource(connectionPool); return dataSource; }
From source file:org.netxilia.api.impl.storage.DataSourceConfigurationServiceImpl.java
public synchronized DataSource buildDataSource(DataSourceConfiguration cfg) { init();//w w w. j a va 2 s . c om Pair<GenericObjectPool, DataSource> poolInfo = pools.get(cfg.getId()); if (poolInfo != null) { return poolInfo.getSecond(); } GenericObjectPool connectionPool = applicationContext.getBean(GenericObjectPool.class); DataSource simpleDataSource = buildSimpleDataSource(cfg); ConnectionFactory connectionFactory = new DataSourceConnectionFactory(simpleDataSource); // ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(cfg.getUrl().replace( // NETXILIA_HOME_VAR, path), cfg.getUsername(), cfg.getPassword()); new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true); PoolingDataSource poolingDataSource = new PoolingDataSource(connectionPool); log.info("Creating a new datasource " + poolingDataSource + " for config:" + cfg.getId()); pools.put(cfg.getId(), new Pair<GenericObjectPool, DataSource>(connectionPool, poolingDataSource)); return poolingDataSource; }
From source file:org.okinawaopenlabs.orientdb.client.ConnectionManagerJdbc.java
/** * @param config//w w w. ja v a2 s .c om * @throws SQLException */ private void initializeDataSource(Config config) { String user = config.getString(CONFIG_KEY_DB_USER); String password = config.getString(CONFIG_KEY_DB_PASSWORD); Properties params = new Properties(); if (isNotEmpty(user) && isNotEmpty(password)) { params.put("user", user); params.put("password", password); } // ?? String driver = config.getString(CONFIG_KEY_DB_DRIVER); boolean loadSuccess = DbUtils.loadDriver(driver); if (!loadSuccess) { String message = "failed to load driver."; throw new RuntimeException(message); } // ??DataSource ?? @SuppressWarnings("rawtypes") GenericObjectPool pool = new GenericObjectPool(); // ??? int maxActive = config.getInt(CONFIG_KEY_DB_MAX_ACTIVE_CONN, 100); long maxWait = Long.parseLong(config.getString(CONFIG_KEY_DB_WAIT, "-1")); pool.setMaxActive(maxActive); pool.setMaxIdle(maxActive); pool.setMaxWait(maxWait); driverUrl = config.getString(CONFIG_KEY_DB_URL); ConnectionFactory connFactory = new DriverManagerConnectionFactory(driverUrl, params); new PoolableConnectionFactory(connFactory, pool, null, null, // validationQuery false, // defaultReadOnly false); // defaultAutoCommit dataSource = new PoolingDataSource(pool); }
From source file:org.onexus.collection.store.h2sql.internal.H2CollectionStore.java
protected DataSource newDataSource() { Driver.load();//from w w w . j a v a 2s . c o m // Initialize the DataSource with a connection pool ConnectionFactory connectionFactory = new H2ConnectionFactory(); ObjectPool connectionPool = new GenericObjectPool(null, GenericObjectPool.DEFAULT_MAX_ACTIVE, GenericObjectPool.WHEN_EXHAUSTED_GROW, GenericObjectPool.DEFAULT_MAX_WAIT); @SuppressWarnings("unused") PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true); return new PoolingDataSource(connectionPool); }
From source file:org.onexus.collection.store.mysql.internal.MysqlCollectionStore.java
protected DataSource newDataSource() { try {/* w ww . j a va 2s . c o m*/ Class.forName(Driver.class.getName()); } catch (Exception e) { LOGGER.error("Exception: " + e.getMessage()); } // Config parameters int maxActive = 8; try { maxActive = Integer.valueOf(getPoolMaxActive().trim()).intValue(); } catch (Exception e) { LOGGER.error("Malformed config parameter 'poolMaxActive'"); } byte whenExhausted = GenericObjectPool.WHEN_EXHAUSTED_BLOCK; try { if (getPoolWhenExhausted().trim().equalsIgnoreCase("FAIL")) { whenExhausted = GenericObjectPool.WHEN_EXHAUSTED_FAIL; } if (getPoolWhenExhausted().trim().equalsIgnoreCase("GROW")) { whenExhausted = GenericObjectPool.WHEN_EXHAUSTED_GROW; } } catch (Exception e) { LOGGER.error("Malformed config parameter 'poolWhenExhausted'"); } long maxWait = GenericObjectPool.DEFAULT_MAX_WAIT; try { maxWait = Long.valueOf(getPoolMaxWait().trim()).longValue(); } catch (Exception e) { LOGGER.error("Malformed config parameter 'poolMaxWait'"); } // Initialize the DataSource with a connection pool ConnectionFactory connectionFactory = new MysqlConnectionFactory(); GenericObjectPool connectionPool = new GenericObjectPool(null, maxActive, whenExhausted, maxWait); connectionPool.setTestWhileIdle(true); connectionPool.setTimeBetweenEvictionRunsMillis(3600); connectionPool.setMinEvictableIdleTimeMillis(3600); @SuppressWarnings("unused") PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true); poolableConnectionFactory.setValidationQuery("SELECT 1"); return new PoolingDataSource(connectionPool); }
From source file:org.onexus.website.api.widgets.tags.tagstore.TagStoreManager.java
public void init() { LOGGER.debug("Connecting to '{}' as '{}'.", database, username); Driver.load();/*from w w w . j av a2 s .c om*/ // Initialize the DataSource with a connection pool ConnectionFactory connectionFactory = new H2ConnectionFactory(); ObjectPool connectionPool = new GenericObjectPool(null, GenericObjectPool.DEFAULT_MAX_ACTIVE, GenericObjectPool.WHEN_EXHAUSTED_GROW, GenericObjectPool.DEFAULT_MAX_WAIT); @SuppressWarnings("unused") PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true); dataSource = new PoolingDataSource(connectionPool); this.tagStores = Collections.synchronizedMap(new HashMap<String, TagStore>()); }
From source file:org.openanzo.datasource.nodecentric.internal.NodeCentricDatasource.java
/** * Initialize a jdbc connection pool/*from w ww .j ava2 s . c o m*/ * * @param type * either rw or query pool * @param maxActive * maximum number of connections in pool * @param configuration * configuration properties used for creating database connections * @return connection pool * @throws AnzoException * {@link ExceptionConstants#RDB.DRIVER_NAME} if there was a problem loading class for database driver */ private GenericObjectPool initializeConnectionFactory(boolean write, int maxActive) throws AnzoException { // Will use in jndi // DataSource ds = (DataSource) ctx.lookup(RepositoryProperties.getDatabaseJndiName(properties)); try { Class.forName(configuration.getDriverClassName()); } catch (ClassNotFoundException e1) { throw new AnzoException(ExceptionConstants.RDB.DRIVER_NAME, e1, configuration.getDriverClassName()); } Properties props = new Properties(); props.put("user", configuration.getUser()); props.put("password", configuration.getPassword()); props.put("SetBigStringTryClob", "true"); ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(configuration.getJdbcUrl(), props); GenericObjectPool connectionPool = new GenericObjectPool(); connectionPool.setMaxActive(maxActive); connectionPool.setMaxIdle(Math.max(1, maxActive / 2)); connectionPool.setMinIdle(0); connectionPool.setMinEvictableIdleTimeMillis(1000 * 60 * 10); connectionPool.setTimeBetweenEvictionRunsMillis(1000 * 60 * 10); connectionPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK); connectionPool.setMaxWait(GenericKeyedObjectPool.DEFAULT_MAX_WAIT); connectionPool.setTestOnBorrow(true); GenericKeyedObjectPoolFactory statementPool = new GenericKeyedObjectPoolFactory(null, PS_CACHE_SIZE, GenericKeyedObjectPool.WHEN_EXHAUSTED_BLOCK, GenericKeyedObjectPool.DEFAULT_MAX_WAIT, PS_CACHE_SIZE, PS_CACHE_SIZE, GenericKeyedObjectPool.DEFAULT_TEST_ON_BORROW, GenericKeyedObjectPool.DEFAULT_TEST_ON_RETURN, GenericKeyedObjectPool.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS, GenericKeyedObjectPool.DEFAULT_NUM_TESTS_PER_EVICTION_RUN, GenericKeyedObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS, GenericKeyedObjectPool.DEFAULT_TEST_WHILE_IDLE); PoolableConnectionFactory pcf = new PoolableConnectionFactory(connectionFactory, connectionPool, statementPool, configuration.getValidationQuery(), false, true) { @Override public synchronized Object makeObject() throws Exception { Connection connection = (Connection) super.makeObject(); initializeConnection(connection); return connection; } }; if (configuration.getSupportsIsolation() && write) pcf.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED); else if (configuration.getSupportsIsolation() && !write) pcf.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED); return connectionPool; }
From source file:org.openanzo.jdbc.container.RDBQuadStoreFactory.java
private PoolableConnectionFactory initializeConnectionFactory(boolean write, int maxActive, CoreDBConfiguration configuration) { // Will use in jndi // DataSource ds = (DataSource) ctx.lookup(RepositoryProperties.getDatabaseJndiName(properties)); try {/*from w w w .j a v a 2 s. c o m*/ Class.forName(configuration.getDriverClassName()); } catch (ClassNotFoundException e1) { throw new AnzoRuntimeException(ExceptionConstants.RDB.DRIVER_NAME, e1, configuration.getDriverClassName()); } ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(configuration.getJdbcUrl(), configuration.getUser(), configuration.getPassword()); connectionPool = new GenericObjectPool(); connectionPool.setMaxActive(maxActive); connectionPool.setMinIdle(1); connectionPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK); connectionPool.setMaxWait(30000); connectionPool.setMaxActive(maxActive); pcf = new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true); if ((!write && configuration.getSupportsIsolation())) pcf.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED); return pcf; }
From source file:org.openbravo.database.ConnectionProviderImpl.java
public void addNewPool(String dbDriver, String dbServer, String dbLogin, String dbPassword, int minConns, int maxConns, double maxConnTime, String dbSessionConfig, String rdbms, String name) throws Exception { log4j.debug("Loading underlying JDBC driver."); try {//from w ww. ja v a 2 s. co m Class.forName(dbDriver); } catch (ClassNotFoundException e) { throw new Exception(e); } log4j.debug("Done."); GenericObjectPool connectionPool = new GenericObjectPool(null); connectionPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_GROW); connectionPool.setMaxActive(maxConns); connectionPool.setTestOnBorrow(false); connectionPool.setTestOnReturn(false); connectionPool.setTestWhileIdle(false); KeyedObjectPoolFactory keyedObject = new StackKeyedObjectPoolFactory(); ConnectionFactory connectionFactory = new OpenbravoDriverManagerConnectionFactory(dbServer, dbLogin, dbPassword, dbSessionConfig, rdbms); @SuppressWarnings("unused") // required by dbcp PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, keyedObject, null, false, true); Class.forName("org.apache.commons.dbcp.PoolingDriver"); PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:"); driver.registerPool(contextName + "_" + name, connectionPool); if (this.defaultPoolName == null || this.defaultPoolName.equals("")) { this.defaultPoolName = name; this.bbdd = dbServer; this.rdbms = rdbms; } }
From source file:org.opencms.db.CmsDbPool.java
/** * Creates a JDBC DriverManager based DBCP connection pool.<p> * //from w w w . j a va 2s. co m * @param config the configuration (opencms.properties) * @param key the key of the database pool in the configuration * @return String the URL to access the created DBCP pool * @throws Exception if the pool could not be initialized */ public static PoolingDriver createDriverManagerConnectionPool(CmsParameterConfiguration config, String key) throws Exception { // read the values of the pool configuration specified by the given key String jdbcDriver = config.get(KEY_DATABASE_POOL + '.' + key + '.' + KEY_JDBC_DRIVER); String jdbcUrl = config.get(KEY_DATABASE_POOL + '.' + key + '.' + KEY_JDBC_URL); String jdbcUrlParams = config.get(KEY_DATABASE_POOL + '.' + key + '.' + KEY_JDBC_URL_PARAMS); int maxActive = config.getInteger(KEY_DATABASE_POOL + '.' + key + '.' + KEY_MAX_ACTIVE, 10); int maxWait = config.getInteger(KEY_DATABASE_POOL + '.' + key + '.' + KEY_MAX_WAIT, 2000); int maxIdle = config.getInteger(KEY_DATABASE_POOL + '.' + key + '.' + KEY_MAX_IDLE, 5); int minEvictableIdleTime = config .getInteger(KEY_DATABASE_POOL + '.' + key + '.' + KEY_MIN_EVICTABLE_IDLE_TIME, 1800000); int minIdle = config.getInteger(KEY_DATABASE_POOL + '.' + key + '.' + KEY_MIN_IDLE, 0); int numTestsPerEvictionRun = config .getInteger(KEY_DATABASE_POOL + '.' + key + '.' + KEY_NUM_TESTS_PER_EVICTION_RUN, 3); int timeBetweenEvictionRuns = config .getInteger(KEY_DATABASE_POOL + '.' + key + '.' + KEY_TIME_BETWEEN_EVICTION_RUNS, 3600000); String testQuery = config.get(KEY_DATABASE_POOL + '.' + key + '.' + KEY_TEST_QUERY); String username = config.get(KEY_DATABASE_POOL + '.' + key + '.' + KEY_USERNAME); String password = config.get(KEY_DATABASE_POOL + '.' + key + '.' + KEY_PASSWORD); String poolUrl = config.get(KEY_DATABASE_POOL + '.' + key + '.' + KEY_POOL_URL); String whenExhaustedActionValue = config .get(KEY_DATABASE_POOL + '.' + key + '.' + KEY_WHEN_EXHAUSTED_ACTION).trim(); byte whenExhaustedAction = 0; boolean testOnBorrow = Boolean .valueOf(config.getString(KEY_DATABASE_POOL + '.' + key + '.' + KEY_TEST_ON_BORROW, "false").trim()) .booleanValue(); boolean testWhileIdle = Boolean .valueOf( config.getString(KEY_DATABASE_POOL + '.' + key + '.' + KEY_TEST_WHILE_IDLE, "false").trim()) .booleanValue(); if ("block".equalsIgnoreCase(whenExhaustedActionValue)) { whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_BLOCK; } else if ("fail".equalsIgnoreCase(whenExhaustedActionValue)) { whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_FAIL; } else if ("grow".equalsIgnoreCase(whenExhaustedActionValue)) { whenExhaustedAction = GenericObjectPool.WHEN_EXHAUSTED_GROW; } else { whenExhaustedAction = GenericObjectPool.DEFAULT_WHEN_EXHAUSTED_ACTION; } if ("".equals(testQuery)) { testQuery = null; } if (username == null) { username = ""; } if (password == null) { password = ""; } // read the values of the statement pool configuration specified by the given key boolean poolingStmts = Boolean.valueOf(config .getString(KEY_DATABASE_STATEMENTS + '.' + key + '.' + KEY_POOLING, CmsStringUtil.TRUE).trim()) .booleanValue(); int maxActiveStmts = config.getInteger(KEY_DATABASE_STATEMENTS + '.' + key + '.' + KEY_MAX_ACTIVE, 25); int maxWaitStmts = config.getInteger(KEY_DATABASE_STATEMENTS + '.' + key + '.' + KEY_MAX_WAIT, 250); int maxIdleStmts = config.getInteger(KEY_DATABASE_STATEMENTS + '.' + key + '.' + KEY_MAX_IDLE, 15); String whenStmtsExhaustedActionValue = config .get(KEY_DATABASE_STATEMENTS + '.' + key + '.' + KEY_WHEN_EXHAUSTED_ACTION); byte whenStmtsExhaustedAction = GenericKeyedObjectPool.WHEN_EXHAUSTED_GROW; if (whenStmtsExhaustedActionValue != null) { whenStmtsExhaustedActionValue = whenStmtsExhaustedActionValue.trim(); whenStmtsExhaustedAction = ("block".equalsIgnoreCase(whenStmtsExhaustedActionValue)) ? GenericKeyedObjectPool.WHEN_EXHAUSTED_BLOCK : ("fail".equalsIgnoreCase(whenStmtsExhaustedActionValue)) ? GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL : GenericKeyedObjectPool.WHEN_EXHAUSTED_GROW; } int connectionAttempts = config.getInteger(KEY_DATABASE_POOL + '.' + key + '.' + KEY_CONNECT_ATTEMTS, 10); int connetionsWait = config.getInteger(KEY_DATABASE_POOL + '.' + key + '.' + KEY_CONNECT_WAITS, 5000); // create an instance of the JDBC driver Class.forName(jdbcDriver).newInstance(); // initialize a keyed object pool to store connections GenericObjectPool connectionPool = new GenericObjectPool(null); /* Abandoned pool configuration: * * In case the systems encounters "pool exhaustion" (runs out of connections), * comment the above line with "new GenericObjectPool(null)" and uncomment the * 5 lines below. This will generate an "abandoned pool" configuration that logs * abandoned connections to the System.out. Unfortunatly this code is deprecated, * so to avoid code warnings it's also disabled here. * Tested with commons-pool v 1.2. */ // AbandonedConfig abandonedConfig = new AbandonedConfig(); // abandonedConfig.setLogAbandoned(true); // abandonedConfig.setRemoveAbandoned(true); // abandonedConfig.setRemoveAbandonedTimeout(5); // GenericObjectPool connectionPool = new AbandonedObjectPool(null, abandonedConfig); // initialize an object pool to store connections connectionPool.setMaxActive(maxActive); connectionPool.setMaxIdle(maxIdle); connectionPool.setMinIdle(minIdle); connectionPool.setMaxWait(maxWait); connectionPool.setWhenExhaustedAction(whenExhaustedAction); if (testQuery != null) { connectionPool.setTestOnBorrow(testOnBorrow); connectionPool.setTestWhileIdle(testWhileIdle); connectionPool.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRuns); connectionPool.setNumTestsPerEvictionRun(numTestsPerEvictionRun); connectionPool.setMinEvictableIdleTimeMillis(minEvictableIdleTime); } // initialize a connection factory to make the DriverManager taking connections from the pool if (jdbcUrlParams != null) { jdbcUrl += jdbcUrlParams; } ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(jdbcUrl, username, password); // Set up statement pool, if desired GenericKeyedObjectPoolFactory statementFactory = null; if (poolingStmts) { statementFactory = new GenericKeyedObjectPoolFactory(null, maxActiveStmts, whenStmtsExhaustedAction, maxWaitStmts, maxIdleStmts); } // initialize a factory to obtain pooled connections and prepared statements new PoolableConnectionFactory(connectionFactory, connectionPool, statementFactory, testQuery, false, true); // initialize a new pooling driver using the pool PoolingDriver driver = new PoolingDriver(); driver.registerPool(poolUrl, connectionPool); Connection con = null; boolean connect = false; int connectionTests = 0; // try to connect once to the database to ensure it can be connected to at all // if the conection cannot be established, multiple attempts will be done to connect // just in cast the database was not fast enough to start before OpenCms was started do { try { // try to connect con = connectionFactory.createConnection(); connect = true; } catch (Exception e) { // connection failed, increase attempts, sleept for some seconds and log a message connectionTests++; if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_WAIT_FOR_DB_4, new Object[] { poolUrl, jdbcUrl, new Integer(connectionTests), new Integer(connetionsWait) })); } Thread.sleep(connetionsWait); } finally { if (con != null) { con.close(); } } } while (!connect && (connectionTests < connectionAttempts)); if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_JDBC_POOL_2, poolUrl, jdbcUrl)); } return driver; }