Java Examples for com.zaxxer.hikari.HikariDataSource

The following java examples will help you to understand the usage of com.zaxxer.hikari.HikariDataSource. These source code samples are taken from different open source projects.

Example 1
Project: micro-server-master  File: HikariCPDataSourceBuilder.java View source code
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 2
Project: testcontainers-java-master  File: JDBCDriverWithPoolTest.java View source code
private static HikariDataSource getHikariDataSourceWithDriverClassName() {
    HikariConfig hikariConfig = new HikariConfig();
    // append a dummy URL element to ensure different DB per test
    hikariConfig.setJdbcUrl(URL + ";TEST=HIKARI_WITH_CLASSNAME");
    hikariConfig.setConnectionTestQuery("SELECT 1");
    hikariConfig.setMinimumIdle(3);
    hikariConfig.setMaximumPoolSize(10);
    hikariConfig.setDriverClassName(ContainerDatabaseDriver.class.getName());
    return new HikariDataSource(hikariConfig);
}
Example 3
Project: spring-cloud-connectors-master  File: HikariCpPooledDataSourceCreator.java View source code
@Override
public DataSource create(RelationalServiceInfo serviceInfo, ServiceConnectorConfig serviceConnectorConfig, String driverClassName, String validationQuery) {
    if (hasClass(HIKARI_DATASOURCE)) {
        logger.info("Found HikariCP on the classpath. Using it for DataSource connection pooling.");
        HikariDataSource ds = new HikariDataSource();
        setBasicDataSourceProperties(ds, serviceInfo, serviceConnectorConfig, driverClassName, validationQuery);
        return ds;
    } else {
        return null;
    }
}
Example 4
Project: enzymeportal-master  File: DevDataConfig.java View source code
@Bean
@Override
public DataSource dataSource() {
    String url = String.format("jdbc:oracle:thin:@%s:%s:%s", env.getRequiredProperty("ep.db.host"), env.getRequiredProperty("ep.db.port"), env.getRequiredProperty("ep.db.instance"));
    String user = env.getRequiredProperty("ep.db.username");
    String password = env.getRequiredProperty("ep.db.password");
    HikariConfig config = new HikariConfig();
    config.setJdbcUrl(url);
    config.setUsername(user);
    config.setPassword(password);
    config.setDriverClassName("oracle.jdbc.pool.OracleDataSource");
    // return new HikariDataSource(config);
    HikariDataSource ds = new HikariDataSource(config);
    ds.addDataSourceProperty("driverType", "thin");
    return ds;
}
Example 5
Project: HikariCP-master  File: TestConnections.java View source code
@Test
public void testCreate() throws SQLException {
    HikariConfig config = new HikariConfig();
    config.setMinimumIdle(1);
    config.setMaximumPoolSize(1);
    config.setConnectionTestQuery("VALUES 1");
    config.setConnectionInitSql("SELECT 1");
    config.setReadOnly(true);
    config.setConnectionTimeout(2500);
    config.setLeakDetectionThreshold(TimeUnit.SECONDS.toMillis(30));
    config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
    try (HikariDataSource ds = new HikariDataSource(config)) {
        ds.setLoginTimeout(10);
        Assert.assertSame(10, ds.getLoginTimeout());
        HikariPool pool = TestElf.getPool(ds);
        ds.getConnection().close();
        Assert.assertSame("Total connections not as expected", 1, pool.getTotalConnections());
        Assert.assertSame("Idle connections not as expected", 1, pool.getIdleConnections());
        Connection connection = ds.getConnection();
        Assert.assertNotNull(connection);
        Assert.assertSame("Total connections not as expected", 1, pool.getTotalConnections());
        Assert.assertSame("Idle connections not as expected", 0, pool.getIdleConnections());
        PreparedStatement statement = connection.prepareStatement("SELECT * FROM device WHERE device_id=?");
        Assert.assertNotNull(statement);
        statement.setInt(1, 0);
        ResultSet resultSet = statement.executeQuery();
        Assert.assertNotNull(resultSet);
        Assert.assertFalse(resultSet.next());
        resultSet.close();
        statement.close();
        connection.close();
        Assert.assertSame("Total connections not as expected", 1, pool.getTotalConnections());
        Assert.assertSame("Idle connections not as expected", 1, pool.getIdleConnections());
    }
}
Example 6
Project: myeslib-master  File: DatabaseModule.java View source code
@Provides
@Singleton
public DataSource datasource() throws SQLException {
    HikariConfig config = new HikariConfig();
    config.setPoolName("db-pool-jdbi-example");
    config.setDataSourceClassName(System.getenv("DB_DATASOURCE_CLASS_NAME"));
    config.addDataSourceProperty("URL", System.getenv("DB_URL"));
    config.addDataSourceProperty("user", System.getenv("DB_USER"));
    config.addDataSourceProperty("password", System.getenv("DB_PASSWORD"));
    config.setMinimumPoolSize(dbPoolMinConnections);
    config.setMaximumPoolSize(dbPoolMaxConnections);
    // oracle dialect
    config.setConnectionInitSql("select 1 + 1 from dual");
    config.setUseInstrumentation(true);
    config.setJdbc4ConnectionTest(true);
    return new HikariDataSource(config);
}
Example 7
Project: report-cockpit-birt-web-master  File: DatabaseConfigTest.java View source code
@Test
public void testReportcockpitDataSourceConfiguration() throws Exception {
    assertThat(dataSource, is(notNullValue()));
    assertThat(((HikariDataSource) dataSource).getJdbcUrl(), is("jdbc:hsqldb:mem:testdb;sql.syntax_ora=true"));
    assertThat(((HikariDataSource) dataSource).getUsername(), is("sa"));
    assertThat(((HikariDataSource) dataSource).getPassword(), is(""));
    assertThat(((HikariDataSource) dataSource).getDriverClassName(), is("org.hsqldb.jdbcDriver"));
}
Example 8
Project: constellation-master  File: PostgreSQLConfiguration.java View source code
@Override
public DataSource createCstlDatasource() {
    // Force loading driver because some containers like tomcat 7.0.21+ disable drivers at startup.
    try {
        Class.forName("org.postgresql.Driver");
    } catch (ClassNotFoundException ex) {
        LOGGER.warn(ex.getMessage(), ex);
    }
    final String databaseURL = Application.getProperty(AppProperty.CSTL_DATABASE_URL);
    if (databaseURL == null) {
        throw new ConfigurationRuntimeException("Property \"" + AppProperty.CSTL_DATABASE_URL.name() + "\" not defined.");
    }
    final HikariConfig config = DatabaseConfigurationUtils.createHikariConfig(databaseURL, "constellation", null);
    return new HikariDataSource(config);
}
Example 9
Project: datacollector-master  File: MysqlSource.java View source code
@Override
protected List<ConfigIssue> init() {
    List<ConfigIssue> issues = super.init();
    // Validate the port number
    try {
        port = Integer.valueOf(getConfig().port);
    } catch (NumberFormatException e) {
        throw new NumberFormatException("Port number must be numeric");
    }
    // ServerId can be empty. Validate if provided.
    try {
        if (getConfig().serverId != null && !getConfig().serverId.isEmpty())
            serverId = Integer.valueOf(getConfig().serverId);
    } catch (NumberFormatException e) {
        throw new NumberFormatException("Server ID must be numeric");
    }
    // check if binlog client connection is possible
    // we don't reuse this client later on, it is used just to check that client can connect, it
    // is immediately closed after connection.
    BinaryLogClient tmpClient = createBinaryLogClient();
    tmpClient.setServerId(serverId);
    try {
        tmpClient.setKeepAlive(false);
        tmpClient.connect(getConfig().connectTimeout);
    } catch (IOExceptionTimeoutException |  e) {
        LOG.error("Error connecting to MySql binlog: {}", e.getMessage(), e);
        issues.add(getContext().createConfigIssue(Groups.MYSQL.name(), null, Errors.MYSQL_003, e.getMessage(), e));
    } finally {
        try {
            tmpClient.disconnect();
        } catch (IOException e) {
            LOG.warn("Error disconnecting from MySql: {}", e.getMessage(), e);
        }
    }
    // create include/ignore filters
    Filter includeFilter = null;
    try {
        includeFilter = createIncludeFilter();
    } catch (IllegalArgumentException e) {
        LOG.error("Error creating include tables filter: {}", e.getMessage(), e);
        issues.add(getContext().createConfigIssue(Groups.ADVANCED.name(), "includeTables", Errors.MYSQL_008, e.getMessage(), e));
    }
    Filter ignoreFilter = null;
    try {
        ignoreFilter = createIgnoreFilter();
    } catch (IllegalArgumentException e) {
        LOG.error("Error creating ignore tables filter: {}", e.getMessage(), e);
        issues.add(getContext().createConfigIssue(Groups.ADVANCED.name(), "ignoreTables", Errors.MYSQL_007, e.getMessage(), e));
    }
    if (ignoreFilter != null && includeFilter != null) {
        eventFilter = includeFilter.and(ignoreFilter);
    }
    // connect to mysql
    HikariConfig hikariConfig = new HikariConfig();
    hikariConfig.setJdbcUrl(String.format("jdbc:mysql://%s:%d", getConfig().hostname, port));
    hikariConfig.setUsername(getConfig().username);
    hikariConfig.setPassword(getConfig().password);
    hikariConfig.setReadOnly(true);
    hikariConfig.addDataSourceProperty("useSSL", getConfig().useSsl);
    try {
        dataSource = new HikariDataSource(hikariConfig);
        offsetFactory = isGtidEnabled() ? new GtidSourceOffsetFactory() : new BinLogPositionOffsetFactory();
    } catch (PoolInitializationException e) {
        LOG.error("Error connecting to MySql: {}", e.getMessage(), e);
        issues.add(getContext().createConfigIssue(Groups.MYSQL.name(), null, Errors.MYSQL_003, e.getMessage(), e));
    }
    return issues;
}
Example 10
Project: developer-bookshelf-heroku-master  File: DatabaseConfiguration.java View source code
@Bean
@Profile(Constants.SPRING_PROFILE_DEVELOPMENT)
public DataSource dataSource() {
    log.debug("Configuring Datasource");
    if (propertyResolver.getProperty("url") == null && propertyResolver.getProperty("databaseName") == null) {
        log.error("Your database connection pool configuration is incorrect! The application" + "cannot start. Please check your Spring profile, current profiles are: {}", Arrays.toString(env.getActiveProfiles()));
        throw new ApplicationContextException("Database connection pool is not configured correctly");
    }
    HikariConfig config = new HikariConfig();
    config.setDataSourceClassName(propertyResolver.getProperty("dataSourceClassName"));
    if (propertyResolver.getProperty("url") == null || "".equals(propertyResolver.getProperty("url"))) {
        config.addDataSourceProperty("databaseName", propertyResolver.getProperty("databaseName"));
        config.addDataSourceProperty("serverName", propertyResolver.getProperty("serverName"));
    } else {
        config.addDataSourceProperty("url", propertyResolver.getProperty("url"));
    }
    config.addDataSourceProperty("user", propertyResolver.getProperty("username"));
    config.addDataSourceProperty("password", propertyResolver.getProperty("password"));
    return new HikariDataSource(config);
}
Example 11
Project: hibhik-master  File: CustomHikariConnectionProvider.java View source code
/**
	 * This is a hack, using reflection to get the pool-instance.
	 * @return
	 */
