Java源码示例:org.apache.commons.dbcp2.ConnectionFactory

示例1
private ScipioErrorDbConnectionFactory() {
    Properties properties = new Properties();
    properties.setProperty("user", DB_USERNAME);
    properties.setProperty("password", DB_PASSWORD);
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(DB_URL, properties);
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null);
    GenericObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory);
    poolableConnectionFactory.setPool(connectionPool); // TODO: REVIEW: circular?
    poolableConnectionFactory.setValidationQuery("SELECT 1");
    poolableConnectionFactory.setValidationQueryTimeout(3);
    poolableConnectionFactory.setDefaultReadOnly(false);
    poolableConnectionFactory.setDefaultAutoCommit(false);
    poolableConnectionFactory.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
    // Original (log4j manual, dbcp lib):
    //PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(
    //        connectionFactory, connectionPool, null, "SELECT 1", 3, false, false, Connection.TRANSACTION_READ_COMMITTED
    //);
    this.dataSource = new PoolingDataSource<>(connectionPool);
}
 
示例2
public static PoolableDataSource create(String url, Properties mysqlConnectionProperties) {
    
    String driver = null;
    try {
        if (url.indexOf(":mysql:") > 0) {
            
            driver = System.getProperty(DRIVER_CLASS_NAME, "com.mysql.cj.jdbc.Driver");
            Class.forName(driver);
            
            ConnectionFactory connectionFactory =
                new DriverManagerConnectionFactory(url, mysqlConnectionProperties);
            return create(connectionFactory);
            
        } else {
            throw new RuntimeException("Cannot figure out how to instantiate this data source: " + url);
        }
    } catch (ClassNotFoundException e) {
        throw new RuntimeException("Cannot load driver class: " + driver);
    } catch (Exception exc) {
        throw new RuntimeException("Failed to create database source(" +
            url + ") with driver(" + driver + ")", exc);
    }
}
 
示例3
@Before
public void setUp() throws Exception {
	org.hsqldb.jdbc.JDBCDriver.class.newInstance();
	Properties connectionProps=new Properties();
	connectionProps.put("user", "SA");
	connectionProps.put("password", "");
	connectionProps.put("create", "true");
	
	ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(
			"jdbc:hsqldb:mem:my-sample",connectionProps);
	
	ObjectName poolName= poolName=new ObjectName("org.moneta", "connectionPool", "TestPool");
	poolableConnectionFactory=
			new PoolableConnectionFactory(connectionFactory,poolName);
	poolableConnectionFactory.setDefaultCatalog("PUBLIC");
	poolableConnectionFactory.setValidationQuery(VALIDATION_SQL);
	
	connectionPool = 
			new GenericObjectPool<PoolableConnection>(poolableConnectionFactory);
	poolableConnectionFactory.setPool(connectionPool);
	connectionPool.setMaxTotal(2);
	connectionPool.setMaxWaitMillis(400);
	
	healthCheck = new DbcpConnectionPoolHealthCheck(connectionPool, "mine");
}
 
示例4
@Override
public void start() {
    File databaseDir = new File(JiveGlobals.getHomeDirectory(), File.separator + "embedded-db");
    // If the database doesn't exist, create it.
    if (!databaseDir.exists()) {
        databaseDir.mkdirs();
    }

    try {
        serverURL = "jdbc:hsqldb:" + databaseDir.getCanonicalPath() + File.separator + "openfire";
    }
    catch (IOException ioe) {
        Log.error("EmbeddedConnectionProvider: Error starting connection pool: ", ioe);
    }
    final ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(serverURL, "sa", "");
    final PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null);
    poolableConnectionFactory.setMaxConnLifetimeMillis((long) (0.5 * JiveConstants.DAY));

    final GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
    poolConfig.setMinIdle(3);
    poolConfig.setMaxTotal(25);
    final GenericObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory, poolConfig);
    poolableConnectionFactory.setPool(connectionPool);
    dataSource = new PoolingDataSource<>(connectionPool);
}
 
示例5
/**
 * Creates a data source
 */
private static DataSource createDataSource(String uri, String username, String password,
                                           Integer maxActive, Integer maxIdle, Long maxWait,
                                           Long timeBtwnEvictionRuns, Long minEvictableIdleTime,
                                           Boolean testWhileIdle, Boolean testOnBorrow,
                                           String validationQuery, Integer isolationLevel) {
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(uri, username, password);
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null);
    GenericObjectPoolConfig config = createPoolConfig(maxActive, maxIdle, maxWait, timeBtwnEvictionRuns, minEvictableIdleTime, testWhileIdle, testOnBorrow);
    ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory, config);
    poolableConnectionFactory.setPool(connectionPool);
    if (validationQuery != null) {
        poolableConnectionFactory.setValidationQuery(validationQuery);
    }
    if (isolationLevel != null) {
        poolableConnectionFactory.setDefaultTransactionIsolation(isolationLevel);
    }
    return new PoolingDataSource<>(connectionPool);
}
 
