package test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class ReqResMismatch {

	public static Connection openConnection() throws Exception{
		String jdbcUrl = "jdbc:mysql://mysql_server:3306/db?autoReconnect=true&socketTimeout=2000";
		return DriverManager.getConnection(jdbcUrl, "user", "password");
	}

	public static long find(PreparedStatement pstmt, long key, int sleepSeconds) throws Exception{
		pstmt.setLong(1,  key);
		pstmt.setInt(2, sleepSeconds);
		ResultSet rs = pstmt.executeQuery();
		try{
			if(rs.next()){
				return rs.getLong("value");
			}
		}finally{
			if(rs!=null) rs.close();
		}

		// Should not come here
		return -1;
	}

	public static void main(String args[]) throws Exception{
		long loop = 0;
		long key = 0;
		long rtn = 0;

		Connection conn = openConnection();
		PreparedStatement pstmt = conn.prepareStatement("select ? as value, sleep(?)");

		while(true){
			loop++;
			try{
				rtn = find(pstmt, ++key, 3);
				if(rtn!=key){
					System.out.println(">> Query-1 : found mismatch : " + key + " ==> " + rtn);
					return;
				}
			}catch(Exception ex){
				System.out.println(">> Query-1, key("+key+") : exception : " + ex.getMessage());
				ex.printStackTrace();
			}

			try{
				rtn = find(pstmt, ++key, 1);
				if(rtn!=key){
					System.out.println(">> Query-2 : found mismatch : " + key + " ==> " + rtn);
					return;
				}
			}catch(Exception ex){
				System.out.println(">> Query-2, key("+key+") : exception : " + ex.getMessage());
				ex.printStackTrace();
			}

			if(loop % 10000 == 0){
				System.out.println(">> Ran " + loop + " test loops");
			}
		}
	}
}