public HikariPool getPool() {
    HikariPool pool = null;
    try {
        Field fhds = HikariConnectionProvider.class.getDeclaredField("hds");
        fhds.setAccessible(true);
        HikariDataSource hds = (HikariDataSource) fhds.get(this);
        Field fpool = HikariDataSource.class.getDeclaredField("pool");
        fpool.setAccessible(true);
        pool = (HikariPool) fpool.get(hds);
    } catch (Exception e) {
        log.error("No pool fetched.", e);
    }
    return pool;
}
Example 12
Project: jfinal-api-scaffold-master  File: HikariCPPlugin.java View source code
@Override
public boolean start() {
    HikariConfig config = new HikariConfig();
    config.setMaximumPoolSize(maxPoolSize);
    //        config.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource");
    config.setDriverClassName(driverClass);
    config.setJdbcUrl(jdbcUrl);
    config.setUsername(user);
    config.setPassword(password);
    //防止中文乱�
    config.addDataSourceProperty("useUnicode", "true");
    config.addDataSourceProperty("characterEncoding", "utf8");
    config.setConnectionTestQuery("SELECT 1");
    this.dataSource = new HikariDataSource(config);
    return true;
}
Example 13
Project: jhipster-example-master  File: DatabaseConfiguration.java View source code
@Bean(destroyMethod = "shutdown")
@ConditionalOnMissingClass(name = "com.mycompany.myapp.config.HerokuDatabaseConfiguration")
@Profile("!" + Constants.SPRING_PROFILE_CLOUD)
public DataSource dataSource() {
    log.debug("Configuring Datasource");
    if (propertyResolver.getProperty("url") == null && propertyResolver.getProperty("databaseName") == null) {
        log.error("Your database connection pool configuration is incorrect! The application" + " cannot start. Please check your Spring profile, current profiles are: {}", Arrays.toString(env.getActiveProfiles()));
        throw new ApplicationContextException("Database connection pool is not configured correctly");
    }
    HikariConfig config = new HikariConfig();
    config.setDataSourceClassName(propertyResolver.getProperty("dataSourceClassName"));
    if (StringUtils.isEmpty(propertyResolver.getProperty("url"))) {
        config.addDataSourceProperty("databaseName", propertyResolver.getProperty("databaseName"));
        config.addDataSourceProperty("serverName", propertyResolver.getProperty("serverName"));
    } else {
        config.addDataSourceProperty("url", propertyResolver.getProperty("url"));
    }
    config.addDataSourceProperty("user", propertyResolver.getProperty("username"));
    config.addDataSourceProperty("password", propertyResolver.getProperty("password"));
    //MySQL optimizations, see https://github.com/brettwooldridge/HikariCP/wiki/MySQL-Configuration
    if ("com.mysql.jdbc.jdbc2.optional.MysqlDataSource".equals(propertyResolver.getProperty("dataSourceClassName"))) {
        config.addDataSourceProperty("cachePrepStmts", propertyResolver.getProperty("cachePrepStmts", "true"));
        config.addDataSourceProperty("prepStmtCacheSize", propertyResolver.getProperty("prepStmtCacheSize", "250"));
        config.addDataSourceProperty("prepStmtCacheSqlLimit", propertyResolver.getProperty("prepStmtCacheSqlLimit", "2048"));
        config.addDataSourceProperty("useServerPrepStmts", propertyResolver.getProperty("useServerPrepStmts", "true"));
    }
    if (metricRegistry != null) {
        config.setMetricRegistry(metricRegistry);
    }
    return new HikariDataSource(config);
}
Example 14
Project: joist-master  File: HikariDataSourceFactory.java View source code
@Override
public HikariDataSource create(ConnectionSettings settings) {
    HikariConfig config = new HikariConfig();
    this.addCommonOptions(settings, config);
    if (settings.db.isPg()) {
        this.addPostgresOptions(settings, config);
    } else if (settings.db.isMySQL()) {
        this.addMySQLOptions(settings, config);
    }
    this.addCustomOptions(settings, config);
    return new HikariDataSource(config);
}
Example 15
Project: org.ops4j.pax.jdbc-master  File: HikariPooledDataSourceFactory.java View source code
@Override
public DataSource create(DataSourceFactory dsf, Properties config) throws SQLException {
    try {
        DataSource ds = dsf.createDataSource(getNonPoolProps(config));
        Properties poolProps = getPoolProps(config);
        HikariConfig hconfig = new HikariConfig(poolProps);
        hconfig.setDataSource(ds);
        return new HikariDataSource(hconfig);
    } catch (Throwable e) {
        if (e instanceof SQLException) {
            throw (SQLException) e;
        } else if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        } else {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
}
Example 16
Project: rapidoid-master  File: JDBCPoolHikariTest.java View source code
@Test(timeout = 30000)
public void testHikariPool() {
    Conf.HIKARI.set("maximumPoolSize", 234);
    JdbcClient jdbc = JDBC.api();
    jdbc.h2("hikari-test");
    jdbc.dataSource(HikariFactory.createDataSourceFor(jdbc));
    jdbc.execute("create table abc (id int, name varchar)");
    jdbc.execute("insert into abc values (?, ?)", 123, "xyz");
    final Map<String, ?> expected = U.map("id", 123, "name", "xyz");
    Msc.benchmarkMT(100, "select", 100000, () -> {
        Map<String, Object> record = U.single(JDBC.query("select id, name from abc").all());
        record = Msc.lowercase(record);
        eq(record, expected);
    });
    HikariDataSource hikari = (HikariDataSource) jdbc.dataSource();
    eq(hikari.getMaximumPoolSize(), 234);
}
Example 17
Project: spring-boot-master  File: DataSourceInitializerTests.java View source code
@Test
public void testDataSourceInitialized() throws Exception {
    EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.initialize:true");
    this.context.register(DataSourceAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class);
    this.context.refresh();
    DataSource dataSource = this.context.getBean(DataSource.class);
    assertThat(dataSource).isInstanceOf(HikariDataSource.class);
    assertThat(dataSource).isNotNull();
    JdbcOperations template = new JdbcTemplate(dataSource);
    assertThat(template.queryForObject("SELECT COUNT(*) from BAR", Integer.class)).isEqualTo(1);
}
Example 18
Project: spring-boot-thymeleaf-heroku-template-master  File: DatabaseConfiguration.java View source code
@Bean
@Profile(Constants.SPRING_PROFILE_DEVELOPMENT)
public DataSource dataSource() {
    log.debug("Configuring Datasource");
    if (propertyResolver.getProperty("url") == null && propertyResolver.getProperty("databaseName") == null) {
        log.error("Your database connection pool configuration is incorrect! The application" + "cannot start. Please check your Spring profile, current profiles are: {}", Arrays.toString(env.getActiveProfiles()));
        throw new ApplicationContextException("Database connection pool is not configured correctly");
    }
    HikariConfig config = new HikariConfig();
    config.setDataSourceClassName(propertyResolver.getProperty("dataSourceClassName"));
    if (propertyResolver.getProperty("url") == null || "".equals(propertyResolver.getProperty("url"))) {
        config.addDataSourceProperty("databaseName", propertyResolver.getProperty("databaseName"));
        config.addDataSourceProperty("serverName", propertyResolver.getProperty("serverName"));
    } else {
        config.addDataSourceProperty("url", propertyResolver.getProperty("url"));
    }
    config.addDataSourceProperty("user", propertyResolver.getProperty("username"));
    config.addDataSourceProperty("password", propertyResolver.getProperty("password"));
    return new HikariDataSource(config);
}
Example 19
Project: strolch-master  File: PostgreSqlDbConnectionBuilder.java View source code
@SuppressWarnings("resource")
@Override
public DataSource build(String realm, String url, String username, String password, Properties props) {
    HikariDataSource ds;
    HikariConfig config = new HikariConfig(props);
    config.setAutoCommit(false);
    config.setPoolName(realm);
    config.setJdbcUrl(url);
    config.setUsername(username);
    config.setPassword(password);
    ds = new HikariDataSource(config);
    logger.info("[" + realm + "] PostgreSQL Connection pool to " + url + " has a maximum pool size of " + ds.getMaximumPoolSize() + " connections");
    return new StrolchPostgreDataSource(ds);
}
Example 20
Project: ABC-Go-master  File: DatabaseConfiguration.java View source code
@Bean(destroyMethod = "shutdown")
@ConditionalOnExpression("#{!environment.acceptsProfiles('cloud') && !environment.acceptsProfiles('heroku') && !environment.acceptsProfiles('openshift')}")
public DataSource dataSource() {
    log.debug("Configuring Datasource");
    if (dataSourcePropertyResolver.getProperty("url") == null && dataSourcePropertyResolver.getProperty("databaseName") == null) {
        log.error("Your database connection pool configuration is incorrect! The application" + " cannot start. Please check your Spring profile, current profiles are: {}", Arrays.toString(env.getActiveProfiles()));
        throw new ApplicationContextException("Database connection pool is not configured correctly");
    }
    HikariConfig config = new HikariConfig();
    config.setDataSourceClassName(dataSourcePropertyResolver.getProperty("dataSourceClassName"));
    if (StringUtils.isEmpty(dataSourcePropertyResolver.getProperty("url"))) {
        config.addDataSourceProperty("databaseName", dataSourcePropertyResolver.getProperty("databaseName"));
        config.addDataSourceProperty("serverName", dataSourcePropertyResolver.getProperty("serverName"));
    } else {
        config.addDataSourceProperty("url", dataSourcePropertyResolver.getProperty("url"));
    }
    config.addDataSourceProperty("user", dataSourcePropertyResolver.getProperty("username"));
    config.addDataSourceProperty("password", dataSourcePropertyResolver.getProperty("password"));
    if (metricRegistry != null) {
        config.setMetricRegistry(metricRegistry);
    }
    return new HikariDataSource(config);
}
Example 21
Project: BikeRentalServiceManager-master  File: DatabaseConfiguration.java View source code
@Bean
public DataSource dataSource() {
    log.debug("Configuring Datasource");
    if (propertyResolver.getProperty("url") == null && propertyResolver.getProperty("databaseName") == null) {
        log.error("Your database connection pool configuration is incorrect! The application" + "cannot start. Please check your Spring profile, current profiles are: {}", Arrays.toString(env.getActiveProfiles()));
        throw new ApplicationContextException("Database connection pool is not configured correctly");
    }
    HikariConfig config = new HikariConfig();
    config.setDataSourceClassName(propertyResolver.getProperty("dataSourceClassName"));
    if (propertyResolver.getProperty("url") == null || "".equals(propertyResolver.getProperty("url"))) {
        config.addDataSourceProperty("databaseName", propertyResolver.getProperty("databaseName"));
        config.addDataSourceProperty("serverName", propertyResolver.getProperty("serverName"));
    } else {
        config.addDataSourceProperty("url", propertyResolver.getProperty("url"));
    }
    config.addDataSourceProperty("user", propertyResolver.getProperty("username"));
    config.addDataSourceProperty("password", propertyResolver.getProperty("password"));
    return new HikariDataSource(config);
}
Example 22
Project: cevent-app-master  File: DatabaseConfiguration.java View source code
@Bean
public DataSource dataSource() {
    log.debug("Configuring Datasource");
    if (propertyResolver.getProperty("url") == null && propertyResolver.getProperty("databaseName") == null) {
        log.error("Your database connection pool configuration is incorrect! The application" + "cannot start. Please check your Spring profile, current profiles are: {}", Arrays.toString(env.getActiveProfiles()));
        throw new ApplicationContextException("Database connection pool is not configured correctly");
    }
    HikariConfig config = new HikariConfig();
    config.setDataSourceClassName(propertyResolver.getProperty("dataSourceClassName"));
    if (propertyResolver.getProperty("url") == null || "".equals(propertyResolver.getProperty("url"))) {
        config.addDataSourceProperty("databaseName", propertyResolver.getProperty("databaseName"));
        config.addDataSourceProperty("serverName", propertyResolver.getProperty("serverName"));
    } else {
        config.addDataSourceProperty("url", propertyResolver.getProperty("url"));
    }
    config.addDataSourceProperty("user", propertyResolver.getProperty("username"));
    config.addDataSourceProperty("password", propertyResolver.getProperty("password"));
    return new HikariDataSource(config);
}
Example 23
Project: csrf-jhipster-master  File: DatabaseConfiguration.java View source code
@Bean
public DataSource dataSource() {
    log.debug("Configuring Datasource");
    if (propertyResolver.getProperty("url") == null && propertyResolver.getProperty("databaseName") == null) {
        log.error("Your database connection pool configuration is incorrect! The application" + "cannot start. Please check your Spring profile, current profiles are: {}", Arrays.toString(env.getActiveProfiles()));
        throw new ApplicationContextException("Database connection pool is not configured correctly");
    }
    HikariConfig config = new HikariConfig();
    config.setDataSourceClassName(propertyResolver.getProperty("dataSourceClassName"));
    if (propertyResolver.getProperty("url") == null || "".equals(propertyResolver.getProperty("url"))) {
        config.addDataSourceProperty("databaseName", propertyResolver.getProperty("databaseName"));
        config.addDataSourceProperty("serverName", propertyResolver.getProperty("serverName"));
    } else {
        config.addDataSourceProperty("url", propertyResolver.getProperty("url"));
    }
    config.addDataSourceProperty("user", propertyResolver.getProperty("username"));
    config.addDataSourceProperty("password", propertyResolver.getProperty("password"));
    return new HikariDataSource(config);
}
Example 24
Project: datakernel-master  File: CubeTestUtils.java View source code
public static Configuration getJooqConfiguration(String databasePropertiesPath, SQLDialect databaseDialect) throws IOException {
    Properties properties = new Properties();
    properties.load(new InputStreamReader(new BufferedInputStream(new FileInputStream(new File(databasePropertiesPath))), UTF_8));
    HikariDataSource dataSource = new HikariDataSource(new HikariConfig(properties));
    Configuration jooqConfiguration = new DefaultConfiguration();
    jooqConfiguration.set(new DataSourceConnectionProvider(dataSource));
    jooqConfiguration.set(databaseDialect);
    return jooqConfiguration;
}
Example 25
Project: ehour-master  File: HikariConnectionProvider.java View source code
// *************************************************************************
// Configurable
// *************************************************************************
@SuppressWarnings("rawtypes")
@Override
public void configure(Map props) throws HibernateException {
    try {
        LOGGER.debug("Configuring HikariCP");
        this.hcfg = HikariConfigurationUtil.loadConfiguration(props);
        this.hds = new HikariDataSource(this.hcfg);
    } catch (Exception e) {
        throw new HibernateException(e);
    }
    LOGGER.debug("HikariCP Configured");
}
Example 26
Project: hammock-master  File: HammockDataSource.java View source code
private static DataSource createDelegate(DataSourceDefinition dataSourceDefinition) {
    HikariConfig config = new HikariConfig();
    if (dataSourceDefinition.url() != null) {
        config.setJdbcUrl(dataSourceDefinition.url());
    }
    if (dataSourceDefinition.user() != null) {
        config.setUsername(dataSourceDefinition.user());
        config.setPassword(dataSourceDefinition.password());
    }
    if (dataSourceDefinition.maxPoolSize() > 0) {
        config.setMaximumPoolSize(dataSourceDefinition.maxPoolSize());
    }
    config.addDataSourceProperty("cachePrepStmts", "true");
    config.addDataSourceProperty("prepStmtCacheSize", "250");
    config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
    return new HikariDataSource(config);
}
Example 27
Project: JavascriptGame-master  File: DatabaseConfiguration.java View source code
@Bean
public DataSource dataSource() {
    log.debug("Configuring Datasource");
    if (propertyResolver.getProperty("url") == null && propertyResolver.getProperty("databaseName") == null) {
        log.error("Your database connection pool configuration is incorrect! The application" + "cannot start. Please check your Spring profile, current profiles are: {}", Arrays.toString(env.getActiveProfiles()));
        throw new ApplicationContextException("Database connection pool is not configured correctly");
    }
    HikariConfig config = new HikariConfig();
    config.setDataSourceClassName(propertyResolver.getProperty("dataSourceClassName"));
    if (propertyResolver.getProperty("url") == null || "".equals(propertyResolver.getProperty("url"))) {
        config.addDataSourceProperty("databaseName", propertyResolver.getProperty("databaseName"));
        config.addDataSourceProperty("serverName", propertyResolver.getProperty("serverName"));
    } else {
        config.addDataSourceProperty("url", propertyResolver.getProperty("url"));
    }
    config.addDataSourceProperty("user", propertyResolver.getProperty("username"));
    config.addDataSourceProperty("password", propertyResolver.getProperty("password"));
    return new HikariDataSource(config);
}
Example 28
Project: liferay-portal-master  File: DataSourceFactoryImplTest.java View source code
@JVMArgsLine("-Dcatalina.base=. -D" + _HIKARICP_JAR_URL + "=${" + _HIKARICP_JAR_URL + "}")
@NewEnv(type = NewEnv.Type.JVM)
@Test
public void testHikariCP() throws Exception {
    RegistryUtil.setRegistry(new BasicRegistryImpl());
    System.setProperty("portal:jdbc.default.liferay.pool.provider", "hikaricp");
    String hikaricpJarURL = System.getProperty(_HIKARICP_JAR_URL);
    if (hikaricpJarURL != null) {
        System.setProperty("portal:" + PropsKeys.SETUP_LIFERAY_POOL_PROVIDER_JAR_URL + "[hikaricp]", hikaricpJarURL);
    }
    InitUtil.init();
    DataSource dataSource = null;
    try (CaptureAppender captureAppender = Log4JLoggerTestUtil.configureLog4JLogger(JarUtil.class.getName(), Level.INFO)) {
        dataSource = DataSourceFactoryUtil.initDataSource(_properties);
        List<LoggingEvent> loggingEvents = captureAppender.getLoggingEvents();
        Assert.assertEquals(loggingEvents.toString(), 4, loggingEvents.size());
        LoggingEvent loggingEvent = loggingEvents.get(0);
        String message = (String) loggingEvent.getMessage();
        Assert.assertTrue(message.startsWith("Downloading "));
        loggingEvent = loggingEvents.get(1);
        message = (String) loggingEvent.getMessage();
        Assert.assertTrue(message.startsWith("Downloaded "));
        loggingEvent = loggingEvents.get(2);
        message = (String) loggingEvent.getMessage();
        Assert.assertTrue(message.startsWith("Installing "));
        loggingEvent = loggingEvents.get(3);
        message = (String) loggingEvent.getMessage();
        Assert.assertTrue(message.startsWith("Installed "));
    }
    Class<?> dataSourceClass = dataSource.getClass();
    Assert.assertEquals("com.zaxxer.hikari.HikariDataSource", dataSourceClass.getName());
    for (int i = 0; i < _CHECKOUT_COUNT; i++) {
        Connection connection = dataSource.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement("SELECT 1 FROM INFORMATION_SCHEMA.SYSTEM_USERS");
        preparedStatement.execute();
    }
    MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
    ObjectName poolName = new ObjectName("com.zaxxer.hikari:type=Pool (TestJDBCPool)");
    int activeConnections = (int) mBeanServer.getAttribute(poolName, "ActiveConnections");
    Assert.assertEquals(_CHECKOUT_COUNT, activeConnections);
    int idleConnections = (int) mBeanServer.getAttribute(poolName, "IdleConnections");
    int totalConnections = (int) mBeanServer.getAttribute(poolName, "TotalConnections");
    Assert.assertEquals(totalConnections, activeConnections + idleConnections);
}
Example 29
Project: MLDS-master  File: DatabaseConfiguration.java View source code
@Bean
public DataSource dataSource() {
    log.debug("Configuring Datasource");
    if (propertyResolver.getProperty("url") == null && propertyResolver.getProperty("databaseName") == null) {
        log.error("Your database connection pool configuration is incorrect! The application" + "cannot start. Please check your Spring profile, current profiles are: {}", Arrays.toString(environment.getActiveProfiles()));
        throw new ApplicationContextException("Database connection pool is not configured correctly");
    }
    HikariConfig config = new HikariConfig();
    config.setDataSourceClassName(propertyResolver.getProperty("dataSourceClassName"));
    if (propertyResolver.getProperty("url") == null || "".equals(propertyResolver.getProperty("url"))) {
        config.addDataSourceProperty("databaseName", propertyResolver.getProperty("databaseName"));
        config.addDataSourceProperty("serverName", propertyResolver.getProperty("serverName"));
    } else {
        config.addDataSourceProperty("url", propertyResolver.getProperty("url"));
    }
    config.addDataSourceProperty("user", propertyResolver.getProperty("username"));
    config.addDataSourceProperty("password", propertyResolver.getProperty("password"));
    return new HikariDataSource(config);
}
Example 30
Project: monitoring-master  File: HikariCpPlugin.java View source code
private void addBasicDataSourceTransformer() {
    transformTemplate.transform("com.zaxxer.hikari.HikariDataSource", new TransformCallback() {

        @Override
        public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
            InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
            target.addInterceptor(HikariCpConstants.INTERCEPTOR_GET_CONNECTION);
            return target.toBytecode();
        }
    });
}
Example 31
Project: parkingfriends-master  File: DatabaseConfiguration.java View source code
@Bean
public DataSource dataSource() {
    log.debug("Configuring Datasource");
    if (propertyResolver.getProperty("url") == null && propertyResolver.getProperty("databaseName") == null) {
        log.error("Your database connection pool configuration is incorrect! The application" + "cannot start. Please check your Spring profile, current profiles are: {}", Arrays.toString(env.getActiveProfiles()));
        throw new ApplicationContextException("Database connection pool is not configured correctly");
    }
    HikariConfig config = new HikariConfig();
    config.setDataSourceClassName(propertyResolver.getProperty("dataSourceClassName"));
    if (propertyResolver.getProperty("url") == null || "".equals(propertyResolver.getProperty("url"))) {
        config.addDataSourceProperty("databaseName", propertyResolver.getProperty("databaseName"));
        config.addDataSourceProperty("serverName", propertyResolver.getProperty("serverName"));
    } else {
        config.addDataSourceProperty("url", propertyResolver.getProperty("url"));
    }
    config.addDataSourceProperty("user", propertyResolver.getProperty("username"));
    config.addDataSourceProperty("password", propertyResolver.getProperty("password"));
    return new HikariDataSource(config);
}
Example 32
Project: pinpoint-master  File: HikariCpPlugin.java View source code
private void addBasicDataSourceTransformer() {
    transformTemplate.transform("com.zaxxer.hikari.HikariDataSource", new TransformCallback() {

        @Override
        public byte[] doInTransform(Instrumentor instrumentor, ClassLoader loader, String className, Class<?> classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws InstrumentException {
            InstrumentClass target = instrumentor.getInstrumentClass(loader, className, classfileBuffer);
            target.addInterceptor(HikariCpConstants.INTERCEPTOR_GET_CONNECTION);
            return target.toBytecode();
        }
    });
}
Example 33
Project: RankSys-master  File: SQLPreferenceDataTest.java View source code
/**
     * Test with toy data.
     */
@Test
public void testToyExample() {
    String url = "jdbc:h2:mem:test";
    try (HikariDataSource ds = new HikariDataSource()) {
        ds.setJdbcUrl(url);
        SQLPreferenceData.create(ds, SQLDialect.H2, "data");
        SQLPreferenceData prefs = new SQLPreferenceData(ds, SQLDialect.H2, "data");
        String[][] data = new String[][] { new String[] { "a", "A", "1" }, new String[] { "a", "B", "2" }, new String[] { "a", "E", "3" }, new String[] { "a", "T", "4" }, new String[] { "a", "Q", "5" }, new String[] { "a", "Y", "1" }, new String[] { "a", "H", "2" }, new String[] { "a", "M", "3" }, new String[] { "a", "D", "4" }, new String[] { "b", "A", "5" }, new String[] { "b", "B", "1" }, new String[] { "b", "C", "2" }, new String[] { "b", "D", "3" }, new String[] { "b", "E", "4" }, new String[] { "c", "A", "5" }, new String[] { "c", "C", "1" }, new String[] { "c", "T", "2" }, new String[] { "c", "Y", "3" }, new String[] { "c", "U", "4" }, new String[] { "c", "I", "5" }, new String[] { "c", "O", "1" } };
        int numPreferences = data.length;
        int numUsers = (int) of(data).map( p -> p[0]).distinct().count();
        int numItems = (int) of(data).map( p -> p[1]).distinct().count();
        for (String[] pref : data) {
            if (!prefs.containsUser(pref[0])) {
                assertTrue(prefs.addUser(pref[0]));
            }
            if (!prefs.containsItem(pref[1])) {
                assertTrue(prefs.addItem(pref[1]));
            }
            assertTrue(prefs.addPref(pref[0], pref[1], parseDouble(pref[2]), null));
        }
        assertTrue(prefs.numPreferences() == numPreferences);
        assertTrue(prefs.numUsers() == numUsers);
        assertTrue(prefs.numItems() == numItems);
        assertTrue(prefs.numItems("a") == 9);
        assertTrue(prefs.numItems("b") == 5);
        assertTrue(prefs.numItems("c") == 7);
        assertTrue(prefs.numUsers("A") == 3);
        assertTrue(prefs.numUsers("B") == 2);
        assertTrue(prefs.removeUser("a"));
        assertTrue(prefs.numPreferences() == numPreferences - 9);
    }
}
Example 34
Project: sample-boot-hibernate-master  File: OrmDataSourceProperties.java View source code
public DataSource dataSource() {
    HikariConfig config = new HikariConfig();
    config.setDriverClassName(driverClassName());
    config.setJdbcUrl(url);
    config.setUsername(username);
    config.setPassword(password);
    config.setMinimumIdle(minIdle);
    config.setMaximumPoolSize(maxPoolSize);
    if (validation) {
        config.setConnectionTestQuery(validationQuery());
    }
    config.setDataSourceProperties(props);
    return new HikariDataSource(config);
}
Example 35
Project: sef4j-master  File: ApplicationConfig.java View source code
/** cf org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration */
@Bean
@ConfigurationProperties(prefix = DataSourceProperties.PREFIX)
public DataSource dataSource() {
    LOG.info("building DataSource");
    //        DataSourceBuilder factory = DataSourceBuilder
    //                .create(this.properties.getClassLoader())
    //                .driverClassName(this.properties.getDriverClassName())
    //                .url(this.properties.getUrl())
    //                .username(this.properties.getUsername())
    //                .password(this.properties.getPassword());
    //        return factory.build();
    HikariConfig config = new HikariConfig();
    //        JDBCDataSource underlyingDS = new JDBCDataSource();
    //        config.setDataSource(underlyingDS);
    config.setDriverClassName(this.properties.getDriverClassName());
    config.setJdbcUrl(this.properties.getUrl());
    config.setUsername(this.properties.getUsername());
    config.setPassword(this.properties.getPassword());
    HikariDataSource ds = new HikariDataSource(config);
    return ds;
}
Example 36
Project: SpringBlog-master  File: JpaConfig.java View source code
@Bean
public DataSource configureDataSource() {
    HikariConfig config = new HikariConfig();
    config.setDriverClassName(driver);
    config.setJdbcUrl(url);
    config.setUsername(username);
    config.setPassword(password);
    config.addDataSourceProperty("useUnicode", "true");
    config.addDataSourceProperty("characterEncoding", "utf8");
    config.addDataSourceProperty("cachePrepStmts", "true");
    config.addDataSourceProperty("prepStmtCacheSize", "250");
    config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
    config.addDataSourceProperty("useServerPrepStmts", "true");
    return new HikariDataSource(config);
}
Example 37
Project: thymeleafexamples-layouts-master  File: JpaConfig.java View source code
@Bean
public DataSource dataSource() {
    HikariConfig config = new HikariConfig();
    config.setDriverClassName(driver);
    config.setJdbcUrl(url);
    config.setUsername(username);
    config.setPassword(password);
    config.addDataSourceProperty("cachePrepStmts", "true");
    config.addDataSourceProperty("prepStmtCacheSize", "250");
    config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
    config.addDataSourceProperty("useServerPrepStmts", "true");
    return new HikariDataSource(config);
}
Example 38
Project: wisdom-jdbc-master  File: PatternsTest.java View source code
@Test
public void testWithMySQLWithoutAttributes() {
    String url = "mysql://clement:secret@localhost/test";
    HikariDataSource source = new HikariDataSource();
    assertThat(Patterns.populate(source, url, false)).isTrue();
    assertThat(source.getJdbcUrl()).isEqualTo("jdbc:mysql://localhost/test?useUnicode=yes&characterEncoding=UTF-8&connectionCollation" + "=utf8_general_ci");
    assertThat(source.getUsername()).isEqualTo("clement");
    assertThat(source.getPassword()).isEqualTo("secret");
}
Example 39
Project: XCoLab-master  File: DataSourceUtil.java View source code
public static HikariDataSource getConfiguredDataSource(PropertyResolver propertyResolver, String schemaPropertyKey) {
    final String driverClassName = propertyResolver.getRequiredProperty(DB_DRIVER_PROPERTY_NAME);
    final String databaseSchema = propertyResolver.getRequiredProperty(schemaPropertyKey);
    final String databaseUrlBase = propertyResolver.getRequiredProperty(DB_URL_BASE_PROPERTY_NAME);
    final String databaseUrlParams = propertyResolver.getRequiredProperty(DB_URL_PARAMS_PROPERTY_NAME);
    final String databaseUsername = propertyResolver.getRequiredProperty(DB_USERNAME_PROPERTY_NAME);
    final String databasePassword = propertyResolver.getRequiredProperty(DB_PASSWORD_PROPERTY_NAME);
    return getConfiguredDataSource(driverClassName, databaseSchema, databaseUrlBase, databaseUrlParams, databaseUsername, databasePassword);
}
Example 40
Project: zipkin-master  File: ZipkinMySQLStorageProperties.java View source code
public DataSource toDataSource() {
    StringBuilder url = new StringBuilder("jdbc:mysql://");
    url.append(getHost()).append(":").append(getPort());
    url.append("/").append(getDb());
    url.append("?autoReconnect=true");
    url.append("&useSSL=").append(isUseSsl());
    url.append("&useUnicode=yes&characterEncoding=UTF-8");
    HikariDataSource result = new HikariDataSource();
    result.setDriverClassName("org.mariadb.jdbc.Driver");
    result.setJdbcUrl(url.toString());
    result.setMaximumPoolSize(getMaxActive());
    result.setUsername(getUsername());
    result.setPassword(getPassword());
    return result;
}
Example 41
Project: BikeMan-master  File: DatabaseConfiguration.java View source code
@Bean(destroyMethod = "shutdown")
@ConditionalOnMissingClass(name = "de.rwth.idsg.bikeman.config.HerokuDatabaseConfiguration")
@Profile("!" + Constants.SPRING_PROFILE_CLOUD)
public DataSource dataSource() {
    log.debug("Configuring Datasource");
    if (propertyResolver.getProperty("url") == null && propertyResolver.getProperty("databaseName") == null) {
        log.error("Your database connection pool configuration is incorrect! The application" + "cannot start. Please check your Spring profile, current profiles are: {}", Arrays.toString(env.getActiveProfiles()));
        throw new ApplicationContextException("Database connection pool is not configured correctly");
    }
    HikariConfig config = new HikariConfig();
    config.setDataSourceClassName(propertyResolver.getProperty("dataSourceClassName"));
    if (propertyResolver.getProperty("url") == null || "".equals(propertyResolver.getProperty("url"))) {
        config.addDataSourceProperty("databaseName", propertyResolver.getProperty("databaseName"));
        config.addDataSourceProperty("serverName", propertyResolver.getProperty("serverName"));
    } else {
        config.addDataSourceProperty("url", propertyResolver.getProperty("url"));
    }
    config.addDataSourceProperty("user", propertyResolver.getProperty("username"));
    config.addDataSourceProperty("password", propertyResolver.getProperty("password"));
    if (metricRegistry != null) {
        config.setMetricRegistry(metricRegistry);
    }
    return new HikariDataSource(config);
}
Example 42
Project: blog-jahia-jhipster2-master  File: DatabaseConfiguration.java View source code
@Bean(destroyMethod = "shutdown")
@ConditionalOnMissingClass(name = "com.ippon.jhipster21.config.HerokuDatabaseConfiguration")
@Profile("!" + Constants.SPRING_PROFILE_CLOUD)
public DataSource dataSource() {
    log.debug("Configuring Datasource");
    if (propertyResolver.getProperty("url") == null && propertyResolver.getProperty("databaseName") == null) {
        log.error("Your database connection pool configuration is incorrect! The application" + "cannot start. Please check your Spring profile, current profiles are: {}", Arrays.toString(env.getActiveProfiles()));
        throw new ApplicationContextException("Database connection pool is not configured correctly");
    }
    HikariConfig config = new HikariConfig();
    config.setDataSourceClassName(propertyResolver.getProperty("dataSourceClassName"));
    if (propertyResolver.getProperty("url") == null || "".equals(propertyResolver.getProperty("url"))) {
        config.addDataSourceProperty("databaseName", propertyResolver.getProperty("databaseName"));
        config.addDataSourceProperty("serverName", propertyResolver.getProperty("serverName"));
    } else {
        config.addDataSourceProperty("url", propertyResolver.getProperty("url"));
    }
    config.addDataSourceProperty("user", propertyResolver.getProperty("username"));
    config.addDataSourceProperty("password", propertyResolver.getProperty("password"));
    //MySQL optimizations, see https://github.com/brettwooldridge/HikariCP/wiki/MySQL-Configuration
    if ("com.mysql.jdbc.jdbc2.optional.MysqlDataSource".equals(propertyResolver.getProperty("dataSourceClassName"))) {
        config.addDataSourceProperty("cachePrepStmts", propertyResolver.getProperty("cachePrepStmts", "true"));
        config.addDataSourceProperty("prepStmtCacheSize", propertyResolver.getProperty("prepStmtCacheSize", "250"));
        config.addDataSourceProperty("prepStmtCacheSqlLimit", propertyResolver.getProperty("prepStmtCacheSqlLimit", "2048"));
        config.addDataSourceProperty("useServerPrepStmts", propertyResolver.getProperty("useServerPrepStmts", "true"));
    }
    if (metricRegistry != null) {
        config.setMetricRegistry(metricRegistry);
    }
    return new HikariDataSource(config);
}
Example 43
Project: CAJPII-master  File: DatabaseConfiguration.java View source code
@Bean(destroyMethod = "shutdown")
@ConditionalOnMissingClass(name = "com.cajp.giros.config.HerokuDatabaseConfiguration")
@Profile("!" + Constants.SPRING_PROFILE_CLOUD)
public DataSource dataSource() {
    log.debug("Configuring Datasource");
    if (propertyResolver.getProperty("url") == null && propertyResolver.getProperty("databaseName") == null) {
        log.error("Your database connection pool configuration is incorrect! The application" + "cannot start. Please check your Spring profile, current profiles are: {}", Arrays.toString(env.getActiveProfiles()));
        throw new ApplicationContextException("Database connection pool is not configured correctly");
    }
    HikariConfig config = new HikariConfig();
    config.setDataSourceClassName(propertyResolver.getProperty("dataSourceClassName"));
    if (propertyResolver.getProperty("url") == null || "".equals(propertyResolver.getProperty("url"))) {
        config.addDataSourceProperty("databaseName", propertyResolver.getProperty("databaseName"));
        config.addDataSourceProperty("serverName", propertyResolver.getProperty("serverName"));
    } else {
        config.addDataSourceProperty("url", propertyResolver.getProperty("url"));
    }
    config.addDataSourceProperty("user", propertyResolver.getProperty("username"));
    config.addDataSourceProperty("password", propertyResolver.getProperty("password"));
    //MySQL optimizations, see https://github.com/brettwooldridge/HikariCP/wiki/MySQL-Configuration
    if ("com.mysql.jdbc.jdbc2.optional.MysqlDataSource".equals(propertyResolver.getProperty("dataSourceClassName"))) {
        config.addDataSourceProperty("cachePrepStmts", propertyResolver.getProperty("cachePrepStmts", "true"));
        config.addDataSourceProperty("prepStmtCacheSize", propertyResolver.getProperty("prepStmtCacheSize", "250"));
        config.addDataSourceProperty("prepStmtCacheSqlLimit", propertyResolver.getProperty("prepStmtCacheSqlLimit", "2048"));
        config.addDataSourceProperty("useServerPrepStmts", propertyResolver.getProperty("useServerPrepStmts", "true"));
    }
    if (metricRegistry != null) {
        config.setMetricRegistry(metricRegistry);
    }
    return new HikariDataSource(config);
}
Example 44
Project: CBIRestAPI-master  File: DatabaseConfiguration.java View source code
@Bean(destroyMethod = "shutdown")
@ConditionalOnMissingClass(name = "org.cbir.retrieval.config.HerokuDatabaseConfiguration")
@Profile("!" + Constants.SPRING_PROFILE_CLOUD)
public DataSource dataSource() {
    log.debug("Configuring Datasource");
    if (propertyResolver.getProperty("url") == null && propertyResolver.getProperty("databaseName") == null) {
        log.error("Your database connection pool configuration is incorrect! The application" + "cannot start. Please check your Spring profile, current profiles are: {}", Arrays.toString(env.getActiveProfiles()));
        throw new ApplicationContextException("Database connection pool is not configured correctly");
    }
    HikariConfig config = new HikariConfig();
    config.setDataSourceClassName(propertyResolver.getProperty("dataSourceClassName"));
    if (propertyResolver.getProperty("url") == null || "".equals(propertyResolver.getProperty("url"))) {
        config.addDataSourceProperty("databaseName", propertyResolver.getProperty("databaseName"));
        config.addDataSourceProperty("serverName", propertyResolver.getProperty("serverName"));
    } else {
        config.addDataSourceProperty("url", propertyResolver.getProperty("url"));
    }
    config.addDataSourceProperty("user", propertyResolver.getProperty("username"));
    config.addDataSourceProperty("password", propertyResolver.getProperty("password"));
    if (metricRegistry != null) {
        config.setMetricRegistry(metricRegistry);
    }
    return new HikariDataSource(config);
}
Example 45
Project: craftconomy3-master  File: OldFormatConverter.java View source code
public void run() throws SQLException, IOException, ParseException {
    String dbType = Common.getInstance().getMainConfig().getString("System.Database.Type");
    HikariConfig config = new HikariConfig();
    if (dbType.equalsIgnoreCase("mysql")) {
        config.setMaximumPoolSize(10);
        config.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource");
        config.addDataSourceProperty("serverName", Common.getInstance().getMainConfig().getString("System.Database.Address"));
        config.addDataSourceProperty("port", Common.getInstance().getMainConfig().getString("System.Database.Port"));
        config.addDataSourceProperty("databaseName", Common.getInstance().getMainConfig().getString("System.Database.Db"));
        config.addDataSourceProperty("user", Common.getInstance().getMainConfig().getString("System.Database.Username"));
        config.addDataSourceProperty("password", Common.getInstance().getMainConfig().getString("System.Database.Password"));
        config.addDataSourceProperty("autoDeserialize", true);
        config.setConnectionTimeout(5000);
        db = new HikariDataSource(config);
    } else if (dbType.equalsIgnoreCase("sqlite")) {
        config.setDriverClassName("org.sqlite.JDBC");
        config.setJdbcUrl("jdbc:sqlite:" + Common.getInstance().getServerCaller().getDataFolder() + File.separator + "database.db");
        config.setConnectionTestQuery("SELECT 1");
        db = new HikariDataSource(config);
    } else {
        Common.getInstance().sendConsoleMessage(Level.SEVERE, "Unknown database type for old format converter!");
        return;
    }
    Connection connection = db.getConnection();
    this.tablePrefix = Common.getInstance().getMainConfig().getString("System.Database.Prefix");
    File accountFile = new File(Common.getInstance().getServerCaller().getDataFolder(), "accounts.json");
    Common.getInstance().sendConsoleMessage(Level.INFO, "Doing a backup in a xml file before doing the conversion.");
    //Document setup
    JSONObject mainObject = new JSONObject();
    Common.getInstance().sendConsoleMessage(Level.INFO, "Saving currency table");
    //Currencies
    PreparedStatement statement = connection.prepareStatement("SELECT * FROM " + tablePrefix + "currency");
    ResultSet set = statement.executeQuery();
    JSONArray array = new JSONArray();
    while (set.next()) {
        JSONObject entry = new JSONObject();
        entry.put("id", set.getInt("id"));
        entry.put("name", set.getString("name"));
        entry.put("plural", set.getString("plural"));
        entry.put("minor", set.getString("minor"));
        entry.put("minorPlural", set.getString("minorPlural"));
        entry.put("sign", set.getString("sign"));
        entry.put("status", set.getBoolean("status"));
        array.add(entry);
    }
    statement.close();
    mainObject.put("currencies", array);
    //World groups
    Common.getInstance().sendConsoleMessage(Level.INFO, "Saving world group table");
    array = new JSONArray();
    statement = connection.prepareStatement("SELECT * FROM " + tablePrefix + "worldgroup");
    set = statement.executeQuery();
    while (set.next()) {
        JSONObject entry = new JSONObject();
        entry.put("groupName", set.getString("groupName"));
        entry.put("worldList", set.getString("worldList"));
        array.add(entry);
    }
    statement.close();
    mainObject.put("worldgroups", array);
    //Exchange table
    Common.getInstance().sendConsoleMessage(Level.INFO, "Saving exchange table");
    array = new JSONArray();
    statement = connection.prepareStatement("SELECT * FROM " + tablePrefix + "exchange");
    set = statement.executeQuery();
    while (set.next()) {
        JSONObject entry = new JSONObject();
        entry.put("from_currency_id", set.getInt("from_currency_id"));
        entry.put("to_currency_id", set.getInt("to_currency_id"));
        entry.put("amount", set.getDouble("amount"));
        array.add(entry);
    }
    statement.close();
    mainObject.put("exchanges", array);
    //config table
    Common.getInstance().sendConsoleMessage(Level.INFO, "Saving config table");
    array = new JSONArray();
    statement = connection.prepareStatement("SELECT * FROM " + tablePrefix + "config");
    set = statement.executeQuery();
    while (set.next()) {
        JSONObject entry = new JSONObject();
        entry.put("name", set.getString("name"));
        entry.put("value", set.getString("value"));
        array.add(entry);
    }
    statement.close();
    mainObject.put("configs", array);
    //account table
    Common.getInstance().sendConsoleMessage(Level.INFO, "Saving account table");
    array = new JSONArray();
    statement = connection.prepareStatement("SELECT * FROM " + tablePrefix + "account");
    set = statement.executeQuery();
    while (set.next()) {
        JSONObject entry = new JSONObject();
        entry.put("name", set.getString("name"));
        entry.put("infiniteMoney", set.getBoolean("infiniteMoney"));
        entry.put("ignoreACL", set.getBoolean("ignoreACL"));
        entry.put("uuid", set.getString("uuid"));
        JSONArray balanceArray = new JSONArray();
        PreparedStatement internalStatement = connection.prepareStatement("SELECT * FROM " + tablePrefix + "balance WHERE username_id=?");
        internalStatement.setInt(1, set.getInt("id"));
        ResultSet internalSet = internalStatement.executeQuery();
        while (internalSet.next()) {
            JSONObject object = new JSONObject();
            object.put("currency_id", internalSet.getInt("currency_id"));
            object.put("worldName", internalSet.getString("worldName"));
            object.put("balance", internalSet.getDouble("balance"));
            balanceArray.add(object);
        }
        internalStatement.close();
        entry.put("balances", balanceArray);
        internalStatement = connection.prepareStatement("SELECT * FROM " + tablePrefix + "log WHERE username_id=?");
        internalStatement.setInt(1, set.getInt("id"));
        internalSet = internalStatement.executeQuery();
        JSONArray logArray = new JSONArray();
        while (internalSet.next()) {
            JSONObject object = new JSONObject();
            object.put("type", getObject(internalSet.getBlob("type")).toString());
            object.put("cause", getObject(internalSet.getBlob("cause")).toString());
            object.put("timestamp", internalSet.getTimestamp("timestamp").getTime());
            object.put("causeReason", internalSet.getString("causeReason"));
            object.put("currencyName", internalSet.getString("currencyName"));
            object.put("worldName", internalSet.getString("worldName"));
            object.put("amount", internalSet.getDouble("amount"));
            logArray.add(object);
        }
        internalStatement.close();
        entry.put("logs", logArray);
        internalStatement = connection.prepareStatement("SELECT * FROM " + tablePrefix + "acl WHERE account_id=?");
        internalStatement.setInt(1, set.getInt("id"));
        internalSet = internalStatement.executeQuery();
        JSONArray aclArray = new JSONArray();
        while (internalSet.next()) {
            JSONObject object = new JSONObject();
            object.put("playerName", internalSet.getString("playerName"));
            object.put("deposit", internalSet.getBoolean("deposit"));
            object.put("withdraw", internalSet.getBoolean("withdraw"));
            object.put("acl", internalSet.getBoolean("acl"));
            object.put("balance", internalSet.getBoolean("balance"));
            object.put("owner", internalSet.getBoolean("owner"));
            aclArray.add(object);
        }
        internalStatement.close();
        entry.put("acls", aclArray);
        array.add(entry);
    }
    statement.close();
    mainObject.put("accounts", array);
    Common.getInstance().sendConsoleMessage(Level.INFO, "Writing json file");
    FileWriter writer = new FileWriter(accountFile);
    writer.write(mainObject.toJSONString());
    writer.flush();
    writer.close();
    Common.getInstance().sendConsoleMessage(Level.INFO, "File written! Dropping all tables");
    //The backup is now saved. Let's drop everything
    statement = connection.prepareStatement("DROP TABLE " + tablePrefix + "config");
    statement.execute();
    statement.close();
    statement = connection.prepareStatement("DROP TABLE " + tablePrefix + "acl");
    statement.execute();
    statement.close();
    statement = connection.prepareStatement("DROP TABLE " + tablePrefix + "balance");
    statement.execute();
    statement.close();
    statement = connection.prepareStatement("DROP TABLE " + tablePrefix + "log");
    statement.execute();
    statement.close();
    statement = connection.prepareStatement("DROP TABLE " + tablePrefix + "worldgroup");
    statement.execute();
    statement.close();
    statement = connection.prepareStatement("DROP TABLE " + tablePrefix + "exchange");
    statement.execute();
    statement.close();
    statement = connection.prepareStatement("DROP TABLE " + tablePrefix + "account");
    statement.execute();
    statement.close();
    statement = connection.prepareStatement("DROP TABLE " + tablePrefix + "currency");
    statement.execute();
    statement.close();
    statement = connection.prepareStatement("DROP TABLE " + tablePrefix + "payday");
    statement.execute();
    statement.close();
    connection.close();
    step2();
}
Example 46
Project: ecs-sync-master  File: MySQLDbService.java View source code
@Override
protected JdbcTemplate createJdbcTemplate() {
    HikariDataSource ds = new HikariDataSource();
    ds.setJdbcUrl(connectString);
    if (username != null)
        ds.setUsername(username);
    if (password != null)
        ds.setPassword(password);
    ds.setMaximumPoolSize(500);
    ds.setMinimumIdle(10);
    ds.addDataSourceProperty("characterEncoding", "utf8");
    ds.addDataSourceProperty("cachePrepStmts", "true");
    ds.addDataSourceProperty("prepStmtCacheSize", "250");
    ds.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
    return new JdbcTemplate(ds);
}
Example 47
Project: hibernate-redis-master  File: HibernateRedisConfiguration.java View source code
@Bean
public DataSource dataSource() {
    HikariConfig config = new HikariConfig();
    config.setDriverClassName("org.h2.Driver");
    config.setJdbcUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;MVCC=TRUE;");
    config.setUsername("sa");
    config.setPassword("");
    config.setInitializationFailFast(true);
    config.setConnectionTestQuery("SELECT 1");
    return new HikariDataSource(config);
}
Example 48
Project: hutool-master  File: HikariDSFactory.java View source code
@Override
public synchronized DataSource getDataSource(String group) {
    if (group == null) {
        group = StrUtil.EMPTY;
    }
    // 如果已�存在已有数��(连接池)直接返回
    final HikariDataSource existedDataSource = dsMap.get(group);
    if (existedDataSource != null) {
        return existedDataSource;
    }
    final HikariDataSource ds = createDataSource(group);
    // 添加到数��池中,以备下次使用
    dsMap.put(group, ds);
    return ds;
}
Example 49
Project: java-test-applications-master  File: DataSourceUtils.java View source code
//
public String getUrl(DataSource dataSource) {
    if (isClass(dataSource, "com.jolbox.bonecp.BoneCPDataSource")) {
        return invokeMethod(dataSource, "getJdbcUrl");
    } else if (isClass(dataSource, "org.apache.commons.dbcp.BasicDataSource")) {
        return invokeMethod(dataSource, "getUrl");
    } else if (isClass(dataSource, "org.apache.commons.dbcp2.BasicDataSource")) {
        return invokeMethod(dataSource, "getUrl");
    } else if (isClass(dataSource, "org.apache.tomcat.dbcp.dbcp.BasicDataSource")) {
        return invokeMethod(dataSource, "getUrl");
    } else if (isClass(dataSource, "org.apache.tomcat.dbcp.dbcp2.BasicDataSource")) {
        return invokeMethod(dataSource, "getUrl");
    } else if (isClass(dataSource, "org.apache.tomcat.jdbc.pool.DataSource")) {
        return invokeMethod(dataSource, "getUrl");
    } else if (isClass(dataSource, "org.springframework.jdbc.datasource.embedded" + ".EmbeddedDatabaseFactory$EmbeddedDataSourceProxy")) {
        return getUrl(getDataSource(dataSource, "dataSource"));
    } else if (isClass(dataSource, "org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy")) {
        return getUrl(getTargetDataSource(dataSource));
    } else if (isClass(dataSource, "org.springframework.jdbc.datasource.SimpleDriverDataSource")) {
        return invokeMethod(dataSource, "getUrl");
    } else if (isClass(dataSource, "org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy")) {
        return getUrl(getTargetDataSource(dataSource));
    } else if (isClass(dataSource, "com.zaxxer.hikari.HikariDataSource")) {
        return invokeMethod(dataSource, "getJdbcUrl");
    } else if (isClass(dataSource, "org.apache.openejb.resource.jdbc.managed.local.ManagedDataSource")) {
        return getUrl(getDataSource(dataSource, "delegate"));
    } else if (isClass(dataSource, "org.apache.tomee.jdbc.TomEEDataSourceCreator$TomEEDataSource")) {
        return invokeMethod(dataSource, "getUrl");
    }
    return String.format("Unable to determine URL for DataSource of type %s", dataSource.getClass().getName());
}
Example 50
Project: jhipster-ionic-master  File: DatabaseConfiguration.java View source code
@Bean(destroyMethod = "shutdown")
@ConditionalOnExpression("#{!environment.acceptsProfiles('cloud') && !environment.acceptsProfiles('heroku')}")
public DataSource dataSource() {
    log.debug("Configuring Datasource");
    if (dataSourcePropertyResolver.getProperty("url") == null && dataSourcePropertyResolver.getProperty("databaseName") == null) {
        log.error("Your database connection pool configuration is incorrect! The application" + " cannot start. Please check your Spring profile, current profiles are: {}", Arrays.toString(env.getActiveProfiles()));
        throw new ApplicationContextException("Database connection pool is not configured correctly");
    }
    HikariConfig config = new HikariConfig();
    config.setDataSourceClassName(dataSourcePropertyResolver.getProperty("dataSourceClassName"));
    if (StringUtils.isEmpty(dataSourcePropertyResolver.getProperty("url"))) {
        config.addDataSourceProperty("databaseName", dataSourcePropertyResolver.getProperty("databaseName"));
        config.addDataSourceProperty("serverName", dataSourcePropertyResolver.getProperty("serverName"));
    } else {
        config.addDataSourceProperty("url", dataSourcePropertyResolver.getProperty("url"));
    }
    config.addDataSourceProperty("user", dataSourcePropertyResolver.getProperty("username"));
    config.addDataSourceProperty("password", dataSourcePropertyResolver.getProperty("password"));
    //MySQL optimizations, see https://github.com/brettwooldridge/HikariCP/wiki/MySQL-Configuration
    if ("com.mysql.jdbc.jdbc2.optional.MysqlDataSource".equals(dataSourcePropertyResolver.getProperty("dataSourceClassName"))) {
        config.addDataSourceProperty("cachePrepStmts", dataSourcePropertyResolver.getProperty("cachePrepStmts", "true"));
        config.addDataSourceProperty("prepStmtCacheSize", dataSourcePropertyResolver.getProperty("prepStmtCacheSize", "250"));
        config.addDataSourceProperty("prepStmtCacheSqlLimit", dataSourcePropertyResolver.getProperty("prepStmtCacheSqlLimit", "2048"));
    }
    if (metricRegistry != null) {
        config.setMetricRegistry(metricRegistry);
    }
    return new HikariDataSource(config);
}
Example 51
Project: jhipster_myapp-master  File: DatabaseConfiguration.java View source code
@Bean(destroyMethod = "shutdown")
@ConditionalOnExpression("#{!environment.acceptsProfiles('cloud') && !environment.acceptsProfiles('heroku')}")
public DataSource dataSource() {
    log.debug("Configuring Datasource");
    if (dataSourcePropertyResolver.getProperty("url") == null && dataSourcePropertyResolver.getProperty("databaseName") == null) {
        log.error("Your database connection pool configuration is incorrect! The application" + " cannot start. Please check your Spring profile, current profiles are: {}", Arrays.toString(env.getActiveProfiles()));
        throw new ApplicationContextException("Database connection pool is not configured correctly");
    }
    HikariConfig config = new HikariConfig();
    config.setDataSourceClassName(dataSourcePropertyResolver.getProperty("dataSourceClassName"));
    if (StringUtils.isEmpty(dataSourcePropertyResolver.getProperty("url"))) {
        config.addDataSourceProperty("databaseName", dataSourcePropertyResolver.getProperty("databaseName"));
        config.addDataSourceProperty("serverName", dataSourcePropertyResolver.getProperty("serverName"));
    } else {
        config.addDataSourceProperty("url", dataSourcePropertyResolver.getProperty("url"));
    }
    config.addDataSourceProperty("user", dataSourcePropertyResolver.getProperty("username"));
    config.addDataSourceProperty("password", dataSourcePropertyResolver.getProperty("password"));
    //MySQL optimizations, see https://github.com/brettwooldridge/HikariCP/wiki/MySQL-Configuration
    if ("com.mysql.jdbc.jdbc2.optional.MysqlDataSource".equals(dataSourcePropertyResolver.getProperty("dataSourceClassName"))) {
        config.addDataSourceProperty("cachePrepStmts", dataSourcePropertyResolver.getProperty("cachePrepStmts", "true"));
        config.addDataSourceProperty("prepStmtCacheSize", dataSourcePropertyResolver.getProperty("prepStmtCacheSize", "250"));
        config.addDataSourceProperty("prepStmtCacheSqlLimit", dataSourcePropertyResolver.getProperty("prepStmtCacheSqlLimit", "2048"));
    }
    if (metricRegistry != null) {
        config.setMetricRegistry(metricRegistry);
    }
    return new HikariDataSource(config);
}
Example 52
Project: jphp-master  File: PSqlDriverManager.java View source code
@Signature
public static PSqlConnectionPool getPool(Environment env, String url, String driverName, @Nullable Properties properties) throws SQLException {
    HikariConfig config = new HikariConfig(properties == null ? new Properties() : properties);
    if (config.getDataSourceClassName() == null) {
        config.setDataSourceClassName(dataSourceClasses.get(driverName));
    }
    HikariDataSource pool = new HikariDataSource(config);
    pool.setDriverClassName(_getDriverClass(driverName));
    pool.setJdbcUrl("jdbc:" + url);
    return new PSqlConnectionPool(env, pool);
}
Example 53
Project: killbill-master  File: TestKillbillJdbcTenantRealm.java View source code
@Override
@BeforeMethod(groups = "slow")
public void beforeMethod() throws Exception {
    super.beforeMethod();
    // Create the tenant
    final DefaultTenantDao tenantDao = new DefaultTenantDao(dbi, clock, cacheControllerDispatcher, new DefaultNonEntityDao(dbi), Mockito.mock(InternalCallContextFactory.class), securityConfig);
    tenant = new DefaultTenant(UUID.randomUUID(), null, null, UUID.randomUUID().toString(), UUID.randomUUID().toString(), UUID.randomUUID().toString());
    tenantDao.create(new TenantModelDao(tenant), internalCallContext);
    // Setup the security manager
    final HikariConfig dbConfig = new HikariConfig();
    dbConfig.setJdbcUrl(helper.getJdbcConnectionString());
    dbConfig.setUsername(helper.getUsername());
    dbConfig.setPassword(helper.getPassword());
    final KillbillJdbcTenantRealm jdbcRealm = new KillbillJdbcTenantRealm(shiroDataSource, securityConfig);
    jdbcRealm.setDataSource(new HikariDataSource(dbConfig));
    securityManager = new DefaultSecurityManager(jdbcRealm);
}
Example 54
Project: lavagna-master  File: DataSourceConfig.java View source code
@Bean(destroyMethod = "close")
public DataSource getDataSource(LavagnaEnvironment env) throws URISyntaxException {
    HikariDataSource dataSource = new HikariDataSource();
    dataSource.setDriverClassName(getDriveClassName(env.getRequiredProperty("datasource.dialect")));
    if (env.containsProperty("datasource.url") && env.containsProperty("datasource.username")) {
        urlAndCredentials(dataSource, env);
    } else {
        urlWithCredentials(dataSource, env);
    }
    if (System.getProperty("startDBManager") != null) {
        DatabaseManagerSwing.main(new String[] { "--url", "jdbc:hsqldb:mem:lavagna", "--noexit" });
    }
    return dataSource;
}
Example 55
Project: lightadmin-jhipster-master  File: DatabaseConfiguration.java View source code
@Bean
public DataSource dataSource() {
    log.debug("Configuring Datasource");
    if (propertyResolver.getProperty("url") == null && propertyResolver.getProperty("databaseName") == null) {
        log.error("Your database connection pool configuration is incorrect! The application" + "cannot start. Please check your Spring profile, current profiles are: {}", Arrays.toString(environment.getActiveProfiles()));
        throw new ApplicationContextException("Database connection pool is not configured correctly");
    }
    HikariConfig config = new HikariConfig();
    config.setDataSourceClassName(propertyResolver.getProperty("dataSourceClassName"));
    if (propertyResolver.getProperty("url") == null || "".equals(propertyResolver.getProperty("url"))) {
        config.addDataSourceProperty("databaseName", propertyResolver.getProperty("databaseName"));
        config.addDataSourceProperty("serverName", propertyResolver.getProperty("serverName"));
    } else {
        config.addDataSourceProperty("url", propertyResolver.getProperty("url"));
    }
    config.addDataSourceProperty("user", propertyResolver.getProperty("username"));
    config.addDataSourceProperty("password", propertyResolver.getProperty("password"));
    //MySQL optimizations, see https://github.com/brettwooldridge/HikariCP/wiki/MySQL-Configuration
    if ("com.mysql.jdbc.jdbc2.optional.MysqlDataSource".equals(propertyResolver.getProperty("dataSourceClassName"))) {
        config.addDataSourceProperty("cachePrepStmts", propertyResolver.getProperty("cachePrepStmts", "true"));
        config.addDataSourceProperty("prepStmtCacheSize", propertyResolver.getProperty("prepStmtCacheSize", "250"));
        config.addDataSourceProperty("prepStmtCacheSqlLimit", propertyResolver.getProperty("prepStmtCacheSqlLimit", "2048"));
        config.addDataSourceProperty("useServerPrepStmts", propertyResolver.getProperty("useServerPrepStmts", "true"));
    }
    return new HikariDataSource(config);
}
Example 56
Project: members_cuacfm-master  File: JpaConfigTest.java View source code
/**
	 * Configure data source.
	 *
	 * @return the data source
	 */
@Bean
public DataSource configureDataSource() {
    HikariConfig config = new HikariConfig();
    config.setDriverClassName(driver);
    config.setJdbcUrl(url);
    config.setUsername(username);
    config.setPassword(password);
    config.addDataSourceProperty("useSSL", useSSL);
    config.addDataSourceProperty("cachePrepStmts", "true");
    config.addDataSourceProperty("prepStmtCacheSize", "250");
    config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
    config.addDataSourceProperty("useServerPrepStmts", "true");
    return new HikariDataSource(config);
}
Example 57
Project: metrics-sql-master  File: H2DbUtil.java View source code
public static DataSource createDataSource() {
    HikariConfig config = new HikariConfig();
    config.setDriverClassName(DRIVER_CLASS.getName());
    config.setJdbcUrl(URL);
    config.setUsername(USERNAME);
    config.setPassword(PASSWORD);
    config.setMaximumPoolSize(5);
    config.setMinimumIdle(3);
    HikariDataSource dataSource = new HikariDataSource(config);
    return dataSource;
}
Example 58
Project: modeshape-master  File: DatabaseBinaryStore.java View source code
private void initManagedDS() {
    logger.debug("Attempting to connect to '{0}' with '{1}' for username '{2}' and password '{3}'", connectionURL, driverClass, username, password);
    HikariDataSource hikariDS = new HikariDataSource();
    hikariDS.setJdbcUrl(connectionURL);
    hikariDS.setDriverClassName(driverClass);
    hikariDS.setUsername(username);
    hikariDS.setPassword(password);
    this.dataSource = hikariDS;
}
Example 59
Project: mystore-jhipster-master  File: DatabaseConfiguration.java View source code
@Bean(destroyMethod = "shutdown")
@ConditionalOnMissingClass(name = "fr.couderc.thomas.mystore.config.HerokuDatabaseConfiguration")
@Profile("!" + Constants.SPRING_PROFILE_CLOUD)
public DataSource dataSource() {
    log.debug("Configuring Datasource");
    if (propertyResolver.getProperty("url") == null && propertyResolver.getProperty("databaseName") == null) {
        log.error("Your database connection pool configuration is incorrect! The application" + "cannot start. Please check your Spring profile, current profiles are: {}", Arrays.toString(env.getActiveProfiles()));
        throw new ApplicationContextException("Database connection pool is not configured correctly");
    }
    HikariConfig config = new HikariConfig();
    config.setDataSourceClassName(propertyResolver.getProperty("dataSourceClassName"));
    if (propertyResolver.getProperty("url") == null || "".equals(propertyResolver.getProperty("url"))) {
        config.addDataSourceProperty("databaseName", propertyResolver.getProperty("databaseName"));
        config.addDataSourceProperty("serverName", propertyResolver.getProperty("serverName"));
    } else {
        config.addDataSourceProperty("url", propertyResolver.getProperty("url"));
    }
    config.addDataSourceProperty("user", propertyResolver.getProperty("username"));
    config.addDataSourceProperty("password", propertyResolver.getProperty("password"));
    //MySQL optimizations, see https://github.com/brettwooldridge/HikariCP/wiki/MySQL-Configuration
    if ("com.mysql.jdbc.jdbc2.optional.MysqlDataSource".equals(propertyResolver.getProperty("dataSourceClassName"))) {
        config.addDataSourceProperty("cachePrepStmts", propertyResolver.getProperty("cachePrepStmts", "true"));
        config.addDataSourceProperty("prepStmtCacheSize", propertyResolver.getProperty("prepStmtCacheSize", "250"));
        config.addDataSourceProperty("prepStmtCacheSqlLimit", propertyResolver.getProperty("prepStmtCacheSqlLimit", "2048"));
        config.addDataSourceProperty("useServerPrepStmts", propertyResolver.getProperty("useServerPrepStmts", "true"));
    }
    if (metricRegistry != null) {
        config.setMetricRegistry(metricRegistry);
    }
    return new HikariDataSource(config);
}
Example 60
Project: siddhi-master  File: RDBMSTableTestUtils.java View source code
private static DataSource initDataSource(TestType type) {
    Properties connectionProperties = new Properties();
    switch(type) {
        case MySQL:
            url = CONNECTION_URL_MYSQL;
            break;
        case H2:
            url = CONNECTION_URL_H2;
            break;
        case ORACLE:
            url = CONNECTION_URL_ORACLE;
            break;
    }
    connectionProperties.setProperty("jdbcUrl", url);
    connectionProperties.setProperty("dataSource.user", USERNAME);
    connectionProperties.setProperty("dataSource.password", PASSWORD);
    HikariConfig config = new HikariConfig(connectionProperties);
    return new HikariDataSource(config);
}
Example 61
Project: spark-jhipster-master  File: DatabaseConfiguration.java View source code
@Bean(destroyMethod = "shutdown")
@ConditionalOnMissingClass(name = "com.mycompany.myapp.config.HerokuDatabaseConfiguration")
@Profile("!" + Constants.SPRING_PROFILE_CLOUD)
public DataSource dataSource() {
    log.debug("Configuring Datasource");
    if (propertyResolver.getProperty("url") == null && propertyResolver.getProperty("databaseName") == null) {
        log.error("Your database connection pool configuration is incorrect! The application" + "cannot start. Please check your Spring profile, current profiles are: {}", Arrays.toString(env.getActiveProfiles()));
        throw new ApplicationContextException("Database connection pool is not configured correctly");
    }
    HikariConfig config = new HikariConfig();
    config.setDataSourceClassName(propertyResolver.getProperty("dataSourceClassName"));
    if (propertyResolver.getProperty("url") == null || "".equals(propertyResolver.getProperty("url"))) {
        config.addDataSourceProperty("databaseName", propertyResolver.getProperty("databaseName"));
        config.addDataSourceProperty("serverName", propertyResolver.getProperty("serverName"));
    } else {
        config.addDataSourceProperty("url", propertyResolver.getProperty("url"));
    }
    config.addDataSourceProperty("user", propertyResolver.getProperty("username"));
    config.addDataSourceProperty("password", propertyResolver.getProperty("password"));
    //MySQL optimizations, see https://github.com/brettwooldridge/HikariCP/wiki/MySQL-Configuration
    if ("com.mysql.jdbc.jdbc2.optional.MysqlDataSource".equals(propertyResolver.getProperty("dataSourceClassName"))) {
        config.addDataSourceProperty("cachePrepStmts", propertyResolver.getProperty("cachePrepStmts", "true"));
        config.addDataSourceProperty("prepStmtCacheSize", propertyResolver.getProperty("prepStmtCacheSize", "250"));
        config.addDataSourceProperty("prepStmtCacheSqlLimit", propertyResolver.getProperty("prepStmtCacheSqlLimit", "2048"));
        config.addDataSourceProperty("useServerPrepStmts", propertyResolver.getProperty("useServerPrepStmts", "true"));
    }
    if (metricRegistry != null) {
        config.setMetricRegistry(metricRegistry);
    }
    return new HikariDataSource(config);
}
Example 62
Project: vertexium-master  File: SqlGraphConfiguration.java View source code
private DataSource createDataSource(Map<String, Object> config) {
    Properties properties = new Properties();
    for (Map.Entry<String, Object> configEntry : config.entrySet()) {
        String key = configEntry.getKey();
        if (key.startsWith(CONFIG_PREFIX)) {
            key = key.substring(CONFIG_PREFIX.length());
            properties.put(key, configEntry.getValue());
        }
    }
    HikariConfig hikariConfig = new HikariConfig(properties);
    return new HikariDataSource(hikariConfig);
}
Example 63
Project: apiman-master  File: DefaultJdbcComponent.java View source code
/**
     * Creates a datasource from the given jdbc config info.
     */
@SuppressWarnings("nls")
protected DataSource datasourceFromConfig(JdbcOptionsBean config) {
    Properties props = new Properties();
    props.putAll(config.getDsProperties());
    setConfigProperty(props, "jdbcUrl", config.getJdbcUrl());
    setConfigProperty(props, "username", config.getUsername());
    setConfigProperty(props, "password", config.getPassword());
    setConfigProperty(props, "connectionTimeout", config.getConnectionTimeout());
    setConfigProperty(props, "idleTimeout", config.getIdleTimeout());
    setConfigProperty(props, "maxPoolSize", config.getMaximumPoolSize());
    setConfigProperty(props, "maxLifetime", config.getMaxLifetime());
    setConfigProperty(props, "minIdle", config.getMinimumIdle());
    setConfigProperty(props, "poolName", config.getPoolName());
    setConfigProperty(props, "autoCommit", config.isAutoCommit());
    HikariConfig hikariConfig = new HikariConfig(props);
    return new HikariDataSource(hikariConfig);
}
Example 64
Project: aries-master  File: AbstractManagedJPADataSourceSetup.java View source code
protected DataSource poolIfNecessary(Map<String, Object> resourceProviderProperties, DataSource unpooled) {
    DataSource toUse;
    if (toBoolean(resourceProviderProperties, CONNECTION_POOLING_ENABLED, true)) {
        HikariConfig hcfg = new HikariConfig();
        hcfg.setDataSource(unpooled);
        // Sizes
        hcfg.setMaximumPoolSize(toInt(resourceProviderProperties, MAX_CONNECTIONS, 10));
        hcfg.setMinimumIdle(toInt(resourceProviderProperties, MIN_CONNECTIONS, 10));
        // Timeouts
        hcfg.setConnectionTimeout(toLong(resourceProviderProperties, CONNECTION_TIMEOUT, SECONDS.toMillis(30)));
        hcfg.setIdleTimeout(toLong(resourceProviderProperties, IDLE_TIMEOUT, TimeUnit.MINUTES.toMillis(3)));
        hcfg.setMaxLifetime(toLong(resourceProviderProperties, CONNECTION_LIFETIME, HOURS.toMillis(3)));
        hcfg.setConnectionTestQuery((String) resourceProviderProperties.get(CONNECTION_TEST_QUERY));
        toUse = new HikariDataSource(hcfg);
    } else {
        toUse = unpooled;
    }
    return toUse;
}
Example 65
Project: auth-server-master  File: AuthServer.java View source code
@Primary
@Bean
public DataSource hikariDataSource() {
    HikariConfig hikariConfig = new HikariConfig();
    hikariConfig.setPoolName("osiam-auth-server-cp");
    hikariConfig.setDriverClassName(driverClassName);
    hikariConfig.setJdbcUrl(databaseUrl);
    hikariConfig.setUsername(databaseUserName);
    hikariConfig.setPassword(databasePassword);
    hikariConfig.setMaximumPoolSize(maximumPoolSize);
    hikariConfig.setConnectionTimeout(connectionTimeoutMs);
    return new HikariDataSource(hikariConfig);
}
Example 66
Project: be-worktajm-master  File: DatabaseConfiguration.java View source code
@Bean(destroyMethod = "close")
@ConditionalOnExpression("#{!environment.acceptsProfiles('cloud') && !environment.acceptsProfiles('heroku')}")
public DataSource dataSource(DataSourceProperties dataSourceProperties, JHipsterProperties jHipsterProperties, CacheManager cacheManager) {
    log.debug("Configuring Datasource");
    if (dataSourceProperties.getUrl() == null) {
        log.error("Your database connection pool configuration is incorrect! The application" + " cannot start. Please check your Spring profile, current profiles are: {}", Arrays.toString(env.getActiveProfiles()));
        throw new ApplicationContextException("Database connection pool is not configured correctly");
    }
    HikariConfig config = new HikariConfig();
    config.setDataSourceClassName(dataSourceProperties.getDriverClassName());
    config.addDataSourceProperty("url", dataSourceProperties.getUrl());
    if (dataSourceProperties.getUsername() != null) {
        config.addDataSourceProperty("user", dataSourceProperties.getUsername());
    } else {
        // HikariCP doesn't allow null user
        config.addDataSourceProperty("user", "");
    }
    if (dataSourceProperties.getPassword() != null) {
        config.addDataSourceProperty("password", dataSourceProperties.getPassword());
    } else {
        // HikariCP doesn't allow null password
        config.addDataSourceProperty("password", "");
    }
    //MySQL optimizations, see https://github.com/brettwooldridge/HikariCP/wiki/MySQL-Configuration
    if ("com.mysql.jdbc.jdbc2.optional.MysqlDataSource".equals(dataSourceProperties.getDriverClassName())) {
        config.addDataSourceProperty("cachePrepStmts", jHipsterProperties.getDatasource().isCachePrepStmts());
        config.addDataSourceProperty("prepStmtCacheSize", jHipsterProperties.getDatasource().getPrepStmtCacheSize());
        config.addDataSourceProperty("prepStmtCacheSqlLimit", jHipsterProperties.getDatasource().getPrepStmtCacheSqlLimit());
    }
    if (metricRegistry != null) {
        config.setMetricRegistry(metricRegistry);
    }
    return new HikariDataSource(config);
}
Example 67
Project: ceeql-master  File: Ceeql.java View source code
private String connectToDatabase() {
    try {
        log.debug("Connecting with driver " + driverName + " to " + url);
        Class clazz = Class.forName(driverName);
        log.debug(clazz);
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl(url);
        config.setUsername(username);
        config.setPassword(password);
        config.addDataSourceProperty("dataSourceClassName", driverName);
        config.setPoolName("HikariPool" + "." + url + "." + username);
        if (metricRegistry != null) {
            config.setMetricRegistry(metricRegistry);
        }
        DataSource ds = new HikariDataSource(config);
        this.dbi = new DBI(ds);
        this.dbi.setSQLLog(new Log4JLog());
        this.isConnected = true;
        return CeeqlMessage.message("Connected");
    } catch (Exception e) {
        this.isConnected = false;
        return CeeqlError.errorType(e.getClass().getSimpleName(), e.getMessage());
    }
}
Example 68
Project: checklistbank-master  File: NameUsageServiceMyBatisIT.java View source code
/**
   * Prepared statements in postgres jdbc have a bug when caching text[] array types.
   * This test shows it and we circumvent this behavior by telling mybatis not to cache results.
   *
   * http://dev.gbif.org/issues/browse/POR-3032
   *
   * https://github.com/pgjdbc/pgjdbc/issues/517
   */
@Test
public void testUsageIssuesJdbc() throws Exception {
    HikariDataSource ds = (HikariDataSource) getInstance(InternalChecklistBankServiceMyBatisModule.DATASOURCE_KEY);
    try (Connection cn = ds.getConnection()) {
        PreparedStatement st = cn.prepareStatement("select issues from name_usage where id=?");
        for (int x = 0; x < 10; x++) {
            st.setInt(1, 100000040);
            st.execute();
            ResultSet rs = st.getResultSet();
            rs.next();
            System.out.println(rs.getString(1));
        }
    } finally {
        ds.close();
    }
}
Example 69
Project: datanucleus-rdbms-master  File: HikariCPConnectionPoolFactory.java View source code
/* (non-Javadoc)
     * @see org.datanucleus.store.rdbms.datasource.ConnectionPoolFactory#createConnectionPool(org.datanucleus.store.StoreManager)
     */
public ConnectionPool createConnectionPool(StoreManager storeMgr) {
    // Check the existence of the necessary pooling classes
    ClassLoaderResolver clr = storeMgr.getNucleusContext().getClassLoaderResolver(null);
    ClassUtils.assertClassForJarExistsInClasspath(clr, "com.zaxxer.hikari.HikariConfig", "hikaricp.jar");
    HikariConfig config = new HikariConfig();
    config.setJdbcUrl(storeMgr.getConnectionURL());
    String dbUser = storeMgr.getConnectionUserName();
    if (dbUser == null) {
        // Some RDBMS (e.g Postgresql) don't like null usernames
        dbUser = "";
    }
    config.setUsername(dbUser);
    String dbPassword = storeMgr.getConnectionPassword();
    if (dbPassword == null) {
        // Some RDBMS (e.g Postgresql) don't like null passwords
        dbPassword = "";
    }
    config.setPassword(dbPassword);
    if (storeMgr.getConnectionDriverName() != null) {
        String dbDriver = storeMgr.getConnectionDriverName();
        loadDriver(dbDriver, clr);
        config.setDriverClassName(dbDriver);
    }
    if (storeMgr.hasProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_MAX_POOL_SIZE)) {
        int size = storeMgr.getIntProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_MAX_POOL_SIZE);
        if (size >= 0) {
            config.setMaximumPoolSize(size);
        }
    }
    if (storeMgr.hasProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_MIN_IDLE)) {
        int idle = storeMgr.getIntProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_MIN_IDLE);
        if (idle >= 0) {
            config.setMinimumIdle(idle);
        }
    }
    if (storeMgr.hasProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_MAX_IDLE)) {
        long idle = storeMgr.getIntProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_MAX_IDLE);
        if (idle >= 0) {
            config.setIdleTimeout(idle);
        }
    }
    if (storeMgr.hasProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_LEAK_DETECTION_THRESHOLD)) {
        long threshold = storeMgr.getIntProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_LEAK_DETECTION_THRESHOLD);
        if (threshold >= 0) {
            config.setLeakDetectionThreshold(threshold);
        }
    }
    if (storeMgr.hasProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_MAX_LIFETIME)) {
        long maxLifeTime = storeMgr.getIntProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_MAX_LIFETIME);
        if (maxLifeTime >= 0) {
            config.setMaxLifetime(maxLifeTime);
        }
    }
    if (storeMgr.hasProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_AUTO_COMMIT)) {
        boolean autoCommit = storeMgr.getBooleanProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_AUTO_COMMIT);
        config.setAutoCommit(autoCommit);
    }
    if (storeMgr.hasProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_CONNECTION_WAIT_TIMEOUT)) {
        long connectionTimeout = storeMgr.getIntProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_CONNECTION_WAIT_TIMEOUT);
        if (connectionTimeout >= 0) {
            config.setConnectionTimeout(connectionTimeout);
        }
    }
    if (storeMgr.hasProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_TEST_SQL)) {
        String connectionTestQuery = storeMgr.getStringProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_TEST_SQL);
        config.setConnectionTestQuery(connectionTestQuery);
    }
    if (storeMgr.hasProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_NAME)) {
        String poolName = storeMgr.getStringProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_NAME);
        config.setPoolName(poolName);
    }
    if (storeMgr.hasProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_TRANSACTION_ISOLATION)) {
        String transactionIsolation = storeMgr.getStringProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_TRANSACTION_ISOLATION);
        config.setTransactionIsolation(transactionIsolation);
    }
    if (storeMgr.hasProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_CATALOG)) {
        String catalog = storeMgr.getStringProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_CATALOG);
        config.setCatalog(catalog);
    }
    if (storeMgr.hasProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_READ_ONLY)) {
        boolean readOnly = storeMgr.getBooleanProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_READ_ONLY);
        config.setReadOnly(readOnly);
    }
    if (storeMgr.hasProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_ALLOW_POOL_SUPSENSION)) {
        boolean allowPoolSuspension = storeMgr.getBooleanProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_ALLOW_POOL_SUPSENSION);
        config.setAllowPoolSuspension(allowPoolSuspension);
    }
    if (storeMgr.hasProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_VALIDATION_TIMEOUT)) {
        long validationTimeout = storeMgr.getIntProperty(RDBMSPropertyNames.PROPERTY_CONNECTION_POOL_VALIDATION_TIMEOUT);
        if (validationTimeout >= 0) {
            config.setValidationTimeout(validationTimeout);
        }
    }
    // Create the actual pool of connections
    HikariDataSource ds = new HikariDataSource(config);
    return new HikariCPConnectionPool(ds);
}
Example 70
Project: extract-master  File: DataSourceFactory.java View source code
public HikariDataSource create(final String poolName) {
    final HikariConfig config = new HikariConfig();
    config.setJdbcUrl("jdbc:mysql://" + (null == serverName ? "localhost" : serverName) + ":" + (port > 0 ? port : 3306) + "/" + (null == databaseName ? "extract" : databaseName));
    config.setUsername(null == user ? "extract" : user);
    config.setPassword(password);
    config.setPoolName(poolName);
    if (maximumPoolSize > 0) {
        config.setMaximumPoolSize(maximumPoolSize);
    }
    config.addDataSourceProperty("cachePrepStmts", true);
    config.addDataSourceProperty("prepStmtCacheSize", 250);
    config.addDataSourceProperty("prepStmtCacheSqlLimit", 2048);
    config.addDataSourceProperty("autoCommit", true);
    config.addDataSourceProperty("useSSL", useSSL);
    config.addDataSourceProperty("requireSSL", requireSSL);
    if (null != caCertificate) {
        String keyStoreType = FilenameUtils.getExtension(caCertificate.getFileName().toString().toUpperCase(Locale.ROOT));
        if (keyStoreType.isEmpty()) {
            keyStoreType = KeyStore.getDefaultType();
        } else if (keyStoreType.equals("P12")) {
            keyStoreType = "PKCS12";
        }
        config.addDataSourceProperty("verifyServerCertificate", true);
        config.addDataSourceProperty("trustCertificateKeyStoreType", keyStoreType);
        config.addDataSourceProperty("trustCertificateKeyStoreUrl", "file://" + caCertificate.toString());
        if (null != caPassword) {
            config.addDataSourceProperty("trustCertificateKeyStorePassword", caPassword);
        } else if (keyStoreType.equals("JKS")) {
            config.addDataSourceProperty("trustCertificateKeyStorePassword", "changeit");
        }
    }
    return new HikariDataSource(config);
}
Example 71
Project: jhipster-sample-app-java7-master  File: DatabaseConfiguration.java View source code
@Bean(destroyMethod = "close")
@ConditionalOnExpression("#{!environment.acceptsProfiles('cloud') && !environment.acceptsProfiles('heroku')}")
public DataSource dataSource(DataSourceProperties dataSourceProperties, JHipsterProperties jHipsterProperties) {
    log.debug("Configuring Datasource");
    // Standard property not available in DataSourceProperties
    String databaseName = env.getProperty("spring.datasource.name");
    if (dataSourceProperties.getUrl() == null && databaseName == null) {
        log.error("Your database connection pool configuration is incorrect! The application" + " cannot start. Please check your Spring profile, current profiles are: {}", Arrays.toString(env.getActiveProfiles()));
        throw new ApplicationContextException("Database connection pool is not configured correctly");
    }
    HikariConfig config = new HikariConfig();
    config.setDataSourceClassName(dataSourceProperties.getDriverClassName());
    if (StringUtils.isEmpty(dataSourceProperties.getUrl())) {
        config.addDataSourceProperty("databaseName", databaseName);
        config.addDataSourceProperty("serverName", jHipsterProperties.getDatasource().getServerName());
    } else {
        config.addDataSourceProperty("url", dataSourceProperties.getUrl());
    }
    if (dataSourceProperties.getUsername() != null) {
        config.addDataSourceProperty("user", dataSourceProperties.getUsername());
    } else {
        // HikariCP doesn't allow null user
        config.addDataSourceProperty("user", "");
    }
    if (dataSourceProperties.getPassword() != null) {
        config.addDataSourceProperty("password", dataSourceProperties.getPassword());
    } else {
        // HikariCP doesn't allow null password
        config.addDataSourceProperty("password", "");
    }
    //MySQL optimizations, see https://github.com/brettwooldridge/HikariCP/wiki/MySQL-Configuration
    if ("com.mysql.jdbc.jdbc2.optional.MysqlDataSource".equals(dataSourceProperties.getDriverClassName())) {
        config.addDataSourceProperty("cachePrepStmts", jHipsterProperties.getDatasource().isCachePrepStmts());
        config.addDataSourceProperty("prepStmtCacheSize", jHipsterProperties.getDatasource().getPrepStmtCacheSize());
        config.addDataSourceProperty("prepStmtCacheSqlLimit", jHipsterProperties.getDatasource().getPrepStmtCacheSqlLimit());
    }
    if (metricRegistry != null) {
        config.setMetricRegistry(metricRegistry);
    }
    return new HikariDataSource(config);
}
Example 72
Project: lab-master  File: NotificationDataConfig.java View source code
/**
	 * Datasource to JPA
	 * @param env Enviroment Variables/Properties
	 * @return DataSource
	 */
