Search in sources :

Example 6 with StubDataSource

use of com.zaxxer.hikari.mocks.StubDataSource in project HikariCP by brettwooldridge.

the class UnwrapTest method testUnwrapDataSource.

@Test
public void testUnwrapDataSource() throws SQLException {
    HikariConfig config = newHikariConfig();
    config.setMinimumIdle(1);
    config.setMaximumPoolSize(1);
    config.setInitializationFailTimeout(0);
    config.setConnectionTestQuery("VALUES 1");
    config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
    try (HikariDataSource ds = new HikariDataSource(config)) {
        StubDataSource unwrap = ds.unwrap(StubDataSource.class);
        assertNotNull(unwrap);
        assertTrue(unwrap instanceof StubDataSource);
        assertTrue(ds.isWrapperFor(HikariDataSource.class));
        assertTrue(ds.unwrap(HikariDataSource.class) instanceof HikariDataSource);
        assertFalse(ds.isWrapperFor(getClass()));
        try {
            ds.unwrap(getClass());
        } catch (SQLException e) {
            assertTrue(e.getMessage().contains("Wrapped DataSource"));
        }
    }
}
Also used : HikariDataSource(com.zaxxer.hikari.HikariDataSource) SQLException(java.sql.SQLException) HikariConfig(com.zaxxer.hikari.HikariConfig) TestElf.newHikariConfig(com.zaxxer.hikari.pool.TestElf.newHikariConfig) StubDataSource(com.zaxxer.hikari.mocks.StubDataSource) Test(org.junit.Test)

Example 7 with StubDataSource

use of com.zaxxer.hikari.mocks.StubDataSource in project HikariCP by brettwooldridge.

the class TestJNDI method testJndiLookup4.

@Test
public void testJndiLookup4() throws Exception {
    System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.osjava.sj.memory.MemoryContextFactory");
    System.setProperty("org.osjava.sj.jndi.shared", "true");
    InitialContext ic = new InitialContext();
    StubDataSource ds = new StubDataSource();
    Context subcontext = ic.createSubcontext("java:/comp/env/jdbc");
    subcontext.bind("java:/comp/env/jdbc/myDS", ds);
    HikariConfig config = newHikariConfig();
    config.setDataSourceJNDI("java:/comp/env/jdbc/myDS");
    try (HikariDataSource hds = new HikariDataSource(config);
        Connection conn = hds.getConnection()) {
        assertNotNull(conn);
    }
}
Also used : InitialContext(javax.naming.InitialContext) AbstractContext(org.osjava.sj.jndi.AbstractContext) Context(javax.naming.Context) TestElf.newHikariDataSource(com.zaxxer.hikari.pool.TestElf.newHikariDataSource) HikariDataSource(com.zaxxer.hikari.HikariDataSource) Connection(java.sql.Connection) HikariConfig(com.zaxxer.hikari.HikariConfig) TestElf.newHikariConfig(com.zaxxer.hikari.pool.TestElf.newHikariConfig) StubDataSource(com.zaxxer.hikari.mocks.StubDataSource) InitialContext(javax.naming.InitialContext) Test(org.junit.Test)

Example 8 with StubDataSource

use of com.zaxxer.hikari.mocks.StubDataSource in project HikariCP by brettwooldridge.

the class ConnectionPoolSizeVsThreadsTest method testPoolSize.

