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

The following examples show how to use org.apache.commons.dbcp.BasicDataSource#setPassword() . 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: PersistService.java    From diamond with 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 2
Source File: MysqlDagStateStoreTest.java    From incubator-gobblin with 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 3
Source File: DataSourceContainer.java    From DBus with Apache License 2.0 6 votes vote down vote up
public boolean register(JdbcVo conf) {
    boolean isOk = true;
    try {
        BasicDataSource bds = new BasicDataSource();
        bds.setDriverClassName(conf.getDriverClass());
        bds.setUrl(conf.getUrl());
        bds.setUsername(conf.getUserName());
        bds.setPassword(conf.getPassword());
        bds.setInitialSize(conf.getInitialSize());
        bds.setMaxActive(conf.getMaxActive());
        bds.setMaxIdle(conf.getMaxIdle());
        bds.setMinIdle(conf.getMinIdle());
        cmap.put(conf.getKey(), bds);
    } catch (Exception e) {
        logger.error("[db container init key " + conf.getKey() + " datasource error!]", e);
        isOk = false;
    }
    return isOk;
}
 
Example 4
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 5
Source File: DBCPConnectionPool.java    From localization_nifi with 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 6
Source File: DataSourceFactory.java    From polyjdbc with Apache License 2.0 5 votes vote down vote up
public static DataSource create(Dialect dialect, String databaseUrl, String user, String password) {
    BasicDataSource dataSource = new BasicDataSource();

    dataSource.setDriverClassName(DIALECT_DRIVER_CLASS.get(dialect.getCode()));
    dataSource.setUrl(databaseUrl);
    dataSource.setUsername(user);
    dataSource.setPassword(password);
    dataSource.setDefaultAutoCommit(false);

    return dataSource;
}
 
Example 7
Source File: MysqlDatasetStateStoreTest.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public void setUp() throws Exception {
  testMetastoreDatabase = TestMetastoreDatabaseFactory.get();
  String jdbcUrl = 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);

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

  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();
  dbDatasetStateStore = stateStoreFactory.createStateStore(configBuilder.build());

  // clear data that may have been left behind by a prior test run
  dbJobStateStore.delete(TEST_JOB_NAME);
  dbDatasetStateStore.delete(TEST_JOB_NAME);
  dbJobStateStore.delete(TEST_JOB_NAME2);
  dbDatasetStateStore.delete(TEST_JOB_NAME2);
}
 
Example 8
Source File: ConnectionPoolingIT.java    From snowflake-jdbc with Apache License 2.0 5 votes vote down vote up
private void setUpDBCPConnection()
{
  bds = new BasicDataSource();
  bds.setDriverClassName(BaseJDBCTest.DRIVER_CLASS);
  bds.setUsername(this.user);
  bds.setPassword(this.password);
  bds.setUrl(connectStr);

  String propertyString = String.format(
      "ssl=%s;db=%s;schema=%s;account=%s;",
      this.ssl, this.database, this.schema, this.account
  );
  bds.setConnectionProperties(propertyString);
}
 
Example 9
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 10
Source File: JobEventRdbConfigurationTest.java    From shardingsphere-elasticjob-cloud with Apache License 2.0 5 votes vote down vote up
@Test
public void assertCreateJobEventListenerSuccess() throws JobEventListenerConfigurationException {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(org.h2.Driver.class.getName());
    dataSource.setUrl("jdbc:h2:mem:job_event_storage");
    dataSource.setUsername("sa");
    dataSource.setPassword("");
    Assert.assertThat(new JobEventRdbConfiguration(dataSource).createJobEventListener(), CoreMatchers.instanceOf(JobEventRdbListener.class));
}
 
Example 11
Source File: PoolingConnectionProvider.java    From AsuraFramework with Apache License 2.0 5 votes vote down vote up
/**
 * Create the underlying DBCP BasicDataSource with the 
 * default supported properties.
 */
