Java Code Examples for org.apache.commons.dbcp2.BasicDataSource#setDriverClassName()

The following examples show how to use org.apache.commons.dbcp2.BasicDataSource#setDriverClassName() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DatabaseConnectionFactoryTest.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
@Test
public void testOpenConnectionToSqliteDbHavingAllSupportedPersistenceProperties() throws Exception {
    // This test is about a fall back functionality
    // GIVEN
    final File dbFile = folder.newFile("test.db");

    final BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(SQLITE_DRIVER_CLASS_PROP_VALUE);
    ds.setUsername(USERNAME_PROP_VALUE);
    ds.setPassword(PASSWORD_PROP_VALUE);
    ds.setUrl(SQLITE_CONNECTION_URL_PROP_PREFIX + dbFile.getAbsolutePath());

    // WHEN
    connection = DatabaseConnectionFactory.openConnection(ds);

    // THEN
    assertThat(connection, notNullValue());
    assertThat(connection.getClass(), equalTo(DatabaseConnection.class));
}
 
Example 2
Source File: ConfigTestUtils.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void createDatasource(String dsNameControlKey, SimpleNamingContextBuilder builder, Properties testConfig) {
    String beanName = testConfig.getProperty("jdbc." + dsNameControlKey + ".beanName");
    try {
        String className = testConfig.getProperty("jdbc." + dsNameControlKey + ".driverClassName");
        String url = testConfig.getProperty("jdbc." + dsNameControlKey + ".url");
        String username = testConfig.getProperty("jdbc." + dsNameControlKey + ".username");
        String password = testConfig.getProperty("jdbc." + dsNameControlKey + ".password");
        Class.forName(className);
        BasicDataSource ds = new BasicDataSource();
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        ds.setMaxTotal(12);
        ds.setMaxIdle(4);
        ds.setDriverClassName(className);
        builder.bind("java:comp/env/jdbc/" + beanName, ds);
    } catch (Throwable t) {
        throw new RuntimeException("Error on creation datasource '" + beanName + "'", t);
    }
}
 
Example 3
Source File: ConcurrentQueryTest.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
@SuppressWarnings({ "resource", "unused", "rawtypes" })
@BeforeClass
public static void setUpBeforeClass() throws Exception {

	dataSource = new BasicDataSource();
	assertNotNull("Connection correctly established", dataSource);
	dataSource.setDriverClassName("com.mysql.jdbc.Driver");
	dataSource.setUrl("jdbc:mysql://localhost/foodmart_key");
	dataSource.setUsername("root");
	dataSource.setPassword("lancer");
	dataSource.setDefaultAutoCommit(false);
	dataSource.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
	// dataSource.setInitialSize(100);

	tasks = new ArrayList<ConcurrentQuery>();
	executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * SCALE_FACTOR);

	values = getPlainValues(null);

	results = new HashSet<String>();
}
 
Example 4
Source File: SqlDbConfiguration.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
public DataSource createDataSource() {
    final String driverClass = (String) dbConfig.get("javax.persistence.jdbc.driver");
    final String connectionUrl = (String) dbConfig.get("javax.persistence.jdbc.url");
    final String username = (String) dbConfig.get("javax.persistence.jdbc.user");
    final String password = (String) dbConfig.get("javax.persistence.jdbc.password");

    final BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(driverClass);
    ds.setUsername(username);
    ds.setPassword(password);
    ds.setUrl(connectionUrl);
    ds.setMinIdle(1);
    ds.setMaxIdle(2);

    return ds;
}
 
