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

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

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 TestConcurrency {
    private static Integer get(Connection con, String key) throws SQLException {
        PreparedStatement pstmt = con.prepareStatement("SELECT cvalue FROM concurrency_cache WHERE ckey = ?");
        pstmt.setString(1, key);
        ResultSet rs = pstmt.executeQuery();
        Integer res = null;
        if(rs.next()) {
            res = rs.getInt(1);
        }
        rs.close();
        pstmt.close();
        return res;
    }
    private static void put(Connection con, String key, Integer value) throws SQLException {
        PreparedStatement pstmt = con.prepareStatement("MERGE INTO concurrency_cache(ckey,cvalue) VALUES(?,?)");
        pstmt.setString(1, key);
        pstmt.setInt(2, value);
        pstmt.executeUpdate();
        pstmt.close();
    }
    private static void add(Connection con, String key, Integer delta) throws SQLException {
        PreparedStatement pstmt = con.prepareStatement("UPDATE concurrency_cache SET cvalue = cvalue + ? WHERE ckey = ?");
        pstmt.setInt(1, delta);
        pstmt.setString(2, key);
        pstmt.executeUpdate();
        pstmt.close();
    }
    private static class Test1 implements Runnable {
        @Override
        public void run() {
            try {
                Connection con = DriverManager.getConnection("jdbc:apache:commons:dbcp:ignite");
                int hot = get(con, "hot");
                hot = hot + 1;
                put(con, "hot", hot);
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    ////private static class Test5 implements Runnable {
    ////    @Override
    ////    public void run() {
    ////        try {
    ////            Connection con = DriverManager.getConnection("jdbc:apache:commons:dbcp:ignite");
    ////            con.setAutoCommit(false);
    ////            boolean done = false;
    ////            while(!done) {
    ////                try {
    ////                    int hot = get(con, "hot");
    ////                    hot = hot + 1;
    ////                    put(con, "hot", hot);
    ////                    con.commit();
    ////                    done = true;
    ////                } catch (SQLException e) {
    ////                    // retry
    ////                }
    ////            }
    ////            con.close();
    ////        } catch (SQLException e) {
    ////            e.printStackTrace();
    ////        }
    ////    }
    ////}
    private static class Test6 implements Runnable {
        @Override
        public void run() {
            try {
                Connection con = DriverManager.getConnection("jdbc:apache:commons:dbcp:ignite");
                boolean done = false;
                while(!done) {
                    try {
                        add(con, "hot", 1);
                        done = true;
                    } catch (SQLException e) {
                        // retry
                    }
                }
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    private static final int NTHREADS = 100;
    private static final int NOPS = 10000;
    private static void test(Connection con, String lbl, Runnable action) throws InterruptedException, SQLException {
        long t1 = System.currentTimeMillis();
        put(con, "hot", 0);
        ExecutorService es = Executors.newFixedThreadPool(NTHREADS);
        for(int i = 0; i < NOPS; i++) {
            es.submit(action);
        }
        es.shutdown();
        es.awaitTermination(300, TimeUnit.SECONDS);
        int hot = get(con, "hot");
        long t2 = System.currentTimeMillis();
        System.out.printf("%s : %d = %d (%d ms)\n", lbl, hot, NOPS, t2 - t1);
    }
    public static void main(String[] args) throws Exception {
        Class.forName("org.apache.commons.dbcp2.PoolingDriver");
        PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:"); // Ignite Connection is not thread safe and connecting is slow so a connection pool is necessary
        PoolableConnectionFactory pcf = new PoolableConnectionFactory(new DriverManagerConnectionFactory("jdbc:ignite:thin://localhost:10800"), null);
        GenericObjectPool<PoolableConnection> cp = new GenericObjectPool<>(pcf);
        cp.setMinIdle(1);
        cp.setMaxTotal(NTHREADS + 1);
        pcf.setPool(cp);
        driver.registerPool("ignite", cp);
        Connection con = DriverManager.getConnection("jdbc:apache:commons:dbcp:ignite");
        Statement stmt = con.createStatement();
        stmt.executeUpdate("CREATE TABLE IF NOT EXISTS concurrency_cache (ckey VARCHAR(16) NOT NULL, cvalue INTEGER NOT NULL, PRIMARY KEY(ckey))");
        stmt.close();
        test(con, "No handling", new Test1());
        // transaction with retry does not work for my config
        ////test(con, "Transaction with retry", new Test5());
        test(con, "Update with retry", new Test6());
        con.close();
        driver.closePool("ignite");
    }
}