private void initialize(
    String dbDriver, 
    String dbURL, 
    String dbUser,
    String dbPassword, 
    int maxConnections, 
    String dbValidationQuery) throws SQLException {
    if (dbURL == null) {
        throw new SQLException(
            "DBPool could not be created: DB URL cannot be null");
    }
    
    if (dbDriver == null) {
        throw new SQLException(
            "DBPool '" + dbURL + "' could not be created: " +
            "DB driver class name cannot be null!");
    }
    
    if (maxConnections < 0) {
        throw new SQLException(
            "DBPool '" + dbURL + "' could not be created: " + 
            "Max connections must be greater than zero!");
    }

    datasource = new BasicDataSource();
    datasource.setDriverClassName(dbDriver);
    datasource.setUrl(dbURL);
    datasource.setUsername(dbUser);
    datasource.setPassword(dbPassword);
    datasource.setMaxActive(maxConnections);
    if (dbValidationQuery != null) {
        datasource.setValidationQuery(dbValidationQuery);
    }
}
 
Example 12
Source File: RDBJobEventSearchTest.java    From shardingsphere-elasticjob-lite with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setUpClass() throws SQLException {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName(org.h2.Driver.class.getName());
    dataSource.setUrl("jdbc:h2:mem:");
    dataSource.setUsername("sa");
    dataSource.setPassword("");
    storage = new RDBJobEventStorage(dataSource);
    repository = new RDBJobEventSearch(dataSource);
    initStorage();
}
 
Example 13
Source File: TestUtils.java    From carbon-identity-framework with 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 14
Source File: AbstractSoftTransactionIntegrationTest.java    From sharding-jdbc-1.5.1 with Apache License 2.0 5 votes vote down vote up
private DataSource createDataSource(final String dataSourceName) {
    BasicDataSource result = new BasicDataSource();
    result.setDriverClassName(org.h2.Driver.class.getName());
    result.setUrl("jdbc:h2:mem:" + dataSourceName);
    result.setUsername("sa");
    result.setPassword("");
    return result;
}
 
Example 15
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 16
Source File: JdbcStorageTest.java    From apicurio-studio with 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 17
Source File: DBDatasProcessor.java    From sofa-acts with Apache License 2.0 4 votes vote down vote up
/**
 * Init data source.
 */
public void initDataSource() {
    dataAccessConfigManager = (DataAccessConfigManager) applicationContext
        .getBean("dataAccessConfigManager");

    String bundleName = ConfigrationFactory.getConfigration()
        .getPropertyValue("datasource_bundle_name").replace(";", "");

    ConfigrationFactory.loadFromConfig("config/dbConf/"
                                       + ConfigrationFactory.getConfigration()
                                           .getPropertyValue("dbmode") + "db.conf");
    Map<String, String> configs = ConfigrationFactory.getConfigration().getConfig();
    if (configs == null) {
        Assert
            .assertTrue(
                false,
                "datasource config not exist, add config in [acts-config.properties] ,modify datasource config starting with [ds_]");

    }
    for (String key : configs.keySet()) {
        if (key.startsWith("ds_")) {
            String dsName = key.replace("ds_", "");
            List<String> tables = new ArrayList<String>();
            for (String tableName : configs.get(key).split(",")) {
                tables.add(tableName);
            }

            DataSource ds = null;
            //Attempt to read db.conf to obtain configs
            if (configs.containsKey(dsName + "_url")) {
                String db_url = configs.get(dsName + "_url");
                String db_username = configs.get(dsName + "_username");
                String db_password = configs.get(dsName + "_password");
                BasicDataSource datasource = new BasicDataSource();
                String type = getDBType(db_url);

                try {
                    if (type.equalsIgnoreCase("oracle")) {
                        Class.forName("oracle.jdbc.OracleDriver");
                        datasource.setDriverClassName("oracle.jdbc.OracleDriver");
                    } else {
                        Class.forName("com.mysql.jdbc.Driver");
                        datasource.setDriverClassName("com.mysql.jdbc.Driver");
                    }
                    datasource.setUrl(db_url);
                    datasource.setUsername(db_username);
                    datasource.setPassword(db_password);
                    ds = datasource;
                } catch (Exception e) {
                    throw new ActsTestException("Failed obtaining datasource:" + dsName, e);
                }

            } else {

                ds = ((DataSource) applicationContext.getBean(dsName));
                if (ds == null) {
                    //default on-the-fly-bundle
                    ds = ((DataSource) applicationContext.getBean(dsName));
                }
            }
            if (ds == null) {
                Assert.assertTrue(false, "Failed obtaining datasource,bean:[" + dsName
                                         + "] specified bundleName: [" + bundleName + "]");
            }

            JdbcTemplate jdbcTemplate = new JdbcTemplate(ds);
            if (jdbcTemplateMap == null) {
                jdbcTemplateMap = new HashMap<String, JdbcTemplate>();
            }
            jdbcTemplateMap.put(dsName, jdbcTemplate);
            DataAccessConfigManager.dataSourceMap.put(dsName, tables);
        }

    }

}
 