private Counts testPoolSize(final int minIdle, final int maxPoolSize, final int threadCount, final long workTimeMs, final long restTimeMs, final long connectionAcquisitionTimeMs, final int iterations, final long postTestTimeMs) throws Exception {
    LOGGER.info("Starting test (minIdle={}, maxPoolSize={}, threadCount={}, workTimeMs={}, restTimeMs={}, connectionAcquisitionTimeMs={}, iterations={}, postTestTimeMs={})", minIdle, maxPoolSize, threadCount, workTimeMs, restTimeMs, connectionAcquisitionTimeMs, iterations, postTestTimeMs);
    final HikariConfig config = newHikariConfig();
    config.setMinimumIdle(minIdle);
    config.setMaximumPoolSize(maxPoolSize);
    config.setInitializationFailTimeout(Long.MAX_VALUE);
    config.setConnectionTimeout(2500);
    config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
    final AtomicReference<Exception> ref = new AtomicReference<>(null);
    // Initialize HikariPool with no initial connections and room to grow
    try (final HikariDataSource ds = new HikariDataSource(config)) {
        final StubDataSource stubDataSource = ds.unwrap(StubDataSource.class);
        // connection acquisition takes more than 0 ms in a real system
        stubDataSource.setConnectionAcquistionTime(connectionAcquisitionTimeMs);
        final ExecutorService threadPool = newFixedThreadPool(threadCount);
        final CountDownLatch allThreadsDone = new CountDownLatch(iterations);
        for (int i = 0; i < iterations; i++) {
            threadPool.submit(() -> {
                if (ref.get() == null) {
                    quietlySleep(restTimeMs);
                    try (Connection c2 = ds.getConnection()) {
                        quietlySleep(workTimeMs);
                    } catch (Exception e) {
                        ref.set(e);
                    }
                }
                allThreadsDone.countDown();
            });
        }
        final HikariPool pool = getPool(ds);
        // collect pool usage data while work is still being done
        final Counts underLoad = new Counts();
        while (allThreadsDone.getCount() > 0 || pool.getTotalConnections() < minIdle) {
            quietlySleep(50);
            underLoad.updateMaxCounts(pool);
        }
        // wait for long enough any pending acquisitions have already been done
        LOGGER.info("Test Over, waiting for post delay time {}ms ", postTestTimeMs);
        quietlySleep(connectionAcquisitionTimeMs + workTimeMs + restTimeMs);
        // collect pool data while there is no work to do.
        final Counts postLoad = new Counts();
        final long start = currentTime();
        while (elapsedMillis(start) < postTestTimeMs) {
            quietlySleep(50);
            postLoad.updateMaxCounts(pool);
        }
        allThreadsDone.await();
        threadPool.shutdown();
        threadPool.awaitTermination(30, SECONDS);
        if (ref.get() != null) {
            LOGGER.error("Task failed", ref.get());
            fail("Task failed");
        }
        LOGGER.info("Under Load... {}", underLoad);
        LOGGER.info("Post Load.... {}", postLoad);
        // verify that the no connections created after the work has stopped
        if (postTestTimeMs > 0) {
            if (postLoad.maxActive != 0) {
                fail("Max Active was greater than 0 after test was done");
            }
            final int createdAfterWorkAllFinished = postLoad.maxTotal - underLoad.maxTotal;
            assertEquals("Connections were created when there was no waiting consumers", 0, createdAfterWorkAllFinished, 1);
        }
        return underLoad;
    }
}
Also used : HikariDataSource(com.zaxxer.hikari.HikariDataSource) Connection(java.sql.Connection) AtomicReference(java.util.concurrent.atomic.AtomicReference) HikariConfig(com.zaxxer.hikari.HikariConfig) TestElf.newHikariConfig(com.zaxxer.hikari.pool.TestElf.newHikariConfig) CountDownLatch(java.util.concurrent.CountDownLatch) ExecutorService(java.util.concurrent.ExecutorService) StubDataSource(com.zaxxer.hikari.mocks.StubDataSource)

Example 9 with StubDataSource

use of com.zaxxer.hikari.mocks.StubDataSource in project HikariCP by brettwooldridge.

the class TestConnectionTimeoutRetry method testConnectionRetries5.

@Test
public void testConnectionRetries5() throws SQLException {
    HikariConfig config = newHikariConfig();
    config.setMinimumIdle(0);
    config.setMaximumPoolSize(2);
    config.setConnectionTimeout(1000);
    config.setValidationTimeout(1000);
    config.setConnectionTestQuery("VALUES 1");
    config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
    try (HikariDataSource ds = new HikariDataSource(config)) {
        final Connection connection1 = ds.getConnection();
        long start = currentTime();
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
        scheduler.schedule(new Runnable() {

            @Override
            public void run() {
                try {
                    connection1.close();
                } catch (Exception e) {
                    e.printStackTrace(System.err);
                }
            }
        }, 250, MILLISECONDS);
        StubDataSource stubDataSource = ds.unwrap(StubDataSource.class);
        stubDataSource.setThrowException(new SQLException("Connection refused"));
        try {
            try (Connection connection2 = ds.getConnection()) {
            // close immediately
            }
            long elapsed = elapsedMillis(start);
            assertTrue("Waited too long to get a connection.", (elapsed >= 250) && (elapsed < config.getConnectionTimeout()));
        } catch (SQLException e) {
            fail("Should not have timed out.");
        } finally {
            scheduler.shutdownNow();
        }
    }
}
Also used : ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) HikariDataSource(com.zaxxer.hikari.HikariDataSource) SQLException(java.sql.SQLException) Connection(java.sql.Connection) StubConnection(com.zaxxer.hikari.mocks.StubConnection) HikariConfig(com.zaxxer.hikari.HikariConfig) TestElf.newHikariConfig(com.zaxxer.hikari.pool.TestElf.newHikariConfig) StubDataSource(com.zaxxer.hikari.mocks.StubDataSource) SQLException(java.sql.SQLException) Test(org.junit.Test)