示例6
@Override
protected ConnectionFactory createConnectionFactory() throws SQLException {
    final String xaDataSource = getXADataSource();
    if (xaDataSource != null & getXaDataSourceInstance() == null) {
        try {
            try {
                Thread.currentThread().getContextClassLoader().loadClass(xaDataSource);
            } catch (final ClassNotFoundException | NoClassDefFoundError cnfe) {
                setJndiXaDataSource(xaDataSource);
            }
        } catch (final Throwable th) {
            // no-op
        }
    }
    return super.createConnectionFactory();
}
 
示例7
@Override
public void start() throws SystemServiceStartException
{
    if (!atomicStarted.getAndSet(true))
    {
        Properties props = new Properties();
        if (linstorConfig.getDbUser() != null)
        {
            props.setProperty("user", linstorConfig.getDbUser());
        }
        if (linstorConfig.getDbPassword() != null)
        {
            props.setProperty("password", linstorConfig.getDbPassword());
        }
        ConnectionFactory connFactory = new DriverManagerConnectionFactory(dbConnectionUrl, props);
        PoolableConnectionFactory poolConnFactory = new PoolableConnectionFactory(connFactory, null);

        GenericObjectPoolConfig<PoolableConnection> poolConfig = new GenericObjectPoolConfig<>();
        poolConfig.setMinIdle(DEFAULT_MIN_IDLE_CONNECTIONS);
        poolConfig.setMaxIdle(DEFAULT_MAX_IDLE_CONNECTIONS);
        poolConfig.setBlockWhenExhausted(true);
        poolConfig.setFairness(true);
        GenericObjectPool<PoolableConnection> connPool = new GenericObjectPool<>(poolConnFactory, poolConfig);

        poolConnFactory.setPool(connPool);
        poolConnFactory.setValidationQueryTimeout(dbTimeout);
        poolConnFactory.setMaxOpenPreparedStatements(dbMaxOpen);
        poolConnFactory.setMaxConnLifetimeMillis(DEFAULT_IDLE_TIMEOUT);
        poolConnFactory.setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);

        dataSource = new PoolingDataSource<>(connPool);
    }
}
 
示例8
private static PoolingDataSource<PoolableConnection> initConnectionProvider(
    final String connUrl,
    final String user,
    final String password)
{
    Properties dbProps = new Properties();
    if (user != null)
    {
        dbProps.setProperty("user", user);
    }
    if (password != null)
    {
        dbProps.setProperty("password", password);
    }
    ConnectionFactory connFactory = new DriverManagerConnectionFactory(
        connUrl,
        dbProps
    );
    PoolableConnectionFactory poolConnFactory = new PoolableConnectionFactory(connFactory, null);

    GenericObjectPoolConfig<PoolableConnection> poolConfig = new GenericObjectPoolConfig<PoolableConnection>();
    poolConfig.setBlockWhenExhausted(true);
    poolConfig.setFairness(true);

    GenericObjectPool<PoolableConnection> connPool = new GenericObjectPool<>(poolConnFactory, poolConfig);

    poolConnFactory.setPool(connPool);

    return new PoolingDataSource<>(connPool);
}
 
示例9
static PoolableDataSource create(ConnectionFactory connectionFactory) {

        // setup our pool config object
        
        GenericObjectPoolConfig config = setupPoolConfig();
        
        PoolableConnectionFactory poolableConnectionFactory =
            new PoolableConnectionFactory(connectionFactory, null);
         
        // Set max lifetime of a connection in milli-secs, after which it will
        // always fail activation, passivation, and validation.
        // Value of -1 means infinite life time. The default value
        // defined in this class is 10 minutes.
        long connTtlMillis = retrieveConfigSetting(ATHENZ_PROP_DBPOOL_MAX_TTL, MAX_TTL_CONN_MS);
        poolableConnectionFactory.setMaxConnLifetimeMillis(connTtlMillis);
        if (LOG.isInfoEnabled()) {
            LOG.info("Setting Time-To-Live interval for live connections ({}) msecs", connTtlMillis);
        }

        // set the validation query for our jdbc connector
        final String validationQuery = System.getProperty(ATHENZ_PROP_DBPOOL_VALIDATION_QUERY, MYSQL_VALIDATION_QUERY);
        poolableConnectionFactory.setValidationQuery(validationQuery);

        ObjectPool<PoolableConnection> connectionPool =
                new GenericObjectPool<>(poolableConnectionFactory, config);
        poolableConnectionFactory.setPool(connectionPool);

        return new AthenzDataSource(connectionPool);
    }
 
