Java Code Examples for org.apache.commons.dbcp.BasicDataSource#setUrl()

The following examples show how to use org.apache.commons.dbcp.BasicDataSource#setUrl() . 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: MysqlStateStore.java    From incubator-gobblin with 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 2
Source File: DynamicDBUtil.java    From jeecg with Apache License 2.0 6 votes vote down vote up
/**
 * 获取数据源【最底层方法,不要随便调用】
 * @param dynamicSourceEntity
 * @return
 */
@Deprecated
private static BasicDataSource getJdbcDataSource(final DynamicDataSourceEntity dynamicSourceEntity) {
	BasicDataSource dataSource = new BasicDataSource();
	
	String driverClassName = dynamicSourceEntity.getDriverClass();
	String url = dynamicSourceEntity.getUrl();
	String dbUser = dynamicSourceEntity.getDbUser();

	//设置数据源的时候,要重新解密
	//String dbPassword = dynamicSourceEntity.getDbPassword();
	String dbPassword  = PasswordUtil.decrypt(dynamicSourceEntity.getDbPassword(), dynamicSourceEntity.getDbUser(), PasswordUtil.getStaticSalt());//解密字符串;

	
	dataSource.setDriverClassName(driverClassName);
	dataSource.setUrl(url);
	dataSource.setUsername(dbUser);
	dataSource.setPassword(dbPassword);
	return dataSource;
}
 
Example 3
Source File: JdbcDataSourceFactory.java    From obevo with Apache License 2.0 6 votes vote down vote up
private static DataSource createFromJdbcUrl(Class<? extends Driver> driverClass, String url,
        Credential credential, int numThreads, ImmutableList<String> initSqls, Properties extraConnectionProperties) {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(driverClass.getName());
    // TODO validate non-null host name, notably for postgresl jdbc url
    dataSource.setUrl(url);
    dataSource.setUsername(credential.getUsername());
    dataSource.setPassword(credential.getPassword());

    // connection pool settings
    dataSource.setInitialSize(numThreads);
    dataSource.setMaxActive(numThreads);
    // keep the connections open if possible; only close them via the removeAbandonedTimeout feature
    dataSource.setMaxIdle(numThreads);
    dataSource.setMinIdle(0);
    dataSource.setRemoveAbandonedTimeout(300);

    dataSource.setConnectionInitSqls(initSqls.castToList());
    if (extraConnectionProperties != null) {
        for (String key : extraConnectionProperties.stringPropertyNames()) {
            dataSource.addConnectionProperty(key, extraConnectionProperties.getProperty(key));
        }
    }

    return dataSource;
}
 
Example 4
Source File: JDBCPersistenceProvider.java    From oxd with 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 5
Source File: Main.java    From sharding-jdbc-1.5.1 with 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 6
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 7
Source File: GreenplumDataSourceFactoryBean.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
@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 8
Source File: DataStoreBaseTest.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
protected void initH2DB(String databaseName, String scriptPath) throws Exception {

        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("org.h2.Driver");
        dataSource.setUsername("username");
        dataSource.setPassword("password");
        dataSource.setUrl("jdbc:h2:mem:test" + databaseName);
        try (Connection connection = dataSource.getConnection()) {
            connection.createStatement().executeUpdate("RUNSCRIPT FROM '" + scriptPath + "'");
        }
        dataSourceMap.put(databaseName, dataSource);
    }
 
