Java Code Examples for com.zaxxer.hikari.HikariDataSource#setPassword()

The following examples show how to use com.zaxxer.hikari.HikariDataSource#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
@Test
public void assertAddAlias() {
    HikariDataSource actualDataSource = new HikariDataSource();
    actualDataSource.setDriverClassName("org.h2.Driver");
    actualDataSource.setJdbcUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MySQL");
    actualDataSource.setUsername("root");
    actualDataSource.setPassword("root");
    DataSourceConfiguration actual = DataSourceConfiguration.getDataSourceConfiguration(actualDataSource);
    actual.addAlias("url", "jdbcUrl");
    actual.addAlias("user", "username");
    assertThat(actual.getDataSourceClassName(), is(HikariDataSource.class.getName()));
    assertThat(actual.getProps().get("driverClassName").toString(), is("org.h2.Driver"));
    assertThat(actual.getProps().get("jdbcUrl").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"));
    assertThat(actual.getProps().get("jdbcUrl"), is(actual.getProps().get("url")));
    assertThat(actual.getProps().get("username"), is(actual.getProps().get("user")));
}
 
Example 2
Source File: EnodeTestDataSourceConfig.java    From enode with MIT License 6 votes vote down vote up
@Bean("enodePgDataSource")
@ConditionalOnProperty(prefix = "spring.enode", name = "eventstore", havingValue = "pg")
public HikariDataSource pgDataSource() {
    HikariDataSource dataSource = new HikariDataSource();
    dataSource.setJdbcUrl("jdbc:postgresql://localhost:5432/enode");
    dataSource.setUsername("postgres");
    dataSource.setPassword("mysecretpassword");
    dataSource.setDriverClassName(org.postgresql.Driver.class.getName());
    return dataSource;
}
 
Example 3
Source File: PostgreSqlDataSource.java    From AuthMeReloaded with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Sets up the connection arguments to the database.
 */
private void setConnectionArguments() {
    ds = new HikariDataSource();
    ds.setPoolName("AuthMePostgreSQLPool");

    // Pool Settings
    ds.setMaximumPoolSize(poolSize);
    ds.setMaxLifetime(maxLifetime * 1000);

    // Database URL
    ds.setDriverClassName("org.postgresql.Driver");
    ds.setJdbcUrl("jdbc:postgresql://" + this.host + ":" + this.port + "/" + this.database);

    // Auth
    ds.setUsername(this.username);
    ds.setPassword(this.password);

    // Random stuff
    ds.addDataSourceProperty("reWriteBatchedInserts", "true");

    // Caching
    ds.addDataSourceProperty("cachePrepStmts", "true");
    ds.addDataSourceProperty("preparedStatementCacheQueries", "275");

    logger.info("Connection arguments loaded, Hikari ConnectionPool ready!");
}
 
Example 4
Source File: DataSourceService.java    From mapper-generator-javafx with Apache License 2.0 6 votes vote down vote up
/**
 * 测试数据源
 *
 * @param dataSource 数据源
 * @return true 成功 false 失败
 */
public boolean testConnection(DataSource dataSource) {
    HikariDataSource hikariDataSource = new HikariDataSource();
    hikariDataSource.setUsername(dataSource.getUser());
    hikariDataSource.setPassword(dataSource.getPassword());
    hikariDataSource.setJdbcUrl("jdbc:mysql://" + dataSource.getHost() + ":" + dataSource.getPort() + "/" + dataSource.getDatabase() + "?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&useSSL=false&serverTimezone=CTT");
    hikariDataSource.setDriverClassName(dataSource.getDriveName());
    hikariDataSource.setConnectionTimeout(250);
    JdbcTemplate jdbcTemplate = applicationContext.getBean(JdbcTemplate.class);
    jdbcTemplate.setDataSource(hikariDataSource);

    try {
        jdbcTemplate.query("SELECT 1", (rs, rowNum) -> rs.getString(1));
    } catch (Exception e) {
        return false;
    }
    return true;
}
 
Example 5
Source File: DataSourceConfigurationTest.java    From shardingsphere with Apache License 2.0 6 votes vote down vote up
@Test
public void assertGetDataSourceConfiguration() throws SQLException {
    HikariDataSource actualDataSource = new HikariDataSource();
    actualDataSource.setDriverClassName("org.h2.Driver");
    actualDataSource.setJdbcUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MySQL");
    actualDataSource.setUsername("root");
    actualDataSource.setPassword("root");
    actualDataSource.setLoginTimeout(1);
    DataSourceConfiguration actual = DataSourceConfiguration.getDataSourceConfiguration(actualDataSource);
    assertThat(actual.getDataSourceClassName(), is(HikariDataSource.class.getName()));
    assertThat(actual.getProps().get("driverClassName").toString(), is("org.h2.Driver"));
    assertThat(actual.getProps().get("jdbcUrl").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"));
}
 
Example 6
Source File: JobConfiguration.java    From CogStack-Pipeline with Apache License 2.0 6 votes vote down vote up
@Profile({"jdbc_out", "jdbc_out_map"})
@Bean(destroyMethod = "close")
@Qualifier("targetDataSource")
public DataSource targetDataSource() {
    HikariDataSource mainDatasource = new HikariDataSource();
    // read and set the mandatory DB connector properties
    executeSessionScripts(mainDatasource, env.getRequiredProperty("target.Driver"));
    mainDatasource.setDriverClassName(env.getRequiredProperty("target.Driver"));
    mainDatasource.setJdbcUrl(env.getRequiredProperty("target.JdbcPath"));
    mainDatasource.setUsername(env.getRequiredProperty("target.username"));
    mainDatasource.setPassword(env.getRequiredProperty("target.password"));
    // set optional properties
    mainDatasource.setIdleTimeout(targetIdleTimeout);
    mainDatasource.setMaxLifetime(targetMaxLifeTime);
    if (targetPoolSize > 0){
        mainDatasource.setMaximumPoolSize(targetPoolSize);
    }
    return mainDatasource;
}
 
Example 7
Source File: DbUtil.java    From spring-boot-demo with MIT License 5 votes vote down vote up
public HikariDataSource buildFromTableRequest(TableRequest request) {
    HikariDataSource dataSource = new HikariDataSource();
    dataSource.setJdbcUrl(request.getPrepend() + request.getUrl());
    dataSource.setUsername(request.getUsername());
    dataSource.setPassword(request.getPassword());
    return dataSource;
}
 
Example 8
Source File: DynamicDataSource.java    From spring-boot-demo with MIT License 5 votes vote down vote up
/**
 * 初始化数据源
 * @param id 数据源id
 * @return 数据源
 */
private HikariDataSource initDatasource(Long id) {
    HikariDataSource dataSource = new HikariDataSource();

    // 判断是否是默认数据源
    if (DatasourceHolder.DEFAULT_ID.equals(id)) {
        // 默认数据源根据 application.yml 配置的生成
        DataSourceProperties properties = SpringUtil.getBean(DataSourceProperties.class);
        dataSource.setJdbcUrl(properties.getUrl());
        dataSource.setUsername(properties.getUsername());
        dataSource.setPassword(properties.getPassword());
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
    } else {
        // 不是默认数据源,通过缓存获取对应id的数据源的配置
        DatasourceConfig datasourceConfig = DatasourceConfigCache.INSTANCE.getConfig(id);

        if (datasourceConfig == null) {
            throw new RuntimeException("无此数据源");
        }

        dataSource.setJdbcUrl(datasourceConfig.buildJdbcUrl());
        dataSource.setUsername(datasourceConfig.getUsername());
        dataSource.setPassword(datasourceConfig.getPassword());
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
    }
    // 将创建的数据源添加到数据源管理器中,绑定当前线程
    DatasourceHolder.INSTANCE.addDatasource(id, dataSource);
    return dataSource;
}
 
Example 9
Source File: YamlDataSourceFactory.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
public static DataSource createDataSource(final File yamlFile) throws IOException {
    DatasourceConfiguration datasourceConfig = YamlEngine.unmarshal(yamlFile, DatasourceConfiguration.class);
    HikariDataSource result = new HikariDataSource();
    result.setDriverClassName(datasourceConfig.getDriverClassName());
    result.setJdbcUrl(datasourceConfig.getJdbcUrl());
    result.setUsername(datasourceConfig.getUsername());
    result.setPassword(datasourceConfig.getPassword());
    return result;
}
 
Example 10
Source File: GenericDataSource.java    From light-4j with Apache License 2.0 5 votes vote down vote up
protected HikariDataSource createDataSource() {
    // get the configured datasources
    Map<String, Object> dataSourceMap = Config.getInstance().getJsonMapConfig(DATASOURCE);

    // get the decrypted secret file
    Map<String, Object> secret = Config.getInstance().getJsonMapConfig(SECRET);

    // get the requested datasource
    Map<String, Object> mainParams = (Map<String, Object>) dataSourceMap.get(getDsName());
    Map<String, String> configParams = (Map<String, String>)mainParams.get("parameters");

    // create the DataSource
    ds = new HikariDataSource();
    ds.setJdbcUrl((String)mainParams.get("jdbcUrl"));
    ds.setUsername((String)mainParams.get("username"));

    // use encrypted password
    String password = (String)mainParams.get(DB_PASSWORD);
    if (password==null) {
        password = (String)secret.get(getDbPassKey());
    }
    ds.setPassword(password);

    // set datasource paramters
    ds.setMaximumPoolSize((Integer)mainParams.get("maximumPoolSize"));
    ds.setConnectionTimeout((Integer)mainParams.get("connectionTimeout"));

    // add datasource specific connection parameters
    if(configParams != null) configParams.forEach((k, v) -> ds.addDataSourceProperty(k, v));

    return ds;
}
 
Example 11
Source File: IntegrationTestSupport.java    From r2dbc-mysql with Apache License 2.0 5 votes vote down vote up
static JdbcTemplate jdbc(MySqlConnectionConfiguration configuration, @Nullable String timezone) {
    HikariDataSource source = new HikariDataSource();

    source.setJdbcUrl(String.format("jdbc:mysql://%s:%d/%s", configuration.getDomain(), configuration.getPort(), configuration.getDatabase()));
    source.setUsername(configuration.getUser());
    source.setPassword(Optional.ofNullable(configuration.getPassword()).map(Object::toString).orElse(null));
    source.setMaximumPoolSize(1);
    source.setConnectionTimeout(Optional.ofNullable(configuration.getConnectTimeout()).map(Duration::toMillis).orElse(0L));

    if (timezone != null) {
        source.addDataSourceProperty("serverTimezone", timezone);
    }

    return new JdbcTemplate(source);
}
 
Example 12
Source File: HikariDataSourceFactory.java    From PeonyFramwork with Apache License 2.0 5 votes vote down vote up
private DataSource create() {
        HikariDataSource ds = new HikariDataSource();
        ds.setJdbcUrl(url);
        ds.setUsername(username);
        ds.setPassword(password);
        ds.setDriverClassName(driver);

        ds.setReadOnly(false);
        // 等待连接池分配连接的最大时长(毫秒),超过这个时长还没可用的连接则发生SQLException, 缺省:30秒
        ds.setConnectionTimeout(30000);
        // 一个连接idle状态的最大时长(毫秒),超时则被释放(retired),缺省:10分钟
//        config.setIdleTimeout(configEntity.getMaxIdleTime());
        // 一个连接的生命时长(毫秒),超时而且没被使用则被释放(retired),缺省:30分钟,建议设置比数据库超时时长少30秒,参考MySQLwait_timeout参数(show variables like '%timeout%';)
        ds.setMaxLifetime(1800000 - 60000);
        // 连接池中允许的最大连接数。缺省值:10;推荐的公式:((core_count * 2) + effective_spindle_count)
        ds.setMaximumPoolSize(Runtime.getRuntime().availableProcessors() * 5 + 30);
        ds.setConnectionInitSql("set names utf8mb4"); // 支持表情符
//        ds.setInitialSize(1);
//        config.setMinIdle(1);
//        ds.setMaxActive(400);
//        ds.setMaxWait(10000);
//        ds.setTimeBetweenEvictionRunsMillis(600000);
//        ds.setMinEvictableIdleTimeMillis(600000);
//        ds.setTestWhileIdle(true);
//        ds.setTestOnBorrow(true);
//        ds.setTestOnReturn(false);
//        ds.setValidationQuery("select 1");
//        ds.setConnectionInitSqls(Arrays.asList("set names utf8mb4")); // 支持表情符

//        ds.addDataSourceProperty("cachePrepStmts", "true");
//        ds.addDataSourceProperty("prepStmtCacheSize", "250");
//        ds.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
        return ds;
    }
 
Example 13
Source File: HikariDataSourceConfiguration.java    From sofa-tracer with Apache License 2.0 5 votes vote down vote up
@Bean
public DataSource hikariDataSource() {
    HikariDataSource dataSource = new HikariDataSource();
    dataSource.setJdbcUrl(jdbcUrl);
    dataSource.setDriverClassName(driverClassName);
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    return dataSource;
}
 
Example 14
Source File: ACSShell.java    From freeacs with MIT License 5 votes vote down vote up
public static DataSource getHikariDataSource(String prefix) {
  HikariDataSource ds = new HikariDataSource();
  String jdbcUrl = prefix + ".datasource.jdbcUrl";
  ds.setJdbcUrl(
      Optional.ofNullable(System.getProperty(jdbcUrl))
          .orElseGet(() -> Properties.pr.getProperty(jdbcUrl)));
  String className = prefix + ".datasource.driverClassName";
  ds.setDriverClassName(
      Optional.ofNullable(System.getProperty(className))
          .orElseGet(() -> Properties.pr.getProperty(className)));
  String user = prefix + ".datasource.username";
  ds.setUsername(
      Optional.ofNullable(System.getProperty(user))
          .orElseGet(() -> Properties.pr.getProperty(user)));
  String password = prefix + ".datasource.password";
  ds.setPassword(
      Optional.ofNullable(System.getProperty(password))
          .orElseGet(() -> Properties.pr.getProperty(password)));
  String poolSize = prefix + ".datasource.maximum-pool-size";
  ds.setMaximumPoolSize(
      Integer.parseInt(
          Optional.ofNullable(System.getProperty(poolSize))
              .orElseGet(() -> Properties.pr.getProperty(poolSize))));
  String minimumIdle = prefix + ".datasource.minimum-idle";
  ds.setMinimumIdle(
      Integer.parseInt(
          Optional.ofNullable(System.getProperty(minimumIdle))
              .orElseGet(() -> Properties.pr.getProperty(minimumIdle))));
  String poolName = prefix + ".datasource.poolName";
  ds.setPoolName(
      Optional.ofNullable(System.getProperty(poolName))
          .orElseGet(() -> Properties.pr.getProperty(poolName)));
  return ds;
}
 
Example 15
Source File: DataSourceService.java    From mapper-generator-javafx with Apache License 2.0 5 votes vote down vote up
/**
 * 注册dataSource至Spring
 *
 * @param dataSource 数据源信息
 */
private void addDataSourceToSpring(DataSource dataSource) {
    ConfigurableApplicationContext applicationContext = (ConfigurableApplicationContext) this.applicationContext;
    HikariDataSource hikariDataSource = new HikariDataSource();
    hikariDataSource.setUsername(dataSource.getUser());
    hikariDataSource.setPassword(dataSource.getPassword());
    hikariDataSource.setJdbcUrl("jdbc:mysql://" + dataSource.getHost() + ":" + dataSource.getPort() + "/" + dataSource.getDatabase() + "?useUnicode=true&characterEncoding=utf-8&autoReconnect=true&useSSL=false&serverTimezone=CTT");
    hikariDataSource.setDriverClassName(dataSource.getDriveName());
    JdbcTemplate jdbcTemplate = new JdbcTemplate(hikariDataSource);
    if (!applicationContext.containsBean(dataSource.toString())) {
        applicationContext.getBeanFactory().registerSingleton(dataSource.toString(), jdbcTemplate);
    }
}
 
Example 16
Source File: DatabaseProvider.java    From database with Apache License 2.0 5 votes vote down vote up
public static Pool createPool(Config config) {
  String url = config.getString("database.url");
  if (url == null) {
    throw new DatabaseException("You must provide database.url");
  }

  HikariDataSource ds = new HikariDataSource();
  // If we don't provide a pool name it will automatically generate one, but
  // the way it does that requires PropertyPermission("*", "read,write") and
  // will fail if the security sandbox is enabled
  ds.setPoolName(config.getString("database.pool.name", "HikariPool-" + poolNameCounter.getAndAdd(1)));
  ds.setJdbcUrl(url);
  String driverClassName = config.getString("database.driver.class", Flavor.driverForJdbcUrl(url));
  ds.setDriverClassName(driverClassName);
  ds.setUsername(config.getString("database.user"));
  ds.setPassword(config.getString("database.password"));
  int poolSize = config.getInteger("database.pool.size", 10);
  ds.setMaximumPoolSize(poolSize);
  ds.setAutoCommit(false);

  Flavor flavor;
  String flavorString = config.getString("database.flavor");
  if (flavorString != null) {
    flavor = Flavor.valueOf(flavorString);
  } else {
    flavor = Flavor.fromJdbcUrl(url);
  }

  log.debug("Created '" + flavor + "' connection pool of size " + poolSize + " using driver " + driverClassName);

  return new Pool(ds, poolSize, flavor, ds);
}
 
Example 17
Source File: DataSourceUtil.java    From opensharding-spi-impl-example with Apache License 2.0 5 votes vote down vote up
public static DataSource createDataSource(final String dataSourceName) {
    HikariDataSource result = new HikariDataSource();
    result.setDriverClassName(com.mysql.jdbc.Driver.class.getName());
    result.setJdbcUrl(String.format("jdbc:mysql://%s:%s/%s?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF-8", HOST, PORT, dataSourceName));
    result.setUsername(USER_NAME);
    result.setPassword(PASSWORD);
    return result;
}
 
Example 18
Source File: EnodeTestDataSourceConfig.java    From enode with MIT License 5 votes vote down vote up
@Bean("enodeTiDBDataSource")
@ConditionalOnProperty(prefix = "spring.enode", name = "eventstore", havingValue = "tidb")
public HikariDataSource tidbDataSource() {
    HikariDataSource dataSource = new HikariDataSource();
    dataSource.setJdbcUrl("jdbc:mysql://127.0.0.1:4000/enode?");
    dataSource.setUsername("root");
    dataSource.setPassword("");
    dataSource.setDriverClassName(com.mysql.cj.jdbc.Driver.class.getName());
    return dataSource;
}
 
Example 19
Source File: HikariCPDataSourceBuilder.java    From micro-server with Apache License 2.0 5 votes vote down vote up
private DataSource getDataSource() {
	HikariDataSource ds = new HikariDataSource();

	ds.setDriverClassName(mainEnv.getDriverClassName());
	ds.setJdbcUrl(mainEnv.getUrl());
	ds.setUsername(mainEnv.getUsername());
	ds.setPassword(mainEnv.getPassword());
	ds.setMaximumPoolSize(hikariCPEnv.getMaxPoolSize());
	ds.setMinimumIdle(hikariCPEnv.getMinimumIdle());
	ds.setIdleTimeout(hikariCPEnv.getIdleTimeout());

	return ds;
}
 
Example 20
Source File: HikariCPProvider.java    From tastjava with MIT License 4 votes vote down vote up
@Override
public boolean register() {
    if (IsRegistered) {
        return HAS_REGISTERED;
    }

    HikariDataSource ds = new HikariDataSource();

    //basic config
    ds.setJdbcUrl(jdbcURL);
    ds.setDriverClassName(jdbcDriver);
    ds.setUsername(jdbcUsername);
    ds.setPassword(jdbcPassword);

    //custom config
    ds.setAutoCommit(autoCommit);
    ds.setConnectionTimeout(connectionTimeout);
    ds.setIdleTimeout(idleTimeout);
    ds.setMaxLifetime(maxLifetime);
    ds.setMaximumPoolSize(maximumPoolSize);
    ds.setValidationTimeout(validationTimeout);
    ds.setLeakDetectionThreshold(leakDetectionThreshold);

    if (!StrUtil.isBlank(poolName)) {
        ds.setPoolName(poolName);
    }

    if (!StrUtil.isBlank(catalog)) {
        ds.setCatalog(catalog);
    }

    if (!StrUtil.isBlank(connectionInitSql)) {
        ds.setConnectionInitSql(connectionInitSql);
    }

    if (!StrUtil.isBlank(transactionIsolation)) {
        ds.setTransactionIsolation(transactionIsolation);
    }

    if (jdbcURL.contains(":mysql:")) {
        ds.addDataSourceProperty("cachePrepStmts", "true");
        ds.addDataSourceProperty("prepStmtCacheSize", "250");
        ds.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
        ds.addDataSourceProperty("useServerPrepStmts", "true");
    }

    setDataSource(ds);
    setIsRegistered(HAS_REGISTERED);
    return HAS_REGISTERED;
}