Java Code Examples for org.apache.commons.dbcp.BasicDataSource

The following examples show how to use org.apache.commons.dbcp.BasicDataSource. These examples are extracted from open source projects. 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
/**
 * Get the job event rdb config.
 *
 * @return job event rdb config
 */
public Optional<JobEventRdbConfiguration> getJobEventRdbConfiguration() {
    String driver = getValue(EnvironmentArgument.EVENT_TRACE_RDB_DRIVER);
    String url = getValue(EnvironmentArgument.EVENT_TRACE_RDB_URL);
    String username = getValue(EnvironmentArgument.EVENT_TRACE_RDB_USERNAME);
    String password = getValue(EnvironmentArgument.EVENT_TRACE_RDB_PASSWORD);
    if (!Strings.isNullOrEmpty(driver) && !Strings.isNullOrEmpty(url) && !Strings.isNullOrEmpty(username)) {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return Optional.of(new JobEventRdbConfiguration(dataSource));
    }
    return Optional.absent();
}
 
Example 2
Source Project: incubator-gobblin   Source File: MysqlStateStore.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * creates a new {@link BasicDataSource}
 * @param config the properties used for datasource instantiation
 * @return
 */
public static BasicDataSource newDataSource(Config config) {
  BasicDataSource basicDataSource = new BasicDataSource();
  PasswordManager passwordManager = PasswordManager.getInstance(ConfigUtils.configToProperties(config));

  basicDataSource.setDriverClassName(ConfigUtils.getString(config, ConfigurationKeys.STATE_STORE_DB_JDBC_DRIVER_KEY,
      ConfigurationKeys.DEFAULT_STATE_STORE_DB_JDBC_DRIVER));
  // MySQL server can timeout a connection so need to validate connections before use
  basicDataSource.setValidationQuery("select 1");
  basicDataSource.setTestOnBorrow(true);
  basicDataSource.setDefaultAutoCommit(false);
  basicDataSource.setTimeBetweenEvictionRunsMillis(60000);
  basicDataSource.setUrl(config.getString(ConfigurationKeys.STATE_STORE_DB_URL_KEY));
  basicDataSource.setUsername(passwordManager.readPassword(
      config.getString(ConfigurationKeys.STATE_STORE_DB_USER_KEY)));
  basicDataSource.setPassword(passwordManager.readPassword(
      config.getString(ConfigurationKeys.STATE_STORE_DB_PASSWORD_KEY)));
  basicDataSource.setMinEvictableIdleTimeMillis(
      ConfigUtils.getLong(config, ConfigurationKeys.STATE_STORE_DB_CONN_MIN_EVICTABLE_IDLE_TIME_KEY,
          ConfigurationKeys.DEFAULT_STATE_STORE_DB_CONN_MIN_EVICTABLE_IDLE_TIME));

  return basicDataSource;
}
 
Example 3
@Test
public void testDifferentKey() throws IOException {

  Config config1 = ConfigFactory.parseMap(ImmutableMap.of(ConfigurationKeys.STATE_STORE_DB_URL_KEY, "url1",
      ConfigurationKeys.STATE_STORE_DB_USER_KEY, "user",
      ConfigurationKeys.STATE_STORE_DB_PASSWORD_KEY, "dummypwd"));

  Config config2 = ConfigFactory.parseMap(ImmutableMap.of(ConfigurationKeys.STATE_STORE_DB_URL_KEY, "url2",
      ConfigurationKeys.STATE_STORE_DB_USER_KEY, "user",
      ConfigurationKeys.STATE_STORE_DB_PASSWORD_KEY, "dummypwd"));

  BasicDataSource basicDataSource1 = MysqlDataSourceFactory.get(config1,
      SharedResourcesBrokerFactory.getImplicitBroker());

  BasicDataSource basicDataSource2 = MysqlDataSourceFactory.get(config2,
      SharedResourcesBrokerFactory.getImplicitBroker());

  Assert.assertNotEquals(basicDataSource1, basicDataSource2);
}
 
