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

The following examples show how to use org.apache.commons.dbcp2.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: DataSourceConfigurationTest.java    From shardingsphere with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void assertGetDataSourceConfigurationWithConnectionInitSqls() {
    BasicDataSource actualDataSource = new BasicDataSource();
    actualDataSource.setDriverClassName("org.h2.Driver");
    actualDataSource.setUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MySQL");
    actualDataSource.setUsername("root");
    actualDataSource.setPassword("root");
    actualDataSource.setConnectionInitSqls(Arrays.asList("set names utf8mb4;", "set names utf8;"));
    DataSourceConfiguration actual = DataSourceConfiguration.getDataSourceConfiguration(actualDataSource);
    assertThat(actual.getDataSourceClassName(), is(BasicDataSource.class.getName()));
    assertThat(actual.getProps().get("driverClassName").toString(), is("org.h2.Driver"));
    assertThat(actual.getProps().get("url").toString(), is("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MySQL"));
    assertThat(actual.getProps().get("username").toString(), is("root"));
    assertThat(actual.getProps().get("password").toString(), is("root"));
    assertNull(actual.getProps().get("loginTimeout"));
    assertThat(actual.getProps().get("connectionInitSqls"), instanceOf(List.class));
    List<String> actualConnectionInitSql = (List<String>) actual.getProps().get("connectionInitSqls");
    assertThat(actualConnectionInitSql, hasItem("set names utf8mb4;"));
    assertThat(actualConnectionInitSql, hasItem("set names utf8;"));
}
 
Example 2
Source File: DatabaseConnectionFactoryTest.java    From jpa-unit with Apache License 2.0 6 votes vote down vote up
@Test
public void testOpenConnectionToH2DbHavingAllSupportedPersistenceProperties() throws ClassNotFoundException {
    // GIVEN
    final BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(H2_DRIVER_CLASS_PROP_VALUE);
    ds.setUsername(USERNAME_PROP_VALUE);
    ds.setPassword(PASSWORD_PROP_VALUE);
    ds.setUrl(H2_CONNECTION_URL_PROP_VALUE);

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

    // THEN
    assertThat(connection, notNullValue());
    assertThat(connection, instanceOf(H2Connection.class));
}
 
Example 3
Source File: MultiJdbcSchemaJoinTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Tests {@link org.apache.calcite.adapter.jdbc.JdbcCatalogSchema}. */
@Test void test3() throws SQLException {
  final BasicDataSource dataSource = new BasicDataSource();
  dataSource.setUrl(TempDb.INSTANCE.getUrl());
  dataSource.setUsername("");
  dataSource.setPassword("");
  final JdbcCatalogSchema schema =
      JdbcCatalogSchema.create(null, "", dataSource, "PUBLIC");
  assertThat(schema.getSubSchemaNames(),
      is(Sets.newHashSet("INFORMATION_SCHEMA", "PUBLIC", "SYSTEM_LOBS")));
  final CalciteSchema rootSchema0 =
      CalciteSchema.createRootSchema(false, false, "", schema);
  final Driver driver = new Driver();
  final CalciteJdbc41Factory factory = new CalciteJdbc41Factory();
  final String sql = "select count(*) as c from information_schema.schemata";
  try (Connection connection =
           factory.newConnection(driver, factory,
               "jdbc:calcite:", new Properties(), rootSchema0, null);
       Statement stmt3 = connection.createStatement();
       ResultSet rs = stmt3.executeQuery(sql)) {
    assertThat(CalciteAssert.toString(rs), equalTo("C=3\n"));
  }
}
 
