List of usage examples for org.apache.commons.dbcp PoolingDataSource setAccessToUnderlyingConnectionAllowed
public void setAccessToUnderlyingConnectionAllowed(boolean allow)
From source file:com.zimbra.cs.db.DbPool.java
/** Initializes the connection pool. */ private static synchronized PoolingDataSource getPool() { if (isShutdown) throw new RuntimeException("DbPool permanently shutdown"); if (sPoolingDataSource != null) return sPoolingDataSource; PoolConfig pconfig = Db.getInstance().getPoolConfig(); sConnectionPool = new GenericObjectPool(null, pconfig.mPoolSize, pconfig.whenExhaustedAction, -1, pconfig.mPoolSize);//from w w w. j a va 2s . c om ConnectionFactory cfac = ZimbraConnectionFactory.getConnectionFactory(pconfig); boolean defAutoCommit = false, defReadOnly = false; new PoolableConnectionFactory(cfac, sConnectionPool, null, null, defReadOnly, defAutoCommit); try { Class.forName(pconfig.mDriverClassName).newInstance(); //derby requires the .newInstance() call Class.forName("org.apache.commons.dbcp.PoolingDriver"); } catch (Exception e) { ZimbraLog.system.fatal("can't instantiate DB driver/pool class", e); System.exit(1); } try { PoolingDataSource pds = new PoolingDataSource(sConnectionPool); pds.setAccessToUnderlyingConnectionAllowed(true); Db.getInstance().startup(pds, pconfig.mPoolSize); sPoolingDataSource = pds; } catch (SQLException e) { ZimbraLog.system.fatal("can't initialize connection pool", e); System.exit(1); } if (pconfig.mSupportsStatsCallback) ZimbraPerf.addStatsCallback(new DbStats()); return sPoolingDataSource; }
From source file:com.qualogy.qafe.business.resource.rdb.DriverManagerDataSource.java
public void init(ApplicationContext context) { DriverManagerResource driverManagerResource = (DriverManagerResource) getBindResource(); String userName = driverManagerResource.getUsername(); String password = driverManagerResource.getPassword(); String url = driverManagerResource.getUrl(); String driverClassName = driverManagerResource.getDriverClassName(); DataSource springDS = new org.springframework.jdbc.datasource.DriverManagerDataSource(url, userName, password);/*from w ww . j a va2 s . c o m*/ ((org.springframework.jdbc.datasource.DriverManagerDataSource) springDS) .setDriverClassName(driverClassName); GenericObjectPool pool = new GenericObjectPool(); pool.setMinEvictableIdleTimeMillis(300000); pool.setTimeBetweenEvictionRunsMillis(60000); PoolableConnectionFactory connectionFactory = new PoolableConnectionFactory( new DataSourceConnectionFactory(springDS), pool, null, null, false, true); PoolingDataSource poolingDataSource = new PoolingDataSource(pool); poolingDataSource.setAccessToUnderlyingConnectionAllowed(true); setDataSource(poolingDataSource); postInit(context); }
From source file:com.jaspersoft.jasperserver.api.engine.jasperreports.service.impl.TibcoDriverManagerImpl.java
public Connection unlockConnection(DataSource dataSource) throws SQLException { Connection originalConnection = getOriginalConnection(dataSource); if (unlockDSConnection(originalConnection)) return originalConnection; GenericObjectPool connectionPool = new GenericObjectPool(null); DataSourceConnectionFactory connectionFactory = new DataSourceConnectionFactory(dataSource); PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true); PoolingDataSource ds = new PoolingDataSource(connectionPool); if (ds != null) { Connection connection = getOriginalConnection(ds); ds.setAccessToUnderlyingConnectionAllowed(true); if (unlockDSConnection(connection)) return connection; }// w ww. j a va 2 s. c o m return originalConnection; }
From source file:net.sf.farrago.namespace.jdbc.MedJdbcDataServer.java
private void initializeDataSource() throws SQLException { assert (!disableConnectionPool); if (jndiName != null) { try {// w w w.j a v a 2 s. c o m // TODO: Allow specification of initial context factory and // provider URL via addition options. These should be stored // in jndiEnv before the initJndi call and the names (keys) of // the those properties would be used in the JndiUtil // constructor. Can also allow artibrary env properties. JndiUtil jndiUtil = new JndiUtil("", Context.INITIAL_CONTEXT_FACTORY, Context.PROVIDER_URL); Properties jndiEnv = new Properties(); jndiUtil.initJndi(jndiEnv); InitialContext initCtx = jndiUtil.newInitialContext(jndiEnv); dataSource = jndiUtil.lookup(initCtx, jndiName, DataSource.class); if (dataSource == null) { throw FarragoResource.instance().MedJdbc_InvalidDataSource.ex(jndiName); } return; } catch (NamingException e) { throw FarragoResource.instance().MedJdbc_InvalidDataSource.ex(jndiName, e); } } String userName = getUserName(); String password = getPassword(); ConnectionFactory connectionFactory; if (connectProps != null) { if (userName != null) { connectProps.setProperty("user", userName); } if (password != null) { connectProps.setProperty("password", password); } connectionFactory = new DriverManagerConnectionFactory(url, connectProps); } else if (userName == null) { connectionFactory = new DriverManagerConnectionFactory(url, new Properties()); } else { if (password == null) { password = ""; } connectionFactory = new DriverManagerConnectionFactory(url, userName, password); } if (validateWhileIdle && (evictionTimerPeriodMillis <= 0L)) { logger.warning("Request to validate on idle ignored: property " + PROP_EVICTION_TIMER_PERIOD_MILLIS + " must be > 0"); if ((validationQuery != null) && !validateOnBorrow && !validateOnReturn) { validateOnBorrow = true; logger.warning("Enabling validation on request"); } } connectionPool = new GenericObjectPool(); connectionPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_GROW); connectionPool.setMaxActive(-1); connectionPool.setTestOnBorrow(validateOnBorrow); connectionPool.setTestOnReturn(validateOnReturn); connectionPool.setTestWhileIdle(validateWhileIdle); connectionPool.setMaxIdle(maxIdleConnections); connectionPool.setTimeBetweenEvictionRunsMillis(evictionTimerPeriodMillis); connectionPool.setMinEvictableIdleTimeMillis(minEvictionIdleMillis); CustomPoolableConnectionFactory poolableConnectionFactory = new CustomPoolableConnectionFactory( connectionFactory, connectionPool, validationQuery, autocommit, null); connectionPool.setFactory(poolableConnectionFactory); PoolingDataSource pds = new PoolingDataSource(connectionPool); pds.setAccessToUnderlyingConnectionAllowed(true); dataSource = pds; }
From source file:org.apache.ojb.broker.accesslayer.ConnectionFactoryDBCPImpl.java
/** * Wraps the specified object pool for connections as a DataSource. * * @param jcd the OJB connection descriptor for the pool to be wrapped * @param connectionPool the connection pool to be wrapped * @return a DataSource attached to the connection pool. * Connections will be wrapped using DBCP PoolGuard, that will not allow * unwrapping unless the "accessToUnderlyingConnectionAllowed=true" configuration * is specified./*from w ww. java 2 s. c o m*/ */ protected DataSource wrapAsDataSource(JdbcConnectionDescriptor jcd, ObjectPool connectionPool) { final boolean allowConnectionUnwrap; if (jcd == null) { allowConnectionUnwrap = false; } else { final Properties properties = jcd.getConnectionPoolDescriptor().getDbcpProperties(); final String allowConnectionUnwrapParam; allowConnectionUnwrapParam = properties.getProperty(PARAM_NAME_UNWRAP_ALLOWED); allowConnectionUnwrap = allowConnectionUnwrapParam != null && Boolean.valueOf(allowConnectionUnwrapParam).booleanValue(); } final PoolingDataSource dataSource; dataSource = new PoolingDataSource(connectionPool); dataSource.setAccessToUnderlyingConnectionAllowed(allowConnectionUnwrap); if (jcd != null) { final AbandonedConfig ac = jcd.getConnectionPoolDescriptor().getAbandonedConfig(); if (ac.getRemoveAbandoned() && ac.getLogAbandoned()) { final LoggerWrapperPrintWriter loggerPiggyBack; loggerPiggyBack = new LoggerWrapperPrintWriter(log, Logger.ERROR); dataSource.setLogWriter(loggerPiggyBack); } } return dataSource; }
From source file:org.pentaho.platform.engine.services.connection.datasource.dbcp.PooledDatasourceHelper.java
public static PoolingDataSource setupPooledDataSource(IDatabaseConnection databaseConnection) throws DBDatasourceServiceException { PoolingDataSource poolingDataSource = null; String driverClass = null;/* w ww . j a va 2s . c om*/ String url = null; try { if (databaseConnection.getAccessType().equals(DatabaseAccessType.JNDI)) { throw new DBDatasourceServiceException(Messages.getInstance().getErrorString( "PooledDatasourceHelper.ERROR_0008_UNABLE_TO_POOL_DATASOURCE_IT_IS_JNDI", databaseConnection.getName())); } ICacheManager cacheManager = PentahoSystem.getCacheManager(null); IDatabaseDialectService databaseDialectService = PentahoSystem.get(IDatabaseDialectService.class); if (databaseDialectService == null) { throw new DBDatasourceServiceException(Messages.getInstance().getErrorString( "PooledDatasourceHelper.ERROR_0005_UNABLE_TO_POOL_DATASOURCE_NO_DIALECT_SERVICE", databaseConnection.getName())); } IDatabaseDialect dialect = databaseDialectService.getDialect(databaseConnection); if (dialect == null || dialect.getDatabaseType() == null) { throw new DBDatasourceServiceException(Messages.getInstance().getErrorString( "PooledDatasourceHelper.ERROR_0004_UNABLE_TO_POOL_DATASOURCE_NO_DIALECT", databaseConnection.getName())); } if (databaseConnection.getDatabaseType().getShortName().equals("GENERIC")) { //$NON-NLS-1$ driverClass = databaseConnection.getAttributes() .get(GenericDatabaseDialect.ATTRIBUTE_CUSTOM_DRIVER_CLASS); if (StringUtils.isEmpty(driverClass)) { throw new DBDatasourceServiceException(Messages.getInstance().getErrorString( "PooledDatasourceHelper.ERROR_0006_UNABLE_TO_POOL_DATASOURCE_NO_CLASSNAME", databaseConnection.getName())); } } else { driverClass = dialect.getNativeDriver(); if (StringUtils.isEmpty(driverClass)) { throw new DBDatasourceServiceException(Messages.getInstance().getErrorString( "PooledDatasourceHelper.ERROR_0007_UNABLE_TO_POOL_DATASOURCE_NO_DRIVER", databaseConnection.getName())); } } try { url = dialect.getURLWithExtraOptions(databaseConnection); } catch (DatabaseDialectException e) { url = null; } // Read default connection pooling parameter String maxdleConn = PentahoSystem.getSystemSetting("dbcp-defaults/max-idle-conn", null); //$NON-NLS-1$ String minIdleConn = PentahoSystem.getSystemSetting("dbcp-defaults/min-idle-conn", null); //$NON-NLS-1$ String maxActConn = PentahoSystem.getSystemSetting("dbcp-defaults/max-act-conn", null); //$NON-NLS-1$ String validQuery = null; String whenExhaustedAction = PentahoSystem.getSystemSetting("dbcp-defaults/when-exhausted-action", //$NON-NLS-1$ null); String wait = PentahoSystem.getSystemSetting("dbcp-defaults/wait", null); //$NON-NLS-1$ String testWhileIdleValue = PentahoSystem.getSystemSetting("dbcp-defaults/test-while-idle", null); //$NON-NLS-1$ String testOnBorrowValue = PentahoSystem.getSystemSetting("dbcp-defaults/test-on-borrow", null); //$NON-NLS-1$ String testOnReturnValue = PentahoSystem.getSystemSetting("dbcp-defaults/test-on-return", null); //$NON-NLS-1$ // property initialization boolean testWhileIdle = !StringUtil.isEmpty(testWhileIdleValue) ? Boolean.parseBoolean(testWhileIdleValue) : false; boolean testOnBorrow = !StringUtil.isEmpty(testOnBorrowValue) ? Boolean.parseBoolean(testOnBorrowValue) : false; boolean testOnReturn = !StringUtil.isEmpty(testOnReturnValue) ? Boolean.parseBoolean(testOnReturnValue) : false; int maxActiveConnection = !StringUtil.isEmpty(maxActConn) ? Integer.parseInt(maxActConn) : -1; long waitTime = !StringUtil.isEmpty(wait) ? Integer.parseInt(wait) : -1; byte whenExhaustedActionType = !StringUtil.isEmpty(whenExhaustedAction) ? Byte.parseByte(whenExhaustedAction) : GenericObjectPool.WHEN_EXHAUSTED_BLOCK; int minIdleConnection = !StringUtil.isEmpty(minIdleConn) ? Integer.parseInt(minIdleConn) : -1; int maxIdleConnection = !StringUtil.isEmpty(maxdleConn) ? Integer.parseInt(maxdleConn) : -1; // setting properties according to user specifications Map<String, String> attributes = databaseConnection.getConnectionPoolingProperties(); if (attributes.containsKey(IDBDatasourceService.MAX_ACTIVE_KEY) && NumberUtils.isNumber(attributes.get(IDBDatasourceService.MAX_ACTIVE_KEY))) { maxActiveConnection = Integer.parseInt(attributes.get(IDBDatasourceService.MAX_ACTIVE_KEY)); } if (attributes.containsKey(IDBDatasourceService.MAX_WAIT_KEY) && NumberUtils.isNumber(attributes.get(IDBDatasourceService.MAX_WAIT_KEY))) { waitTime = Integer.parseInt(attributes.get(IDBDatasourceService.MAX_WAIT_KEY)); } if (attributes.containsKey(IDBDatasourceService.MIN_IDLE_KEY) && NumberUtils.isNumber(attributes.get(IDBDatasourceService.MIN_IDLE_KEY))) { minIdleConnection = Integer.parseInt(attributes.get(IDBDatasourceService.MIN_IDLE_KEY)); } if (attributes.containsKey(IDBDatasourceService.MAX_IDLE_KEY) && NumberUtils.isNumber(attributes.get(IDBDatasourceService.MAX_IDLE_KEY))) { maxIdleConnection = Integer.parseInt(attributes.get(IDBDatasourceService.MAX_IDLE_KEY)); } if (attributes.containsKey(IDBDatasourceService.QUERY_KEY)) { validQuery = attributes.get(IDBDatasourceService.QUERY_KEY); } if (attributes.containsKey(IDBDatasourceService.TEST_ON_BORROW)) { testOnBorrow = Boolean.parseBoolean(attributes.get(IDBDatasourceService.TEST_ON_BORROW)); } if (attributes.containsKey(IDBDatasourceService.TEST_ON_RETURN)) { testOnReturn = Boolean.parseBoolean(attributes.get(IDBDatasourceService.TEST_ON_RETURN)); } if (attributes.containsKey(IDBDatasourceService.TEST_WHILE_IDLE)) { testWhileIdle = Boolean.parseBoolean(attributes.get(IDBDatasourceService.TEST_WHILE_IDLE)); } poolingDataSource = new PoolingDataSource(); Class.forName(driverClass); // As the name says, this is a generic pool; it returns basic Object-class objects. GenericObjectPool pool = new GenericObjectPool(null); // if removedAbandoned = true, then an AbandonedObjectPool object will take GenericObjectPool's place if (attributes.containsKey(IDBDatasourceService.REMOVE_ABANDONED) && true == Boolean.parseBoolean(attributes.get(IDBDatasourceService.REMOVE_ABANDONED))) { AbandonedConfig config = new AbandonedConfig(); config.setRemoveAbandoned( Boolean.parseBoolean(attributes.get(IDBDatasourceService.REMOVE_ABANDONED))); if (attributes.containsKey(IDBDatasourceService.LOG_ABANDONED)) { config.setLogAbandoned( Boolean.parseBoolean(attributes.get(IDBDatasourceService.LOG_ABANDONED))); } if (attributes.containsKey(IDBDatasourceService.REMOVE_ABANDONED_TIMEOUT) && NumberUtils.isNumber(attributes.get(IDBDatasourceService.REMOVE_ABANDONED_TIMEOUT))) { config.setRemoveAbandonedTimeout( Integer.parseInt(attributes.get(IDBDatasourceService.REMOVE_ABANDONED_TIMEOUT))); } pool = new AbandonedObjectPool(null, config); } pool.setWhenExhaustedAction(whenExhaustedActionType); // Tuning the connection pool pool.setMaxActive(maxActiveConnection); pool.setMaxIdle(maxIdleConnection); pool.setMaxWait(waitTime); pool.setMinIdle(minIdleConnection); pool.setTestWhileIdle(testWhileIdle); pool.setTestOnReturn(testOnReturn); pool.setTestOnBorrow(testOnBorrow); pool.setTestWhileIdle(testWhileIdle); if (attributes.containsKey(IDBDatasourceService.TIME_BETWEEN_EVICTION_RUNS_MILLIS) && NumberUtils .isNumber(attributes.get(IDBDatasourceService.TIME_BETWEEN_EVICTION_RUNS_MILLIS))) { pool.setTimeBetweenEvictionRunsMillis( Long.parseLong(attributes.get(IDBDatasourceService.TIME_BETWEEN_EVICTION_RUNS_MILLIS))); } /* * ConnectionFactory creates connections on behalf of the pool. Here, we use the DriverManagerConnectionFactory * because that essentially uses DriverManager as the source of connections. */ ConnectionFactory factory = null; if (url.startsWith("jdbc:mysql:")) { Properties props = new Properties(); props.put("user", databaseConnection.getUsername()); props.put("password", databaseConnection.getPassword()); props.put("socketTimeout", "0"); props.put("connectTimeout", "5000"); factory = new DriverManagerConnectionFactory(url, props); } else { factory = new DriverManagerConnectionFactory(url, databaseConnection.getUsername(), databaseConnection.getPassword()); } boolean defaultReadOnly = attributes.containsKey(IDBDatasourceService.DEFAULT_READ_ONLY) ? Boolean.parseBoolean(attributes.get(IDBDatasourceService.TEST_WHILE_IDLE)) : false; // default to false boolean defaultAutoCommit = attributes.containsKey(IDBDatasourceService.DEFAULT_AUTO_COMMIT) ? Boolean.parseBoolean(attributes.get(IDBDatasourceService.DEFAULT_AUTO_COMMIT)) : true; // default to true KeyedObjectPoolFactory kopf = null; if (attributes.containsKey(IDBDatasourceService.POOL_PREPARED_STATEMENTS) && true == Boolean .parseBoolean(attributes.get(IDBDatasourceService.POOL_PREPARED_STATEMENTS))) { int maxOpenPreparedStatements = -1; // unlimited if (attributes.containsKey(IDBDatasourceService.MAX_OPEN_PREPARED_STATEMENTS) && NumberUtils .isNumber(attributes.get(IDBDatasourceService.MAX_OPEN_PREPARED_STATEMENTS))) { maxOpenPreparedStatements = Integer .parseInt(attributes.get(IDBDatasourceService.MAX_OPEN_PREPARED_STATEMENTS)); } kopf = new GenericKeyedObjectPoolFactory(null, pool.getMaxActive(), pool.getWhenExhaustedAction(), pool.getMaxWait(), pool.getMaxIdle(), maxOpenPreparedStatements); } /* * Puts pool-specific wrappers on factory connections. For clarification: "[PoolableConnection]Factory," not * "Poolable[ConnectionFactory]." */ PoolableConnectionFactory pcf = new PoolableConnectionFactory(factory, // ConnectionFactory pool, // ObjectPool kopf, // KeyedObjectPoolFactory validQuery, // String (validation query) defaultReadOnly, // boolean (default to read-only?) defaultAutoCommit // boolean (default to auto-commit statements?) ); if (attributes.containsKey(IDBDatasourceService.DEFAULT_TRANSACTION_ISOLATION) && !IDBDatasourceService.TRANSACTION_ISOLATION_NONE_VALUE .equalsIgnoreCase(attributes.get(IDBDatasourceService.DEFAULT_TRANSACTION_ISOLATION))) { Isolation isolationLevel = Isolation .valueOf(attributes.get(IDBDatasourceService.DEFAULT_TRANSACTION_ISOLATION)); if (isolationLevel != null) { pcf.setDefaultTransactionIsolation(isolationLevel.value()); } } if (attributes.containsKey(IDBDatasourceService.DEFAULT_CATALOG)) { pcf.setDefaultCatalog(attributes.get(IDBDatasourceService.DEFAULT_CATALOG)); } /* * initialize the pool to X connections */ Logger.debug(PooledDatasourceHelper.class, "Pool defaults to " + maxActiveConnection + " max active/" + maxIdleConnection + "max idle" //$NON-NLS-3$ + "with " + waitTime + "wait time"//$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-4$ //$NON-NLS-5$ + " idle connections."); //$NON-NLS-1$ for (int i = 0; i < maxIdleConnection; ++i) { pool.addObject(); } Logger.debug(PooledDatasourceHelper.class, "Pool now has " + pool.getNumActive() + " active/" + pool.getNumIdle() + " idle connections."); //$NON-NLS-3$ //$NON-NLS-2$ //$NON-NLS-3$ /* * All of this is wrapped in a DataSource, which client code should already know how to handle (since it's the * same class of object they'd fetch via the container's JNDI tree */ poolingDataSource.setPool(pool); if (attributes.containsKey(IDBDatasourceService.ACCESS_TO_UNDERLYING_CONNECTION_ALLOWED)) { poolingDataSource.setAccessToUnderlyingConnectionAllowed(Boolean.parseBoolean( attributes.get(IDBDatasourceService.ACCESS_TO_UNDERLYING_CONNECTION_ALLOWED))); } // store the pool, so we can get to it later cacheManager.putInRegionCache(IDBDatasourceService.JDBC_POOL, databaseConnection.getName(), pool); return (poolingDataSource); } catch (Exception e) { throw new DBDatasourceServiceException(e); } }