Java Code Examples for com.zaxxer.hikari.HikariDataSource

The following examples show how to use com.zaxxer.hikari.HikariDataSource. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: freeacs   Source File: AbstractEmbeddedDataSourceHelper.java    License: MIT License 8 votes vote down vote up
public static void setUpBeforeClass() throws ManagedProcessException {
    randomFolder = "./db/" + UUID.randomUUID();
    DBConfigurationBuilder configBuilder = DBConfigurationBuilder.newBuilder();
    configBuilder.setPort(3307);
    configBuilder.setDataDir(randomFolder);
    db = DB.newEmbeddedDB(configBuilder.build());
    db.start();
    db.createDB("acs", "acs", "acs");
    db.source("install.sql", "acs", "acs", "acs");
    String url = configBuilder.getURL("acs");
    HikariConfig hikariConfig = new HikariConfig();
    hikariConfig.setDataSourceClassName("org.mariadb.jdbc.MariaDbDataSource");
    hikariConfig.addDataSourceProperty("url", url);
    hikariConfig.addDataSourceProperty("user", "acs");
    hikariConfig.addDataSourceProperty("password", "acs");
    dataSource = new HikariDataSource(hikariConfig);
}
 
Example 2
Source Project: Java-11-Cookbook-Second-Edition   Source File: HikariPool.java    License: MIT License 7 votes vote down vote up
private static DataSource createDataSource3() {
    Properties props = new Properties();
    props.setProperty("poolName", "cookpool");
    props.setProperty("driverClassName", "org.postgresql.Driver");
    props.setProperty("jdbcUrl", "jdbc:postgresql://localhost/cookbook");
    props.setProperty("username", "cook");
    //props.setProperty("password", "123Secret");
    props.setProperty("maximumPoolSize", "10");
    props.setProperty("minimumIdle", "2");
    props.setProperty("dataSource.cachePrepStmts","true");
    props.setProperty("dataSource.prepStmtCacheSize", "256");
    props.setProperty("dataSource.prepStmtCacheSqlLimit", "2048");
    props.setProperty("dataSource.useServerPrepStmts","true");

    HikariConfig config = new HikariConfig(props);
    HikariDataSource ds = new HikariDataSource(config);
    return ds;
}
 
Example 3
Source Project: nexus-public   Source File: MyBatisDataStore.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected void doStart(final String storeName, final Map<String, String> attributes) throws Exception {
  boolean isContentStore = !CONFIG_DATASTORE_NAME.equalsIgnoreCase(storeName);

  dataSource = new HikariDataSource(configureHikari(storeName, attributes));
  Environment environment = new Environment(storeName, new JdbcTransactionFactory(), dataSource);
  sessionFactory = new DefaultSqlSessionFactory(configureMyBatis(environment));

  registerCommonTypeHandlers(isContentStore);

  if (beanLocator != null) {
    // register the appropriate type handlers with the store
    beanLocator.watch(TYPE_HANDLER_KEY,
        isContentStore ? CONTENT_TYPE_HANDLER_MEDIATOR : CONFIG_TYPE_HANDLER_MEDIATOR, this);
  }
}
 
Example 4
Source Project: cloudbreak   Source File: DatabaseConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
public DataSource dataSource() throws SQLException {
    DatabaseUtil.createSchemaIfNeeded("postgresql", databaseAddress, dbName, dbUser, dbPassword, dbSchemaName);
    HikariConfig config = new HikariConfig();
    if (ssl && Files.exists(Paths.get(certFile))) {
        config.addDataSourceProperty("ssl", "true");
        config.addDataSourceProperty("sslfactory", "org.postgresql.ssl.SingleCertValidatingFactory");
        config.addDataSourceProperty("sslfactoryarg", "file://" + certFile);
    }
    if (nodeConfig.isNodeIdSpecified()) {
        config.addDataSourceProperty("ApplicationName", nodeConfig.getId());
    }
    config.setDriverClassName("io.opentracing.contrib.jdbc.TracingDriver");
    config.setJdbcUrl(String.format("jdbc:tracing:postgresql://%s/%s?currentSchema=%s", databaseAddress, dbName, dbSchemaName));
    config.setUsername(dbUser);
    config.setPassword(dbPassword);
    config.setMaximumPoolSize(poolSize);
    config.setMinimumIdle(minimumIdle);
    config.setConnectionTimeout(SECONDS.toMillis(connectionTimeout));
    config.setIdleTimeout(MINUTES.toMillis(idleTimeout));
    return new HikariDataSource(config);
}
 