Example 5
Source File: TestEntandoJndiUtils.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static void createDatasource(String dsNameControlKey, SimpleNamingContextBuilder builder, Properties testConfig) {
    String beanName = testConfig.getProperty("jdbc." + dsNameControlKey + ".beanName");
    try {
        String className = testConfig.getProperty("jdbc." + dsNameControlKey + ".driverClassName");
        String url = testConfig.getProperty("jdbc." + dsNameControlKey + ".url");
        String username = testConfig.getProperty("jdbc." + dsNameControlKey + ".username");
        String password = testConfig.getProperty("jdbc." + dsNameControlKey + ".password");
        Class.forName(className);
        BasicDataSource ds = new BasicDataSource();
        ds.setUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        ds.setMaxTotal(12);
        ds.setMaxIdle(4);
        ds.setDriverClassName(className);
        builder.bind("java:comp/env/jdbc/" + beanName, ds);
    } catch (Throwable t) {
        throw new RuntimeException("Error on creation datasource '" + beanName + "'", t);
    }
    logger.debug("created datasource {}", beanName);
}
 
Example 6
Source File: DataSourceDecoratorAutoConfigurationTests.java    From spring-boot-data-source-decorator with Apache License 2.0 5 votes vote down vote up
@Bean
public DataSource dataSource() {
    BasicDataSource pool = new BasicDataSource();
    pool.setDriverClassName("org.hsqldb.jdbcDriver");
    pool.setUrl("jdbc:hsqldb:target/overridedb");
    pool.setUsername("sa");
    return pool;
}
 
Example 7
Source File: MyDataSourceFactory.java    From spring-boot with Apache License 2.0 5 votes vote down vote up
protected static DataSource getDBCP2DataSource2() {
    //创建BasicDataSource类对象
    BasicDataSource datasource = new BasicDataSource();
    //数据库连接信息(必须)
    datasource.setDriverClassName("com.mysql.jdbc.Driver");
    datasource.setUrl("jdbc:mysql://129.9.100.16:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false");
    datasource.setUsername("test");
    datasource.setPassword("123456");
    //连接池中的连接数量配置(可选)
    datasource.setInitialSize(10);//初始化的连接数
    datasource.setMaxOpenPreparedStatements(8);//最大连接数
    datasource.setMaxIdle(5);//最大空闲连接
    datasource.setMinIdle(1);//最小空闲连接
    return datasource;
}
 
Example 8
Source File: DatabaseConfigurationTestHelper.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the internal data source. This method also initializes the
 * database.
 *
 * @return the data source
 * @throws Exception if an error occurs
 */
private DataSource setUpDataSource() throws Exception
{
    final BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(DATABASE_DRIVER);
    ds.setUrl(DATABASE_URL);
    ds.setUsername(DATABASE_USERNAME);
    ds.setPassword(DATABASE_PASSWORD);
    ds.setDefaultAutoCommit(!isAutoCommit());

    // prepare the database
    final Connection conn = ds.getConnection();
    final IDatabaseConnection connection = new DatabaseConnection(conn);
    final IDataSet dataSet = new XmlDataSet(new FileInputStream(
            ConfigurationAssert.getTestFile("dataset.xml")));

    try
    {
        DatabaseOperation.CLEAN_INSERT.execute(connection, dataSet);
    }
    finally
    {
        if (!isAutoCommit())
        {
            conn.commit();
        }
        connection.close();
    }

    return ds;
}
 
Example 9
Source File: ConfigCenterTest.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
private DataSource createDataSourceWithConnectionInitSqls(final String name) {
    BasicDataSource result = new BasicDataSource();
    result.setDriverClassName("com.mysql.jdbc.Driver");
    result.setUrl("jdbc:mysql://localhost:3306/" + name);
    result.setUsername("root");
    result.setPassword("root");
    result.setConnectionInitSqls(Arrays.asList("set names utf8mb4;", "set names utf8;"));
    return result;
}
 