Example 4
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 5
Source File: ResourceFactory.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
private static void internal_dbcp2() throws Exception {

		for (Entry<String, DataServer> entry : Config.nodes().dataServers().entrySet()) {

			BasicDataSource dataSource = new BasicDataSource();

			String url = "jdbc:h2:tcp://" + entry.getKey() + ":" + entry.getValue().getTcpPort() + "/X;JMX="
					+ (entry.getValue().getJmxEnable() ? "TRUE" : "FALSE") + ";CACHE_SIZE="
					+ (entry.getValue().getCacheSize() * 1024);
			dataSource.setDriverClassName(SlicePropertiesBuilder.driver_h2);
			dataSource.setUrl(url);
			dataSource.setInitialSize(0);
			dataSource.setMinIdle(0);
			dataSource.setMaxTotal(50);
			dataSource.setMaxIdle(50);
			dataSource.setUsername("sa");
			dataSource.setTestOnCreate(false);
			dataSource.setTestWhileIdle(false);
			dataSource.setTestOnReturn(false);
			dataSource.setTestOnBorrow(false);
			dataSource.setPassword(Config.token().getPassword());
			String name = Config.nodes().dataServers().name(entry.getValue());
			new Resource(Config.RESOURCE_JDBC_PREFIX + name, dataSource);

		}
	}
 
Example 6
Source File: DBCP2DataSourcePool.java    From EasyReport with Apache License 2.0 6 votes vote down vote up
@Override
public DataSource wrap(final ReportDataSource rptDs) {
    try {
        final BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(rptDs.getDriverClass());
        dataSource.setUrl(rptDs.getJdbcUrl());
        dataSource.setUsername(rptDs.getUser());
        dataSource.setPassword(rptDs.getPassword());
        dataSource.setInitialSize(MapUtils.getInteger(rptDs.getOptions(), "initialSize", 3));
        dataSource.setMaxIdle(MapUtils.getInteger(rptDs.getOptions(), "maxIdle", 20));
        dataSource.setMinIdle(MapUtils.getInteger(rptDs.getOptions(), "minIdle", 1));
        dataSource.setLogAbandoned(MapUtils.getBoolean(rptDs.getOptions(), "logAbandoned", true));
        dataSource.setRemoveAbandonedTimeout(
            MapUtils.getInteger(rptDs.getOptions(), "removeAbandonedTimeout", 180));
        dataSource.setMaxWaitMillis(MapUtils.getInteger(rptDs.getOptions(), "maxWait", 1000));
        return dataSource;
    } catch (final Exception ex) {
        throw new RuntimeException("C3p0DataSourcePool Create Error", ex);
    }
}
 
Example 7
Source File: DBCPPool.java    From MtgDesktopCompanion with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void init(String url, String user, String pass, boolean enable) {

	logger.debug("init connection to " + url + ", Pooling="+enable);
	dataSource =  new BasicDataSource();
       dataSource.setUrl(url);
       dataSource.setUsername(user);
       dataSource.setPassword(pass);

       props.entrySet().forEach(ks->{
       	try {
			BeanUtils.setProperty(dataSource, ks.getKey().toString(), ks.getValue());
		} catch (Exception e) {
			logger.error(e);
		} 
       });
       
       if(!enable) {
		  dataSource.setMinIdle(1);
          dataSource.setMaxIdle(1);
          dataSource.setInitialSize(0);
          dataSource.setMaxTotal(1);
	  }
 	}
 
Example 8
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 9
Source File: DataSourceSwapperTest.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
private DataSource createDBCPDataSource() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setUrl("jdbc:mysql://localhost:3306/demo_ds");
    dataSource.setUsername("root");
    dataSource.setPassword("root");
    return dataSource;
}
 
Example 10
Source File: PgConnectionHelper.java    From pg-index-health with Apache License 2.0 5 votes vote down vote up
private static void setCommonProperties(@Nonnull final BasicDataSource dataSource,
                                        @Nonnull final String userName,
                                        @Nonnull final String password) {
    dataSource.setDriverClassName("org.postgresql.Driver");
    dataSource.setUsername(userName);
    dataSource.setPassword(password);
    dataSource.setValidationQuery("select 1");
    dataSource.setMaxTotal(1);
    dataSource.setMaxIdle(1);
    dataSource.setMaxOpenPreparedStatements(1);
}
 
Example 11
Source File: DataSourceFactory.java    From jweb-cms with GNU Affero General Public License v3.0 5 votes vote down vote up
public DataSource build() {
    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setUrl(resetBaseDir(options.url));
    dataSource.setUsername(options.username);
    dataSource.setPassword(options.password);
    dataSource.setMaxTotal(options.pool.max);
    dataSource.setMinIdle(options.pool.min);
    return dataSource;
}
 
