
import java.io.*;
import java.sql.*;
import com.bitmechanic.sql.*;

/**
 * example invocation: java PoolTest exgwe.sql.gweMysqlDriver \
 *                     jdbc:mysql://localhost:3306/mydb username pw 5 300 120
 *
 */
public class PoolTest {

  private ConnectionPoolManager pool;
  private DataInputStream in;
  private String alias = "jdbcalias";

  public static void main(String argv[]) {
    if(argv.length < 7) {
      System.err.println("Usage: java PoolTest <jdbc driver> <jdbc url> <username> <password> <max connections> <idle timeout> <checkout timeout>");
    }
    else {
      try {
	PoolTest test = new PoolTest(argv);
	
	BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
	System.out.print("Enter query [q to quit]: ");
	String command = in.readLine();
	while(!command.equals("q")) {
	  test.execute(command);
	  System.out.print("Enter query [q to quit]: ");
	  command = in.readLine();
	}
	
	test.stats();
      }
      catch(Exception e) {
	e.printStackTrace();
      }
    }
  }

  public PoolTest(String argv[]) throws Exception {
    // Create the pool - alias is used to identify different pools inside
    // the VM. we're only using one pool in this example, but theoretically
    // you could have the pool manage connections to dozens of JDBC 
    // datasources
    pool = new ConnectionPoolManager(120);
    pool.addAlias(alias, argv[0], argv[1], argv[2], argv[3],
		  Integer.parseInt(argv[4]), Integer.parseInt(argv[5]),
		  Integer.parseInt(argv[6]));
  }

  public void execute(String command) throws Exception {
    // Run a query
    Connection conn = DriverManager.getConnection(ConnectionPoolManager.URL_PREFIX + alias, null, null);
    Statement stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery(command);
    ResultSetMetaData meta = rs.getMetaData();
    int numCols = meta.getColumnCount();
    while(rs.next()) {
      for(int x = 1; x <= numCols; x++) {
	if(x != 1) System.out.print("\t");
	    System.out.print(rs.getString(x));
      }
      System.out.println();
    }
    rs.close();
    stmt.close();
    conn.close();
  }
  
  public void stats() throws SQLException {
    // Gather statistics
    ConnectionPool p = pool.getPool(alias);
    System.out.println("Pool Statistics: ");
    System.out.println("  Current size: " + p.size() + " of " + 
		       p.getMaxConn());
    System.out.println("  Connection requests: " + p.getNumRequests());
    System.out.println("  Number of waits: " + p.getNumWaits());
    System.out.println("  Number of timeouts: " +p.getNumCheckoutTimeouts());
  }
}
