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, AbandonedConfig config)
From source file:com.gramercysoftware.persistence.dao.GSPDataSourceFactory.java
private void createDataSource() { Properties properties = getDataSourceConfig(); initializeDatabaseDriver(properties); ObjectPool connectionPool = createConnectionPool(properties); ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(properties.getProperty("jdbc.url"), properties.getProperty("jdbc.user"), properties.getProperty("jdbc.password")); new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true, Connection.TRANSACTION_SERIALIZABLE); dataSource = new PoolingDataSource(connectionPool); }
From source file:mondrian.rolap.RolapConnectionPool.java
/** * Gets or creates a connection pool for a particular connect * specification./* w w w . jav a2s .com*/ */ private synchronized ObjectPool getPool(Object key, ConnectionFactory connectionFactory) { ObjectPool connectionPool = mapConnectKeyToPool.get(key); if (connectionPool == null) { // use GenericObjectPool, which provides for resource limits connectionPool = new GenericObjectPool(null, // PoolableObjectFactory, can be null 50, // max active GenericObjectPool.WHEN_EXHAUSTED_BLOCK, // action when exhausted 3000, // max wait (milli seconds) 10, // max idle false, // test on borrow false, // test on return 60000, // time between eviction runs (millis) 5, // number to test on eviction run 30000, // min evictable idle time (millis) true); // test while idle // create a PoolableConnectionFactory AbandonedConfig abandonedConfig = new AbandonedConfig(); // flag to remove abandoned connections from pool abandonedConfig.setRemoveAbandoned(true); // timeout (seconds) before removing abandoned connections abandonedConfig.setRemoveAbandonedTimeout(300); // Flag to log stack traces for application code which abandoned a // Statement or Connection abandonedConfig.setLogAbandoned(true); PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory( // the connection factory connectionFactory, // the object pool connectionPool, // statement pool factory for pooling prepared statements, // or null for no pooling null, // validation query (must return at least 1 row e.g. Oracle: // select count(*) from dual) to test connection, can be // null null, // default "read only" setting for borrowed connections false, // default "auto commit" setting for returned connections true, // AbandonedConfig object configures how to handle abandoned // connections abandonedConfig); // "poolableConnectionFactory" has registered itself with // "connectionPool", somehow, so we don't need the value any more. Util.discard(poolableConnectionFactory); mapConnectKeyToPool.put(key, connectionPool); } return connectionPool; }
From source file:com.cloud.utils.db.TransactionLegacy.java
@SuppressWarnings({ "rawtypes", "unchecked" }) public static void initDataSource(Properties dbProps) { try {/*from ww w .j a va 2 s . c om*/ if (dbProps.size() == 0) return; s_dbHAEnabled = Boolean.valueOf(dbProps.getProperty("db.ha.enabled")); s_logger.info("Is Data Base High Availiability enabled? Ans : " + s_dbHAEnabled); String loadBalanceStrategy = dbProps.getProperty("db.ha.loadBalanceStrategy"); // FIXME: If params are missing...default them???? final int cloudMaxActive = Integer.parseInt(dbProps.getProperty("db.cloud.maxActive")); final int cloudMaxIdle = Integer.parseInt(dbProps.getProperty("db.cloud.maxIdle")); final long cloudMaxWait = Long.parseLong(dbProps.getProperty("db.cloud.maxWait")); final String cloudUsername = dbProps.getProperty("db.cloud.username"); final String cloudPassword = dbProps.getProperty("db.cloud.password"); final String cloudHost = dbProps.getProperty("db.cloud.host"); final String cloudDriver = dbProps.getProperty("db.cloud.driver"); final int cloudPort = Integer.parseInt(dbProps.getProperty("db.cloud.port")); final String cloudDbName = dbProps.getProperty("db.cloud.name"); final boolean cloudAutoReconnect = Boolean.parseBoolean(dbProps.getProperty("db.cloud.autoReconnect")); final String cloudValidationQuery = dbProps.getProperty("db.cloud.validationQuery"); final String cloudIsolationLevel = dbProps.getProperty("db.cloud.isolation.level"); int isolationLevel = Connection.TRANSACTION_READ_COMMITTED; if (cloudIsolationLevel == null) { isolationLevel = Connection.TRANSACTION_READ_COMMITTED; } else if (cloudIsolationLevel.equalsIgnoreCase("readcommitted")) { isolationLevel = Connection.TRANSACTION_READ_COMMITTED; } else if (cloudIsolationLevel.equalsIgnoreCase("repeatableread")) { isolationLevel = Connection.TRANSACTION_REPEATABLE_READ; } else if (cloudIsolationLevel.equalsIgnoreCase("serializable")) { isolationLevel = Connection.TRANSACTION_SERIALIZABLE; } else if (cloudIsolationLevel.equalsIgnoreCase("readuncommitted")) { isolationLevel = Connection.TRANSACTION_READ_UNCOMMITTED; } else { s_logger.warn("Unknown isolation level " + cloudIsolationLevel + ". Using read uncommitted"); } final boolean cloudTestOnBorrow = Boolean.parseBoolean(dbProps.getProperty("db.cloud.testOnBorrow")); final boolean cloudTestWhileIdle = Boolean.parseBoolean(dbProps.getProperty("db.cloud.testWhileIdle")); final long cloudTimeBtwEvictionRunsMillis = Long .parseLong(dbProps.getProperty("db.cloud.timeBetweenEvictionRunsMillis")); final long cloudMinEvcitableIdleTimeMillis = Long .parseLong(dbProps.getProperty("db.cloud.minEvictableIdleTimeMillis")); final boolean cloudPoolPreparedStatements = Boolean .parseBoolean(dbProps.getProperty("db.cloud.poolPreparedStatements")); final String url = dbProps.getProperty("db.cloud.url.params"); String cloudDbHAParams = null; String cloudSlaves = null; if (s_dbHAEnabled) { cloudDbHAParams = getDBHAParams("cloud", dbProps); cloudSlaves = dbProps.getProperty("db.cloud.slaves"); s_logger.info("The slaves configured for Cloud Data base is/are : " + cloudSlaves); } final boolean useSSL = Boolean.parseBoolean(dbProps.getProperty("db.cloud.useSSL")); if (useSSL) { System.setProperty("javax.net.ssl.keyStore", dbProps.getProperty("db.cloud.keyStore")); System.setProperty("javax.net.ssl.keyStorePassword", dbProps.getProperty("db.cloud.keyStorePassword")); System.setProperty("javax.net.ssl.trustStore", dbProps.getProperty("db.cloud.trustStore")); System.setProperty("javax.net.ssl.trustStorePassword", dbProps.getProperty("db.cloud.trustStorePassword")); } final GenericObjectPool cloudConnectionPool = new GenericObjectPool(null, cloudMaxActive, GenericObjectPool.DEFAULT_WHEN_EXHAUSTED_ACTION, cloudMaxWait, cloudMaxIdle, cloudTestOnBorrow, false, cloudTimeBtwEvictionRunsMillis, 1, cloudMinEvcitableIdleTimeMillis, cloudTestWhileIdle); final String cloudConnectionUri = cloudDriver + "://" + cloudHost + (s_dbHAEnabled ? "," + cloudSlaves : "") + ":" + cloudPort + "/" + cloudDbName + "?autoReconnect=" + cloudAutoReconnect + (url != null ? "&" + url : "") + (useSSL ? "&useSSL=true" : "") + (s_dbHAEnabled ? "&" + cloudDbHAParams : "") + (s_dbHAEnabled ? "&loadBalanceStrategy=" + loadBalanceStrategy : ""); DriverLoader.loadDriver(cloudDriver); final ConnectionFactory cloudConnectionFactory = new DriverManagerConnectionFactory(cloudConnectionUri, cloudUsername, cloudPassword); final KeyedObjectPoolFactory poolableObjFactory = (cloudPoolPreparedStatements ? new StackKeyedObjectPoolFactory() : null); final PoolableConnectionFactory cloudPoolableConnectionFactory = new PoolableConnectionFactory( cloudConnectionFactory, cloudConnectionPool, poolableObjFactory, cloudValidationQuery, false, false, isolationLevel); // Default Data Source for CloudStack s_ds = new PoolingDataSource(cloudPoolableConnectionFactory.getPool()); // Configure the usage db final int usageMaxActive = Integer.parseInt(dbProps.getProperty("db.usage.maxActive")); final int usageMaxIdle = Integer.parseInt(dbProps.getProperty("db.usage.maxIdle")); final long usageMaxWait = Long.parseLong(dbProps.getProperty("db.usage.maxWait")); final String usageUsername = dbProps.getProperty("db.usage.username"); final String usagePassword = dbProps.getProperty("db.usage.password"); final String usageHost = dbProps.getProperty("db.usage.host"); final String usageDriver = dbProps.getProperty("db.usage.driver"); final int usagePort = Integer.parseInt(dbProps.getProperty("db.usage.port")); final String usageDbName = dbProps.getProperty("db.usage.name"); final boolean usageAutoReconnect = Boolean.parseBoolean(dbProps.getProperty("db.usage.autoReconnect")); final String usageUrl = dbProps.getProperty("db.usage.url.params"); final GenericObjectPool usageConnectionPool = new GenericObjectPool(null, usageMaxActive, GenericObjectPool.DEFAULT_WHEN_EXHAUSTED_ACTION, usageMaxWait, usageMaxIdle); final String usageConnectionUri = usageDriver + "://" + usageHost + (s_dbHAEnabled ? "," + dbProps.getProperty("db.cloud.slaves") : "") + ":" + usagePort + "/" + usageDbName + "?autoReconnect=" + usageAutoReconnect + (usageUrl != null ? "&" + usageUrl : "") + (s_dbHAEnabled ? "&" + getDBHAParams("usage", dbProps) : "") + (s_dbHAEnabled ? "&loadBalanceStrategy=" + loadBalanceStrategy : ""); DriverLoader.loadDriver(usageDriver); final ConnectionFactory usageConnectionFactory = new DriverManagerConnectionFactory(usageConnectionUri, usageUsername, usagePassword); final PoolableConnectionFactory usagePoolableConnectionFactory = new PoolableConnectionFactory( usageConnectionFactory, usageConnectionPool, new StackKeyedObjectPoolFactory(), null, false, false); // Data Source for usage server s_usageDS = new PoolingDataSource(usagePoolableConnectionFactory.getPool()); try { // Configure the simulator db final int simulatorMaxActive = Integer.parseInt(dbProps.getProperty("db.simulator.maxActive")); final int simulatorMaxIdle = Integer.parseInt(dbProps.getProperty("db.simulator.maxIdle")); final long simulatorMaxWait = Long.parseLong(dbProps.getProperty("db.simulator.maxWait")); final String simulatorUsername = dbProps.getProperty("db.simulator.username"); final String simulatorPassword = dbProps.getProperty("db.simulator.password"); final String simulatorHost = dbProps.getProperty("db.simulator.host"); final String simulatorDriver = dbProps.getProperty("db.simulator.driver"); final int simulatorPort = Integer.parseInt(dbProps.getProperty("db.simulator.port")); final String simulatorDbName = dbProps.getProperty("db.simulator.name"); final boolean simulatorAutoReconnect = Boolean .parseBoolean(dbProps.getProperty("db.simulator.autoReconnect")); final GenericObjectPool simulatorConnectionPool = new GenericObjectPool(null, simulatorMaxActive, GenericObjectPool.DEFAULT_WHEN_EXHAUSTED_ACTION, simulatorMaxWait, simulatorMaxIdle); final String simulatorConnectionUri = simulatorDriver + "://" + simulatorHost + ":" + simulatorPort + "/" + simulatorDbName + "?autoReconnect=" + simulatorAutoReconnect; DriverLoader.loadDriver(simulatorDriver); final ConnectionFactory simulatorConnectionFactory = new DriverManagerConnectionFactory( simulatorConnectionUri, simulatorUsername, simulatorPassword); final PoolableConnectionFactory simulatorPoolableConnectionFactory = new PoolableConnectionFactory( simulatorConnectionFactory, simulatorConnectionPool, new StackKeyedObjectPoolFactory(), null, false, false); s_simulatorDS = new PoolingDataSource(simulatorPoolableConnectionFactory.getPool()); } catch (Exception e) { s_logger.debug("Simulator DB properties are not available. Not initializing simulator DS"); } } catch (final Exception e) { s_ds = getDefaultDataSource("cloud"); s_usageDS = getDefaultDataSource("cloud_usage"); s_simulatorDS = getDefaultDataSource("cloud_simulator"); s_logger.warn( "Unable to load db configuration, using defaults with 5 connections. Falling back on assumed datasource on localhost:3306 using username:password=cloud:cloud. Please check your configuration", e); } }
From source file:org.apache.flume.channel.jdbc.impl.JdbcChannelProviderImpl.java
/** //from w w w . j a v a 2s . co m * Initializes the datasource and the underlying connection pool. * @param properties */ private void initializeDataSource(Context context) { driverClassName = getConfigurationString(context, ConfigurationConstants.CONFIG_JDBC_DRIVER_CLASS, ConfigurationConstants.OLD_CONFIG_JDBC_DRIVER_CLASS, null); connectUrl = getConfigurationString(context, ConfigurationConstants.CONFIG_URL, ConfigurationConstants.OLD_CONFIG_URL, null); String userName = getConfigurationString(context, ConfigurationConstants.CONFIG_USERNAME, ConfigurationConstants.OLD_CONFIG_USERNAME, null); String password = getConfigurationString(context, ConfigurationConstants.CONFIG_PASSWORD, ConfigurationConstants.OLD_CONFIG_PASSWORD, null); String jdbcPropertiesFile = getConfigurationString(context, ConfigurationConstants.CONFIG_JDBC_PROPS_FILE, ConfigurationConstants.OLD_CONFIG_JDBC_PROPS_FILE, null); String dbTypeName = getConfigurationString(context, ConfigurationConstants.CONFIG_DATABASE_TYPE, ConfigurationConstants.OLD_CONFIG_DATABASE_TYPE, null); // If connect URL is not specified, use embedded Derby if (connectUrl == null || connectUrl.trim().length() == 0) { LOGGER.warn("No connection URL specified. " + "Using embedded derby database instance."); driverClassName = DEFAULT_DRIVER_CLASSNAME; userName = DEFAULT_USERNAME; password = DEFAULT_PASSWORD; dbTypeName = DEFAULT_DBTYPE; String homePath = System.getProperty("user.home").replace('\\', '/'); String defaultDbDir = homePath + "/.flume/jdbc-channel"; File dbDir = new File(defaultDbDir); String canonicalDbDirPath = null; try { canonicalDbDirPath = dbDir.getCanonicalPath(); } catch (IOException ex) { throw new JdbcChannelException("Unable to find canonical path of dir: " + defaultDbDir, ex); } if (!dbDir.exists()) { if (!dbDir.mkdirs()) { throw new JdbcChannelException("unable to create directory: " + canonicalDbDirPath); } } connectUrl = "jdbc:derby:" + canonicalDbDirPath + "/db;create=true"; // No jdbc properties file will be used jdbcPropertiesFile = null; LOGGER.warn("Overriding values for - driver: " + driverClassName + ", user: " + userName + "connectUrl: " + connectUrl + ", jdbc properties file: " + jdbcPropertiesFile + ", dbtype: " + dbTypeName); } // Right now only Derby and MySQL supported databaseType = DatabaseType.getByName(dbTypeName); switch (databaseType) { case DERBY: case MYSQL: break; default: throw new JdbcChannelException("Database " + databaseType + " not supported at this time"); } // Register driver if (driverClassName == null || driverClassName.trim().length() == 0) { throw new JdbcChannelException("No jdbc driver specified"); } try { Class.forName(driverClassName); } catch (ClassNotFoundException ex) { throw new JdbcChannelException("Unable to load driver: " + driverClassName, ex); } // JDBC Properties Properties jdbcProps = new Properties(); if (jdbcPropertiesFile != null && jdbcPropertiesFile.trim().length() > 0) { File jdbcPropsFile = new File(jdbcPropertiesFile.trim()); if (!jdbcPropsFile.exists()) { throw new JdbcChannelException("Jdbc properties file does not exist: " + jdbcPropertiesFile); } InputStream inStream = null; try { inStream = new FileInputStream(jdbcPropsFile); jdbcProps.load(inStream); } catch (IOException ex) { throw new JdbcChannelException( "Unable to load jdbc properties " + "from file: " + jdbcPropertiesFile, ex); } finally { if (inStream != null) { try { inStream.close(); } catch (IOException ex) { LOGGER.error("Unable to close file: " + jdbcPropertiesFile, ex); } } } } if (userName != null) { Object oldUser = jdbcProps.put("user", userName); if (oldUser != null) { LOGGER.warn("Overriding user from: " + oldUser + " to: " + userName); } } if (password != null) { Object oldPass = jdbcProps.put("password", password); if (oldPass != null) { LOGGER.warn( "Overriding password from the jdbc properties with " + " the one specified explicitly."); } } if (LOGGER.isDebugEnabled()) { StringBuilder sb = new StringBuilder("JDBC Properties {"); boolean first = true; Enumeration<?> propertyKeys = jdbcProps.propertyNames(); while (propertyKeys.hasMoreElements()) { if (first) { first = false; } else { sb.append(", "); } String key = (String) propertyKeys.nextElement(); sb.append(key).append("="); if (key.equalsIgnoreCase("password")) { sb.append("*******"); } else { sb.append(jdbcProps.get(key)); } } sb.append("}"); LOGGER.debug(sb.toString()); } // Transaction Isolation String txIsolation = getConfigurationString(context, ConfigurationConstants.CONFIG_TX_ISOLATION_LEVEL, ConfigurationConstants.OLD_CONFIG_TX_ISOLATION_LEVEL, TransactionIsolation.READ_COMMITTED.getName()); TransactionIsolation txIsolationLevel = TransactionIsolation.getByName(txIsolation); LOGGER.debug("Transaction isolation will be set to: " + txIsolationLevel); // Setup Datasource ConnectionFactory connFactory = new DriverManagerConnectionFactory(connectUrl, jdbcProps); connectionPool = new GenericObjectPool(); String maxActiveConnections = getConfigurationString(context, ConfigurationConstants.CONFIG_MAX_CONNECTIONS, ConfigurationConstants.OLD_CONFIG_MAX_CONNECTIONS, "10"); int maxActive = 10; if (maxActiveConnections != null && maxActiveConnections.length() > 0) { try { maxActive = Integer.parseInt(maxActiveConnections); } catch (NumberFormatException nfe) { LOGGER.warn("Max active connections has invalid value: " + maxActiveConnections + ", Using default: " + maxActive); } } LOGGER.debug("Max active connections for the pool: " + maxActive); connectionPool.setMaxActive(maxActive); statementPool = new GenericKeyedObjectPoolFactory(null); // Creating the factory instance automatically wires the connection pool new PoolableConnectionFactory(connFactory, connectionPool, statementPool, databaseType.getValidationQuery(), false, false, txIsolationLevel.getCode()); dataSource = new PoolingDataSource(connectionPool); txFactory = new JdbcTransactionFactory(dataSource, this); }
From source file:org.apache.ojb.broker.accesslayer.ConnectionFactoryDBCPImpl.java
/** * Returns a new ObjectPool for the specified connection descriptor. * Override this method to setup your own pool. * @param jcd the connection descriptor for which to set up the pool * @return a newly created object pool/*from w w w.jav a 2s . c o m*/ */ protected ObjectPool setupPool(JdbcConnectionDescriptor jcd) { log.info("Create new ObjectPool for DBCP connections:" + jcd); try { ClassHelper.newInstance(jcd.getDriver()); } catch (InstantiationException e) { log.fatal( "Unable to instantiate the driver class: " + jcd.getDriver() + " in ConnectionFactoryDBCImpl!", e); } catch (IllegalAccessException e) { log.fatal("IllegalAccessException while instantiating the driver class: " + jcd.getDriver() + " in ConnectionFactoryDBCImpl!", e); } catch (ClassNotFoundException e) { log.fatal("Could not find the driver class : " + jcd.getDriver() + " in ConnectionFactoryDBCImpl!", e); } // Get the configuration for the connection pool GenericObjectPool.Config conf = jcd.getConnectionPoolDescriptor().getObjectPoolConfig(); // Get the additional abandoned configuration AbandonedConfig ac = jcd.getConnectionPoolDescriptor().getAbandonedConfig(); // Create the ObjectPool that serves as the actual pool of connections. final ObjectPool connectionPool = createConnectionPool(conf, ac); // Create a DriverManager-based ConnectionFactory that // the connectionPool will use to create Connection instances final org.apache.commons.dbcp.ConnectionFactory connectionFactory; connectionFactory = createConnectionFactory(jcd); // Create PreparedStatement object pool (if any) KeyedObjectPoolFactory statementPoolFactory = createStatementPoolFactory(jcd); // Set validation query and auto-commit mode final String validationQuery; final boolean defaultAutoCommit; final boolean defaultReadOnly = false; validationQuery = jcd.getConnectionPoolDescriptor().getValidationQuery(); defaultAutoCommit = (jcd.getUseAutoCommit() != JdbcConnectionDescriptor.AUTO_COMMIT_SET_FALSE); // // Now we'll create the PoolableConnectionFactory, which wraps // the "real" Connections created by the ConnectionFactory with // the classes that implement the pooling functionality. // final PoolableConnectionFactory poolableConnectionFactory; poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, statementPoolFactory, validationQuery, defaultReadOnly, defaultAutoCommit, ac); return poolableConnectionFactory.getPool(); }
From source file:org.apache.slide.store.impl.rdbms.JDBCStore.java
/** * Initializes driver.//from w ww . j ava2 s . c o m * <p/> * Occurs in four steps : * <li>Driver class is loaded</li> * <li>Driver is instantiated</li> * <li>Driver registration in the driver manager</li> * <li>Creation of the basic tables, if they didn't exist before</li> * * @exception ServiceInitializationFailedException Throws an exception * if the data source has already been initialized before */ public synchronized void initialize(NamespaceAccessToken token) throws ServiceInitializationFailedException { // XXX might be done already in setParameter if (!alreadyInitialized) { try { // Loading and registering driver getLogger().log("Loading and registering driver '" + driver + "'", LOG_CHANNEL, Logger.INFO); Class driverClass = Class.forName(driver); Driver driverInstance = (Driver) driverClass.newInstance(); String levelString = isolationLevelToString(isolationLevel); getLogger().log("Setting isolation level '" + levelString + "'", LOG_CHANNEL, Logger.INFO); // use DBCP pooling if enabled if (useDbcpPooling) { getLogger().log("Using DBCP pooling", LOG_CHANNEL, Logger.INFO); GenericObjectPool connectionPool = new GenericObjectPool(null); if (maxPooledConnections != -1) { connectionPool.setMaxActive(maxPooledConnections); } getLogger().log("Number of connections set to " + connectionPool.getMaxActive(), LOG_CHANNEL, Logger.INFO); DriverManagerConnectionFactory connectionFactory = new DriverManagerConnectionFactory(url, user, password); new PoolableConnectionFactory(connectionFactory, connectionPool, // TODO switching on pooling of prepared statements causes problems with closing of connections // switched off for now // new StackKeyedObjectPoolFactory(), null, null, false, false, isolationLevel); PoolingDriver driver = new PoolingDriver(); driver.registerPool(dbcpPoolName, connectionPool); // already done when loding PoolingDriver class // DriverManager.registerDriver(driver); } else { DriverManager.registerDriver(driverInstance); getLogger().log("Not using DBCP pooling", LOG_CHANNEL, Logger.WARNING); } } catch (Exception e) { getLogger().log("Loading and registering driver '" + driver + "' failed (" + e.getMessage() + ")", LOG_CHANNEL, Logger.ERROR); throw new ServiceInitializationFailedException(this, e); } finally { alreadyInitialized = true; } } }
From source file:org.apache.sqoop.repository.JdbcRepositoryProvider.java
private void initializeRepositoryHandler() { String jdbcHandlerClassName = repoContext.getHandlerClassName(); Class<?> handlerClass = ClassUtils.loadClass(jdbcHandlerClassName); if (handlerClass == null) { throw new SqoopException(RepositoryError.JDBCREPO_0001, jdbcHandlerClassName); }// www .j a va 2s . c o m try { handler = (JdbcRepositoryHandler) handlerClass.newInstance(); } catch (Exception ex) { throw new SqoopException(RepositoryError.JDBCREPO_0001, jdbcHandlerClassName, ex); } String connectUrl = repoContext.getConnectionUrl(); if (connectUrl == null || connectUrl.trim().length() == 0) { throw new SqoopException(RepositoryError.JDBCREPO_0002); } String jdbcDriverClassName = repoContext.getDriverClass(); if (jdbcDriverClassName == null || jdbcDriverClassName.trim().length() == 0) { throw new SqoopException(RepositoryError.JDBCREPO_0003); } // Initialize a datasource Class<?> driverClass = ClassUtils.loadClass(jdbcDriverClassName); if (driverClass == null) { throw new SqoopException(RepositoryError.JDBCREPO_0003, jdbcDriverClassName); } try { driver = (Driver) driverClass.newInstance(); } catch (Exception ex) { throw new SqoopException(RepositoryError.JDBCREPO_0003, jdbcDriverClassName, ex); } Properties jdbcProps = repoContext.getConnectionProperties(); ConnectionFactory connFactory = new DriverManagerConnectionFactory(connectUrl, jdbcProps); connectionPool = new GenericObjectPool(); connectionPool.setMaxActive(repoContext.getMaximumConnections()); statementPool = new GenericKeyedObjectPoolFactory(null); // creating the factor automatically wires the connection pool new PoolableConnectionFactory(connFactory, connectionPool, statementPool, handler.validationQuery(), false, false, repoContext.getTransactionIsolation().getCode()); dataSource = new PoolingDataSource(connectionPool); txFactory = new JdbcRepositoryTransactionFactory(dataSource); repoContext.initialize(dataSource, txFactory); handler.initialize(repoContext); repository = new JdbcRepository(handler, repoContext); LOG.info("JdbcRepositoryProvider initialized"); }
From source file:org.apache.sqoop.repository.JdbcRepositoryProvider.java
@Override public void configurationChanged() { LOG.info("Begin JdbcRepository reconfiguring."); JdbcRepositoryContext oldRepoContext = repoContext; repoContext = new JdbcRepositoryContext(SqoopConfiguration.getInstance().getContext()); // reconfigure jdbc handler String newJdbcHandlerClassName = repoContext.getHandlerClassName(); if (newJdbcHandlerClassName == null || newJdbcHandlerClassName.trim().length() == 0) { throw new SqoopException(RepositoryError.JDBCREPO_0001, newJdbcHandlerClassName); }// w ww . j a v a 2 s. c o m String oldJdbcHandlerClassName = oldRepoContext.getHandlerClassName(); if (!newJdbcHandlerClassName.equals(oldJdbcHandlerClassName)) { LOG.warn("Repository JDBC handler cannot be replaced at the runtime. " + "You might need to restart the server."); } // reconfigure jdbc driver String newJdbcDriverClassName = repoContext.getDriverClass(); if (newJdbcDriverClassName == null || newJdbcDriverClassName.trim().length() == 0) { throw new SqoopException(RepositoryError.JDBCREPO_0003, newJdbcDriverClassName); } String oldJdbcDriverClassName = oldRepoContext.getDriverClass(); if (!newJdbcDriverClassName.equals(oldJdbcDriverClassName)) { LOG.warn("Repository JDBC driver cannot be replaced at the runtime. " + "You might need to restart the server."); } // reconfigure max connection connectionPool.setMaxActive(repoContext.getMaximumConnections()); // reconfigure the url of repository String connectUrl = repoContext.getConnectionUrl(); String oldurl = oldRepoContext.getConnectionUrl(); if (connectUrl != null && !connectUrl.equals(oldurl)) { LOG.warn( "Repository URL cannot be replaced at the runtime. " + "You might need to restart the server."); } // if connection properties or transaction isolation option changes boolean connFactoryChanged = false; // compare connection properties if (!connFactoryChanged) { Properties oldProp = oldRepoContext.getConnectionProperties(); Properties newProp = repoContext.getConnectionProperties(); if (newProp.size() != oldProp.size()) { connFactoryChanged = true; } else { for (Object key : newProp.keySet()) { if (!newProp.getProperty((String) key).equals(oldProp.getProperty((String) key))) { connFactoryChanged = true; break; } } } } // compare the transaction isolation option if (!connFactoryChanged) { String oldTxOption = oldRepoContext.getTransactionIsolation().toString(); String newTxOption = repoContext.getTransactionIsolation().toString(); if (!newTxOption.equals(oldTxOption)) { connFactoryChanged = true; } } if (connFactoryChanged) { // try to reconfigure connection factory try { LOG.info("Reconfiguring Connection Factory."); Properties jdbcProps = repoContext.getConnectionProperties(); ConnectionFactory connFactory = new DriverManagerConnectionFactory(connectUrl, jdbcProps); new PoolableConnectionFactory(connFactory, connectionPool, statementPool, handler.validationQuery(), false, false, repoContext.getTransactionIsolation().getCode()); } catch (IllegalStateException ex) { // failed to reconfigure connection factory LOG.warn("Repository connection cannot be reconfigured currently. " + "You might need to restart the server."); } } // ignore the create schema option, because the repo url is not allowed to change LOG.info("JdbcRepository reconfigured."); }
From source file:org.eclipse.osee.jdbc.internal.PooledDataSourceFetcher.java
@SuppressWarnings({ "rawtypes", "unchecked" }) private ObjectPool<Connection> createConnectionPool() throws Exception { MetaData metadata = manager.getMetaData(dbInfo); JdbcConnectionFactory proxiedFactory = manager.getFactory(dbInfo.getDriver()); ConnectionFactory connectionFactory = new ConnectionFactoryProxy(proxiedFactory, dbInfo, metadata.isTxIsolationLevelSupported()); AbandonedObjectPool connectionPool = new AbandonedObjectPool(null, getAbandonedConnectionConfig(poolConfig)); connectionPool.setConfig(getPoolConfig(poolConfig)); GenericKeyedObjectPoolFactory statementPool = null; if (poolConfig.isPoolPreparedStatementsAllowed()) { statementPool = new GenericKeyedObjectPoolFactory(null, getStatementPoolConfig(poolConfig)); }// w w w . j a v a2 s. co m AbandonedConfig abandoned = new AbandonedConfig(); abandoned.setLogAbandoned(true); abandoned.setLogWriter(new PrintWriter(System.out)); String validationQuery = metadata.getValidationQuery(); int validationQueryTimeoutSecs = poolConfig.getPoolValidationQueryTimeoutSecs(); boolean defaultReadOnly = false; boolean defaultAutoCommit = true; new PoolableConnectionFactory(connectionFactory, connectionPool, statementPool, validationQuery, validationQueryTimeoutSecs, defaultReadOnly, defaultAutoCommit); return connectionPool; }
From source file:org.opensubsystems.core.persist.jdbc.connectionpool.dbcp.DBCPDatabaseConnectionFactoryImpl.java
/** * {@inheritDoc}//from w w w.jav a2 s.c o m */ @Override protected Object createConnectionPool(String strConnectionPoolName, Database database, String strDriverName, String strUrl, String strUser, String strPassword, int iTransactionIsolation) throws OSSException { // I am using here the PoolingDriver instead of PoolingDataSource because // in DBCP version 1.1 the PoolingDriver has clear way how to shutdown // the pool and PoolingDataSource doesn't. // This code was inspired by method setupDriver from // ManualPoolingDriverExample.java in commons-dbcp package v 1.6 ObjectPool connectionPool; ConnectionFactory connectionFactory; PoolableConnectionFactory poolableConnectionFactory; PooledDatabaseConnectionFactorySetupReader setupReader = new PooledDatabaseConnectionFactorySetupReader( strConnectionPoolName, database.getDatabaseTypeIdentifier()); int iInitialPoolSize = setupReader .getIntegerParameterValue(PooledDatabaseConnectionFactorySetupReader.DBPOOL_INITIAL_SIZE) .intValue(); int iMinimalPoolSize = setupReader .getIntegerParameterValue(PooledDatabaseConnectionFactorySetupReader.DBPOOL_MIN_SIZE).intValue(); int iMaximalPoolSize = setupReader .getIntegerParameterValue(PooledDatabaseConnectionFactorySetupReader.DBPOOL_MAX_SIZE).intValue(); boolean bCanGrow = setupReader .getBooleanParameterValue(PooledDatabaseConnectionFactorySetupReader.DBPOOL_CAN_GROW) .booleanValue(); long lMaxWaitTimeForConnection = setupReader .getLongParameterValue(PooledDatabaseConnectionFactorySetupReader.DBPOOL_WAIT_PERIOD).longValue(); boolean bValidateOnBorrow = setupReader .getBooleanParameterValue(PooledDatabaseConnectionFactorySetupReader.DBPOOL_VALIDATE_BORROW) .booleanValue(); boolean bValidateOnReturn = setupReader .getBooleanParameterValue(PooledDatabaseConnectionFactorySetupReader.DBPOOL_VALIDATE_RETURN) .booleanValue(); boolean bValidateOnIdle = setupReader .getBooleanParameterValue(PooledDatabaseConnectionFactorySetupReader.DBPOOL_VALIDATE_IDLE) .booleanValue(); long lTimeBetweenEvictionRunsMillis = setupReader .getLongParameterValue(PooledDatabaseConnectionFactorySetupReader.DBPOOL_IDLE_CHECK_PERIOD) .longValue(); int iNumTestsPerEvictionRun = setupReader .getIntegerParameterValue(PooledDatabaseConnectionFactorySetupReader.DBPOOL_IDLE_CHECK_SIZE) .intValue(); long lMinEvictableIdleTimeMillis = setupReader .getLongParameterValue(PooledDatabaseConnectionFactorySetupReader.DBPOOL_IDLE_PERIOD).longValue(); int iPreparedStatementCacheSize = setupReader.getIntegerParameterValue( PooledDatabaseConnectionFactorySetupReader.DBPOOL_PREPSTATEMENT_CACHE_SIZE).intValue(); // First, we'll need a ObjectPool that serves as the actual pool of // connections. We'll use a GenericObjectPool instance, although // any ObjectPool implementation will suffice. connectionPool = new GenericObjectPool(null, // factory will be specified below iMaximalPoolSize, bCanGrow ? GenericObjectPool.WHEN_EXHAUSTED_GROW : GenericObjectPool.WHEN_EXHAUSTED_BLOCK, lMaxWaitTimeForConnection, iMaximalPoolSize, // max idle - if no connections are used // the pool should not fall under this size iMinimalPoolSize, // min idle - if connection count falls // under this limit (e.g. closed connections) // new connections will be created bValidateOnBorrow, bValidateOnReturn, lTimeBetweenEvictionRunsMillis, iNumTestsPerEvictionRun, lMinEvictableIdleTimeMillis, bValidateOnIdle); // Next, we'll create a ConnectionFactory that the pool will use to // create Connections. I am using DriverManagerConnectionFactory instead // of DriverConnectionFactory because it allows me to specify user name // and password directly connectionFactory = new DriverManagerConnectionFactory(strUrl, strUser, strPassword); // This configuration of prepared statement caching is inspired by // Commons-DBCP Wiki available at http://wiki.apache.org/jakarta-commons/DBCP // null can be used as parameter because this parameter is set in // PoolableConnectionFactory when creating a new PoolableConnection // 0 according to documentation should mean no limit KeyedObjectPoolFactory statementPool = null; if (iPreparedStatementCacheSize >= 0) { statementPool = new GenericKeyedObjectPoolFactory(null, iPreparedStatementCacheSize); } // Now we'll create the PoolableConnectionFactory, which wraps // the "real" Connections created by the ConnectionFactory with // the classes that implement the pooling functionality. poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, statementPool, DatabaseImpl.getInstance().getConnectionTestStatement(), false, // not read-only connection false, // Default auto commit is false iTransactionIsolation); // PoolableConnectionFactory doesn't support the initialSize attribute of // DBCP so I have replicated the code from BasicDataSource v1.37 here try { for (int iIndex = 0; iIndex < iInitialPoolSize; iIndex++) { connectionPool.addObject(); } } catch (Exception e) { throw new OSSDatabaseAccessException("Error preloading the connection pool", e); } if (GlobalConstants.ERROR_CHECKING) { // Put this check here to trick checkstyle assert poolableConnectionFactory != null : "Poolable connection factory cannot be null."; } return connectionPool; }