Example 9
Source File: CleanableMysqlDatasetStoreDatasetTest.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public void setUp() throws Exception {
  this.testMetastoreDatabase = TestMetastoreDatabaseFactory.get();
  String jdbcUrl = this.testMetastoreDatabase.getJdbcUrl();
  ConfigBuilder configBuilder = ConfigBuilder.create();
  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);

  this.dbJobStateStore = new MysqlStateStore<>(mySqlDs, TEST_STATE_STORE, false, JobState.class);

  configBuilder.addPrimitive("selection.timeBased.lookbackTime", "10m");
  configBuilder.addPrimitive(ConfigurationKeys.STATE_STORE_TYPE_KEY, "mysql");
  configBuilder.addPrimitive(ConfigurationKeys.STATE_STORE_DB_TABLE_KEY, TEST_STATE_STORE);
  configBuilder.addPrimitive(ConfigurationKeys.STATE_STORE_DB_URL_KEY, jdbcUrl);
  configBuilder.addPrimitive(ConfigurationKeys.STATE_STORE_DB_USER_KEY, TEST_USER);
  configBuilder.addPrimitive(ConfigurationKeys.STATE_STORE_DB_PASSWORD_KEY, TEST_PASSWORD);

  ClassAliasResolver<DatasetStateStore.Factory> resolver = new ClassAliasResolver<>(DatasetStateStore.Factory.class);

  DatasetStateStore.Factory stateStoreFactory = resolver.resolveClass("mysql").newInstance();
  this.config = configBuilder.build();
  this.dbDatasetStateStore = stateStoreFactory.createStateStore(configBuilder.build());

  // clear data that may have been left behind by a prior test run
  this.dbJobStateStore.delete(TEST_JOB_NAME1);
  this.dbDatasetStateStore.delete(TEST_JOB_NAME1);
  this.dbJobStateStore.delete(TEST_JOB_NAME2);
  this.dbDatasetStateStore.delete(TEST_JOB_NAME2);
}
 
Example 10
Source File: ExecutionQueueRepositoryTest.java    From score with Apache License 2.0 5 votes vote down vote up
@Bean
DataSource dataSource(){
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName("org.h2.Driver");
    ds.setUrl("jdbc:h2:mem:test");
    ds.setUsername("sa");
    ds.setPassword("sa");
    ds.setDefaultAutoCommit(false);
    return new TransactionAwareDataSourceProxy(ds);
}
 
Example 11
Source File: JDBCMailRepositoryTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
private BasicDataSource getDataSource() {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(EmbeddedDriver.class.getName());
    ds.setUrl("jdbc:derby:target/testdb;create=true");
    ds.setUsername("james");
    ds.setPassword("james");
    return ds;
}
 
Example 12
Source File: ConnectionAndTxLifecycleIT.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public void executeApp() throws Exception {
    dataSource = new BasicDataSource();
    dataSource.setDriverClassName("org.hsqldb.jdbc.JDBCDriver");
    dataSource.setUrl("jdbc:hsqldb:mem:test");
    // BasicDataSource opens and closes a test connection on first getConnection(),
    // so just getting that out of the way before starting transaction
    dataSource.getConnection().close();
    transactionMarker();
}
 
Example 13
Source File: MySQLDBConnection.java    From Gatekeeper with Apache License 2.0 5 votes vote down vote up
private JdbcTemplate connect(String url, String gkUserPassword) throws SQLException {
    String dbUrl = "jdbc:mysql://" + url;

    BasicDataSource dataSource = new BasicDataSource();

    dataSource.setDriverClassName("org.mariadb.jdbc.Driver");
    dataSource.setUrl(dbUrl+"?"+ssl);
    dataSource.setUsername(gkUserName);
    dataSource.setPassword(gkUserPassword);
    dataSource.setMinIdle(0);
    dataSource.setMaxIdle(0);

    return new JdbcTemplate(dataSource);
}
 
Example 14
Source File: YamlShardingDataSourceTest.java    From sharding-jdbc-1.5.1 with Apache License 2.0 5 votes vote down vote up
private DataSource createDataSource() {
    BasicDataSource result = new BasicDataSource();
    result.setDriverClassName(Driver.class.getName());
    result.setUrl("jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MYSQL");
    result.setUsername("sa");
    result.setPassword("");
    return result;
}
 
Example 15
Source File: GenericDatabaseInterface.java    From wandora with GNU General Public License v3.0 5 votes vote down vote up
protected void initConnectionPool(){
    connectionPool=new BasicDataSource();
    connectionPool.setDriverClassName(driver);
    connectionPool.setUrl(connectionString);
    connectionPool.setUsername(userName);
    connectionPool.setPassword(password);
    
    connectionPool.setMaxActive(-1); // no limit
    
    connectionPool.setValidationQuery("select 1");
    connectionPool.setTestOnBorrow(true);
    connectionPool.setValidationQueryTimeout(1);
    
    fireDatabaseStarted();        
}
 