Example 5
@Override
public DataSource actualDataSource() {
    final HikariDataSource dataSource = (HikariDataSource) super.actualDataSource();

    com.vladmihalcea.flexypool.config.Configuration<HikariDataSource> configuration =
        new com.vladmihalcea.flexypool.config.Configuration.Builder<>(
            "flexy-pool-test",
            dataSource,
            HikariCPPoolAdapter.FACTORY
        )
    .build();

    return new FlexyPoolDataSource<>(
        configuration
    );
}
 
Example 6
Source Project: helper   Source File: HelperSql.java    License: MIT License 6 votes vote down vote up
public HelperSql(@Nonnull DatabaseCredentials credentials) {
    final HikariConfig hikari = new HikariConfig();

    hikari.setPoolName("helper-sql-" + POOL_COUNTER.getAndIncrement());

    hikari.setDataSourceClassName(DATA_SOURCE_CLASS);
    hikari.addDataSourceProperty("serverName", credentials.getAddress());
    hikari.addDataSourceProperty("port", credentials.getPort());
    hikari.addDataSourceProperty("databaseName", credentials.getDatabase());

    hikari.setUsername(credentials.getUsername());
    hikari.setPassword(credentials.getPassword());

    hikari.setMaximumPoolSize(MAXIMUM_POOL_SIZE);
    hikari.setMinimumIdle(MINIMUM_IDLE);

    hikari.setMaxLifetime(MAX_LIFETIME);
    hikari.setConnectionTimeout(CONNECTION_TIMEOUT);
    hikari.setLeakDetectionThreshold(LEAK_DETECTION_THRESHOLD);

    // ensure we use unicode (this calls #setProperties, a hack for the mariadb driver)
    hikari.addDataSourceProperty("properties", "useUnicode=true;characterEncoding=utf8");

    this.source = new HikariDataSource(hikari);
    this.stream = SqlStream.connect(this.source);
}
 