Example 12
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 13
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 14
Source File: ConfigCenterTest.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 15
Source File: DbTests.java    From morpheus-core with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a newly created DataSource based on Apache Commons DBCP
 * @param dbType        the database type
 * @param path          the path to the database file
 * @return              the newly created data source
 */
private static DataSource createDataSource(DbType dbType, File path) {
    System.out.println("Creating DataSource for " + path.getAbsolutePath());
    path.getParentFile().mkdirs();
    final BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDefaultAutoCommit(true);
    switch (dbType) {
        case H2:
            dataSource.setDriverClassName("org.h2.Driver");
            dataSource.setUrl("jdbc:h2://" + path.getAbsolutePath());
            dataSource.setUsername("sa");
            return dataSource;
        case HSQL:
            dataSource.setDriverClassName("org.hsqldb.jdbcDriver");
            dataSource.setUrl("jdbc:hsqldb:" + path.getAbsolutePath());
            dataSource.setUsername("sa");
            return dataSource;
        case SQLITE:
            dataSource.setDriverClassName("org.sqlite.JDBC");
            dataSource.setUrl("jdbc:sqlite:" + path.getAbsolutePath());
            dataSource.setUsername("");
            dataSource.setPassword("");
            return dataSource;

    }
    return dataSource;
}
 
Example 16
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 17
Source File: DatabaseConfiguration.java    From airsonic with GNU General Public License v3.0 5 votes vote down vote up
@Bean
@Profile("embed")
public DataSource embedDataSource(@Value("${DatabaseConfigEmbedDriver}") String driver,
                                       @Value("${DatabaseConfigEmbedUrl}") String url,
                                       @Value("${DatabaseConfigEmbedUsername}") String username,
                                       @Value("${DatabaseConfigEmbedPassword}") String password) {
    BasicDataSource basicDataSource = new BasicDataSource();
    basicDataSource.setDriverClassName(driver);
    basicDataSource.setUrl(url);
    basicDataSource.setUsername(username);
    basicDataSource.setPassword(password);
    return basicDataSource;
}
 
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: CommonUtil.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
/**
 * check the database url
 *
 * @param databaseUrl data bae url
 * @return connection
 */
public static Connection getDbcpConnection(String databaseUrl, String databaseType) {
    try {
        Map<String, String> requestUrlMap = uRLRequest(databaseUrl);
        // check all parameter
        if (!requestUrlMap.containsKey("user") || !requestUrlMap.containsKey("password") || StringUtils.isEmpty(urlPage(databaseUrl))) {
            return null;
        }
        // use the cache
        if (dsMap.containsKey(databaseUrl)) {
            // use the old connection
            return dsMap.get(databaseUrl).getConnection();
        } else {
            Properties properties = new Properties();
            BasicDataSource ds = BasicDataSourceFactory.createDataSource(properties);
            dsMap.put(databaseUrl, ds);
            if (DatabaseTypeEnum.H2_DATABASE.getCode().equals(databaseType)) {
                ds.setDriverClassName("org.h2.Driver");
            } else {
                ds.setDriverClassName("org.mariadb.jdbc.Driver");
            }
            ds.setUrl(urlPage(databaseUrl));
            ds.setUsername(requestUrlMap.get("user"));
            ds.setPassword(requestUrlMap.get("password"));

            ds.setInitialSize(Integer.parseInt(Objects.requireNonNull(ProcessorApplication.environment.getProperty("spring.datasource.dbcp2.initial-size"))));
            ds.setMinIdle(Integer.parseInt(Objects.requireNonNull(ProcessorApplication.environment.getProperty("spring.datasource.dbcp2.min-idle"))));
            ds.setMaxWaitMillis(Integer.parseInt(Objects.requireNonNull(ProcessorApplication.environment.getProperty("spring.datasource.dbcp2.max-wait-millis"))));
            ds.setMaxTotal(Integer.parseInt(Objects.requireNonNull(ProcessorApplication.environment.getProperty("spring.datasource.dbcp2.max-total"))));

            return ds.getConnection();
        }
    } catch (Exception e) {
        log.error("e:{}", e.toString());
        return null;
    }
}
 
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;
}