Java Code Examples for com.zaxxer.hikari.HikariDataSource#getConnection()
The following examples show how to use
com.zaxxer.hikari.HikariDataSource#getConnection() .
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: MySqlIntegrationTest.java From AuthMeReloaded with GNU General Public License v3.0 | 6 votes |
@Before public void initializeConnectionAndTable() throws SQLException { HikariConfig config = new HikariConfig(); config.setDataSourceClassName("org.h2.jdbcx.JdbcDataSource"); config.setConnectionTestQuery("VALUES 1"); // Note "ignorecase=true": H2 does not support `COLLATE NOCASE` for case-insensitive equals queries. // MySQL is by default case-insensitive so this is OK to make as an assumption. config.addDataSourceProperty("URL", "jdbc:h2:mem:test;ignorecase=true"); config.addDataSourceProperty("user", "sa"); config.addDataSourceProperty("password", "sa"); HikariDataSource ds = new HikariDataSource(config); Connection connection = ds.getConnection(); try (Statement st = connection.createStatement()) { st.execute("DROP TABLE IF EXISTS authme"); st.execute(sqlInitialize); } hikariSource = ds; }
Example 2
Source File: MySQLDAOTestUtil.java From conductor with Apache License 2.0 | 6 votes |
private void createDatabase(String dbName) { HikariDataSource dataSource = new HikariDataSource(); dataSource.setJdbcUrl("jdbc:mysql://localhost:33307/conductor"); dataSource.setUsername("root"); dataSource.setPassword("root"); dataSource.setAutoCommit(false); dataSource.setMaximumPoolSize(2); try (Connection connection = dataSource.getConnection()) { try(Statement statement = connection.createStatement()) { statement.execute("CREATE DATABASE IF NOT EXISTS "+dbName); } } catch (SQLException sqlException) { logger.error("Unable to create default connection for docker mysql db", sqlException); throw new RuntimeException(sqlException); }finally { dataSource.close(); } }
Example 3
Source File: TestJdbcUtil.java From datacollector with Apache License 2.0 | 6 votes |
@Test public void testGetMinValuesTime() throws SQLException { HikariPoolConfigBean config = createConfigBean(); HikariDataSource dataSource = jdbcUtil.createDataSourceForRead(config); Connection connection = dataSource.getConnection(); Map<String, String> dataTableMin = jdbcUtil.getMinimumOffsetValues( DatabaseVendor.UNKNOWN, connection, schema, dataTypesTestTable, QuoteChar.NONE, Arrays.asList("MY_TIME") ); assertThat(dataTableMin.size(), equalTo(1)); assertThat(dataTableMin, hasEntry("MY_TIME", String.valueOf(WHOLE_DAY_MILLIS - 1000L))); }
Example 4
Source File: TestJdbcUtil.java From datacollector with Apache License 2.0 | 6 votes |
@Test public void testGetMinValuesDate() throws SQLException { HikariPoolConfigBean config = createConfigBean(); HikariDataSource dataSource = jdbcUtil.createDataSourceForRead(config); Connection connection = dataSource.getConnection(); Map<String, String> dataTableMin = jdbcUtil.getMinimumOffsetValues( DatabaseVendor.UNKNOWN, connection, schema, dataTypesTestTable, QuoteChar.NONE, Arrays.asList("MY_DATE") ); assertThat(dataTableMin.size(), equalTo(1)); assertThat(dataTableMin, hasEntry("MY_DATE", String.valueOf(WHOLE_DAY_MILLIS))); }
Example 5
Source File: PostgreSqlIntegrationTest.java From AuthMeReloaded with GNU General Public License v3.0 | 6 votes |
@Before public void initializeConnectionAndTable() throws SQLException { HikariConfig config = new HikariConfig(); config.setDataSourceClassName("org.h2.jdbcx.JdbcDataSource"); config.setConnectionTestQuery("VALUES 1"); config.addDataSourceProperty("URL", "jdbc:h2:mem:test;ignorecase=true"); config.addDataSourceProperty("user", "sa"); config.addDataSourceProperty("password", "sa"); HikariDataSource ds = new HikariDataSource(config); Connection connection = ds.getConnection(); try (Statement st = connection.createStatement()) { st.execute("DROP TABLE IF EXISTS authme"); st.execute(sqlInitialize); } hikariSource = ds; }
Example 6
Source File: HikariCpJDK7IT.java From pinpoint with Apache License 2.0 | 5 votes |
@Test public void defaultTest1() throws InterruptedException, SQLException, NoSuchMethodException { final HikariConfig config = new HikariConfig(); config.setDataSourceClassName(DATA_SOURCE_CLASS_NAME); config.addDataSourceProperty("url", JDBC_URL); HikariDataSource dataSource = new HikariDataSource(config); try { Connection connection = dataSource.getConnection(); Assert.assertNotNull(connection); Thread.sleep(500); connection.close(); Thread.sleep(500); Constructor<HikariDataSource> constructor = HikariDataSource.class.getConstructor(HikariConfig.class); PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance(); verifier.printCache(); verifier.verifyTrace(event(serviceType, "com.zaxxer.hikari.HikariDataSource.HikariDataSource(com.zaxxer.hikari.HikariConfig)")); verifier.verifyTrace(event(serviceType, "com.zaxxer.hikari.pool.BaseHikariPool.BaseHikariPool(com.zaxxer.hikari.HikariConfig, java.lang.String, java.lang.String)")); verifier.verifyTrace(event(serviceType, getConnectionMethod1)); verifier.verifyTrace(event(serviceType, proxyConnectionMethod)); } finally { if (dataSource != null) { dataSource.close(); } } }
Example 7
Source File: TestJdbcUtil.java From datacollector with Apache License 2.0 | 5 votes |
@Test public void testGetMinValues() throws Exception { HikariPoolConfigBean config = createConfigBean(); HikariDataSource dataSource = jdbcUtil.createDataSourceForRead(config); Connection connection = dataSource.getConnection(); Map<String, String> emptyTableMin = jdbcUtil.getMinimumOffsetValues( DatabaseVendor.UNKNOWN, connection, schema, emptyTableName, QuoteChar.NONE, Arrays.asList("P_ID") ); assertThat(emptyTableMin.size(), equalTo(0)); Map<String, String> typedTableMin = jdbcUtil.getMinimumOffsetValues( DatabaseVendor.UNKNOWN, connection, schema, dataTypesTestTable, QuoteChar.NONE, Arrays.asList("P_ID") ); assertThat(typedTableMin.size(), equalTo(1)); assertThat(typedTableMin, hasEntry("P_ID", "1")); }
Example 8
Source File: TestJdbcUtil.java From datacollector with Apache License 2.0 | 5 votes |
@Test public void testTransactionIsolation() throws Exception { HikariPoolConfigBean config = createConfigBean(); config.transactionIsolation = TransactionIsolationLevel.TRANSACTION_READ_COMMITTED; HikariDataSource dataSource = jdbcUtil.createDataSourceForRead(config); Connection connection = dataSource.getConnection(); assertNotNull(connection); assertEquals(Connection.TRANSACTION_READ_COMMITTED, connection.getTransactionIsolation()); }
Example 9
Source File: HikariCpIT.java From pinpoint with Apache License 2.0 | 5 votes |
@Test public void defaultTest2() throws InterruptedException, SQLException { HikariDataSource dataSource = new HikariDataSource(); dataSource.setDataSourceClassName(DATA_SOURCE_CLASS_NAME); dataSource.addDataSourceProperty("url", JDBC_URL); try { Connection connection = dataSource.getConnection(); Assert.assertNotNull(connection); Thread.sleep(500); connection.close(); Thread.sleep(500); PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance(); verifier.printCache(); verifier.verifyTrace(event(serviceType, "com.zaxxer.hikari.HikariDataSource.HikariDataSource()")); verifier.verifyTrace(event(serviceType, getConnectionMethod1)); verifier.verifyTrace(event(serviceType, "com.zaxxer.hikari.pool.BaseHikariPool.BaseHikariPool(com.zaxxer.hikari.HikariConfig, java.lang.String, java.lang.String)")); verifier.verifyTrace(event(serviceType, proxyConnectionMethod)); } finally { if (dataSource != null) { dataSource.close(); } } }
Example 10
Source File: TestJdbcMultiRowRecordWriter.java From datacollector with Apache License 2.0 | 5 votes |
@Before public void setUp() throws Exception { id = 0L; // Create a table in H2 and put some data in it for querying. HikariConfig config = new HikariConfig(); config.setJdbcUrl(connectionString); config.setUsername(username); config.setPassword(password); config.setMaximumPoolSize(3); dataSource = new HikariDataSource(config); connection = dataSource.getConnection(); try (Statement statement = connection.createStatement()) { // Setup table statement.addBatch("CREATE SCHEMA IF NOT EXISTS TEST;"); statement.addBatch( "CREATE TABLE IF NOT EXISTS TEST.TEST_TABLE " + "(P_ID INT NOT NULL, F1 INT, F2 INT, F3 INT, F4 DATETIME, UNIQUE(P_ID), PRIMARY KEY(P_ID));" ); String unprivUser = "unpriv_user"; String unprivPassword = "unpriv_pass"; statement.addBatch("CREATE USER IF NOT EXISTS " + unprivUser + " PASSWORD '" + unprivPassword + "';"); statement.addBatch("GRANT SELECT ON TEST.TEST_TABLE TO " + unprivUser + ";"); statement.executeBatch(); } }
Example 11
Source File: HikariCpIT.java From pinpoint with Apache License 2.0 | 5 votes |
@Test public void defaultTest3() throws InterruptedException, SQLException { HikariDataSource dataSource = new HikariDataSource(); dataSource.setDataSourceClassName(DATA_SOURCE_CLASS_NAME); dataSource.addDataSourceProperty("url", JDBC_URL); try { Connection connection = dataSource.getConnection("", ""); Assert.assertNotNull(connection); Thread.sleep(500); connection.close(); Thread.sleep(500); PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance(); verifier.printCache(); verifier.verifyTrace(event(serviceType, "com.zaxxer.hikari.HikariDataSource.HikariDataSource()")); verifier.verifyTrace(event(serviceType, getConnectionMethod2, annotation(AnnotationKey.ARGS0.getName(), ""))); verifier.verifyTrace(event(serviceType, proxyConnectionMethod)); } finally { if (dataSource != null) { dataSource.close(); } } }
Example 12
Source File: TestGenericRecordWriter.java From datacollector with Apache License 2.0 | 5 votes |
@Before public void setUp() throws SQLException { // Create a table in H2 and put some data in it for querying. HikariConfig config = new HikariConfig(); config.setJdbcUrl(connectionString); config.setUsername(username); config.setPassword(password); config.setMaximumPoolSize(2); dataSource = new HikariDataSource(config); connection = dataSource.getConnection(); try (Statement statement = connection.createStatement()) { // Setup table statement.addBatch("CREATE SCHEMA IF NOT EXISTS TEST;"); statement.addBatch( "CREATE TABLE IF NOT EXISTS TEST.TEST_TABLE " + "(P_ID INT NOT NULL, MSG VARCHAR(255), PRIMARY KEY(P_ID));" ); statement.addBatch( "CREATE TABLE IF NOT EXISTS TEST.COMPOSITE_KEY " + "(P_ID INT NOT NULL, P_IDB INT NOT NULL, MSG VARCHAR(255), PRIMARY KEY(P_ID, P_IDB));" ); String unprivUser = "unpriv_user"; String unprivPassword = "unpriv_pass"; statement.addBatch("CREATE USER IF NOT EXISTS " + unprivUser + " PASSWORD '" + unprivPassword + "';"); statement.addBatch("GRANT SELECT ON TEST.TEST_TABLE TO " + unprivUser + ";"); statement.executeBatch(); } }
Example 13
Source File: HikariCpIT.java From pinpoint with Apache License 2.0 | 5 votes |
@Test public void defaultTest1() throws InterruptedException, SQLException, NoSuchMethodException { final HikariConfig config = new HikariConfig(); config.setDataSourceClassName(DATA_SOURCE_CLASS_NAME); config.addDataSourceProperty("url", JDBC_URL); HikariDataSource dataSource = new HikariDataSource(config); try { Connection connection = dataSource.getConnection(); Assert.assertNotNull(connection); Thread.sleep(500); connection.close(); Thread.sleep(500); Constructor<HikariDataSource> constructor = HikariDataSource.class.getConstructor(HikariConfig.class); PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance(); verifier.printCache(); verifier.verifyTrace(event(serviceType, "com.zaxxer.hikari.HikariDataSource.HikariDataSource(com.zaxxer.hikari.HikariConfig)")); verifier.verifyTrace(event(serviceType, "com.zaxxer.hikari.pool.BaseHikariPool.BaseHikariPool(com.zaxxer.hikari.HikariConfig, java.lang.String, java.lang.String)")); verifier.verifyTrace(event(serviceType, getConnectionMethod1)); verifier.verifyTrace(event(serviceType, proxyConnectionMethod)); } finally { if (dataSource != null) { dataSource.close(); } } }
Example 14
Source File: HikariCpJDK7IT.java From pinpoint with Apache License 2.0 | 5 votes |
@Test public void defaultTest3() throws InterruptedException, SQLException, NoSuchMethodException { HikariDataSource dataSource = new HikariDataSource(); dataSource.setDataSourceClassName(DATA_SOURCE_CLASS_NAME); dataSource.addDataSourceProperty("url", JDBC_URL); try { Connection connection = dataSource.getConnection("", ""); Assert.assertNotNull(connection); Thread.sleep(500); connection.close(); Thread.sleep(500); PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance(); verifier.printCache(); verifier.verifyTrace(event(serviceType, "com.zaxxer.hikari.HikariDataSource.HikariDataSource()")); verifier.verifyTrace(event(serviceType, getConnectionMethod2, annotation(AnnotationKey.ARGS0.getName(), ""))); verifier.verifyTrace(event(serviceType, proxyConnectionMethod)); } finally { if (dataSource != null) { dataSource.close(); } } }
Example 15
Source File: JdbcUtil.java From datacollector with Apache License 2.0 | 4 votes |
public HikariDataSource createDataSourceForWrite( HikariPoolConfigBean hikariConfigBean, String schemaNameTemplate, String tableNameTemplate, boolean caseSensitive, List<Stage.ConfigIssue> issues, List<JdbcFieldColumnParamMapping> customMappings, Stage.Context context, boolean tableAutoCreate ) throws SQLException, StageException { HikariDataSource dataSource = new HikariDataSource(createDataSourceConfig(hikariConfigBean, hikariConfigBean.isAutoCommit(), false)); // Can only validate schema+table configuration when the user specified plain constant values and table auto // create is not set if (isPlainString(schemaNameTemplate) && isPlainString(tableNameTemplate) && !tableAutoCreate) { try ( Connection connection = dataSource.getConnection(); ResultSet res = getTableMetadata(connection, schemaNameTemplate, tableNameTemplate); ) { if (!res.next()) { issues.add(context.createConfigIssue(Groups.JDBC.name(), TABLE_NAME, JdbcErrors.JDBC_16, tableNameTemplate)); } else { try(ResultSet columns = getColumnMetadata(connection, schemaNameTemplate, tableNameTemplate)) { Set<String> columnNames = new HashSet<>(); while (columns.next()) { columnNames.add(columns.getString(4)); } for (JdbcFieldColumnParamMapping customMapping : customMappings) { if (customMapping.columnName.isEmpty()) { issues.add(context.createConfigIssue(Groups.JDBC.name(), CUSTOM_MAPPINGS, JdbcErrors.JDBC_59 )); } if (!columnNames.contains(customMapping.columnName)) { issues.add(context.createConfigIssue(Groups.JDBC.name(), CUSTOM_MAPPINGS, JdbcErrors.JDBC_07, customMapping.field, customMapping.columnName )); } } } } } } return dataSource; }
Example 16
Source File: EchoPetPlugin.java From SonarPet with GNU General Public License v3.0 | 4 votes |
private void prepareSqlDatabase() { String host = mainConfig.getString("sql.host", "localhost"); int port = mainConfig.getInt("sql.port", 3306); String db = mainConfig.getString("sql.database", "EchoPet"); String user = mainConfig.getString("sql.username", "none"); String pass = mainConfig.getString("sql.password", "none"); HikariConfig config = new HikariConfig(); config.setJdbcUrl("jdbc:mysql://" + host + ":" + port + "/" + db); config.setUsername(user); config.setPassword(pass); dbPool = new HikariDataSource(config); Connection connection = null; Statement statement = null; try { connection = dbPool.getConnection(); statement = connection.createStatement(); statement.executeUpdate("CREATE TABLE IF NOT EXISTS EchoPet_version3 (" + "OwnerName varchar(36)," + "PetType varchar(255)," + "PetName varchar(255)," + "PetData BIGINT," + "RiderPetType varchar(255)," + "RiderPetName varchar(255), " + "RiderPetData BIGINT," + "PRIMARY KEY (OwnerName)" + ");"); // Convert previous database versions TableMigrationUtil.migrateTables(); } catch (SQLException e) { Logger.log(Logger.LogLevel.SEVERE, "Table generation failed [MySQL DataBase: " + db + "].", e, true); } finally { try { if (statement != null) { statement.close(); } if (connection != null) { connection.close(); } } catch (SQLException ignored) { } } // Make sure to convert those UUIDs! }
Example 17
Source File: HikariCpJDK7IT.java From pinpoint with Apache License 2.0 | 4 votes |
@Test public void defaultTest2() throws InterruptedException, SQLException, NoSuchMethodException { HikariDataSource dataSource = new HikariDataSource(); dataSource.setDataSourceClassName(DATA_SOURCE_CLASS_NAME); dataSource.addDataSourceProperty("url", JDBC_URL); try { Connection connection = dataSource.getConnection(); Assert.assertNotNull(connection); Thread.sleep(500); connection.close(); Thread.sleep(500); PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance(); verifier.printCache(); verifier.verifyTrace(event(serviceType, "com.zaxxer.hikari.HikariDataSource.HikariDataSource()")); verifier.verifyTrace(event(serviceType, getConnectionMethod1)); verifier.verifyTrace(event(serviceType, "com.zaxxer.hikari.pool.BaseHikariPool.BaseHikariPool(com.zaxxer.hikari.HikariConfig, java.lang.String, java.lang.String)")); verifier.verifyTrace(event(serviceType, proxyConnectionMethod)); } finally { if (dataSource != null) { dataSource.close(); } } }
Example 18
Source File: MySQLUserDataSource.java From MCAuthenticator with GNU General Public License v3.0 | 4 votes |
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);"); } } }
Example 19
Source File: JDBCProvider.java From funcatron with Apache License 2.0 | 4 votes |
/** * Obtain a connection. Initialize the pool if this is the first time through * @param logger the Logger * @return the Connection if the pool is set up correctly */ protected static Connection _obtainConnection(Logger logger) { try { synchronized (syncObj) { if (!initialized) { initialized = true; Map<String, Object> contextProps = ContextImpl.staticProperties(); String dbUrl = fromMap("jdbc.url", contextProps); if (null != dbUrl) { Properties dbProps = new Properties(); dbProps.put("jdbcUrl", dbUrl); String dbname = fromMap("jdbc.classname", contextProps); if (null != dbname) { dbProps.put("driverClassName", dbname); } dbProps.put("autoCommit", false); String user = fromMap("jdbc.username", contextProps); if (null != user) { dbProps.put("username", user); } String pwd = fromMap("jdbc.password", contextProps); if (null != pwd) { dbProps.put("password", pwd); } HikariConfig config = new HikariConfig(dbProps); pool = new HikariDataSource(config); } } } if (null != pool) { return pool.getConnection(); } } catch (SQLException sqe) { if (null != logger) { logger.log(Level.SEVERE, sqe, () -> "Catastrophic DB pool error"); } } return null; }
Example 20
Source File: ClickhouseWriterTest.java From flink-clickhouse-sink with MIT License | 4 votes |
@Before public void setUp() throws Exception { Config config = ConfigFactory.load(); Map<String, String> params = ConfigUtil.toMap(config); params.put(ClickhouseClusterSettings.CLICKHOUSE_USER, ""); params.put(ClickhouseClusterSettings.CLICKHOUSE_PASSWORD, ""); int dockerActualPort = clickhouse.getMappedPort(HTTP_CLICKHOUSE_PORT); // container with CH is raised for every test -> we should config host and port every time params.put(ClickhouseClusterSettings.CLICKHOUSE_HOSTS, "http://localhost:" + dockerActualPort); asyncHttpClient = asyncHttpClient(); try { Class.forName(JDBC_DRIVER); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } HikariConfig hikariConfig = new HikariConfig(); hikariConfig.setJdbcUrl(clickhouse.getJdbcUrl()); hikariConfig.setUsername(clickhouse.getUsername()); hikariConfig.setPassword(clickhouse.getPassword()); hikariDataSource = new HikariDataSource(hikariConfig); try (Connection connection = hikariDataSource.getConnection(); Statement statement = connection.createStatement()) { statement.executeQuery("CREATE DATABASE IF NOT EXISTS test;"); statement.executeQuery("DROP TABLE IF EXISTS test.test0;"); statement.executeQuery("CREATE TABLE test.test0 (" + "id UInt64," + "title String," + "container String," + "drm String," + "quality String)" + "ENGINE = Log;"); statement.executeQuery("DROP TABLE IF EXISTS test.test1;"); statement.executeQuery("CREATE TABLE test.test1 (" + "id UInt64," + "title String," + "num UInt64)" + "ENGINE = Log;"); } sinkManager = new ClickhouseSinkManager(params); }