Example 10 with StubDataSource

use of com.zaxxer.hikari.mocks.StubDataSource in project HikariCP by brettwooldridge.

the class TestConnections method testInvalidConnectionTestQuery.

@Test
public void testInvalidConnectionTestQuery() {
    class BadConnection extends StubConnection {

        /** {@inheritDoc} */
        @Override
        public Statement createStatement() throws SQLException {
            throw new SQLException("Simulated exception in createStatement()");
        }
    }
    StubDataSource stubDataSource = new StubDataSource() {

        /** {@inheritDoc} */
        @Override
        public Connection getConnection() throws SQLException {
            return new BadConnection();
        }
    };
    HikariConfig config = newHikariConfig();
    config.setMinimumIdle(1);
    config.setMaximumPoolSize(2);
    config.setConnectionTimeout(TimeUnit.SECONDS.toMillis(3));
    config.setConnectionTestQuery("VALUES 1");
    config.setInitializationFailTimeout(TimeUnit.SECONDS.toMillis(2));
    config.setDataSource(stubDataSource);
    try (HikariDataSource ds = new HikariDataSource(config)) {
        try (Connection c = ds.getConnection()) {
            fail("getConnection() should have failed");
        } catch (SQLException e) {
            assertSame("Simulated exception in createStatement()", e.getNextException().getMessage());
        }
    } catch (PoolInitializationException e) {
        assertSame("Simulated exception in createStatement()", e.getCause().getMessage());
    }
    config.setInitializationFailTimeout(0);
    try (HikariDataSource ds = new HikariDataSource(config)) {
        fail("Initialization should have failed");
    } catch (PoolInitializationException e) {
    // passed
    }
}
Also used : TestElf.newHikariDataSource(com.zaxxer.hikari.pool.TestElf.newHikariDataSource) HikariDataSource(com.zaxxer.hikari.HikariDataSource) SQLException(java.sql.SQLException) StubConnection(com.zaxxer.hikari.mocks.StubConnection) Connection(java.sql.Connection) StubConnection(com.zaxxer.hikari.mocks.StubConnection) HikariConfig(com.zaxxer.hikari.HikariConfig) TestElf.newHikariConfig(com.zaxxer.hikari.pool.TestElf.newHikariConfig) StubDataSource(com.zaxxer.hikari.mocks.StubDataSource) PoolInitializationException(com.zaxxer.hikari.pool.HikariPool.PoolInitializationException) Test(org.junit.Test) TestElf.setConfigUnitTest(com.zaxxer.hikari.pool.TestElf.setConfigUnitTest)

Aggregations

HikariDataSource (com.zaxxer.hikari.HikariDataSource)10 StubDataSource (com.zaxxer.hikari.mocks.StubDataSource)10 Connection (java.sql.Connection)9 Test (org.junit.Test)9 HikariConfig (com.zaxxer.hikari.HikariConfig)8 TestElf.newHikariConfig (com.zaxxer.hikari.pool.TestElf.newHikariConfig)8 SQLException (java.sql.SQLException)7 StubConnection (com.zaxxer.hikari.mocks.StubConnection)6 TestElf.newHikariDataSource (com.zaxxer.hikari.pool.TestElf.newHikariDataSource)5 TestElf.setConfigUnitTest (com.zaxxer.hikari.pool.TestElf.setConfigUnitTest)3 PoolInitializationException (com.zaxxer.hikari.pool.HikariPool.PoolInitializationException)2 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)2 CountDownLatch (java.util.concurrent.CountDownLatch)1 ExecutorService (java.util.concurrent.ExecutorService)1 AtomicReference (java.util.concurrent.atomic.AtomicReference)1 Context (javax.naming.Context)1 InitialContext (javax.naming.InitialContext)1 AbstractContext (org.osjava.sj.jndi.AbstractContext)1