List of usage examples for org.apache.commons.pool.impl GenericKeyedObjectPoolFactory GenericKeyedObjectPoolFactory
public GenericKeyedObjectPoolFactory(KeyedPoolableObjectFactory factory)
From source file:org.apache.flume.channel.jdbc.impl.JdbcChannelProviderImpl.java
/** /*from ww w. j av a 2s .c om*/ * 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.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); }//from w w w. j a v a2s. com 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.rimudb.pool.DBCPConnectionManager.java
public void connect(String user, String password) throws Exception { // Load the jdbc driver Class.forName(poolConfiguration.getJdbcDriver()); // Create an ObjectPool that serves as the actual pool of connections. connectionPool = new GenericObjectPool(null); connectionPool.setMaxActive(99999);/*from w ww . ja v a 2 s . co m*/ connectionPool.setTimeBetweenEvictionRunsMillis(poolConfiguration.getTimeBetweenEvictionRunsSecs() * 1000L); connectionPool.setMaxActive(poolConfiguration.getMaxActive()); connectionPool.setMinEvictableIdleTimeMillis(poolConfiguration.getMinEvictableIdleTimeSecs() * 1000L); connectionPool.setMinIdle(poolConfiguration.getMinIdle()); connectionPool.setMaxIdle(poolConfiguration.getMaxIdle()); connectionPool.setMaxWait(poolConfiguration.getMaxWaitSecs() * 1000L); // Create a Properties object for the connection factory Properties props = new Properties(); // Pass all the properties from the configuration into the connection factory properties if (poolConfiguration.getProperties() != null) { props.putAll(poolConfiguration.getProperties()); } // Set user and password if (user != null && password != null) { props.setProperty("user", user); props.setProperty("pasword", password); } props.setProperty("poolPreparedStatements", "" + poolConfiguration.getStatementCaching()); // Create a ConnectionFactory that the pool will use to create Connections. ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(poolConfiguration.getJdbcURL(), props); KeyedObjectPoolFactory stmtPoolFactory = null; if (poolConfiguration.getStatementCaching()) { stmtPoolFactory = new GenericKeyedObjectPoolFactory(null); } // Create the PoolableConnectionFactory, which wraps the "real" Connections created by the ConnectionFactory with // the classes that implement the pooling functionality. PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, stmtPoolFactory, null, false, true); // Create the PoolingDriver itself Class.forName("org.apache.commons.dbcp.PoolingDriver"); PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:"); // Register the pool driver.registerPool(dbConfig.getDatabaseID(), connectionPool); }
From source file:org.topazproject.ambra.auth.db.DatabaseContext.java
/** * Construct a db context/* w w w.ja v a2 s. co m*/ * @param jdbcDriver jdbcDriver * @param dbProperties dbProperties including url, user, password * @param initialSize initialSize of the pool * @param maxActive maxActive number of connections, after which it will block until a connection is * released * @param validationQuery to validate that the connection is still valid * @throws DatabaseException DatabaseException */ private DatabaseContext(final String jdbcDriver, final Properties dbProperties, final int initialSize, final int maxActive, final String validationQuery) throws DatabaseException { try { Class.forName(jdbcDriver); } catch (final ClassNotFoundException e) { throw new DatabaseException("Unable to load the db driver:" + jdbcDriver, e); } final ConnectionFactory connectionFactory = new DriverManagerConnectionFactory( dbProperties.getProperty("url"), dbProperties.getProperty("user"), dbProperties.getProperty("password")); connectionPool = new GenericObjectPool(); connectionPool.setTestOnReturn(true); connectionPool.setMaxActive(maxActive); connectionPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_BLOCK); connectionPool.getMaxActive(); final KeyedObjectPoolFactory stmtPool = new GenericKeyedObjectPoolFactory(null); /* * During instantiation, the PoolableConnectionFactory class registers itself to the * GenericObjectPool instance passed in its constructor. This factory class is used to create * new instances of the JDBC connections. */ new PoolableConnectionFactory(connectionFactory, connectionPool, stmtPool, validationQuery, false, true); for (int i = 0; i < initialSize; i++) { try { connectionPool.addObject(); } catch (final Exception e) { throw new DatabaseException("Error initlaizing initial number of connections", e); } } dataSource = new PoolingDataSource(connectionPool); }