Example 10
Source File: DBCPDataSourceServiceImporter.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Override
protected BasicDataSource setupDataSourcePool( DataSourceConfiguration config )
        throws Exception
{
    BasicDataSource pool = new BasicDataSource();

    Class.forName( config.driver().get() );
    pool.setDriverClassName( config.driver().get() );
    pool.setUrl( config.url().get() );

    if ( !config.username().get().equals( "" ) ) {
        pool.setUsername( config.username().get() );
        pool.setPassword( config.password().get() );
    }

    if ( config.minPoolSize().get() != null ) {
        pool.setMinIdle( config.minPoolSize().get() );
    }
    if ( config.maxPoolSize().get() != null ) {
        pool.setMaxTotal( config.maxPoolSize().get() );
    }
    if ( config.loginTimeoutSeconds().get() != null ) {
        pool.setLoginTimeout( config.loginTimeoutSeconds().get() );
    }
    if ( config.maxConnectionAgeSeconds().get() != null ) {
        pool.setMinEvictableIdleTimeMillis( config.maxConnectionAgeSeconds().get() * 1000 );
    }
    if ( config.validationQuery().get() != null ) {
        pool.setValidationQuery( config.validationQuery().get() );
    }

    return pool;
}
 
Example 11
Source File: ConnectionUtils.java    From simpleci with MIT License 5 votes vote down vote up
public static DataSource createDataSource(String host, int port, String name, String user, String password) {
    BasicDataSource bds = new BasicDataSource();

    bds.setDriverClassName("com.mysql.jdbc.Driver");
    bds.setUrl(String.format("jdbc:mysql://%s:%d/%s", host, port, name));
    bds.setUsername(user);
    bds.setPassword(password);
    bds.setInitialSize(5);

    return bds;
}
 
Example 12
Source File: DataSourceUtil.java    From skywalking with Apache License 2.0 5 votes vote down vote up
public static void createDataSource(final String dataSourceName) {
    BasicDataSource result = new BasicDataSource();
    result.setDriverClassName("org.h2.Driver");
    result.setUrl(String.format("jdbc:h2:mem:%s", dataSourceName));
    result.setUsername("sa");
    result.setPassword("");
    datasourceMap.put(dataSourceName, result);
}
 
Example 13
Source File: DataSourceConverterTest.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
private DataSource createDataSource(final String name) {
    BasicDataSource result = new BasicDataSource();
    result.setDriverClassName("com.mysql.jdbc.Driver");
    result.setUrl("jdbc:mysql://localhost:3306/" + name);
    result.setUsername("root");
    result.setPassword("root");
    return result;
}
 
Example 14
Source File: DBCPDataSourceBuilder.java    From micro-server with Apache License 2.0 5 votes vote down vote up
private DataSource getDataSource() {
	BasicDataSource ds = new BasicDataSource();

	ds.setDriverClassName(mainEnv.getDriverClassName());
	ds.setUrl(mainEnv.getUrl());
	ds.setUsername(mainEnv.getUsername());
	ds.setPassword(mainEnv.getPassword());

	retrySetup(ds);

	return ds;
}
 
Example 15
Source File: AbstractSpringJUnitTest.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
private DataSource createDataSource(final String dataSetFile) {
    BasicDataSource result = new BasicDataSource();
    result.setDriverClassName(org.h2.Driver.class.getName());
    result.setUrl(String.format("jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL", getFileName(dataSetFile)));
    result.setUsername("sa");
    result.setPassword("");
    result.setMaxTotal(100);
    return result;
}
 
Example 16
Source File: AbstractYamlDataSourceTest.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
protected static DataSource createDataSource(final String dsName) {
    BasicDataSource result = new BasicDataSource();
    result.setDriverClassName(org.h2.Driver.class.getName());
    result.setUrl(String.format("jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL", dsName));
    result.setUsername("sa");
    result.setMaxTotal(100);
    return result;
}
 