Example 18
Source File: GfxdDdlUtils.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
protected BasicDataSource handleDataSourceOptions(
    final DataSourceOptions dsOpts, final String cmd,
    final String cmdDescKey) {

  if (dsOpts.url != null) {
    // client options should not be present in this case
    if (dsOpts.clientPort >= 0 || dsOpts.clientBindAddress != null) {
      showUsage(LocalizedResource.getMessage(
          "DDLUTILS_BOTH_URL_CLIENT_ERROR"), cmd, cmdDescKey);
      throw new GemFireTerminateError(
          "exiting due to incorrect connection options", 1);
    }
    if (dsOpts.driverClass == null) {
      showUsage(LocalizedResource.getMessage(
          "DDLUTILS_MISSING_DRIVER_CLASS_ERROR"), cmd, cmdDescKey);
      throw new GemFireTerminateError(
          "exiting due to missing driverClass option", 1);
    }
  }
  else {
    handleConnectionOptions(dsOpts, cmd, cmdDescKey);
  }

  final BasicDataSource dataSource = new BasicDataSource();
  final StringBuilder urlBuilder = new StringBuilder();
  if (dsOpts.url != null) {
    dataSource.setDriverClassName(dsOpts.driverClass);
    urlBuilder.append(dsOpts.url);
  }
  else if (dsOpts.clientPort < 0) {
    dataSource.setDriverClassName(GemFireXDPeerPlatform.JDBC_PEER_DRIVER);
    urlBuilder.append(Attribute.PROTOCOL).append(";host-data=false");
  }
  else {
    final String hostName = dsOpts.clientBindAddress != null
        ? dsOpts.clientBindAddress : "localhost";
    dataSource.setDriverClassName(GemFireXDPlatform.JDBC_CLIENT_DRIVER);
    urlBuilder.append(Attribute.DNC_PROTOCOL).append(hostName).append(':')
        .append(dsOpts.clientPort).append('/');
  }
  if (dsOpts.properties.length() > 0) {
    urlBuilder.append(dsOpts.properties);
  }
  dataSource.setUrl(urlBuilder.toString());
  if (dsOpts.user != null) {
    dataSource.setUsername(dsOpts.user);
  }
  if (dsOpts.password != null) {
    dataSource.setPassword(dsOpts.password);
  }
  return dataSource;
}
 
Example 19
Source File: DdlUtilsTest.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
static void runImportExportTest_Import(final Connection netConn,
    final String clientUrl, final String userName, final String password,
    final String schemaFileName, final String dataFileName) throws Throwable {

  // now load the tables using the XML data

  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);

  // next check for the success case
  toDBTask = new DdlToDatabaseTask();
  toDBTask.addConfiguredDatabase(dataSource);
  toDBTask.setSchemaFile(schemaFile);

  toDBTask.addWriteDataToDatabase(writeDataToDB);
  toDBTask.execute();

  dataSource.close();

  // end load the tables using the XML data
}
 
Example 20
Source File: DdlUtilsTest.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
static void runImportExportTest_Import(final Connection netConn,
    final String clientUrl, final String userName, final String password,
    final String schemaFileName, final String dataFileName) throws Throwable {

  // now load the tables using the XML data

  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);

  // next check for the success case
  toDBTask = new DdlToDatabaseTask();
  toDBTask.addConfiguredDatabase(dataSource);
  toDBTask.setSchemaFile(schemaFile);

  toDBTask.addWriteDataToDatabase(writeDataToDB);
  toDBTask.execute();

  dataSource.close();

  // end load the tables using the XML data
}