示例10
private void createConnectionPool(String url, String user, String dbPrefix,
    Properties properties) throws SQLException, ClassNotFoundException {

  String driverClass = properties.getProperty(DRIVER_KEY);
  if (driverClass != null && (driverClass.equals("com.facebook.presto.jdbc.PrestoDriver")
          || driverClass.equals("io.prestosql.jdbc.PrestoDriver"))) {
    // Only add valid properties otherwise presto won't work.
    for (String key : properties.stringPropertyNames()) {
      if (!PRESTO_PROPERTIES.contains(key)) {
        properties.remove(key);
      }
    }
  }

  ConnectionFactory connectionFactory =
          new DriverManagerConnectionFactory(url, properties);

  PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(
          connectionFactory, null);
  final String maxConnectionLifetime =
      StringUtils.defaultIfEmpty(getProperty("zeppelin.jdbc.maxConnLifetime"), "-1");
  poolableConnectionFactory.setMaxConnLifetimeMillis(Long.parseLong(maxConnectionLifetime));
  poolableConnectionFactory.setValidationQuery("show databases");
  ObjectPool connectionPool = new GenericObjectPool(poolableConnectionFactory);

  poolableConnectionFactory.setPool(connectionPool);
  Class.forName(driverClass);
  PoolingDriver driver = new PoolingDriver();
  driver.registerPool(dbPrefix + user, connectionPool);
  getJDBCConfiguration(user).saveDBDriverPool(dbPrefix, driver);
}
 
示例11
@Override
public void start() {

    try {
        Class.forName(driver);
    } catch (final ClassNotFoundException e) {
        throw new RuntimeException("Unable to find JDBC driver " + driver, e);
    }

    final ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(serverURL, username, password);
    final PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null);
    poolableConnectionFactory.setValidationQuery(testSQL);
    poolableConnectionFactory.setValidationQueryTimeout(testTimeout);
    poolableConnectionFactory.setMaxConnLifetimeMillis((long) (connectionTimeout * JiveConstants.DAY));

    final GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
    poolConfig.setTestOnBorrow(testBeforeUse);
    poolConfig.setTestOnReturn(testAfterUse);
    poolConfig.setMinIdle(minConnections);
    if( minConnections > GenericObjectPoolConfig.DEFAULT_MAX_IDLE )
    {
        poolConfig.setMaxIdle(minConnections);
    }
    poolConfig.setMaxTotal(maxConnections);
    poolConfig.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRuns);
    poolConfig.setSoftMinEvictableIdleTimeMillis(minIdleTime);
    poolConfig.setMaxWaitMillis(maxWaitTime);
    connectionPool = new GenericObjectPool<>(poolableConnectionFactory, poolConfig);
    poolableConnectionFactory.setPool(connectionPool);
    dataSource = new PoolingDataSource<>(connectionPool);
}
 
示例12
@SuppressWarnings({"unchecked", "rawtypes"})
private static DataSource getDefaultDataSource(final String database) {
    final ConnectionFactory connectionFactory = new DriverManagerConnectionFactory("jdbc:mysql://localhost:3306/" + database, "cloud", "cloud");
    final PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null);
    final GenericObjectPool connectionPool = new GenericObjectPool(poolableConnectionFactory);
    return new PoolingDataSource(connectionPool);
}
 
示例13
@Override
protected ConnectionFactory createConnectionFactory() throws SQLException {
    if (delegate != null) {
        if (XADataSource.class.isInstance(delegate)) {
            return new DataSourceXAConnectionFactory(OpenEJB.getTransactionManager(), XADataSource.class.cast(delegate), getUsername(), getPassword());
        }
        return new DataSourceConnectionFactory(DataSource.class.cast(delegate), getUsername(), getPassword());
    }
    return super.createConnectionFactory();
}
 
