import java.sql.*;
import org.postgresql.*;

public class SequenceTest extends Thread
{
	Connection con = null;
	Object obj = null;
	int index = 0;
	int loop = 0;

	public SequenceTest(Object obj, int index, int loop)
	{
		this.obj   = obj;
		this.index = index;
		this.loop  = loop;

		try {
			Class.forName("org.postgresql.Driver");
			org.postgresql.Driver.setLogLevel(org.postgresql.Driver.DEBUG);
			
			con = DriverManager.getConnection("jdbc:postgresql:GSC=//st19:5432/gsc@testdb", "snaga", "snaga");
			con.setAutoCommit(false);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			System.exit(-1);
		}
	}

	public void run()
	{
		runtest();
	}

	private void runtest()
	{
		Sequence seq = new Sequence(con, "seq");

		boolean failed = false;

		System.out.println("Start running...");
		for (int i=0 ; i<loop ; i++)
		{
			try {
				//				con.setAutoCommit(true);
				//				con.setAutoCommit(false);
				seq.nextval("test");

				con.commit();
			}
			catch (Exception e)
			{
				failed = true;
				//System.out.print("" + index + ":" + i + ":" + e.getMessage());
				System.out.print(e.getMessage());
				//				e.printStackTrace();
			}

			if ( failed )
			{
				try {
			    	con.rollback();
					failed = false;
				}
				catch (Exception e)
				{
					System.out.print("" + index + ":" + i + ":" + e.getMessage());
					e.printStackTrace();
				}
				loop--;
			}
		}

		try {
			con.close();
		}
		catch (Exception e)
		{
			System.out.println("" + index + ":" + e.getMessage());
		}

		synchronized (obj)
		{
			obj.notify();
		}
	}

    public static void main(String[] args)
    {
		SequenceTest[] tests = new SequenceTest[100];
		Object obj = new Object();
		int nclients = 64;

		try {
			for (int i=0 ; i<nclients ; i++)
			{
				tests[i] = new SequenceTest(obj, i, 100);
			}

			synchronized (obj)
			{
				for (int i=0 ; i<nclients ; i++)
				{
					tests[i].start();
				}
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
			System.exit(-1);
		}
    }
}
