// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package javadb;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.apache.commons.dbcp2.DriverManagerConnectionFactory;
import org.apache.commons.dbcp2.PoolableConnection;
import org.apache.commons.dbcp2.PoolableConnectionFactory;
import org.apache.commons.dbcp2.PoolingDriver;
import org.apache.commons.pool2.impl.GenericObjectPool;

public class PoolDemo {
    private static void startPool(String pool, int min, int max, String url, String un, String pw) throws SQLException {
        PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");
        PoolableConnectionFactory pcf = new PoolableConnectionFactory(new DriverManagerConnectionFactory(url, un, pw), null);
        GenericObjectPool<PoolableConnection> cp = new GenericObjectPool<>(pcf);
        cp.setMinIdle(min);
        cp.setMaxTotal(max);
        pcf.setPool(cp);
        driver.registerPool(pool, cp);
    }
    private static void stopPool(String pool) throws SQLException {
        PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");
        driver.closePool(pool);
    }
    public static void testNonPool(String url, String un, String pw) throws SQLException {
        try(Connection con = DriverManager.getConnection(url, un, pw)) {
            // nothing
        }
    }
    public static void testPool(String pool) throws SQLException {
        try(Connection con = DriverManager.getConnection("jdbc:apache:commons:dbcp:" + pool)) {
            // nothing
        }
    }
    public static void testManyNonPool(int n, String url, String un, String pw) throws SQLException {
        long t1 = System.currentTimeMillis();
        for(int i = 0; i < n; i++) {
            testNonPool(url, un, pw);
        }
        long t2 = System.currentTimeMillis();
        System.out.printf("Non pooled connection time = %.3f ms\n", (t2 - t1) * 1.0 / n);
    }
    public static void testManyPool(int n, String pool) throws SQLException {
        long t1 = System.currentTimeMillis();
        for(int i = 0; i < n; i++) {
            testPool(pool);
        }
        long t2 = System.currentTimeMillis();
        System.out.printf("Pooled connection time = %.3f ms\n", (t2 - t1) * 1.0 / n);
    }
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        Class.forName("org.apache.commons.dbcp2.PoolingDriver");
        startPool("Test", 10, 100, "jdbc:db2://localhost:50000/Test", "arne", "xxxxxx");
        testNonPool("jdbc:db2://localhost:50000/Test", "arne", "xxxxxx");
        testPool("Test");
        testManyNonPool(10000, "jdbc:db2://localhost:50000/Test", "arne", "xxxxxx");
        testManyPool(10000, "Test");
        stopPool("Test");
    }
}