Example 4
Source Project: diamond   Source File: PersistService.java    License: Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void initDataSource() throws Exception {
    // 读取jdbc.properties配置, 加载数据源
    Properties props = ResourceUtils.getResourceAsProperties("jdbc.properties");
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(JDBC_DRIVER_NAME);
    ds.setUrl(ensurePropValueNotNull(props.getProperty("db.url")));
    ds.setUsername(ensurePropValueNotNull(props.getProperty("db.user")));
    ds.setPassword(ensurePropValueNotNull(props.getProperty("db.password")));
    ds.setInitialSize(Integer.parseInt(ensurePropValueNotNull(props.getProperty("db.initialSize"))));
    ds.setMaxActive(Integer.parseInt(ensurePropValueNotNull(props.getProperty("db.maxActive"))));
    ds.setMaxIdle(Integer.parseInt(ensurePropValueNotNull(props.getProperty("db.maxIdle"))));
    ds.setMaxWait(Long.parseLong(ensurePropValueNotNull(props.getProperty("db.maxWait"))));
    ds.setPoolPreparedStatements(Boolean.parseBoolean(ensurePropValueNotNull(props
        .getProperty("db.poolPreparedStatements"))));

    this.jt = new JdbcTemplate();
    this.jt.setDataSource(ds);
    // 设置最大记录数,防止内存膨胀
    this.jt.setMaxRows(MAX_ROWS);
    // 设置JDBC执行超时时间
    this.jt.setQueryTimeout(QUERY_TIMEOUT);
}
 
