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

The following examples show how to use org.apache.commons.dbcp.BasicDataSource#setUsername() . 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: DynamicDBUtil.java    From teaching with 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 2
Source File: DataSourceConfig.java    From mango with Apache License 2.0 6 votes vote down vote up
public static DataSource getDataSource(int i, boolean autoCommit, int maxActive) {
  String driverClassName = getDriverClassName(i);
  String url = getUrl(i);
  String username = getUsername(i);
  String password = getPassword(i);

  BasicDataSource ds = new BasicDataSource();
  ds.setUrl(url);
  ds.setUsername(username);
  ds.setPassword(password);
  ds.setInitialSize(1);
  ds.setMaxActive(maxActive);
  ds.setDriverClassName(driverClassName);
  ds.setDefaultAutoCommit(autoCommit);
  return ds;
}
 
Example 3
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 4
Source File: JdbcStorageUpgradeTest.java    From apicurio-studio with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a datasource from a DB file found in the test resources.
 * @throws SQLException
 */
private static BasicDataSource createDatasourceFrom(String sqlFileName) throws Exception {
    // Step 1 - copy the db file from the classpath to a temp location
    URL sqlUrl = JdbcStorageUpgradeTest.class.getResource(sqlFileName);
    Assert.assertNotNull(sqlUrl);
    File tempDbFile = File.createTempFile("_apicurio_junit", ".mv.db");
    tempDbFile.deleteOnExit();

    String jdbcUrl = "jdbc:h2:file:" + tempDbFile.getAbsolutePath().replaceAll(".mv.db", "");
    
    // Step 2 - create a datasource from the file path
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(Driver.class.getName());
    ds.setUsername("sa");
    ds.setPassword("sa");
    ds.setUrl(jdbcUrl);
    
    try (Connection connection = ds.getConnection(); Reader reader = new InputStreamReader(sqlUrl.openStream())) {
        RunScript.execute(connection, reader);
    }
    
    return ds;
}
 
Example 5
Source File: JpaUnitPostProcessor.java    From zstack with 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 6
Source File: DbCommonServiceImpl.java    From bdf3 with Apache License 2.0 5 votes vote down vote up
@Override
public DataSource createDataSource(String url, String driverClassName, String username, String password) {
	BasicDataSource ds = new SerializableBasicDataSource();
	ds.setUsername(username);
	ds.setPassword(password);
	ds.setUrl(url);
	ds.setDriverClassName(driverClassName);
	ds.setMaxActive(5);
	ds.setMaxIdle(2);
	return ds;
}
 
Example 7
Source File: JdbcMetricsAccessorTest.java    From apiman with 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 8
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 9
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 10
Source File: AbstractLocalDataSourceConfig.java    From spring-music with Apache License 2.0 5 votes vote down vote up
protected DataSource createDataSource(String jdbcUrl, String driverClass, String userName, String password) {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setUrl(jdbcUrl);
    dataSource.setDriverClassName(driverClass);
    dataSource.setUsername(userName);
    dataSource.setPassword(password);
    return dataSource;
}
 
Example 11
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 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: PartitionTemplateWithEmfTest.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 14
Source File: ManagerApiTestServer.java    From apiman with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an h2 file based datasource.
 * @throws SQLException
 */
private static BasicDataSource createFileDatasource(File outputDirectory) throws SQLException {
    TestUtil.setProperty("apiman.hibernate.dialect", "org.hibernate.dialect.H2Dialect");
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(Driver.class.getName());
    ds.setUsername("sa");
    ds.setPassword("");
    ds.setUrl("jdbc:h2:" + outputDirectory.toString() + "/apiman-manager-api;MVCC=true");
    Connection connection = ds.getConnection();
    connection.close();
    System.out.println("DataSource created and bound to JNDI.");
    return ds;
}
 
Example 15
Source File: AbstractSpringDBUnitTest.java    From sharding-jdbc-1.5.1 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.setMaxActive(100);
    return result;
}
 
Example 16
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 17
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 18
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 19
Source File: DdlUtilsTest.java    From gemfirexd-oss with Apache License 2.0 4 votes vote down vote up
static void runImportExportTest_Export(final String clientUrl,
    final String userName, final String password,
    final String schemaFileName, final String dataFileName) throws Throwable {

  // first dump this to XML

  String dbtype = (new PlatformUtils()).determineDatabaseType(
      "com.pivotal.gemfirexd.jdbc.ClientDriver", "jdbc:gemfirexd://" + clientUrl);
  getLogger().info("DB TYPE = " + dbtype);

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

  DatabaseToDdlTask fromDBTask = new DatabaseToDdlTask();
  fromDBTask.addConfiguredDatabase(dataSource);
  fromDBTask.setDatabaseType(dbtype);

  WriteSchemaToFileCommand writeSchemaToFile = new WriteSchemaToFileCommand();
  File schemaFile = new File(schemaFileName);
  writeSchemaToFile.setFailOnError(true);
  writeSchemaToFile.setOutputFile(schemaFile);

  WriteDataToFileCommand writeDataToFile = new WriteDataToFileCommand();
  File dataFile = new File(dataFileName);
  writeDataToFile.setFailOnError(true);
  writeDataToFile.setOutputFile(dataFile);

  fromDBTask.addWriteSchemaToFile(writeSchemaToFile);
  fromDBTask.addWriteDataToFile(writeDataToFile);

  fromDBTask.execute();

  dataSource.close();

  // end dump to XML
}
 
Example 20
Source File: DefaultDataSourceFactory.java    From smart-framework with Apache License 2.0 4 votes vote down vote up
@Override
public void setUsername(BasicDataSource ds, String username) {
    ds.setUsername(username);
}