@Bean(destroyMethod = "close")
DataSource dataSource(Environment env) {
    HikariConfig config = new HikariConfig();
    config.setDriverClassName(env.getProperty("db.driver"));
    config.setJdbcUrl(env.getProperty("db.url"));
    config.setUsername(env.getProperty("db.username"));
    config.setPassword(env.getProperty("db.password"));
    config.setConnectionTestQuery(env.getProperty("db.test"));
    HikariDataSource ds = new HikariDataSource(config);
    return ds;
}
Example 73
Project: mariadb-connector-j-master  File: ConnectionPoolTest.java View source code
@Test
public void testBasicPool() throws SQLException {
    final HikariDataSource ds = new HikariDataSource();
    ds.setMaximumPoolSize(20);
    ds.setDriverClassName("org.mariadb.jdbc.Driver");
    ds.setJdbcUrl(connU);
    ds.addDataSourceProperty("user", username);
    if (password != null)
        ds.addDataSourceProperty("password", password);
    ds.setAutoCommit(false);
    validateDataSource(ds);
}
Example 74
Project: olca-modules-master  File: MySQLDatabase.java View source code
private void initConnectionPool() {
    try {
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl(url);
        config.setUsername(user);
        config.setPassword(password);
        connectionPool = new HikariDataSource(config);
    } catch (Exception e) {
        log.error("failed to initialize connection pool", e);
        throw new DatabaseException("Could not create a connection", e);
    }
}
Example 75
Project: Quartz-master  File: HikariCpPoolingConnectionProviderTest.java View source code
private void validateHikariCpPoolProviderClassWithExtraProps() throws Exception {
    DBConnectionManager dbManager = DBConnectionManager.getInstance();
    ConnectionProvider provider = dbManager.getConnectionProvider("myDS");
    HikariDataSource ds = ((HikariCpPoolingConnectionProvider) provider).getDataSource();
    Assert.assertThat(ds.getDriverClassName(), Matchers.is("org.apache.derby.jdbc.ClientDriver"));
    Assert.assertThat(ds.getJdbcUrl(), Matchers.is(JdbcQuartzDerbyUtilities.DATABASE_CONNECTION_PREFIX));
    Assert.assertThat(ds.getUsername(), Matchers.is("quartz"));
    Assert.assertThat(ds.getPassword(), Matchers.is("quartz"));
    Assert.assertThat(ds.getMaximumPoolSize(), Matchers.is(5));
    Assert.assertThat(ds.getTransactionIsolation(), Matchers.is("TRANSACTION_REPEATABLE_READ"));
    Assert.assertThat(ds.isReadOnly(), Matchers.is(false));
    Assert.assertThat(ds.isAutoCommit(), Matchers.is(false));
}
Example 76
Project: resource-server-master  File: ResourceServer.java View source code
@Primary
@Bean
public DataSource dataSource() {
    HikariConfig hikariConfig = new HikariConfig();
    hikariConfig.setPoolName("osiam-resource-server-cp");
    hikariConfig.setDriverClassName(driverClassName);
    hikariConfig.setJdbcUrl(databaseUrl);
    hikariConfig.setUsername(databaseUserName);
    hikariConfig.setPassword(databasePassword);
    hikariConfig.setMaximumPoolSize(maximumPoolSize);
    hikariConfig.setConnectionTimeout(connectionTimeoutMs);
    return new HikariDataSource(hikariConfig);
}
Example 77
Project: spring-data-jpa-examples-master  File: PersistenceContext.java View source code
/**
     * Creates and configures the HikariCP datasource bean.
     * @param env   The runtime environment of  our application.
     * @return
     */