Example 17
Source File: DataSourceUtil.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
private static DataSource createDBCP(final DatabaseType databaseType, final String dataSourceName) {
    BasicDataSource result = new BasicDataSource();
    DatabaseEnvironment databaseEnvironment = IntegrateTestEnvironment.getInstance().getDatabaseEnvironments().get(databaseType);
    result.setDriverClassName(databaseEnvironment.getDriverClassName());
    result.setUrl(null == dataSourceName ? databaseEnvironment.getURL() : databaseEnvironment.getURL(dataSourceName));
    result.setUsername(databaseEnvironment.getUsername());
    result.setPassword(databaseEnvironment.getPassword());
    result.setMaxTotal(2);
    result.setValidationQuery("SELECT 1");
    if ("Oracle".equals(databaseType.getName())) {
        result.setConnectionInitSqls(Collections.singleton("ALTER SESSION SET CURRENT_SCHEMA = " + dataSourceName));
    }
    return result;
}
 
Example 18
Source File: SpringBootJNDITest.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
private static DataSource createNewDataSource(final String dsName) {
    BasicDataSource result = new BasicDataSource();
    result.setUrl(String.format(TEST_DATASOURCE_URL, dsName));
    result.setUsername("sa");
    result.setPassword("");
    result.setDriverClassName("org.h2.Driver");
    return result;
}
 
Example 19
Source File: ActiveSchemaManager.java    From replicator with Apache License 2.0 5 votes vote down vote up
private BasicDataSource getDataSource(String driverClass, String hostname, int port, String username, String password) {
    BasicDataSource dataSource = new BasicDataSource();

    dataSource.setDriverClassName(driverClass);
    dataSource.setUrl(String.format(ActiveSchemaManager.BARE_CONNECTION_URL_FORMAT, hostname, port));
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    dataSource.setTestOnBorrow(true);
    return dataSource;
}
 
Example 20
Source File: DynamicJdbcIO.java    From DataflowTemplates with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
DataSource buildDatasource() {
  BasicDataSource basicDataSource = new BasicDataSource();
  if (getDriverClassName() != null) {
    if (getDriverClassName().get() == null) {
      throw new RuntimeException("Driver class name is required.");
    }
    basicDataSource.setDriverClassName(getDriverClassName().get());
  }
  if (getUrl() != null) {
    if (getUrl().get() == null) {
      throw new RuntimeException("Connection url is required.");
    }
    basicDataSource.setUrl(getUrl().get());
  }
  if (getUsername() != null) {
    basicDataSource.setUsername(getUsername().get());
  }
  if (getPassword() != null) {
    basicDataSource.setPassword(getPassword().get());
  }
  if (getConnectionProperties() != null && getConnectionProperties().get() != null) {
    basicDataSource.setConnectionProperties(getConnectionProperties().get());
  }

  /**
   * Since the jdbc connection connection class might have dependencies that are not available
   * to the template, we will localize the user provided dependencies from GCS and create a new
   * {@link URLClassLoader} that is added to the {@link
   * BasicDataSource#setDriverClassLoader(ClassLoader)}
   */
  if (getDriverJars() != null) {
    ClassLoader urlClassLoader = getNewClassLoader(getDriverJars());
    basicDataSource.setDriverClassLoader(urlClassLoader);
  }

  // wrapping the datasource as a pooling datasource
  DataSourceConnectionFactory connectionFactory =
      new DataSourceConnectionFactory(basicDataSource);
  PoolableConnectionFactory poolableConnectionFactory =
      new PoolableConnectionFactory(connectionFactory, null);
  GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
  poolConfig.setMaxTotal(1);
  poolConfig.setMinIdle(0);
  poolConfig.setMinEvictableIdleTimeMillis(10000);
  poolConfig.setSoftMinEvictableIdleTimeMillis(30000);
  GenericObjectPool connectionPool =
      new GenericObjectPool(poolableConnectionFactory, poolConfig);
  poolableConnectionFactory.setPool(connectionPool);
  poolableConnectionFactory.setDefaultAutoCommit(false);
  poolableConnectionFactory.setDefaultReadOnly(false);
  PoolingDataSource poolingDataSource = new PoolingDataSource(connectionPool);
  return poolingDataSource;
}