Java Code Examples for com.zaxxer.hikari.HikariConfig#setMaximumPoolSize()

The following examples show how to use com.zaxxer.hikari.HikariConfig#setMaximumPoolSize() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PostgresDataSourceProvider.java    From conductor with Apache License 2.0 6 votes vote down vote up
private HikariConfig createConfiguration(){
    HikariConfig cfg = new HikariConfig();
    cfg.setJdbcUrl(configuration.getJdbcUrl());
    cfg.setUsername(configuration.getJdbcUserName());
    cfg.setPassword(configuration.getJdbcPassword());
    cfg.setAutoCommit(false);
    cfg.setMaximumPoolSize(configuration.getConnectionPoolMaxSize());
    cfg.setMinimumIdle(configuration.getConnectionPoolMinIdle());
    cfg.setMaxLifetime(configuration.getConnectionMaxLifetime());
    cfg.setIdleTimeout(configuration.getConnectionIdleTimeout());
    cfg.setConnectionTimeout(configuration.getConnectionTimeout());
    cfg.setTransactionIsolation(configuration.getTransactionIsolationLevel());
    cfg.setAutoCommit(configuration.isAutoCommit());

    ThreadFactory tf = new ThreadFactoryBuilder()
            .setDaemon(true)
            .setNameFormat("hikari-postgres-%d")
            .build();

    cfg.setThreadFactory(tf);
    return cfg;
}
 
Example 2
Source File: DataSourceConfig.java    From momo-cloud-permission with Apache License 2.0 6 votes vote down vote up
@Bean(name = "primaryDataSource")
    @Primary
//    @ConfigurationProperties(prefix = "spring.datasource")
    public HikariDataSource dataSource() {
        HikariConfig hikariConfig = new HikariConfig();
        hikariConfig.setDriverClassName(hikariDattaSourceConfig.getDriverClassName());
        hikariConfig.setJdbcUrl(hikariDattaSourceConfig.getJdbcUrl());
        hikariConfig.setUsername(hikariDattaSourceConfig.getUsername());
        hikariConfig.setPassword(hikariDattaSourceConfig.getPassword());
        hikariConfig.setMaxLifetime(hikariDattaSourceConfig.getMaxlifetime());
        hikariConfig.setConnectionTestQuery(hikariDattaSourceConfig.getConnectionTestQuery());
        hikariConfig.setPoolName(hikariDattaSourceConfig.getPoolName());
        hikariConfig.setIdleTimeout(hikariDattaSourceConfig.getIdleTimeout());
        hikariConfig.setAutoCommit(true);
        hikariConfig.setConnectionTimeout(hikariDattaSourceConfig.getConnectionTimeout());
        hikariConfig.setMinimumIdle(hikariDattaSourceConfig.getMinimumTdle());
        hikariConfig.setMaximumPoolSize(hikariDattaSourceConfig.getMaximumPoolSize());
        hikariConfig.addDataSourceProperty("dataSource.cachePrepStmts", "true");
        hikariConfig.addDataSourceProperty("dataSource.prepStmtCacheSize", "250");
        hikariConfig.addDataSourceProperty("dataSource.prepStmtCacheSqlLimit", "2048");
        hikariConfig.addDataSourceProperty("dataSource.useServerPrepStmts", "true");
        return new HikariDataSource(hikariConfig);
    }
 
Example 3
Source File: HikariPool.java    From Java-11-Cookbook-Second-Edition with MIT License 6 votes vote down vote up
private static DataSource createDataSource2() {
    HikariConfig config = new HikariConfig();
    config.setPoolName("cookpool");
    config.setDriverClassName("org.postgresql.Driver");
    config.setJdbcUrl("jdbc:postgresql://localhost/cookbook");
    config.setUsername("cook");
    //conf.setPassword("123Secret");
    config.setMaximumPoolSize(10);
    config.setMinimumIdle(2);
    config.addDataSourceProperty("cachePrepStmts", true);
    config.addDataSourceProperty("prepStmtCacheSize", 256);
    config.addDataSourceProperty("prepStmtCacheSqlLimit", 2048);
    config.addDataSourceProperty("useServerPrepStmts", true);

    HikariDataSource ds = new HikariDataSource(config);
    return ds;
}
 