@Bean(destroyMethod = "close")
DataSource dataSource(Environment env) {
    HikariConfig dataSourceConfig = new HikariConfig();
    dataSourceConfig.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DB_DRIVER_CLASS));
    dataSourceConfig.setJdbcUrl(env.getRequiredProperty(PROPERTY_NAME_DB_URL));
    dataSourceConfig.setUsername(env.getRequiredProperty(PROPERTY_NAME_DB_USER));
    dataSourceConfig.setPassword(env.getRequiredProperty(PROPERTY_NAME_DB_PASSWORD));
    return new HikariDataSource(dataSourceConfig);
}
Example 78
Project: vertx-jdbc-client-master  File: HikariCPDataSourceProvider.java View source code
@Override
public DataSource getDataSource(JsonObject json) throws SQLException {
    final HikariConfig config = new HikariConfig();
    for (Map.Entry<String, Object> entry : json) {
        switch(entry.getKey()) {
            case "dataSourceClassName":
                config.setDataSourceClassName((String) entry.getValue());
                break;
            case "jdbcUrl":
                config.setJdbcUrl((String) entry.getValue());
                break;
            case "username":
                config.setUsername((String) entry.getValue());
                break;
            case "password":
                config.setPassword((String) entry.getValue());
                break;
            case "autoCommit":
                config.setAutoCommit((Boolean) entry.getValue());
                break;
            case "connectionTimeout":
                config.setConnectionTimeout(getLong(entry.getValue()));
                break;
            case "idleTimeout":
                config.setIdleTimeout(getLong(entry.getValue()));
                break;
            case "maxLifetime":
                config.setMaxLifetime(getLong(entry.getValue()));
                break;
            case "connectionTestQuery":
                config.setConnectionTestQuery((String) entry.getValue());
                break;
            case "minimumIdle":
                config.setMinimumIdle((Integer) entry.getValue());
                break;
            case "maximumPoolSize":
                config.setMaximumPoolSize((Integer) entry.getValue());
                break;
            case "metricRegistry":
                throw new UnsupportedOperationException(entry.getKey());
            case "healthCheckRegistry":
                throw new UnsupportedOperationException(entry.getKey());
            case "poolName":
                config.setPoolName((String) entry.getValue());
                break;
            case "initializationFailFast":
                config.setInitializationFailFast((Boolean) entry.getValue());
                break;
            case "isolationInternalQueries":
                config.setIsolateInternalQueries((Boolean) entry.getValue());
                break;
            case "allowPoolSuspension":
                config.setAllowPoolSuspension((Boolean) entry.getValue());
                break;
            case "readOnly":
                config.setReadOnly((Boolean) entry.getValue());
                break;
            case "registerMBeans":
                config.setRegisterMbeans((Boolean) entry.getValue());
                break;
            case "catalog":
                config.setCatalog((String) entry.getValue());
                break;
            case "connectionInitSql":
                config.setConnectionInitSql((String) entry.getValue());
                break;
            case "driverClassName":
                config.setDriverClassName((String) entry.getValue());
                break;
            case "transactionIsolation":
                config.setTransactionIsolation((String) entry.getValue());
                break;
            case "validationTimeout":
                config.setValidationTimeout(getLong(entry.getValue()));
                break;
            case "leakDetectionThreshold":
                config.setLeakDetectionThreshold(getLong(entry.getValue()));
                break;
            case "dataSource":
                throw new UnsupportedOperationException(entry.getKey());
            case "threadFactory":
                throw new UnsupportedOperationException(entry.getKey());
            case "datasource":
                // extension to support configuring datasource.* properties
                for (Map.Entry<String, Object> key : ((JsonObject) entry.getValue())) {
                    config.addDataSourceProperty(key.getKey(), key.getValue());
                }
                break;
        }
    }
    return new HikariDataSource(config);
}
Example 79
Project: Yank-master  File: YankPoolManager.java View source code
/**
   * Creates a Hikari connection pool and puts it in the pools map.
   *
   * @param poolName
   * @param connectionPoolProperties
   */