Example 16
Source File: DAOUtils.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
public static void initializeDataSource(String databaseName, String scriptPath) throws Exception {

        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("org.h2.Driver");
        dataSource.setUsername("username");
        dataSource.setPassword("password");
        dataSource.setUrl("jdbc:h2:mem:" + databaseName);

        try (Connection connection = dataSource.getConnection()) {
            connection.createStatement().executeUpdate("RUNSCRIPT FROM '" + scriptPath + "'");
        }
        dataSourceMap.put(databaseName, dataSource);
    }
 
Example 17
Source File: Connections.java    From glowroot with Apache License 2.0 4 votes vote down vote up
static BasicDataSource createCommonsDbcpWrappedDataSource() {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName("org.hsqldb.jdbc.JDBCDriver");
    ds.setUrl("jdbc:hsqldb:mem:test");
    return ds;
}
 
Example 18
Source File: HiveConnectionPool.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
/**
 * Configures connection pool by creating an instance of the
 * {@link BasicDataSource} based on configuration provided with
 * {@link ConfigurationContext}.
 * <p>
 * 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 {

    connectionUrl = context.getProperty(DATABASE_URL).getValue();

    ComponentLog log = getLogger();

    final String configFiles = context.getProperty(HIVE_CONFIGURATION_RESOURCES).getValue();
    final Configuration hiveConfig = hiveConfigurator.getConfigurationFromFiles(configFiles);
    final String validationQuery = context.getProperty(VALIDATION_QUERY).evaluateAttributeExpressions().getValue();

    // add any dynamic properties to the Hive configuration
    for (final Map.Entry<PropertyDescriptor, String> entry : context.getProperties().entrySet()) {
        final PropertyDescriptor descriptor = entry.getKey();
        if (descriptor.isDynamic()) {
            hiveConfig.set(descriptor.getName(), entry.getValue());
        }
    }

    final String drv = HiveDriver.class.getName();
    if (SecurityUtil.isSecurityEnabled(hiveConfig)) {
        final String principal = context.getProperty(kerberosProperties.getKerberosPrincipal()).getValue();
        final String keyTab = context.getProperty(kerberosProperties.getKerberosKeytab()).getValue();

        log.info("Hive Security Enabled, logging in as principal {} with keytab {}", new Object[]{principal, keyTab});
        try {
            ugi = hiveConfigurator.authenticate(hiveConfig, principal, keyTab, TICKET_RENEWAL_PERIOD, log);
        } catch (AuthenticationFailedException ae) {
            log.error(ae.getMessage(), ae);
        }
        getLogger().info("Successfully logged in as principal {} with keytab {}", new Object[]{principal, keyTab});

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

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

    final String dburl = context.getProperty(DATABASE_URL).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);
}
 
Example 19
Source File: DdlUtilsTest.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
static void runImportExportTest_ImportFail(final Connection netConn,
    final String clientUrl, final String userName, final String password,
    final int rowSize, final String schema, final String schemaFileName,
    final String dataFileName) throws Throwable {

  final String schemaPrefix = schema != null ? (schema + '.') : "";
  final Statement stmt = netConn.createStatement();
  final char[] desc = new char[rowSize];
  final int id;

  // check for failure in loading tables using the XML data with existing
  // duplicate data (atomically for batching)

  BasicDataSource dataSource = new BasicDataSource();
  dataSource.setDriverClassName("com.pivotal.gemfirexd.jdbc.ClientDriver");
  dataSource.setUrl("jdbc:gemfirexd://" + clientUrl);
  if (userName != null) {
    dataSource.setUsername(userName);
    dataSource.setPassword(password);
  }

  DdlToDatabaseTask toDBTask = new DdlToDatabaseTask();
  toDBTask.addConfiguredDatabase(dataSource);
  File schemaFile = new File(schemaFileName);
  toDBTask.setSchemaFile(schemaFile);

  WriteSchemaToDatabaseCommand writeSchemaToDB =
      new WriteSchemaToDatabaseCommand();
  writeSchemaToDB.setAlterDatabase(true);
  writeSchemaToDB.setFailOnError(true);

  toDBTask.addWriteSchemaToDatabase(writeSchemaToDB);
  toDBTask.execute();

  WriteDataToDatabaseCommand writeDataToDB = new WriteDataToDatabaseCommand();
  File dataFile = new File(dataFileName);
  writeDataToDB.setIsolationLevel(Connection.TRANSACTION_READ_COMMITTED);
  writeDataToDB.setUseBatchMode(true);
  writeDataToDB.setBatchSize(1000);
  writeDataToDB.setDataFile(dataFile);
  writeDataToDB.setFailOnError(true);

  id = 10;
  stmt.execute("insert into " + schemaPrefix + "language values (" + id
      + ", 'lang" + id + "')");
  final PreparedStatement pstmt = netConn.prepareStatement("insert into "
      + schemaPrefix + "film (film_id, title, description, language_id, "
      + "original_language_id) values (?, ?, ?, ?, ?)");
  pstmt.setInt(1, id);
  pstmt.setString(2, "film" + id);
  for (int index = 0; index < desc.length; index++) {
    desc[index] = (char)('<' + (index % 32));
  }
  pstmt.setString(3, new String(desc));
  pstmt.setInt(4, id);
  pstmt.setInt(5, id);
  pstmt.execute();

  toDBTask = new DdlToDatabaseTask();
  toDBTask.addConfiguredDatabase(dataSource);
  toDBTask.setSchemaFile(schemaFile);

  toDBTask.addWriteDataToDatabase(writeDataToDB);
  try {
    toDBTask.execute();
    fail("expected constraint violation");
  } catch (Throwable t) {
    while (t.getCause() != null && !(t instanceof SQLException)) {
      t = t.getCause();
    }
    if (!(t instanceof SQLException)
        || !"23505".equals(((SQLException)t).getSQLState())) {
      throw t;
    }
  }

  assertEquals(1, stmt.executeUpdate("delete from " + schemaPrefix
      + "film where film_id=" + id));
  assertEquals(1, stmt.executeUpdate("delete from " + schemaPrefix
      + "language where language_id=" + id));

  dataSource.close();
}
 
Example 20
Source File: DataSourceUrlTest.java    From sofa-tracer with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetDataSourceUrl() throws Throwable {
    // Druid
    DruidDataSource druidDataSource = new DruidDataSource();
    druidDataSource.setUrl("test-url");
    Method method = ReflectionUtils.findMethod(druidDataSource.getClass(),
        DataSourceUtils.METHOD_GET_URL);
    Assert.assertNotNull(method);
    Assert.assertEquals("test-url", method.invoke(druidDataSource));

    // dbcp
    BasicDataSource basicDataSource = new BasicDataSource();
    basicDataSource.setUrl("test-url");
    method = ReflectionUtils.findMethod(basicDataSource.getClass(),
        DataSourceUtils.METHOD_GET_URL);
    Assert.assertNotNull(method);
    Assert.assertEquals("test-url", method.invoke(basicDataSource));

    // tomcat datasource
    DataSource dataSource = new DataSource();
    dataSource.setUrl("test-url");
    method = ReflectionUtils.findMethod(dataSource.getClass(), DataSourceUtils.METHOD_GET_URL);
    Assert.assertNotNull(method);
    Assert.assertEquals("test-url", method.invoke(dataSource));

    // c3p0
    ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
    comboPooledDataSource.setJdbcUrl("test-url");
    method = ReflectionUtils.findMethod(comboPooledDataSource.getClass(),
        DataSourceUtils.METHOD_GET_JDBC_URL);
    Assert.assertNotNull(method);
    Assert.assertEquals("test-url", method.invoke(comboPooledDataSource));

    // hikari
    HikariDataSource hikariDataSource = new HikariDataSource();
    hikariDataSource.setJdbcUrl("test-url");
    method = ReflectionUtils.findMethod(hikariDataSource.getClass(),
        DataSourceUtils.METHOD_GET_JDBC_URL);
    Assert.assertNotNull(method);
    Assert.assertEquals("test-url", method.invoke(hikariDataSource));
}