Example 4
Source File: DatabaseConfig.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Bean
public DataSource dataSource() throws SQLException {
    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
Source File: DataSourceConfig.java    From freeacs with 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 6
Source File: JooqJobActivityConnectorComponent.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
@Bean
@Primary
public JooqContext getJooqContext(JooqConfiguration jooqConfiguration, EmbeddedPostgresService embeddedPostgresService) {
    HikariConfig hikariConfig = new HikariConfig();

    hikariConfig.setAutoCommit(true);

    // Connection management
    hikariConfig.setConnectionTimeout(10000);
    hikariConfig.setMaximumPoolSize(10);
    hikariConfig.setLeakDetectionThreshold(3000);

    if (jooqConfiguration.isInMemoryDb()) {
        hikariConfig.setDataSource(embeddedPostgresService.getDataSource());
    } else {
        hikariConfig.addDataSourceProperty(PGProperty.SSL.getName(), "true");
        hikariConfig.addDataSourceProperty(PGProperty.SSL_MODE.getName(), "verify-ca");
        hikariConfig.addDataSourceProperty(PGProperty.SSL_FACTORY.getName(), RDSSSLSocketFactory.class.getName());
        hikariConfig.setJdbcUrl(jooqConfiguration.getDatabaseUrl());
    }

    return new JooqContext(jooqConfiguration, new HikariDataSource(hikariConfig), embeddedPostgresService);
}
 
Example 7
Source File: ConnectionPool.java    From StubbornJava with 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 8
Source File: Server.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static DataSource createPostgresDataSource() throws ClassNotFoundException {
    Class.forName("org.postgresql.Driver");
    HikariConfig config = new HikariConfig();
    config.setJdbcUrl("jdbc:postgresql://tfb-database:5432/hello_world");
    config.setUsername("benchmarkdbuser");
    config.setPassword("benchmarkdbpass");
    config.setMaximumPoolSize(64);
    return new HikariDataSource(config);
}
 
Example 9
Source File: DatabaseConfiguration.java    From patient-batch-loader with GNU General Public License v3.0 5 votes vote down vote up
@Bean(name = "batchDataSource")
public DataSource batchDataSource() {
    HikariConfig config = new HikariConfig();
    config.setJdbcUrl(env.getRequiredProperty("spring.datasource.url"));
    config.setUsername(env.getProperty("spring.datasource.username"));
    config.setPassword(env.getProperty("spring.datasource.password"));
    config.setMinimumIdle(env.getProperty("spring.datasource.min-idle",
        Integer.class, 2));
    config.setMaximumPoolSize(env.getProperty("spring.datasource.max-active",
        Integer.class, 100));
    config.setTransactionIsolation("TRANSACTION_READ_COMMITTED");
    config.setRegisterMbeans(true);
    return new HikariDataSource(config);
}
 
Example 10
Source File: Storage.java    From Kepler with GNU Lesser General Public License v3.0 5 votes vote down vote up
private Storage(String host, int port, String username, String password, String db) {
    try {
        HikariConfig config = new HikariConfig();
        config.setDriverClassName("org.mariadb.jdbc.Driver");
        config.setJdbcUrl("jdbc:mariadb://" + host + ":" + port + "/" + db);
        config.setUsername(username);
        config.setPassword(password);

        config.setPoolName("processing");

        // No martinmine/Leon/other Habbotards, you don't know better.
        // Read up on this first, before commenting dumb shit
        // https://github.com/brettwooldridge/HikariCP/wiki/About-Pool-Sizing
        // availableProcessors() already returns thread count on hyper-threaded processors
        // Thus we don't need the * 2 described there
        config.setMaximumPoolSize(Runtime.getRuntime().availableProcessors() + 1);
        config.setMinimumIdle(1);

        config.addDataSourceProperty("cachePrepStmts", "true");
        config.addDataSourceProperty("prepStmtCacheSize", "250");
        config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048");
        config.addDataSourceProperty("characterEncoding", "utf8");
        config.addDataSourceProperty("useUnicode", "true");
        config.addDataSourceProperty("useSSL", "false");
        config.addDataSourceProperty("serverTimezone", "UTC");
        config.addDataSourceProperty("sessionVariables", "sql_mode='STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION'");

        this.ds = new HikariDataSource(config);
        this.isConnected = true;

    } catch (Exception ex) {
        Storage.logError(ex);
    }
}
 
Example 11
Source File: Utils.java    From Rulette with Apache License 2.0 5 votes vote down vote up
/**
 * This method build a {@link HikariConfig} object from the given properties file.
 * @param props An {@link Properties} object encapsulating Hikari properties
 */
public static HikariConfig getHikariConfig(Properties props) {
    HikariConfig hikariConfig = new HikariConfig();
    hikariConfig.setDriverClassName(props.getProperty(PROPERTY_MYSQL_DRIVER_CLASS));
    hikariConfig.setJdbcUrl(props.getProperty(PROPERTY_JDBC_URL));
    hikariConfig.setUsername(props.getProperty(PROPERTY_USER_NAME));
    hikariConfig.setPassword(props.getProperty(PROPERTY_PASSWORD));
    hikariConfig.setMaximumPoolSize(Integer.parseInt(props.getProperty(PROPERTY_MAX_POOL_SIZE)));
    hikariConfig.setConnectionTimeout(Long.parseLong(props.getProperty(PROPERTY_CONN_TIMEOUT)));

    return hikariConfig;
}
 
Example 12
Source File: OracleJDBCDriverTest.java    From testcontainers-java with MIT License 5 votes vote down vote up
private HikariDataSource getDataSource(String jdbcUrl, int poolSize) {
    HikariConfig hikariConfig = new HikariConfig();
    hikariConfig.setJdbcUrl(jdbcUrl);
    hikariConfig.setConnectionTestQuery("SELECT 1 FROM dual");
    hikariConfig.setMinimumIdle(1);
    hikariConfig.setMaximumPoolSize(poolSize);

    return new HikariDataSource(hikariConfig);
}
 
Example 13
Source File: DefaultDataSourceFactory.java    From qmq with Apache License 2.0 5 votes vote down vote up
@Override
public DataSource createDataSource(DynamicConfig config) {
	final HikariConfig cpConfig = new HikariConfig();
	cpConfig.setDriverClassName(config.getString("jdbc.driverClassName", "com.mysql.jdbc.Driver"));
	cpConfig.setJdbcUrl(config.getString("jdbc.url"));
	cpConfig.setUsername(config.getString("jdbc.username"));
	cpConfig.setPassword(config.getString("jdbc.password"));
	cpConfig.setMaximumPoolSize(config.getInt("pool.size.max", 10));

	return new HikariDataSource(cpConfig);
}
 
Example 14
Source File: ProxyDataSourceUtil.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
private static DataSource createHikariCP(final DatabaseType databaseType, final String dataSourceName) {
    HikariConfig result = new HikariConfig();
    DatabaseEnvironment databaseEnvironment = IntegrateTestEnvironment.getInstance().getDatabaseEnvironments().get(databaseType);
    result.setDriverClassName(databaseEnvironment.getDriverClassName());
    result.setJdbcUrl(getURL(databaseType, dataSourceName));
    result.setUsername("root");
    result.setPassword("root");
    result.setMaximumPoolSize(2);
    result.setTransactionIsolation("TRANSACTION_READ_COMMITTED");
    result.setConnectionTestQuery("SELECT 1");
    if ("Oracle".equals(databaseType.getName())) {
        result.setConnectionInitSql("ALTER SESSION SET CURRENT_SCHEMA = " + dataSourceName);
    }
    return new HikariDataSource(result);
}
 
Example 15
Source File: Tools.java    From flowchat with GNU General Public License v3.0 5 votes vote down vote up
public static final HikariConfig hikariConfig() {
    HikariConfig hc = new HikariConfig();
    DataSources.PROPERTIES = Tools.loadProperties(DataSources.PROPERTIES_FILE);
    hc.setJdbcUrl(DataSources.PROPERTIES.getProperty("jdbc.url"));
    hc.setUsername(DataSources.PROPERTIES.getProperty("jdbc.username"));
    hc.setPassword(DataSources.PROPERTIES.getProperty("jdbc.password"));
    hc.setMaximumPoolSize(10);
    return hc;
}
 
Example 16
Source File: Settings.java    From factions-top with MIT License 5 votes vote down vote up
private HikariConfig loadHikariConfig() {
    HikariConfig hikariConfig = new HikariConfig();
    hikariConfig.setJdbcUrl(getString("settings.database.jdbc-url", "jdbc:h2:./plugins/FactionsTop/database"));
    hikariConfig.setUsername(getString("settings.database.username", "root"));
    hikariConfig.setPassword(getString("settings.database.password", "pa$$w0rd"));
    hikariConfig.setMaximumPoolSize(getInt("settings.database.maximum-pool-size", 10));
    hikariConfig.setMaxLifetime(getLong("settings.database.max-lifetime", 5000));
    hikariConfig.setIdleTimeout(getLong("settings.database.idle-timeout", 5000));
    hikariConfig.setConnectionTimeout(getLong("settings.database.connection-timeout", 5000));
    hikariConfig.setThreadFactory(new ThreadFactoryBuilder().setDaemon(true)
            .setNameFormat("factions-top-sql-pool-%d").build());
    return hikariConfig;
}
 
Example 17
Source File: ConnectionPoolContextListener.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
@SuppressFBWarnings(
    value = "USBR_UNNECESSARY_STORE_BEFORE_RETURN",
    justification = "Necessary for sample region tag.")
private DataSource createConnectionPool() {
  // [START cloud_sql_mysql_servlet_create]
  // The configuration object specifies behaviors for the connection pool.
  HikariConfig config = new HikariConfig();

  // Configure which instance and what database user to connect with.
  config.setJdbcUrl(String.format("jdbc:mysql:///%s", DB_NAME));
  config.setUsername(DB_USER); // e.g. "root", "postgres"
  config.setPassword(DB_PASS); // e.g. "my-password"

  // For Java users, the Cloud SQL JDBC Socket Factory can provide authenticated connections.
  // See https://github.com/GoogleCloudPlatform/cloud-sql-jdbc-socket-factory for details.
  config.addDataSourceProperty("socketFactory", "com.google.cloud.sql.mysql.SocketFactory");
  config.addDataSourceProperty("cloudSqlInstance", CLOUD_SQL_CONNECTION_NAME);

  // ... Specify additional connection properties here.
  // [START_EXCLUDE]

  // [START cloud_sql_mysql_servlet_limit]
  // maximumPoolSize limits the total number of concurrent connections this pool will keep. Ideal
  // values for this setting are highly variable on app design, infrastructure, and database.
  config.setMaximumPoolSize(5);
  // minimumIdle is the minimum number of idle connections Hikari maintains in the pool.
  // Additional connections will be established to meet this value unless the pool is full.
  config.setMinimumIdle(5);
  // [END cloud_sql_mysql_servlet_limit]

  // [START cloud_sql_mysql_servlet_timeout]
  // setConnectionTimeout is the maximum number of milliseconds to wait for a connection checkout.
  // Any attempt to retrieve a connection from this pool that exceeds the set limit will throw an
  // SQLException.
  config.setConnectionTimeout(10000); // 10 seconds
  // idleTimeout is the maximum amount of time a connection can sit in the pool. Connections that
  // sit idle for this many milliseconds are retried if minimumIdle is exceeded.
  config.setIdleTimeout(600000); // 10 minutes
  // [END cloud_sql_mysql_servlet_timeout]

  // [START cloud_sql_mysql_servlet_backoff]
  // Hikari automatically delays between failed connection attempts, eventually reaching a
  // maximum delay of `connectionTimeout / 2` between attempts.
  // [END cloud_sql_mysql_servlet_backoff]

  // [START cloud_sql_mysql_servlet_lifetime]
  // maxLifetime is the maximum possible lifetime of a connection in the pool. Connections that
  // live longer than this many milliseconds will be closed and reestablished between uses. This
  // value should be several minutes shorter than the database's timeout value to avoid unexpected
  // terminations.
  config.setMaxLifetime(1800000); // 30 minutes
  // [END cloud_sql_mysql_servlet_lifetime]

  // [END_EXCLUDE]

  // Initialize the connection pool using the configuration object.
  DataSource pool = new HikariDataSource(config);
  // [END cloud_sql_mysql_servlet_create]
  return pool;
}
 
Example 18
Source File: ConnectionPoolContextListener.java    From java-docs-samples with Apache License 2.0 4 votes vote down vote up
@SuppressFBWarnings(
    value = "USBR_UNNECESSARY_STORE_BEFORE_RETURN",
    justification = "Necessary for sample region tag.")
private DataSource createConnectionPool() {
  // [START cloud_sql_postgres_servlet_create]
  // The configuration object specifies behaviors for the connection pool.
  HikariConfig config = new HikariConfig();

  // Configure which instance and what database user to connect with.
  config.setJdbcUrl(String.format("jdbc:postgresql:///%s", DB_NAME));
  config.setUsername(DB_USER); // e.g. "root", "postgres"
  config.setPassword(DB_PASS); // e.g. "my-password"

  // For Java users, the Cloud SQL JDBC Socket Factory can provide authenticated connections.
  // See https://github.com/GoogleCloudPlatform/cloud-sql-jdbc-socket-factory for details.
  config.addDataSourceProperty("socketFactory", "com.google.cloud.sql.postgres.SocketFactory");
  config.addDataSourceProperty("cloudSqlInstance", CLOUD_SQL_CONNECTION_NAME);

  // ... Specify additional connection properties here.
  // [START_EXCLUDE]

  // [START cloud_sql_postgres_servlet_limit]
  // maximumPoolSize limits the total number of concurrent connections this pool will keep. Ideal
  // values for this setting are highly variable on app design, infrastructure, and database.
  config.setMaximumPoolSize(5);
  // minimumIdle is the minimum number of idle connections Hikari maintains in the pool.
  // Additional connections will be established to meet this value unless the pool is full.
  config.setMinimumIdle(5);
  // [END cloud_sql_postgres_servlet_limit]

  // [START cloud_sql_postgres_servlet_timeout]
  // setConnectionTimeout is the maximum number of milliseconds to wait for a connection checkout.
  // Any attempt to retrieve a connection from this pool that exceeds the set limit will throw an
  // SQLException.
  config.setConnectionTimeout(10000); // 10 seconds
  // idleTimeout is the maximum amount of time a connection can sit in the pool. Connections that
  // sit idle for this many milliseconds are retried if minimumIdle is exceeded.
  config.setIdleTimeout(600000); // 10 minutes
  // [END cloud_sql_postgres_servlet_timeout]

  // [START cloud_sql_postgres_servlet_backoff]
  // Hikari automatically delays between failed connection attempts, eventually reaching a
  // maximum delay of `connectionTimeout / 2` between attempts.
  // [END cloud_sql_postgres_servlet_backoff]

  // [START cloud_sql_postgres_servlet_lifetime]
  // maxLifetime is the maximum possible lifetime of a connection in the pool. Connections that
  // live longer than this many milliseconds will be closed and reestablished between uses. This
  // value should be several minutes shorter than the database's timeout value to avoid unexpected
  // terminations.
  config.setMaxLifetime(1800000); // 30 minutes
  // [END cloud_sql_postgres_servlet_lifetime]

  // [END_EXCLUDE]

  // Initialize the connection pool using the configuration object.
  DataSource pool = new HikariDataSource(config);
  // [END cloud_sql_postgres_servlet_create]
  return pool;
}
 
Example 19
Source File: SkinStorage.java    From ChangeSkin with MIT License 4 votes vote down vote up
public SkinStorage(ChangeSkinCore core, String driver, String host, int port, String database
        , String user, String pass, boolean useSSL) {
    this.logger = core.getLogger();

    HikariConfig config = new HikariConfig();
    config.setPoolName(core.getPlugin().getName());

    config.setUsername(user);
    config.setPassword(pass);
    config.setDriverClassName(driver);

    ThreadFactory threadFactory = core.getPlugin().getThreadFactory();
    if (threadFactory != null) {
        config.setThreadFactory(threadFactory);
    }

    Properties properties = new Properties();

    String jdbcUrl = "jdbc:";
    if (driver.contains("sqlite")) {
        String folderPath = core.getPlugin().getPluginFolder().toAbsolutePath().toString();
        database = database.replace("{pluginDir}", folderPath);

        jdbcUrl += "sqlite://" + database;
        config.setConnectionTestQuery("SELECT 1");
        config.setMaximumPoolSize(1);

        //a try to fix https://www.spigotmc.org/threads/fastlogin.101192/page-26#post-1874647
        properties.setProperty("date_string_format", "yyyy-MM-dd HH:mm:ss");
    } else {
        jdbcUrl += "mysql://" + host + ':' + port + '/' + database;
        properties.setProperty("useSSL", String.valueOf(useSSL));
        // enable MySQL specific optimizations
        // default prepStmtCacheSize 25 - amount of cached statements - enough for us
        // default prepStmtCacheSqlLimit 256 - length of SQL - our queries are not longer
        // disabled by default - will return the same prepared statement instance
        config.addDataSourceProperty("cachePrepStmts", true);
        // default false - available in newer versions caches the statements server-side
        config.addDataSourceProperty("useServerPrepStmts", true);
    }

    config.setJdbcUrl(jdbcUrl);
    config.setDataSourceProperties(properties);
    this.dataSource = new HikariDataSource(config);
}
 
Example 20
Source File: MySQLUserDataSource.java    From MCAuthenticator with GNU General Public License v3.0 4 votes vote down vote up
public MySQLUserDataSource(String connectionURL, String username, String password, int queryTimeout) throws SQLException {
    this.queryTimeout = queryTimeout;
    this.updateHook = new UpdateHook() {
        @Override
        public void update(UpdatableFlagData me) {
            toUpdate.add(me);
        }
    };
    HikariConfig cfg = new HikariConfig();
    cfg.setDriverClassName("com.mysql.jdbc.Driver");
    cfg.setJdbcUrl(connectionURL);
    cfg.setUsername(username);
    cfg.setPassword(password);
    cfg.setMaximumPoolSize(2);

    pool = new HikariDataSource(cfg);

    try (Connection c = pool.getConnection()) {
        ResultSet resultSet = c.createStatement().executeQuery("SHOW TABLES;");
        boolean found = false;
        while (resultSet.next()) {
            if (resultSet.getString(1).equalsIgnoreCase("2fa")) {
                found = true;
                break;
            }
        }
        resultSet.close();

        if (found) {
            try (ResultSet rs = c.createStatement().executeQuery("SHOW COLUMNS FROM 2FA;")) {
                // Determine secret field (1.0.2 and before) and add type row
                boolean hasAuthType = false;
                while (rs.next()) {
                    String field = rs.getString("Field");
                    if (!field.equalsIgnoreCase("secret")) {
                        if (field.equalsIgnoreCase("authtype"))
                            hasAuthType = true;
                        continue;
                    }

                    // Secret field
                    if (!rs.getString("Type").equalsIgnoreCase("tinytext")) {
                        c.createStatement().execute("alter table 2FA MODIFY secret TINYTEXT;");
                        break;
                    }
                }
                if (!hasAuthType) {
                    c.createStatement().execute("alter table 2FA add authtype int DEFAULT 0;");
                }
            }
        } else {
            c.createStatement().execute("CREATE TABLE 2FA(" +
                    "uuid CHAR(32) PRIMARY KEY," +
                    "ip VARCHAR(255)," +
                    "secret TINYTEXT," +
                    "authtype INT DEFAULT 0," +
                    "locked BIT(1));");
            c.createStatement().execute("CREATE INDEX uuid_index ON 2FA (uuid);");
        }
    }
}