private void createPool(String poolName, Properties connectionPoolProperties) {
    releaseConnectionPool(poolName);
    // DBUtils execute methods require autoCommit to be true.
    connectionPoolProperties.put("autoCommit", true);
    HikariConfig config = new HikariConfig(connectionPoolProperties);
    config.setPoolName(poolName);
    HikariDataSource ds = new HikariDataSource(config);
    pools.put(poolName, ds);
    logger.info("Initialized pool '{}'", poolName);
}
Example 80
Project: audit4j-db-master  File: ConnectionFactory.java View source code
/**
     * initialize connection factory. This will created the necessary connection
     * pools and jndi lookups in advance.
     */
void init() {
    if (dataSource == null) {
        if (connectionType.equals(ConnectionType.POOLED)) {
            HikariConfig config = new HikariConfig();
            config.setMaximumPoolSize(maximumPoolSize);
            config.setDataSourceClassName(dataSourceClass);
            config.addDataSourceProperty("url", url);
            config.addDataSourceProperty("user", user);
            config.addDataSourceProperty("password", password);
            config.setPoolName(CONNECTION_POOL_NAME);
            config.setAutoCommit(autoCommit);
            config.setMaximumPoolSize(maximumPoolSize);
            if (connectionTimeout != null) {
                config.setConnectionTimeout(connectionTimeout);
            }
            if (idleTimeout != null) {
                config.setIdleTimeout(idleTimeout);
            }
            if (maxLifetime != null) {
                config.setMaxLifetime(maxLifetime);
            }
            if (minimumIdle != null) {
                config.setMinimumIdle(minimumIdle);
            }
            ds = new HikariDataSource(config);
            dataSource = ds;
        } else if (connectionType.equals(ConnectionType.JNDI)) {
            if (null == jndiDataSource) {
                throw new InitializationException("Could not obtain the db connection: jndi data source is null");
            }
            String DATASOURCE_CONTEXT = jndiDataSource;
            try {
                Context initialContext = new InitialContext();
                dataSource = (DataSource) initialContext.lookup(DATASOURCE_CONTEXT);
                if (dataSource == null) {
                    Log.error("Failed to lookup datasource.");
                    throw new InitializationException("Could not obtain the db connection: Failed to lookup datasource: " + jndiDataSource);
                }
            } catch (NamingException ex) {
                throw new InitializationException("Could not obtain the db connection: jndi lookup failed", ex);
            }
        }
    }
}
Example 81
Project: jooby-master  File: Jdbc.java View source code
protected void configure(final Env env, final Config config, final Binder binder, final BiConsumer<String, HikariDataSource> extensions) {
    Config dbconf;
    String url, dbname, dbkey;
    boolean seturl = false;
    if (dbref.startsWith("jdbc:")) {
        dbconf = config;
        url = dbref;
        dbname = DB_NAME.apply(url);
        dbkey = dbname;
        seturl = true;
    } else {
        dbconf = dbConfig(dbref, config);
        url = dbconf.getString(dbref + ".url");
        dbname = DB_NAME.apply(url);
        dbkey = dbref;
    }
    HikariConfig hikariConf = hikariConfig(url, dbkey, dbname, dbconf);
    if (seturl) {
        Properties props = hikariConf.getDataSourceProperties();
        props.setProperty("url", url);
    }
    callback(hikariConf, config);
    HikariDataSource ds = new HikariDataSource(hikariConf);
    extensions.accept(dbname, ds);
    env.serviceKey().generate(DataSource.class, dbname,  k -> binder.bind(k).toInstance(ds));
    env.onStop(ds::close);
}
Example 82
Project: jOOQ-master  File: SakilaReportService.java View source code
private static void initDB() throws Exception {
    final Properties properties = new Properties();
    properties.load(SakilaReportService.class.getResourceAsStream("/config.properties"));
    Class.forName(properties.getProperty("db.driver"));
    HikariDataSource ds = new HikariDataSource();
    ds.setJdbcUrl(properties.getProperty("db.url"));
    ds.setUsername(properties.getProperty("db.username"));
    ds.setPassword(properties.getProperty("db.password"));
    // Some nice debug logging of formatted queries and the first 5 rows in each result set.
    dsl = DSL.using(new DefaultConfiguration().set(ds).set(DefaultExecuteListenerProvider.providers(new DefaultExecuteListener() {

        @Override
        public void executeEnd(ExecuteContext ctx) {
            Configuration config = ctx.configuration().derive();
            config.settings().setRenderFormatted(true);
            log.info("\n" + DSL.using(config).renderInlined(ctx.query()));
        }

        @Override
        public void fetchEnd(ExecuteContext ctx) {
            log.info("\n" + ctx.result().format(5));
        }
    })));
}
Example 83
Project: killbill-commons-master  File: TestDataSourceProvider.java View source code
@Test(groups = "fast")
public void testDataSourceProviderHikariCP() throws Exception {
    DataSourceProvider.DatabaseType databaseType;
    DaoConfig daoConfig;
    String poolName;
    DataSourceProvider dataSourceProvider;
    // H2
    databaseType = DataSourceProvider.DatabaseType.H2;
    daoConfig = buildDaoConfig(DataSourceConnectionPoolingType.HIKARICP, databaseType);
    poolName = TEST_POOL_PREFIX + "-0-" + databaseType;
    dataSourceProvider = new DataSourceProvider(daoConfig, poolName);
    assertTrue(dataSourceProvider.get() instanceof HikariDataSource);
    // Generic
    databaseType = DataSourceProvider.DatabaseType.GENERIC;
    daoConfig = buildDaoConfig(DataSourceConnectionPoolingType.HIKARICP, databaseType);
    poolName = TEST_POOL_PREFIX + "-0-" + databaseType;
    dataSourceProvider = new DataSourceProvider(daoConfig, poolName);
    assertTrue(dataSourceProvider.get() instanceof HikariDataSource);
}
Example 84
Project: meta-server-master  File: JettyMain.java View source code
/**
     * @param args ignored
     * @throws Exception
     */