示例14
@BeforeEach
public void setUp() throws Exception {
    // create a GeronimoTransactionManager for testing
    transactionManager = new TransactionManagerImpl();

    // create a driver connection factory
    final Properties properties = new Properties();
    properties.setProperty("user", "userName");
    properties.setProperty("password", "password");
    final ConnectionFactory connectionFactory = new DriverConnectionFactory(new TesterDriver(), "jdbc:apache:commons:testdriver", properties);

    // wrap it with a LocalXAConnectionFactory
    final XAConnectionFactory xaConnectionFactory = new LocalXAConnectionFactory(transactionManager, connectionFactory);

    // create the pool object factory
    final PoolableConnectionFactory factory =
        new PoolableConnectionFactory(xaConnectionFactory, null);
    factory.setValidationQuery("SELECT DUMMY FROM DUAL");
    factory.setDefaultReadOnly(Boolean.TRUE);
    factory.setDefaultAutoCommit(Boolean.TRUE);

    // create the pool
    pool = new GenericObjectPool<>(factory);
    factory.setPool(pool);
    pool.setMaxTotal(getMaxTotal());
    pool.setMaxWaitMillis(getMaxWaitMillis());

    // finally create the datasource
    ds = new ManagedDataSource<>(pool, xaConnectionFactory.getTransactionRegistry());
    ds.setAccessToUnderlyingConnectionAllowed(true);
}
 
示例15
@BeforeEach
public void setUp()
    throws Exception {
    // create a GeronimoTransactionManager for testing
    transactionManager = new TransactionManagerImpl();

    // create a driver connection factory
    final Properties properties = new Properties();
    properties.setProperty("user", "userName");
    properties.setProperty("password", "password");
    final ConnectionFactory connectionFactory = new DriverConnectionFactory(new TesterDriver(), "jdbc:apache:commons:testdriver", properties);

    // wrap it with a LocalXAConnectionFactory
    final XAConnectionFactory xaConnectionFactory = new UncooperativeLocalXAConnectionFactory(transactionManager, connectionFactory);

    // create the pool object factory
    final PoolableConnectionFactory factory = new PoolableConnectionFactory(xaConnectionFactory, null);
    factory.setValidationQuery("SELECT DUMMY FROM DUAL");
    factory.setDefaultReadOnly(Boolean.TRUE);
    factory.setDefaultAutoCommit(Boolean.TRUE);

    // create the pool
    pool = new GenericObjectPool<>(factory);
    factory.setPool(pool);
    pool.setMaxTotal(10);
    pool.setMaxWaitMillis(100);

    // finally create the datasource
    ds = new ManagedDataSource<>(pool, xaConnectionFactory.getTransactionRegistry());
    ds.setAccessToUnderlyingConnectionAllowed(true);
}
 
示例16
public UncooperativeLocalXAConnectionFactory(final TransactionManager transactionManager, final ConnectionFactory connectionFactory) {
    super(transactionManager, connectionFactory);

    try {
        // inject our own TransactionRegistry which returns Uncooperative Transactions which always fail to enlist a XAResource
        final Field field = LocalXAConnectionFactory.class.getDeclaredField("transactionRegistry");
        field.setAccessible(true);
        field.set(this, new UncooperativeTransactionRegistry(transactionManager));
    } catch (final Exception e) {
        e.printStackTrace();
    }
}
 
示例17
@BeforeEach
public void setUp() throws Exception {
    // create a GeronimoTransactionManager for testing
    transactionManager = new TransactionManagerImpl();

    // create a driver connection factory
    final Properties properties = new Properties();
    properties.setProperty("user", "userName");
    properties.setProperty("password", "password");
    final ConnectionFactory connectionFactory = new DriverConnectionFactory(new TesterDriver(), "jdbc:apache:commons:testdriver", properties);

    // wrap it with a LocalXAConnectionFactory
    final XAConnectionFactory xaConnectionFactory = new LocalXAConnectionFactory(transactionManager, connectionFactory);

    // create transaction registry
    transactionRegistry = xaConnectionFactory.getTransactionRegistry();

    // create the pool object factory
    final PoolableConnectionFactory factory = new PoolableConnectionFactory(xaConnectionFactory, null);
    factory.setValidationQuery("SELECT DUMMY FROM DUAL");
    factory.setDefaultReadOnly(Boolean.TRUE);
    factory.setDefaultAutoCommit(Boolean.TRUE);

    // create the pool
    pool = new GenericObjectPool<>(factory);
    factory.setPool(pool);
    pool.setMaxTotal(10);
    pool.setMaxWaitMillis(100);
}
 
示例18
@Override
protected ConnectionFactory createConnectionFactory() throws SQLException {
    return new DataSourceConnectionFactory(this.ds, getUsername(), getPassword());
}
 