Example 5
Source Project: incubator-gobblin   Source File: MysqlDagStateStoreTest.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected StateStore<State> createStateStore(Config config) {
  try {
    // Setting up mock DB
    ITestMetastoreDatabase testMetastoreDatabase = TestMetastoreDatabaseFactory.get();
    String jdbcUrl = testMetastoreDatabase.getJdbcUrl();
    BasicDataSource mySqlDs = new BasicDataSource();

    mySqlDs.setDriverClassName(ConfigurationKeys.DEFAULT_STATE_STORE_DB_JDBC_DRIVER);
    mySqlDs.setDefaultAutoCommit(false);
    mySqlDs.setUrl(jdbcUrl);
    mySqlDs.setUsername(TEST_USER);
    mySqlDs.setPassword(TEST_PASSWORD);

    return new MysqlStateStore<>(mySqlDs, TEST_DAG_STATE_STORE, false, State.class);
  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}
 
Example 6
Source Project: gemfirexd-oss   Source File: TestTaskBase.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns an instance of the {@link DdlToDatabaseTask}, already configured with
 * a project and the tested database.
 * 
 * @return The task object
 */
protected DdlToDatabaseTask getDdlToDatabaseTaskInstance()
{
    DdlToDatabaseTask task       = new DdlToDatabaseTask();
    Properties        props      = getTestProperties();
    String            catalog    = props.getProperty(DDLUTILS_CATALOG_PROPERTY);
    String            schema     = props.getProperty(DDLUTILS_SCHEMA_PROPERTY);
    DataSource        dataSource = getDataSource();

    if (!(dataSource instanceof BasicDataSource))
    {
        fail("Datasource needs to be of type " + BasicDataSource.class.getName());
    }
    task.setProject(new Project());
    task.addConfiguredDatabase((BasicDataSource)getDataSource());
    task.setCatalogPattern(catalog);
    task.setSchemaPattern(schema);
    task.setUseDelimitedSqlIdentifiers(isUseDelimitedIdentifiers());
    return task;
}
 
Example 7
Source Project: incubator-gobblin   Source File: DataSourceProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Inject
public DataSourceProvider(@Named("dataSourceProperties") Properties properties) {
  this.basicDataSource = new BasicDataSource();
  this.basicDataSource.setDriverClassName(properties.getProperty(CONN_DRIVER, DEFAULT_CONN_DRIVER));
  this.basicDataSource.setUrl(properties.getProperty(CONN_URL));
  if (properties.containsKey(USERNAME) && properties.containsKey(PASSWORD)) {
    this.basicDataSource.setUsername(properties.getProperty(USERNAME));
    this.basicDataSource
        .setPassword(PasswordManager.getInstance(properties).readPassword(properties.getProperty(PASSWORD)));
  }
  if (properties.containsKey(MAX_IDLE_CONNS)) {
    this.basicDataSource.setMaxIdle(Integer.parseInt(properties.getProperty(MAX_IDLE_CONNS)));
  }
  if (properties.containsKey(MAX_ACTIVE_CONNS)) {
    this.basicDataSource.setMaxActive(Integer.parseInt(properties.getProperty(MAX_ACTIVE_CONNS)));
  }
}
 
Example 8
Source Project: teaching   Source File: DynamicDBUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
     * 获取数据源【最底层方法,不要随便调用】
     *
     * @param dbSource
     * @return
     */
    @Deprecated
    private static BasicDataSource getJdbcDataSource(final DynamicDataSourceModel dbSource) {
        BasicDataSource dataSource = new BasicDataSource();

        String driverClassName = dbSource.getDbDriver();
        String url = dbSource.getDbUrl();
        String dbUser = dbSource.getDbUsername();
        String dbPassword = dbSource.getDbPassword();
        //设置数据源的时候,要重新解密
//		String dbPassword  = PasswordUtil.decrypt(dbSource.getDbPassword(), dbSource.getDbUsername(), PasswordUtil.getStaticSalt());//解密字符串;
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(dbUser);
        dataSource.setPassword(dbPassword);
        return dataSource;
    }
 
Example 9
Source Project: kylin   Source File: JdbcPushDownConnectionManager.java    License: Apache License 2.0 6 votes vote down vote up
private JdbcPushDownConnectionManager(KylinConfig config, String id) throws ClassNotFoundException {
    dataSource = new BasicDataSource();

    Class.forName(config.getJdbcDriverClass(id));
    dataSource.setDriverClassName(config.getJdbcDriverClass(id));
    dataSource.setUrl(config.getJdbcUrl(id));
    dataSource.setUsername(config.getJdbcUsername(id));
    dataSource.setPassword(config.getJdbcPassword(id));
    dataSource.setMaxActive(config.getPoolMaxTotal(id));
    dataSource.setMaxIdle(config.getPoolMaxIdle(id));
    dataSource.setMinIdle(config.getPoolMinIdle(id));

    // Default settings
    dataSource.setTestOnBorrow(true);
    dataSource.setValidationQuery("select 1");
    dataSource.setRemoveAbandoned(true);
    dataSource.setRemoveAbandonedTimeout(300);
}
 
Example 10
Source Project: oxd   Source File: JDBCPersistenceProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onCreate() {
    try {
        JDBCConfiguration jdbcConfiguration = asJDBCConfiguration(configurationService.getConfiguration());
        validate(jdbcConfiguration);

        dataSource = new BasicDataSource();
        dataSource.setDriverClassName(jdbcConfiguration.getDriver());
        dataSource.setUrl(jdbcConfiguration.getJdbcUrl());
        dataSource.setUsername(jdbcConfiguration.getUsername());
        dataSource.setPassword(jdbcConfiguration.getPassword());

        dataSource.setMinIdle(5);
        dataSource.setMaxIdle(10);
        dataSource.setMaxOpenPreparedStatements(100);
    } catch (Exception e) {
        LOG.error("Error in creating jdbc connection.", e);
        throw new RuntimeException(e);
    }
}
 
Example 11
Source Project: eagle   Source File: JDBCDataSourceProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public DataSource get() {
    BasicDataSource datasource = new BasicDataSource();
    datasource.setDriverClassName(config.getDriverClassName());
    datasource.setUsername(config.getUsername());
    datasource.setPassword(config.getPassword());
    datasource.setUrl(config.getConnection());
    datasource.setConnectionProperties(config.getConnectionProperties());
    LOGGER.info("Register JDBCDataSourceShutdownHook");
    Runtime.getRuntime().addShutdownHook(new Thread("JDBCDataSourceShutdownHook") {
        @Override
        public void run() {
            try {
                LOGGER.info("Shutting down data source");
                datasource.close();
            } catch (SQLException e) {
                LOGGER.error("SQLException: {}", e.getMessage(), e);
                throw new IllegalStateException("Failed to close datasource", e);
            }
        }
    });
    return datasource;
}
 
Example 12
Source Project: apiman   Source File: BasicAuthJDBCTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates an in-memory datasource.
 * @throws SQLException
 */
private static BasicDataSource createInMemoryDatasource() throws SQLException {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(Driver.class.getName());
    ds.setUsername("sa"); //$NON-NLS-1$
    ds.setPassword(""); //$NON-NLS-1$
    ds.setUrl("jdbc:h2:mem:BasicAuthJDBCTest;DB_CLOSE_DELAY=-1"); //$NON-NLS-1$
    Connection connection = ds.getConnection();
    connection.prepareStatement("CREATE TABLE users ( username varchar(255) NOT NULL, password varchar(255) NOT NULL, PRIMARY KEY (username))").executeUpdate();
    connection.prepareStatement("INSERT INTO users (username, password) VALUES ('bwayne', 'ae2efd698aefdf366736a4eda1bc5241f9fbfec7')").executeUpdate();
    connection.prepareStatement("INSERT INTO users (username, password) VALUES ('ckent', 'ea59f7ca52a2087c99374caba0ff29be1b2dcdbf')").executeUpdate();
    connection.prepareStatement("INSERT INTO users (username, password) VALUES ('ballen', 'ea59f7ca52a2087c99374caba0ff29be1b2dcdbf')").executeUpdate();
    connection.prepareStatement("CREATE TABLE roles (rolename varchar(255) NOT NULL, username varchar(255) NOT NULL)").executeUpdate();
    connection.prepareStatement("INSERT INTO roles (rolename, username) VALUES ('user', 'bwayne')").executeUpdate();
    connection.prepareStatement("INSERT INTO roles (rolename, username) VALUES ('admin', 'bwayne')").executeUpdate();
    connection.prepareStatement("INSERT INTO roles (rolename, username) VALUES ('ckent', 'user')").executeUpdate();
    connection.prepareStatement("INSERT INTO roles (rolename, username) VALUES ('ballen', 'user')").executeUpdate();
    connection.close();
    return ds;
}
 
Example 13
/**
 * Destroy the initial context.
 */
public static void destroy() {

    Map<String, Object> jndiObjectsMap = jndiContextData.get();
    if (jndiObjectsMap != null) {
        for (Map.Entry entry : jndiObjectsMap.entrySet()) {
            Object value = entry.getValue();
            if (value != null && value instanceof BasicDataSource) {
                try {
                    ((BasicDataSource) value).close();
                } catch (SQLException e) {
                    //Just Ignore for now.
                }
            }
        }
        jndiContextData.remove();
    }
}
 
Example 14
Source Project: quickperf   Source File: TestDataSourceBuilder.java    License: Apache License 2.0 5 votes vote down vote up
public DataSource build() {
    int randomInt = Math.abs(ThreadLocalRandom.current().nextInt());
    String url = "jdbc:h2:mem:test" + randomInt;
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName("org.h2.Driver");
    dataSource.setUrl(url);
    dataSource.setUsername("qp");
    dataSource.setPassword("");
    dataSource.setMaxActive(4);
    dataSource.setPoolPreparedStatements(true);
    return dataSource;
}
 
Example 15
Source Project: sharding-jdbc-1.5.1   Source File: AbstractSQLTest.java    License: Apache License 2.0 5 votes vote down vote up
private static BasicDataSource buildDataSource(final String dbName, final DatabaseType type) {
    DataBaseEnvironment dbEnv = new DataBaseEnvironment(type);
    BasicDataSource result = new BasicDataSource();
    result.setDriverClassName(dbEnv.getDriverClassName());
    result.setUrl(dbEnv.getURL(dbName));
    result.setUsername(dbEnv.getUsername());
    result.setPassword(dbEnv.getPassword());
    result.setMaxActive(1000);
    if (DatabaseType.Oracle == dbEnv.getDatabaseType()) {
        result.setConnectionInitSqls(Collections.singleton("ALTER SESSION SET CURRENT_SCHEMA = " + dbName));
    }
    return result;
}
 
Example 16
Source Project: sharding-jdbc-1.5.1   Source File: AbstractSQLTest.java    License: Apache License 2.0 5 votes vote down vote up
private void createDataSources(final String dbName, final DatabaseType type) {
    String dataSource = "dataSource_" + dbName;
    Map<String, DataSource> dataSourceMap = databaseTypeMap.get(type);
    if (null == dataSourceMap) {
        dataSourceMap = new HashMap<>();
        databaseTypeMap.put(type, dataSourceMap);
    }
    BasicDataSource result = buildDataSource(dbName, type);
    dataSourceMap.put(dataSource, result);
}
 
Example 17
Source Project: glowroot   Source File: Connections.java    License: Apache License 2.0 5 votes vote down vote up
static org.apache.commons.dbcp2.BasicDataSource createCommonsDbcp2DataSource() {
    org.apache.commons.dbcp2.BasicDataSource ds =
            new org.apache.commons.dbcp2.BasicDataSource();
    ds.setDriverClassName("org.hsqldb.jdbc.JDBCDriver");
    ds.setUrl("jdbc:hsqldb:mem:test");
    return ds;
}
 
Example 18
Source Project: apiman   Source File: JdbcMetricsAccessorTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates an in-memory datasource.
 * @throws SQLException
 */
private static BasicDataSource createInMemoryDatasource() throws Exception {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(Driver.class.getName());
    ds.setUsername("sa");
    ds.setPassword("");
    ds.setUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1");
    Connection connection = ds.getConnection();
    connection.setAutoCommit(true);
    initDB(connection);
    connection.close();
    return ds;
}
 
Example 19
Source Project: sharding-jdbc-1.5.1   Source File: Main.java    License: Apache License 2.0 5 votes vote down vote up
private static DataSource createDataSource(final String dataSourceName) {
    BasicDataSource result = new BasicDataSource();
    result.setDriverClassName(com.mysql.jdbc.Driver.class.getName());
    result.setUrl(String.format("jdbc:mysql://localhost:3306/%s", dataSourceName));
    result.setUsername("root");
    result.setPassword("");
    return result;
}
 
Example 20
Source Project: pinpoint   Source File: DataSourceConstructorInterceptor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void after(Object target, Object[] args, Object result, Throwable throwable) {
    if (!InterceptorUtils.isSuccess(throwable)) {
        return;
    }

    final BasicDataSource basicDataSource = getBasicDatasource(target);
    if (basicDataSource instanceof DataSourceMonitorAccessor) {
        DbcpDataSourceMonitor dataSourceMonitor = new DbcpDataSourceMonitor(basicDataSource);
        dataSourceMonitorRegistry.register(dataSourceMonitor);

        ((DataSourceMonitorAccessor) basicDataSource)._$PINPOINT$_setDataSourceMonitor(dataSourceMonitor);
    }
}
 
Example 21
Source Project: DataSphereStudio   Source File: DSSMybatisConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean(name = "dataSource", destroyMethod = "close")
@Primary
public DataSource dataSource() {
    BasicDataSource datasource = new BasicDataSource();
    String dbUrl = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_URL.getValue();
    String username = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_USERNAME.getValue();
    String password = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_PASSWORD.getValue();
    String driverClassName = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_DRIVER_CLASS_NAME.getValue();
    int initialSize = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_INITIALSIZE.getValue();
    int minIdle = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_MINIDLE.getValue();
    int maxActive = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_MAXACTIVE.getValue();
    int maxWait = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_MAXWAIT.getValue();
    int timeBetweenEvictionRunsMillis = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_TBERM.getValue();
    int minEvictableIdleTimeMillis = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_MEITM.getValue();
    String validationQuery = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_VALIDATIONQUERY.getValue();
    boolean testWhileIdle = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_TESTWHILEIDLE.getValue();
    boolean testOnBorrow = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_TESTONBORROW.getValue();
    boolean testOnReturn = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_TESTONRETURN.getValue();
    boolean poolPreparedStatements = DSSServerConf.BDP_SERVER_MYBATIS_DATASOURCE_POOLPREPAREDSTATEMENTS.getValue();
    datasource.setUrl(dbUrl);
    datasource.setUsername(username);
    datasource.setPassword(password);
    datasource.setDriverClassName(driverClassName);
    datasource.setInitialSize(initialSize);
    datasource.setMinIdle(minIdle);
    datasource.setMaxActive(maxActive);
    datasource.setMaxWait(maxWait);
    datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    datasource.setValidationQuery(validationQuery);
    datasource.setTestWhileIdle(testWhileIdle);
    datasource.setTestOnBorrow(testOnBorrow);
    datasource.setTestOnReturn(testOnReturn);
    datasource.setPoolPreparedStatements(poolPreparedStatements);
    logger.info("Database connection address information(数据库连接地址信息)=" + dbUrl);
    return datasource;
}
 
Example 22
Source Project: incubator-gobblin   Source File: MysqlDataSourceFactory.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get a {@link BasicDataSource} based on the config
 * @param config configuration
 * @param broker broker
 * @return a {@link BasicDataSource}
 * @throws IOException
 */
public static <S extends ScopeType<S>> BasicDataSource get(Config config,
    SharedResourcesBroker<S> broker) throws IOException {
  try {
    return broker.getSharedResource(new MysqlDataSourceFactory<S>(),
        new MysqlDataSourceKey(MysqlStateStore.getDataSourceId(config), config));
  } catch (NotConfiguredException nce) {
    throw new IOException(nce);
  }
}
 
Example 23
Source Project: flexy-pool   Source File: FlexyPoolConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean(initMethod = "start", destroyMethod = "stop")
public FlexyPoolDataSource dataSource() {
    Configuration<BasicDataSource> configuration = configuration();
    return new FlexyPoolDataSource<BasicDataSource>(configuration,
            new IncrementPoolOnTimeoutConnectionAcquiringStrategy.Factory(5),
            new RetryConnectionAcquiringStrategy.Factory(2)
    );
}
 
Example 24
Source Project: carbon-identity-framework   Source File: TestUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void initiateH2Base() throws Exception {

        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("org.h2.Driver");
        dataSource.setUsername("username");
        dataSource.setPassword("password");
        dataSource.setUrl("jdbc:h2:mem:test" + DB_NAME);
        try (Connection connection = dataSource.getConnection()) {
            connection.createStatement().executeUpdate("RUNSCRIPT FROM '" + getFilePath(H2_SCRIPT_NAME) + "'");
        }
        dataSourceMap.put(DB_NAME, dataSource);
    }
 
Example 25
@Override
protected BasicDataSource createInstance() throws Exception {
	BasicDataSource ds = new BasicDataSource();
	ds.setDriverClassName("org.postgresql.Driver");
	if (StringUtils.hasText(dbUser)) {
		ds.setUsername(dbUser);
	}
	if (StringUtils.hasText(dbPassword)) {
		ds.setPassword(dbPassword);
	}
	ds.setUrl("jdbc:postgresql://" + dbHost + ":" + dbPort + "/" + dbName);
	return ds;
}
 
Example 26
Source Project: glowroot   Source File: ConnectionAndTxLifecycleIT.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void executeApp() throws Exception {
    dataSource = new BasicDataSource() {
        @Override
        public Connection getConnection() throws SQLException {
            throw new SQLException("A getconnection failure");
        }
    };
    dataSource.setDriverClassName("org.hsqldb.jdbc.JDBCDriver");
    dataSource.setUrl("jdbc:hsqldb:mem:test");
    transactionMarker();
}
 
Example 27
Source Project: zstack   Source File: JpaUnitPostProcessor.java    License: Apache License 2.0 5 votes vote down vote up
void init() {
  	dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
String jdbcUrl = String.format("jdbc:mysql://%s/%s", getDbHost(), getDbName());
dataSource.setUrl(jdbcUrl);
dataSource.setUsername(getDbUser());
dataSource.setPassword(getDbPassword());
  }
 
Example 28
Source Project: apicurio-studio   Source File: EditingSessionManagerTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates an in-memory datasource.
 * @throws SQLException
 */
private static BasicDataSource createInMemoryDatasource() {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(Driver.class.getName());
    ds.setUsername("sa");
    ds.setPassword("");
    ds.setUrl("jdbc:h2:mem:test" + (counter++) + ";DB_CLOSE_DELAY=-1");
    return ds;
}
 
Example 29
Source Project: localization_nifi   Source File: DBCPConnectionPool.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Configures connection pool by creating an instance of the
 * {@link BasicDataSource} based on configuration provided with
 * {@link ConfigurationContext}.
 *
 * This operation makes no guarantees that the actual connection could be
 * made since the underlying system may still go off-line during normal
 * operation of the connection pool.
 *
 * @param context
 *            the configuration context
 * @throws InitializationException
 *             if unable to create a database connection
 */
@OnEnabled
public void onConfigured(final ConfigurationContext context) throws InitializationException {

    final String drv = context.getProperty(DB_DRIVERNAME).evaluateAttributeExpressions().getValue();
    final String user = context.getProperty(DB_USER).evaluateAttributeExpressions().getValue();
    final String passw = context.getProperty(DB_PASSWORD).evaluateAttributeExpressions().getValue();
    final Long maxWaitMillis = context.getProperty(MAX_WAIT_TIME).asTimePeriod(TimeUnit.MILLISECONDS);
    final Integer maxTotal = context.getProperty(MAX_TOTAL_CONNECTIONS).asInteger();
    final String validationQuery = context.getProperty(VALIDATION_QUERY).evaluateAttributeExpressions().getValue();

    dataSource = new BasicDataSource();
    dataSource.setDriverClassName(drv);

    // Optional driver URL, when exist, this URL will be used to locate driver jar file location
    final String urlString = context.getProperty(DB_DRIVER_LOCATION).evaluateAttributeExpressions().getValue();
    dataSource.setDriverClassLoader(getDriverClassLoader(urlString, drv));

    final String dburl = context.getProperty(DATABASE_URL).evaluateAttributeExpressions().getValue();

    dataSource.setMaxWait(maxWaitMillis);
    dataSource.setMaxActive(maxTotal);

    if (validationQuery!=null && !validationQuery.isEmpty()) {
        dataSource.setValidationQuery(validationQuery);
        dataSource.setTestOnBorrow(true);
    }

    dataSource.setUrl(dburl);
    dataSource.setUsername(user);
    dataSource.setPassword(passw);

    context.getProperties().keySet().stream().filter(PropertyDescriptor::isDynamic)
            .forEach((dynamicPropDescriptor) -> dataSource.addConnectionProperty(dynamicPropDescriptor.getName(),
                    context.getProperty(dynamicPropDescriptor).evaluateAttributeExpressions().getValue()));

}
 
Example 30
@Before
public void setup() throws SQLException {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(org.h2.Driver.class.getName());
    dataSource.setUrl("jdbc:h2:mem:job_event_storage");
    dataSource.setUsername("sa");
    dataSource.setPassword("");
    storage = new RDBJobEventStorage(dataSource);
}