public static void main(String[] args) throws Exception {
    String portEnv = System.getenv("PORT");
    if (portEnv == null) {
        portEnv = "8080";
        logger.warn("Environment variable 'PORT' not defined - using default {}", portEnv);
    }
    Integer port = Integer.valueOf(portEnv);
    String dbEnv = System.getenv("DATABASE_URL");
    if (dbEnv == null) {
        logger.error("Environment variable 'DATABASE_URL' not defined!");
        return;
    }
    URI dbUri = new URI(dbEnv);
    String secret = System.getenv("EDIT_SECRET");
    if (secret == null) {
        logger.error("Environment variable 'EDIT_SECRET' not defined!");
        return;
    }
    String dbIpApiKey = System.getenv("DBIP_API_KEY");
    if (dbIpApiKey == null) {
        logger.warn("Environment variable 'DBIP_API_KEY' not defined - geo location lookup not available");
    }
    String username = dbUri.getUserInfo().split(":")[0];
    String password = dbUri.getUserInfo().split(":")[1];
    int dbPort = dbUri.getPort();
    String host = "http://artifactory.terasology.org/artifactory";
    String releaseRepo = "terasology-release-local";
    String snapshotRepo = "terasology-snapshot-local";
    String modGroup = "org.terasology.modules";
    String engineGroup = "org.terasology.engine";
    Path cacheFolder = Paths.get("cache", "modules");
    ModuleListModelImpl moduleListModel = new ModuleListModelImpl(cacheFolder);
    Path releaseRepoFolder = cacheFolder.resolve(releaseRepo);
    Path snapshotRepoFolder = cacheFolder.resolve(snapshotRepo);
    // add module repos
    moduleListModel.addRepository(ArtifactoryRepo.release(host, releaseRepo, modGroup, releaseRepoFolder));
    moduleListModel.addRepository(ArtifactoryRepo.snapshot(host, snapshotRepo, modGroup, snapshotRepoFolder));
    // add engine repos
    moduleListModel.addRepository(ArtifactoryRepo.release(host, releaseRepo, engineGroup, releaseRepoFolder));
    moduleListModel.addRepository(ArtifactoryRepo.snapshot(host, snapshotRepo, engineGroup, snapshotRepoFolder));
    HikariConfig config = new HikariConfig();
    config.setJdbcUrl("jdbc:postgresql://" + dbUri.getHost() + ":" + dbPort + dbUri.getPath());
    config.setUsername(username);
    config.setPassword(password);
    config.addDataSourceProperty("sslmode", "require");
    config.setMaximumPoolSize(3);
    config.setMinimumIdle(1);
    GeoLocationService geoService = new GeoLocationServiceDbIp(dbIpApiKey);
    // this is mostly for I18nMap, but can have an influence on other
    // string formats. Note that metainfo.ftl explicitly sets the locale to
    // define the date format.
    Locale.setDefault(Locale.ENGLISH);
    try (HikariDataSource ds = new HikariDataSource(config)) {
        DataBase dataBase = new JooqDatabase(ds, geoService);
        ServerListModel serverListModel = new ServerListModelImpl(dataBase, "servers", secret);
        Server server = createServer(port.intValue(), new AboutServlet(), // the server list servlet
        new ServerServlet(serverListModel), // the module list servlet
        new ModuleServlet(moduleListModel));
        server.start();
        logger.info("Server started on port {}!", port);
        new Thread(moduleListModel::updateAllModules).start();
        server.join();
    }
}
Example 85
Project: norm-master  File: Database.java View source code
/**
	 * Provides the DataSource used by this database. Override this method to change how the DataSource is created or
	 * configured.
	 */