Example 7
Source Project: jfinal-api-scaffold   Source File: HikariCPPlugin.java    License: MIT License 6 votes vote down vote up
@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 8
Source Project: Spring   Source File: TestDataConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
public DataSource dataSource() {
    try {
        final HikariConfig hikariConfig = new HikariConfig();
        hikariConfig.setDriverClassName(driverClassName);
        hikariConfig.setJdbcUrl(url);
        hikariConfig.setUsername(username);
        hikariConfig.setPassword(password);

        hikariConfig.setMaximumPoolSize(5);
        hikariConfig.setConnectionTestQuery("SELECT 1");
        hikariConfig.setPoolName("springHikariCP");

        hikariConfig.addDataSourceProperty("dataSource.cachePrepStmts", "true");
        hikariConfig.addDataSourceProperty("dataSource.prepStmtCacheSize", "250");
        hikariConfig.addDataSourceProperty("dataSource.prepStmtCacheSqlLimit", "2048");
        hikariConfig.addDataSourceProperty("dataSource.useServerPrepStmts", "true");

        return new HikariDataSource(hikariConfig);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 9
@Bean(name = "sessionFactory")
public LocalSessionFactoryBean hibernate5SessionFactoryBean(){
    LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
    localSessionFactoryBean.setDataSource(appContext.getBean(HikariDataSource.class));
    localSessionFactoryBean.setAnnotatedClasses(
            AppUser.class
    );

    Properties properties = new Properties();
    properties.put("hibernate.dialect","org.hibernate.dialect.MySQLDialect");
    //properties.put("hibernate.current_session_context_class","thread");
    properties.put("hibernate.hbm2ddl.auto","update");

    localSessionFactoryBean.setHibernateProperties(properties);
    return localSessionFactoryBean;
}
 
Example 10
Source Project: freeacs   Source File: DataSourceConfig.java    License: MIT License 6 votes vote down vote up
@Bean
public DataSource getDataSource(Environment config) {
    HikariConfig hikariConfig = new HikariConfig();
    hikariConfig.setDriverClassName(config.getProperty("main.datasource.driverClassName"));
    hikariConfig.setJdbcUrl(config.getProperty("main.datasource.jdbcUrl"));
    hikariConfig.setUsername(config.getProperty("main.datasource.username"));
    hikariConfig.setPassword(config.getProperty("main.datasource.password"));

    hikariConfig.setMinimumIdle(config.getProperty("main.datasource.minimum-idle", Integer.class, 1));
    hikariConfig.setMaximumPoolSize(config.getProperty("main.datasource.maximum-pool-size", Integer.class, 10));
    hikariConfig.setConnectionTestQuery("SELECT 1");
    hikariConfig.setPoolName(config.getProperty("main.datasource.poolName"));

    hikariConfig.addDataSourceProperty("dataSource.cachePrepStmts", "true");
    hikariConfig.addDataSourceProperty("dataSource.prepStmtCacheSize", "250");
    hikariConfig.addDataSourceProperty("dataSource.prepStmtCacheSqlLimit", "2048");
    hikariConfig.addDataSourceProperty("dataSource.useServerPrepStmts", "true");

    hikariConfig.setAutoCommit(true);

    return new HikariDataSource(hikariConfig);
}
 
Example 11
Source Project: tutorial   Source File: DataSourceConfig.java    License: MIT License 6 votes vote down vote up
private DataSource createDataSource(String className, String serverName, int port, String dbName,
                                    String user, String password) {
    logger.trace("createDataSource({}, {}, {}, {}, {}, {})", className, serverName, port, dbName, user, password);
    Properties props = new Properties();
    props.setProperty("dataSourceClassName", className);
    props.setProperty("dataSource.serverName", serverName);
    if(port > 0) {
        props.setProperty("dataSource.portNumber", String.valueOf(port));
    }
    props.setProperty("dataSource.databaseName", dbName);
    if(user != null) {
        props.setProperty("dataSource.user", user);
    }
    if(password != null) {
        props.setProperty("dataSource.password", password);
    }
    props.put("dataSource.logWriter", new PrintWriter(System.out));

    HikariConfig config = new HikariConfig(props);
    config.setMaximumPoolSize(15);  //连接池最多15个连接

    HikariDataSource ds = new HikariDataSource(config);

    return ds;
}
 
Example 12
private HikariDataSource createDataSourceWithConnectionPool()
{
    DatabaseConfig databaseConfig = DatabaseConfig.convertFrom(systemConfig, "param_server");
    String url = DatabaseConfig.buildJdbcUrl(databaseConfig);

    HikariConfig hikari = new HikariConfig();
    hikari.setJdbcUrl(url);
    hikari.setDriverClassName(DatabaseMigrator.getDriverClassName(databaseConfig.getType()));
    hikari.setDataSourceProperties(DatabaseConfig.buildJdbcProperties(databaseConfig));

    hikari.setConnectionTimeout(databaseConfig.getConnectionTimeout() * 1000);
    hikari.setIdleTimeout(databaseConfig.getIdleTimeout() * 1000);
    hikari.setValidationTimeout(databaseConfig.getValidationTimeout() * 1000);
    hikari.setMaximumPoolSize(databaseConfig.getMaximumPoolSize());
    hikari.setMinimumIdle(databaseConfig.getMinimumPoolSize());

    // Here should not set connectionTestQuery (that overrides isValid) because
    // ThreadLocalTransactionManager.commit assumes that Connection.isValid returns
    // false when an error happened during a transaction.

    logger.debug("Using postgresql URL {}", hikari.getJdbcUrl());

    return new HikariDataSource(hikari);
}
 
Example 13
@Test
public void assertCreateDataSource() {
    Map<String, Object> props = new HashMap<>();
    props.put("driverClassName", "org.h2.Driver");
    props.put("jdbcUrl", "jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MySQL");
    props.put("username", "root");
    props.put("password", "root");
    props.put("loginTimeout", "5000");
    props.put("test", "test");
    DataSourceConfiguration dataSourceConfig = new DataSourceConfiguration(HikariDataSource.class.getName());
    dataSourceConfig.getProps().putAll(props);
    HikariDataSource actual = (HikariDataSource) dataSourceConfig.createDataSource();
    assertThat(actual.getDriverClassName(), is("org.h2.Driver"));
    assertThat(actual.getJdbcUrl(), is("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MySQL"));
    assertThat(actual.getUsername(), is("root"));
    assertThat(actual.getPassword(), is("root"));
}
 
Example 14
Source Project: StubbornJava   Source File: ConnectionPool.java    License: MIT License 6 votes vote down vote up
public static HikariDataSource getDataSourceFromConfig(
    Config conf
    , MetricRegistry metricRegistry
    , HealthCheckRegistry healthCheckRegistry) {

    HikariConfig jdbcConfig = new HikariConfig();
    jdbcConfig.setPoolName(conf.getString("poolName"));
    jdbcConfig.setMaximumPoolSize(conf.getInt("maximumPoolSize"));
    jdbcConfig.setMinimumIdle(conf.getInt("minimumIdle"));
    jdbcConfig.setJdbcUrl(conf.getString("jdbcUrl"));
    jdbcConfig.setUsername(conf.getString("username"));
    jdbcConfig.setPassword(conf.getString("password"));

    jdbcConfig.addDataSourceProperty("cachePrepStmts", conf.getBoolean("cachePrepStmts"));
    jdbcConfig.addDataSourceProperty("prepStmtCacheSize", conf.getInt("prepStmtCacheSize"));
    jdbcConfig.addDataSourceProperty("prepStmtCacheSqlLimit", conf.getInt("prepStmtCacheSqlLimit"));
    jdbcConfig.addDataSourceProperty("useServerPrepStmts", conf.getBoolean("useServerPrepStmts"));

    // Add HealthCheck
    jdbcConfig.setHealthCheckRegistry(healthCheckRegistry);

    // Add Metrics
    jdbcConfig.setMetricRegistry(metricRegistry);
    return new HikariDataSource(jdbcConfig);
}
 
Example 15
Source Project: apiman   Source File: DefaultJdbcComponent.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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 16
Source Project: pxf   Source File: ConnectionManagerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testPoolExpirationNoActiveConnections() throws SQLException {
    MockTicker ticker = new MockTicker();
    ConnectionManager.DataSourceFactory mockFactory = mock(ConnectionManager.DataSourceFactory.class);
    HikariDataSource mockDataSource = mock(HikariDataSource.class);
    when(mockFactory.createDataSource(anyObject())).thenReturn(mockDataSource);
    when(mockDataSource.getConnection()).thenReturn(mockConnection);

    HikariPoolMXBean mockMBean = mock(HikariPoolMXBean.class);
    when(mockDataSource.getHikariPoolMXBean()).thenReturn(mockMBean);
    when(mockMBean.getActiveConnections()).thenReturn(0);
    manager = new ConnectionManager(mockFactory, ticker, ConnectionManager.CLEANUP_SLEEP_INTERVAL_NANOS);

    manager.getConnection("test-server", "test-url", connProps, true, poolProps, null);

    ticker.advanceTime(ConnectionManager.POOL_EXPIRATION_TIMEOUT_HOURS + 1, TimeUnit.HOURS);
    manager.cleanCache();

    Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);

    verify(mockMBean, times(1)).getActiveConnections();
    verify(mockDataSource, times(1)).close(); // verify datasource is closed when evicted
}
 
Example 17
Source Project: pxf   Source File: ConnectionManagerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testPoolExpirationWithActiveConnections() throws SQLException {
    MockTicker ticker = new MockTicker();
    ConnectionManager.DataSourceFactory mockFactory = mock(ConnectionManager.DataSourceFactory.class);
    HikariDataSource mockDataSource = mock(HikariDataSource.class);
    when(mockFactory.createDataSource(anyObject())).thenReturn(mockDataSource);
    when(mockDataSource.getConnection()).thenReturn(mockConnection);

    HikariPoolMXBean mockMBean = mock(HikariPoolMXBean.class);
    when(mockDataSource.getHikariPoolMXBean()).thenReturn(mockMBean);
    when(mockMBean.getActiveConnections()).thenReturn(2, 1, 0);
    manager = new ConnectionManager(mockFactory, ticker, TimeUnit.MILLISECONDS.toNanos(50));

    manager.getConnection("test-server", "test-url", connProps, true, poolProps, null);

    ticker.advanceTime(ConnectionManager.POOL_EXPIRATION_TIMEOUT_HOURS + 1, TimeUnit.HOURS);
    manager.cleanCache();

    // wait for at least 3 iteration of sleeping
    Uninterruptibles.sleepUninterruptibly(2500, TimeUnit.MILLISECONDS);

    verify(mockMBean, times(3)).getActiveConnections();
    verify(mockDataSource, times(1)).close(); // verify datasource is closed when evicted
}
 
Example 18
Source Project: beihu-boot   Source File: ApiBootBasicDataSource.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * create default basic data source
 *
 * @return DataSource
 * @throws RuntimeException 异常信息
 */
@Override
public DataSource build() throws RuntimeException {
    try {
        DataSource dataSource = DataSourceBuilder.create().url(config.getUrl()).username(config.getUsername()).password(config.getPassword()).driverClassName(config.getDriverClassName())
                // springboot 2.x default is HikariDataSource
                .type(HikariDataSource.class)
                .build();
        return dataSource;
    } catch (Exception e) {
        throw new RuntimeException("Create a default data source exception", e);
    }

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

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

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

    return new JdbcTemplate(source);
}
 
Example 20
Source Project: Plan   Source File: MySQLDB.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void close() {
    super.close();

    if (dataSource instanceof HikariDataSource) {
        ((HikariDataSource) dataSource).close();
    }
}
 
Example 21
Source Project: testcontainers-java   Source File: AbstractJDBCDriverTest.java    License: MIT License 5 votes vote down vote up
private void performTestForJDBCParamUsage(HikariDataSource dataSource) throws SQLException {
    boolean result = new QueryRunner(dataSource).query("select CURRENT_USER", rs -> {
        rs.next();
        String resultUser = rs.getString(1);
        // Not all databases (eg. Postgres) return @% at the end of user name. We just need to make sure the user name matches.
        if (resultUser.endsWith("@%")) {
            resultUser = resultUser.substring(0, resultUser.length() - 2);
        }
        assertEquals("User from query param is created.", "someuser", resultUser);
        return true;
    });

    assertTrue("The database returned a record as expected", result);

    String databaseQuery = "SELECT DATABASE()";
    // Postgres does not have Database() as a function
    String databaseType = ConnectionUrl.newInstance(jdbcUrl).getDatabaseType();
    if (databaseType.equalsIgnoreCase("postgresql") || databaseType.equalsIgnoreCase("postgis")) {
        databaseQuery = "SELECT CURRENT_DATABASE()";
    }

    result = new QueryRunner(dataSource).query(databaseQuery, rs -> {
        rs.next();
        String resultDB = rs.getString(1);
        assertEquals("Database name from URL String is used.", "databasename", resultDB);
        return true;
    });

    assertTrue("The database returned a record as expected", result);
}
 
Example 22
@Before
public void setUp() throws SQLException, ClassNotFoundException {
    BaseConnection connection = (BaseConnection) mock(Class.forName("org.postgresql.core.BaseConnection"));
    DataSource dataSource = DataSourceUtils.build(HikariDataSource.class, DatabaseTypes.getActualDatabaseType("PostgreSQL"), "ds1");
    xaDataSource = XADataSourceFactory.build(DatabaseTypes.getActualDatabaseType("PostgreSQL"), dataSource);
    when(this.connection.unwrap(any())).thenReturn(connection);
    
}
 
Example 23
Source Project: shardingsphere   Source File: DataSourceUtilTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void assertDataSourceForHikariCPAndHyphen() throws ReflectiveOperationException {
    HikariDataSource actual = (HikariDataSource) DataSourceUtil.getDataSource(HikariDataSource.class.getName(), getDataSourcePoolProperties("driver-class-name", "jdbc-url", "username"));
    assertThat(actual.getDriverClassName(), is(org.h2.Driver.class.getName()));
    assertThat(actual.getJdbcUrl(), is("jdbc:h2:mem:%s;DB_CLOSE_DELAY=-1;DATABASE_TO_UPPER=false;MODE=MySQL"));
    assertThat(actual.getUsername(), is("sa"));
}
 
Example 24
Source Project: digdag   Source File: DataSourceProvider.java    License: Apache License 2.0 5 votes vote down vote up
private void createPooledDataSource()
{
    String url = DatabaseConfig.buildJdbcUrl(config);

    HikariConfig hikari = new HikariConfig();
    hikari.setJdbcUrl(url);
    hikari.setDriverClassName(DatabaseMigrator.getDriverClassName(config.getType()));
    hikari.setDataSourceProperties(DatabaseConfig.buildJdbcProperties(config));

    hikari.setConnectionTimeout(config.getConnectionTimeout() * 1000);
    hikari.setIdleTimeout(config.getIdleTimeout() * 1000);
    hikari.setValidationTimeout(config.getValidationTimeout() * 1000);
    hikari.setMaximumPoolSize(config.getMaximumPoolSize());
    hikari.setMinimumIdle(config.getMinimumPoolSize());
    hikari.setRegisterMbeans(config.getEnableJMX());
    hikari.setLeakDetectionThreshold(config.getLeakDetectionThreshold());

    // Here should not set connectionTestQuery (that overrides isValid) because
    // ThreadLocalTransactionManager.commit assumes that Connection.isValid returns
    // false when an error happened during a transaction.

    logger.debug("Using database URL {}", hikari.getJdbcUrl());

    HikariDataSource ds = new HikariDataSource(hikari);
    this.ds = ds;
    this.closer = ds;
}
 
Example 25
Source Project: AuthMeReloaded   Source File: MySQL.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Sets up the connection arguments to the database.
 */
private void setConnectionArguments() {
    ds = new HikariDataSource();
    ds.setPoolName("AuthMeMYSQLPool");

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

    // Database URL
    ds.setJdbcUrl("jdbc:mysql://" + this.host + ":" + this.port + "/" + this.database);

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

    // Request mysql over SSL
    ds.addDataSourceProperty("useSSL", String.valueOf(useSsl));

    // Disabling server certificate verification on need
    if (!serverCertificateVerification) {
        ds.addDataSourceProperty("verifyServerCertificate", String.valueOf(false));
    }

    // Encoding
    ds.addDataSourceProperty("characterEncoding", "utf8");
    ds.addDataSourceProperty("encoding", "UTF-8");
    ds.addDataSourceProperty("useUnicode", "true");

    // Random stuff
    ds.addDataSourceProperty("rewriteBatchedStatements", "true");
    ds.addDataSourceProperty("jdbcCompliantTruncation", "false");

    // Caching
    ds.addDataSourceProperty("cachePrepStmts", "true");
    ds.addDataSourceProperty("prepStmtCacheSize", "275");
    ds.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");

    logger.info("Connection arguments loaded, Hikari ConnectionPool ready!");
}
 
Example 26
@Override
protected void onDestroy()
{
	if (db instanceof HikariDataSource) {
		((HikariDataSource)db).close();
	}
	super.onDestroy();
}
 
Example 27
public static DataSource createDataSource(final String dataSourceName) {
    HikariDataSource result = new HikariDataSource();
    result.setDriverClassName(com.mysql.jdbc.Driver.class.getName());
    result.setJdbcUrl(String.format("jdbc:mysql://%s:%s/%s?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF-8", HOST, PORT, dataSourceName));
    result.setUsername(USER_NAME);
    result.setPassword(PASSWORD);
    return result;
}
 
Example 28
/**
 * Constructor used for MySQL
 * 
 * @param host
 * @param port
 * @param database
 * @param username
 * @param password
 * @throws SQLException 
 */
public DataSourceHandler(final String host, final String port, final String database, final String username, final String password) throws SQLException{
	// Check database's informations and init connection
	this.host = Preconditions.checkNotNull(host);
	this.port = Preconditions.checkNotNull(port);
	this.database = Preconditions.checkNotNull(database);
	this.username = Preconditions.checkNotNull(username);
	this.password = Preconditions.checkNotNull(password);

	BAT.getInstance().getLogger().config("Initialization of HikariCP in progress ...");
	BasicConfigurator.configure(new NullAppender());
	ds = new HikariDataSource();
	ds.setJdbcUrl("jdbc:mysql://" + this.host + ":" + this.port + "/" + this.database + 
			"?useLegacyDatetimeCode=false&serverTimezone=" + TimeZone.getDefault().getID());
	ds.setUsername(this.username);
	ds.setPassword(this.password);
	ds.addDataSourceProperty("cachePrepStmts", "true");
	ds.setMaximumPoolSize(8);
	try {
		final Connection conn = ds.getConnection();
	    int intOffset = Calendar.getInstance().getTimeZone().getOffset(Calendar.getInstance().getTimeInMillis()) / 1000;
	    String offset = String.format("%02d:%02d", Math.abs(intOffset / 3600), Math.abs((intOffset / 60) % 60));
	    offset = (intOffset >= 0 ? "+" : "-") + offset;
		conn.createStatement().executeQuery("SET time_zone='" + offset + "';");
		conn.close();
		BAT.getInstance().getLogger().config("BoneCP is loaded !");
	} catch (final SQLException e) {
		BAT.getInstance().getLogger().severe("BAT encounters a problem during the initialization of the database connection."
				+ " Please check your logins and database configuration.");
		if(e.getCause() instanceof CommunicationsException){
		    BAT.getInstance().getLogger().severe(e.getCause().getMessage());
		}
		if(BAT.getInstance().getConfiguration().isDebugMode()){
		    BAT.getInstance().getLogger().log(Level.SEVERE, e.getMessage(), e);
		}
		throw e;
	}
	sqlite = false;
}
 
Example 29
/**
 * {@inheritDoc}
 */
public void init(PMContext context) throws Exception {
    HikariDataSource ds = AppContextUtil.getSpringBean(HikariDataSource.class);
    setDriver(ds.getDriverClassName());
    setUser(ds.getUsername());
    setPassword(ds.getPassword());
    setUrl(ds.getJdbcUrl());

    setDatabaseType(DbUtil.getSchemaType(ds.getDriverClassName()));
    super.init(context);
}
 
Example 30
Source Project: ShopChest   Source File: SQLite.java    License: MIT License 5 votes vote down vote up
@Override
HikariDataSource getDataSource() {
    try {
        // Initialize driver class so HikariCP can find it
        Class.forName("org.sqlite.JDBC");
    } catch (ClassNotFoundException e) {
        plugin.getLogger().severe("Failed to initialize SQLite driver");
        plugin.debug("Failed to initialize SQLite driver");
        plugin.debug(e);
        return null;
    }

    File folder = plugin.getDataFolder();
    File dbFile = new File(folder, "shops.db");

    if (!dbFile.exists()) {
        try {
            dbFile.createNewFile();
        } catch (IOException ex) {
            plugin.getLogger().severe("Failed to create database file");
            plugin.debug("Failed to create database file");
            plugin.debug(ex);
            return null;
        }
    }
    
    HikariConfig config = new HikariConfig();
    config.setJdbcUrl(String.format("jdbc:sqlite:" + dbFile));
    config.setConnectionTestQuery("SELECT 1");

    return new HikariDataSource(config);
}