示例19
public static DataSource setupDataSource(String connectURI) {
    //
    // First, we'll create a ConnectionFactory that the
    // pool will use to create Connections.
    // We'll use the DriverManagerConnectionFactory,
    // using the connect string passed in the command line
    // arguments.
    //
    ConnectionFactory connectionFactory =
        new DriverManagerConnectionFactory(connectURI,null);

    //
    // Next we'll 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, null);

    //
    // Now 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.
    //
    ObjectPool<PoolableConnection> connectionPool =
            new GenericObjectPool<>(poolableConnectionFactory);
    
    // Set the factory's pool property to the owning pool
    poolableConnectionFactory.setPool(connectionPool);

    //
    // Finally, we create the PoolingDriver itself,
    // passing in the object pool we created.
    //
    PoolingDataSource<PoolableConnection> dataSource =
            new PoolingDataSource<>(connectionPool);

    return dataSource;
}
 
示例20
public static void setupDriver(String connectURI) throws Exception {
    //
    // First, we'll create a ConnectionFactory that the
    // pool will use to create Connections.
    // We'll use the DriverManagerConnectionFactory,
    // using the connect string passed in the command line
    // arguments.
    //
    ConnectionFactory connectionFactory =
        new DriverManagerConnectionFactory(connectURI,null);

    //
    // Next, we'll 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, null);

    //
    // Now 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.
    //
    ObjectPool<PoolableConnection> connectionPool =
        new GenericObjectPool<>(poolableConnectionFactory);
    
    // Set the factory's pool property to the owning pool
    poolableConnectionFactory.setPool(connectionPool);

    //
    // Finally, we create the PoolingDriver itself...
    //
    Class.forName("org.apache.commons.dbcp2.PoolingDriver");
    PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");

    //
    // ...and register our pool with it.
    //
    driver.registerPool("example",connectionPool);

    //
    // Now we can just use the connect string "jdbc:apache:commons:dbcp:example"
    // to access our pool of Connections.
    //
}
 
示例21
/**
 * Set up a connection pool. The driver used in the connection URI should
 * already be loaded using
 * Class.forName("org.apache.commons.dbcp2.PoolingDriver"); After calling
 * this you can use "jdbc:apache:commons:dbcp:FROST-Pool" to connect.
 *
 * @param name The name of the pool to create.
 * @param connectURI The URL of the database to connect to.
 * @param username The username to use when connecting to the database.
 * @param password The password to use when connecting to the database.
 * @throws ClassNotFoundException If the PoolingDriver is not on the
 * classpath.
 * @throws SQLException If the dbcp driver could not be loaded.
 */
public static void setupPoolingDriver(String name, String connectURI, String username, String password) throws ClassNotFoundException, SQLException {
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectURI, username, password);
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, null);
    ObjectPool<PoolableConnection> connectionPool = new GenericObjectPool<>(poolableConnectionFactory);
    poolableConnectionFactory.setPool(connectionPool);
    Class.forName("org.apache.commons.dbcp2.PoolingDriver");
    PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");
    driver.registerPool(name, connectionPool);
}
 
示例22
/**
 * Creates an LocalXAConnectionFactory which uses the specified connection factory to create database connections.
 * The connections are enlisted into transactions using the specified transaction manager.
 *
 * @param transactionManager
 *            the transaction manager in which connections will be enlisted
 * @param transactionSynchronizationRegistry
 *            the optional TSR to register synchronizations with
 * @param connectionFactory
 *            the connection factory from which connections will be retrieved
 * @since 2.8.0
 */
public LocalXAConnectionFactory(final TransactionManager transactionManager,
        final TransactionSynchronizationRegistry transactionSynchronizationRegistry,
        final ConnectionFactory connectionFactory) {
    Objects.requireNonNull(transactionManager, "transactionManager is null");
    Objects.requireNonNull(connectionFactory, "connectionFactory is null");
    this.transactionRegistry = new TransactionRegistry(transactionManager, transactionSynchronizationRegistry);
    this.connectionFactory = connectionFactory;
}
 
示例23
/**
 * Creates an LocalXAConnectionFactory which uses the specified connection factory to create database connections.
 * The connections are enlisted into transactions using the specified transaction manager.
 *
 * @param transactionManager
 *            the transaction manager in which connections will be enlisted
 * @param connectionFactory
 *            the connection factory from which connections will be retrieved
 */
public LocalXAConnectionFactory(final TransactionManager transactionManager,
        final ConnectionFactory connectionFactory) {
    this(transactionManager, null, connectionFactory);
}
 
示例24
/**
 * @return The connection factory.
 * @since 2.6.0
 */
public ConnectionFactory getConnectionFactory() {
    return connectionFactory;
}