protected DataSource getDataSource() throws SQLException {
    HikariConfig config = new HikariConfig();
    config.setMaximumPoolSize(10);
    String dataSourceClassName = System.getProperty("norm.dataSourceClassName");
    if (dataSourceClassName != null) {
        config.setDataSourceClassName(dataSourceClassName);
    }
    String driverClassName = System.getProperty("norm.driverClassName");
    if (driverClassName != null) {
        config.setDriverClassName(driverClassName);
    }
    String jdbcUrl = System.getProperty("norm.jdbcUrl");
    if (jdbcUrl != null) {
        config.setJdbcUrl(jdbcUrl);
    }
    addConfigProperty(config, "serverName", System.getProperty("norm.serverName"));
    addConfigProperty(config, "databaseName", System.getProperty("norm.databaseName"));
    addConfigProperty(config, "user", System.getProperty("norm.user"));
    addConfigProperty(config, "password", System.getProperty("norm.password"));
    return new HikariDataSource(config);
}
Example 86
Project: OpenRate-master  File: HikariCPDataSource.java View source code
/**
  * Create new data source from provided properties.
  *
  * @param ResourceName The name of the DataSourceFactory in the properties
  * @param dataSourceName The name of the data source to create
  * @return The created data source
  * @throws OpenRate.exception.InitializationException
  */
@Override
public DataSource getDataSource(String ResourceName, String dataSourceName) throws InitializationException {
    String db_url = null;
    String driver = null;
    String username = null;
    String password = null;
    String validationSQL = null;
    OpenRate.getOpenRateFrameworkLog().debug("Creating new DataSource <" + dataSourceName + ">");
    try {
        // get the connection parameters
        db_url = PropertyUtils.getPropertyUtils().getDataSourcePropertyValue(dataSourceName, DB_URL_KEY);
        driver = PropertyUtils.getPropertyUtils().getDataSourcePropertyValue(dataSourceName, DRIVER_KEY);
        username = PropertyUtils.getPropertyUtils().getDataSourcePropertyValue(dataSourceName, USERNAME_KEY);
        password = PropertyUtils.getPropertyUtils().getDataSourcePropertyValue(dataSourceName, PASSWORD_KEY);
        validationSQL = PropertyUtils.getPropertyUtils().getDataSourcePropertyValue(dataSourceName, VALIDATION_QUERY_KEY);
        if (db_url == null || db_url.isEmpty()) {
            message = "Error recovering data source parameter <db_url> for data source <" + dataSourceName + ">";
            OpenRate.getOpenRateFrameworkLog().error(message);
            throw new InitializationException(message, getSymbolicName());
        }
        if (driver == null || driver.isEmpty()) {
            message = "Error recovering data source parameter <driver> for data source <" + dataSourceName + ">";
            OpenRate.getOpenRateFrameworkLog().error(message);
            throw new InitializationException(message, getSymbolicName());
        }
        if (username == null || username.isEmpty()) {
            message = "Error recovering data source parameter <username> for data source <" + dataSourceName + ">";
            OpenRate.getOpenRateFrameworkLog().error(message);
            throw new InitializationException(message, getSymbolicName());
        }
        if (password == null) {
            message = "Error recovering data source parameter <password> for data source <" + dataSourceName + ">";
            OpenRate.getOpenRateFrameworkLog().error(message);
            throw new InitializationException(message, getSymbolicName());
        }
        OpenRate.getOpenRateFrameworkLog().info("Creating DataSource <" + dataSourceName + "> using driver <" + driver + "> from URL <" + db_url + ">");
        Class<?> driverClass = Class.forName(driver);
        OpenRate.getOpenRateFrameworkLog().debug("jdbc driver loaded. name = <" + driverClass.getName() + ">");
    } catch (ClassNotFoundException cnfe) {
        message = "Driver class <" + driver + "> not found for data source <" + dataSourceName + ">";
        OpenRate.getOpenRateFrameworkLog().error(message);
        throw new InitializationException(message, getSymbolicName());
    }
    // Initialize pool 
    HikariDataSource dataSource = new HikariDataSource();
    // Set driver class 
    dataSource.setDriverClassName(driver);
    //dataSource.setDataSourceClassName(dsName);
    // Options with defaults
    int minConn = Integer.parseInt(PropertyUtils.getPropertyUtils().getDataSourcePropertyValueDef(dataSourceName, MIN_CONN_KEY, DEFAULT_MIN_CONN));
    int maxConn = Integer.parseInt(PropertyUtils.getPropertyUtils().getDataSourcePropertyValueDef(dataSourceName, MAX_CONN_KEY, DEFAULT_MAX_CONN));
    Long connTimeOut = Long.parseLong(PropertyUtils.getPropertyUtils().getDataSourcePropertyValueDef(dataSourceName, CONN_TIMEOUT_KEY, DEFAULT_CONN_TIMEOUT));
    String poolName = PropertyUtils.getPropertyUtils().getDataSourcePropertyValueDef(dataSourceName, POOL_NAME_KEY, DEFAULT_POOL_NAME);
    // Perform the initialization      
    dataSource.setJdbcUrl(db_url);
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    // Pooling configuration
    dataSource.setMaximumPoolSize(maxConn);
    dataSource.setMinimumIdle(minConn);
    dataSource.setConnectionTimeout(connTimeOut);
    if (!poolName.equals("HikariDefined")) {
        dataSource.setPoolName(poolName);
    }
    if (validationSQL == null || validationSQL.isEmpty()) {
        OpenRate.getOpenRateFrameworkLog().warning("No SQL validation statement found for Datasource <" + dataSourceName + ">");
    } else {
        dataSource.setConnectionTestQuery(validationSQL);
        // Test the data source
        try {
            Connection testConn = dataSource.getConnection();
            PreparedStatement stmt = testConn.prepareStatement(validationSQL);
            stmt.executeQuery();
            // tidy up
            stmt.close();
            testConn.close();
        } catch (SQLException ex) {
            message = "Connection test failed for connection <" + dataSourceName + ">";
            OpenRate.getOpenRateFrameworkLog().error(message);
            throw new InitializationException(message, getSymbolicName());
        }
    }
    return dataSource;
}
Example 87
Project: Stage-master  File: ConnectionMonitoringTransformerTest.java View source code
@Parameterized.Parameters(name = "{index}: {1}")
public static Iterable<Object[]> data() throws Exception {
    final PoolProperties poolProperties = new PoolProperties();
    poolProperties.setDriverClassName(DRIVER_CLASS_NAME);
    poolProperties.setUrl(URL);
    final org.apache.tomcat.jdbc.pool.DataSource tomcatDataSource = new org.apache.tomcat.jdbc.pool.DataSource(poolProperties);
    ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
    comboPooledDataSource.setDriverClass(DRIVER_CLASS_NAME);
    comboPooledDataSource.setJdbcUrl(URL);
    HikariDataSource hikariDataSource = new HikariDataSource();
    hikariDataSource.setDriverClassName(DRIVER_CLASS_NAME);
    hikariDataSource.setJdbcUrl(URL);
    org.apache.commons.dbcp.BasicDataSource dbcp = new org.apache.commons.dbcp.BasicDataSource();
    dbcp.setDriverClassName(DRIVER_CLASS_NAME);
    dbcp.setUrl(URL);
    org.apache.commons.dbcp2.BasicDataSource dbcp2 = new org.apache.commons.dbcp2.BasicDataSource();
    dbcp2.setDriverClassName(DRIVER_CLASS_NAME);
    dbcp2.setUrl(URL);
    DruidDataSource druidDataSource = new DruidDataSource();
    druidDataSource.setDriverClassName(DRIVER_CLASS_NAME);
    druidDataSource.setUrl(URL);
    druidDataSource.setTestWhileIdle(false);
    return Arrays.asList(new Object[][] { { tomcatDataSource, tomcatDataSource.getClass() }, { comboPooledDataSource, comboPooledDataSource.getClass() }, { hikariDataSource, hikariDataSource.getClass() }, { dbcp, dbcp.getClass() }, { dbcp2, dbcp2.getClass() }, { new P6DataSource(druidDataSource), druidDataSource.getClass() } });
}
Example 88
Project: stagemonitor-master  File: ConnectionMonitoringTransformerTest.java View source code
@Parameterized.Parameters(name = "{index}: {1}")
public static Iterable<Object[]> data() throws Exception {
    final PoolProperties poolProperties = new PoolProperties();
    poolProperties.setDriverClassName(DRIVER_CLASS_NAME);
    poolProperties.setUrl(URL);
    final org.apache.tomcat.jdbc.pool.DataSource tomcatDataSource = new org.apache.tomcat.jdbc.pool.DataSource(poolProperties);
    ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
    comboPooledDataSource.setDriverClass(DRIVER_CLASS_NAME);
    comboPooledDataSource.setJdbcUrl(URL);
    HikariDataSource hikariDataSource = new HikariDataSource();
    hikariDataSource.setDriverClassName(DRIVER_CLASS_NAME);
    hikariDataSource.setJdbcUrl(URL);
    org.apache.commons.dbcp.BasicDataSource dbcp = new org.apache.commons.dbcp.BasicDataSource();
    dbcp.setDriverClassName(DRIVER_CLASS_NAME);
    dbcp.setUrl(URL);
    org.apache.commons.dbcp2.BasicDataSource dbcp2 = new org.apache.commons.dbcp2.BasicDataSource();
    dbcp2.setDriverClassName(DRIVER_CLASS_NAME);
    dbcp2.setUrl(URL);
    DruidDataSource druidDataSource = new DruidDataSource();
    druidDataSource.setDriverClassName(DRIVER_CLASS_NAME);
    druidDataSource.setUrl(URL);
    druidDataSource.setTestWhileIdle(false);
    return Arrays.asList(new Object[][] { { tomcatDataSource, tomcatDataSource.getClass() }, { comboPooledDataSource, comboPooledDataSource.getClass() }, { hikariDataSource, hikariDataSource.getClass() }, { dbcp, dbcp.getClass() }, { dbcp2, dbcp2.getClass() }, { new P6DataSource(druidDataSource), druidDataSource.getClass() } });
}
Example 89
Project: steve-master  File: BeanConfiguration.java View source code
/**
     * https://github.com/brettwooldridge/HikariCP/wiki/MySQL-Configuration
     */
private void initDataSource() {
    MysqlDataSource ds = new MysqlDataSource();
    // set standard params
    ds.setServerName(CONFIG.getDb().getIp());
    ds.setPort(CONFIG.getDb().getPort());
    ds.setDatabaseName(CONFIG.getDb().getSchema());
    ds.setUser(CONFIG.getDb().getUserName());
    ds.setPassword(CONFIG.getDb().getPassword());
    // set non-standard params
    ds.getModifiableProperty(PropertyDefinitions.PNAME_cachePrepStmts).setValue(true);
    ds.getModifiableProperty(PropertyDefinitions.PNAME_prepStmtCacheSize).setValue(250);
    ds.getModifiableProperty(PropertyDefinitions.PNAME_prepStmtCacheSqlLimit).setValue(2048);
    ds.getModifiableProperty(PropertyDefinitions.PNAME_characterEncoding).setValue("utf8");
    HikariConfig hc = new HikariConfig();
    hc.setDataSource(ds);
    dataSource = new HikariDataSource(hc);
}
Example 90
Project: torodb-master  File: AbstractDbBackendService.java View source code
private HikariDataSource createPooledDataSource(ConfigurationT configuration, String poolName, int poolSize, TransactionIsolationLevel transactionIsolationLevel, boolean readOnly) {
    HikariConfig hikariConfig = new HikariConfig();
    // Delegate database-specific setting of connection parameters and any specific configuration
    hikariConfig.setDataSource(getConfiguredDataSource(configuration, poolName));
    // Apply ToroDB-specific datasource configuration
    hikariConfig.setConnectionTimeout(configuration.getConnectionPoolTimeout());
    hikariConfig.setPoolName(poolName);
    hikariConfig.setMaximumPoolSize(poolSize);
    hikariConfig.setTransactionIsolation(transactionIsolationLevel.name());
    hikariConfig.setReadOnly(readOnly);
    /*
     * TODO: implement to add metric support. See
     * https://github.com/brettwooldridge/HikariCP/wiki/Codahale-Metrics
     * hikariConfig.setMetricRegistry(...);
     */
    LOGGER.info("Created pool {} with size {} and level {}", poolName, poolSize, transactionIsolationLevel.name());
    return new HikariDataSource(hikariConfig);
}
Example 91
Project: werval-master  File: JDBCPlugin.java View source code
@Override
public void onActivate(Application application) throws ActivationException {
    Config config = application.config();
    Map<String, HikariDataSource> dataSources = new HashMap<>();
    if (config.has(DATASOURCES)) {
        Config allDsConfig = config.atPath(DATASOURCES);
        setupLog4Jdbc(application, allDsConfig);
        for (String dsName : allDsConfig.subKeys()) {
            Config dsConfig = allDsConfig.atKey(dsName);
            HikariDataSource ds = createDataSource(dsName, dsConfig, application, config.bool(METRICS));
            dataSources.put(dsName, ds);
        }
    }
    jdbc = new JDBC(dataSources, config.string(DEFAULT_DATASOURCE));
}
Example 92
Project: alf.io-master  File: DataSourceConfiguration.java View source code
@Bean
public DataSource getDataSource(Environment env, PlatformProvider platform) throws URISyntaxException {
    if (platform == PlatformProvider.CLOUD_FOUNDRY) {
        return new FakeCFDataSource();
    } else {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl(platform.getUrl(env));
        dataSource.setUsername(platform.getUsername(env));
        dataSource.setPassword(platform.getPassword(env));
        dataSource.setDriverClassName(platform.getDriveClassName(env));
        int maxActive = platform.getMaxActive(env);
        dataSource.setMaximumPoolSize(maxActive);
        log.debug("Connection pool properties: max active {}, initial size {}", maxActive, dataSource.getMinimumIdle());
        return dataSource;
    }
}
Example 93
Project: artificer-master  File: HibernateUtil.java View source code
private static void initHikariCP(Map<String, Object> properties) {
    String connectionUrl = (String) properties.remove("hibernate.connection.url");
    String username = (String) properties.remove("hibernate.connection.username");
    String password = (String) properties.remove("hibernate.connection.password");
    HikariConfig hikariConfig = new HikariConfig();
    hikariConfig.setJdbcUrl(connectionUrl);
    hikariConfig.setUsername(username);
    hikariConfig.setPassword(password);
    // In case we're using MySQL, these settings are recommended by HikariCP:
    hikariConfig.addDataSourceProperty("cachePrepStmts", "true");
    hikariConfig.addDataSourceProperty("prepStmtCacheSize", "250");
    hikariConfig.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
    hikariConfig.addDataSourceProperty("useServerPrepStmts", "true");
    String dialect = (String) properties.get("hibernate.dialect");
    if (dialect != null && dialect.contains("PostgreSQL")) {
        // The JDBC jar verion in the IP BOM does not support Connection.isValid(), so need to use this:
        hikariConfig.setConnectionTestQuery("SELECT 1");
    }
    HikariDataSource hikariDataSource = new HikariDataSource(hikariConfig);
    properties.put("hibernate.connection.datasource", hikariDataSource);
}
Example 94
Project: BlockOwn-master  File: MySqlDatabase.java View source code
private HikariDataSource connect(String host, int port, String databaseName, String username, String password) throws SQLException {
    HikariConfig config = new HikariConfig();
    config.setDataSourceClassName("com.mysql.jdbc.jdbc2.optional.MysqlDataSource");
    config.setUsername(username);
    config.setPassword(password);
    config.addDataSourceProperty("url", "jdbc:mysql://" + host + ":" + port + "/" + databaseName);
    config.addDataSourceProperty("cachePrepStmts", "true");
    config.addDataSourceProperty("prepStmtCacheSize", "250");
    config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
    return new HikariDataSource(config);
}
Example 95
Project: ddth-id-master  File: JdbcIdGenerator.java View source code
/**
     * {@inheritDoc}
     */
@Override
public JdbcIdGenerator init() {
    if (dataSource == null) {
        HikariDataSource ds = new HikariDataSource();
        ds.setDriverClassName(jdbcDriverClass);
        ds.setJdbcUrl(jdbcUrl);
        ds.setUsername(jdbcUser);
        ds.setPassword(jdbcPassword);
        ds.setConnectionTimeout(10000);
        ds.setIdleTimeout(900000);
        ds.setMaxLifetime(1800000);
        if (!StringUtils.isBlank(testSql)) {
            ds.setConnectionTestQuery(testSql);
        }
        ds.setValidationTimeout(3000);
        ds.setMaximumPoolSize(concurrency);
        if (!StringUtils.isBlank(initSql)) {
            ds.setConnectionInitSql(initSql);
        }
        ds.setLeakDetectionThreshold(300000);
        this.dataSource = ds;
        myOwnDataSource = true;
    }
    super.init();
    sqlInsert = MessageFormat.format("INSERT INTO {0} ({1}, {2}) VALUES (?, 0)", tableName, colName, colValue);
    sqlUpdateInc = MessageFormat.format("UPDATE {0} SET {2}={2}+1 WHERE {1}=?", tableName, colName, colValue);
    sqlUpdateSet = MessageFormat.format("UPDATE {0} SET {2}=? WHERE {1}=?", tableName, colName, colValue);
    sqlSelect = MessageFormat.format("SELECT {2} FROM {0} WHERE {1}=?", tableName, colName, colValue);
    return this;
}
Example 96
Project: geoserver-master  File: LogStoreInitializer.java View source code
static void dispose(DataSource dataSource) {
    if (dataSource instanceof HikariDataSource) {
        ((HikariDataSource) dataSource).close();
    } else if (dataSource instanceof SingleConnectionDataSource) {
        try {
            ((SingleConnectionDataSource) dataSource).conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
Example 97
Project: jfinal-master  File: HikariCpPlugin.java View source code
@Override
public boolean start() {
    HikariConfig config = new HikariConfig();
    //设定基本�数
    config.setJdbcUrl(jdbcUrl);
    config.setUsername(username);
    config.setPassword(password);
    //设定�外�数
    config.setAutoCommit(autoCommit);
    config.setReadOnly(readOnly);
    config.setConnectionTimeout(connectionTimeout);
    config.setIdleTimeout(idleTimeout);
    config.setMaxLifetime(maxLifetime);
    config.setMaximumPoolSize(maximumPoolSize);
    config.setValidationTimeout(validationTimeout);
    if (StrKit.notBlank(driverClass)) {
        config.setDriverClassName(driverClass);
    }
    if (StrKit.notBlank(transactionIsolation)) {
        config.setTransactionIsolation(transactionIsolation);
    }
    if (this.leakDetectionThreshold != 0) {
        config.setLeakDetectionThreshold(leakDetectionThreshold);
    }
    if (StrKit.notBlank(catalog)) {
        config.setCatalog(catalog);
    }
    if (StrKit.notBlank(connectionTestQuery)) {
        config.setConnectionTestQuery(connectionTestQuery);
    }
    if (StrKit.notBlank(poolName)) {
        config.setPoolName(poolName);
    }
    if (StrKit.notBlank(connectionInitSql)) {
        config.setConnectionInitSql(connectionInitSql);
    }
    if (jdbcUrl.toLowerCase().contains(":mysql:")) {
        config.addDataSourceProperty("cachePrepStmts", "true");
        config.addDataSourceProperty("useServerPrepStmts", "true");
        config.addDataSourceProperty("prepStmtCacheSize", "256");
        config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
    }
    if (jdbcUrl.toLowerCase().contains(":postgresql:")) {
        if (this.readOnly) {
            config.addDataSourceProperty("readOnly", "true");
        }
        config.setConnectionTimeout(0);
        config.addDataSourceProperty("prepareThreshold", "3");
        config.addDataSourceProperty("preparedStatementCacheQueries", "128");
        config.addDataSourceProperty("preparedStatementCacheSizeMiB", "4");
    }
    ds = new HikariDataSource(config);
    return true;
}
Example 98
Project: LanternServer-master  File: LanternSqlService.java View source code
@Override
public HikariDataSource load(@Nonnull ConnectionInfo key) throws Exception {
    final HikariConfig config = new HikariConfig();
    config.setUsername(key.getUser());
    config.setPassword(key.getPassword());
    config.setDriverClassName(key.getDriverClassName());
    // https://github.com/brettwooldridge/HikariCP/wiki/About-Pool-Sizing for info on pool sizing
    config.setMaximumPoolSize((Runtime.getRuntime().availableProcessors() * 2) + 1);
    final Properties driverSpecificProperties = PROTOCOL_SPECIFIC_PROPS.get(key.getDriverClassName());
    if (driverSpecificProperties != null) {
        config.setDataSourceProperties(driverSpecificProperties);
    }
    config.setJdbcUrl(key.getAuthlessUrl());
    return new HikariDataSource(config);
}
Example 99
Project: owsi-core-parent-master  File: JpaConfigUtils.java View source code
public static DataSource dataSource(IDatabaseConnectionPoolConfigurationProvider configurationProvider) {
    HikariDataSource dataSource = new HikariDataSource();
    dataSource.setDriverClassName(configurationProvider.getDriverClass().getName());
    dataSource.setJdbcUrl(configurationProvider.getUrl());
    dataSource.setUsername(configurationProvider.getUser());
    dataSource.setPassword(configurationProvider.getPassword());
    dataSource.addDataSourceProperty("user", configurationProvider.getUser());
    dataSource.addDataSourceProperty("password", configurationProvider.getPassword());
    dataSource.setMinimumIdle(configurationProvider.getMinIdle());
    dataSource.setMaximumPoolSize(configurationProvider.getMaxPoolSize());
    dataSource.setConnectionTestQuery(configurationProvider.getValidationQuery());
    dataSource.setConnectionInitSql(emptyToNull(configurationProvider.getInitSql()));
    return dataSource;
}
Example 100
Project: dcache-master  File: PerformanceTest.java View source code
public static void main(String arguments[]) throws Exception {
    /* Parse arguments.
         */
    Args args = new Args(arguments);
    if (args.argc() < 5) {
        System.err.print("Usage: nsp-performance.sh [-threads=<n>] ");
        for (Operation aOp : Operation.values()) {
            System.err.print("[-" + aOp.getUserInput() + "] ");
        }
        System.err.println(" <file>");
        System.err.println("  where <file> contains a list of paths to load and the remaining ");
        System.err.println("  parameters are the Chimera connection details.");
        System.err.println("Options:");
        for (Operation aOp : Operation.values()) {
            System.err.println(aOp);
        }
        System.err.println("\t-threads\tSets number of concurrent reads");
        System.err.println("\t-delay\tSets delay in seconds between progress updates");
        System.err.println("");
        System.err.println("Remaining arguments are passed on to the provider factory.");
        System.exit(2);
    }
    String jdbc = args.argv(0);
    String user = args.argv(1);
    String password = args.argv(2);
    String fileName = args.argv(3);
    args.shift(5);
    ops = getOps(args);
    int concurrency = (args.hasOption("threads")) ? Integer.parseInt(args.getOpt("threads")) : 1;
    int delay = (args.hasOption("delay")) ? Integer.parseInt(args.getOpt("delay")) : 10;
    /* Instantiate provider.
         */
    System.out.println("Starting chimera... ");
    HikariDataSource dataSource = FsFactory.getDataSource(jdbc, user, password);
    PlatformTransactionManager txManager = new DataSourceTransactionManager(dataSource);
    FileSystemProvider fileSystem = new JdbcFs(dataSource, txManager);
    provider = new ChimeraNameSpaceProvider();
    provider.setAclEnabled(false);
    provider.setExtractor(new ChimeraOsmStorageInfoExtractor(StorageInfo.DEFAULT_ACCESS_LATENCY, StorageInfo.DEFAULT_RETENTION_POLICY));
    provider.setFileSystem(fileSystem);
    provider.setInheritFileOwnership(false);
    provider.setPermissionHandler(new PosixPermissionHandler());
    provider.setUploadDirectory("/upload");
    provider.setVerifyAllLookups(true);
    tx = new TransactionTemplate(txManager);
    /* Read paths.
         */
    System.out.println("Loading " + fileName);
    queue = new LinkedBlockingQueue<>();
    List<String> paths = getPaths(fileName);
    queue.addAll(paths);
    /* Run test.
         */
    System.out.println("Running test...");
    ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
    ExecutorService executor = Executors.newCachedThreadPool();
    ScheduledFuture<?> progressTask = scheduler.scheduleAtFixedRate(new ProgressTask(), delay, delay, TimeUnit.SECONDS);
    Stopwatch watch = Stopwatch.createStarted();
    for (int i = 0; i < concurrency; i++) {
        executor.execute(new PerformanceTest());
    }
    executor.shutdown();
    executor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
    watch.stop();
    progressTask.cancel(false);
    scheduler.shutdownNow();
    /* Report result.
         */
    StringWriter info = new StringWriter();
    provider.getInfo(new PrintWriter(info));
    System.out.println();
    System.out.println(info);
    System.out.println("Number of files  : " + paths.size());
    System.out.println("Number of threads: " + concurrency);
    System.out.println("Operations       : " + ops.stream().map(Operation::getUserInput).collect(joining(",")));
    System.out.println("Total time       : " + watch);
    System.out.println("Average pr. op   : " + ((double) watch.elapsed(TimeUnit.MICROSECONDS)) / paths.size() + " µs");
    System.out.println("Frequency        : " + 1000 * paths.size() / watch.elapsed(TimeUnit.MILLISECONDS) + " Hz");
    fileSystem.close();
    dataSource.close();
}
Example 101
Project: oracle-master  File: Oracle.java View source code
/**
     *
     * @return
     */
public HikariDataSource initDbPool() {
    String dns = "jdbc:mysql://" + getConfig().getNode("db", "host").getString() + ":" + getConfig().getNode("db", "port").getString() + "/" + getConfig().getNode("db", "name").getString();
    HikariConfig config = new HikariConfig();
    config.setJdbcUrl(dns);
    config.setUsername(getConfig().getNode("db", "user").getString());
    config.setPassword(getConfig().getNode("db", "pass").getString());
    pool = new HikariDataSource(config);
    return pool;
}