import java.sql.*;
import java.util.*;


public class test {

    private static final String DB_URL   = "jdbc:hsqldb:c:/temp/hsqldb/test";
    private static final String DB_CLASS = "org.hsqldb.jdbcDriver";

    private void dowork() {

        Connection conn    = null;
        Statement  stmt    = null;
        ResultSet  results = null;

        try {

            //Create the connection
            Class.forName( DB_CLASS );

            Properties props = new Properties();
            props.put( "user", "sa" );
            conn = DriverManager.getConnection( DB_URL, props );
        }catch ( Exception sqlex ) {
            sqlex.printStackTrace();
            return;
        }

        try {

            //Maintain the tables, define the trigger
            stmt = conn.createStatement();

            try {
                stmt.execute( "DROP TABLE CHILD" );
            }catch ( Exception ex ) { }

            try {
                stmt.execute( "DROP TABLE PARENT" );
            }catch ( Exception ex ) { }

            stmt.execute( "CREATE TABLE PARENT( parent_key INTEGER NOT NULL, gen_id INTEGER NULL, value VARCHAR(32), PRIMARY KEY(parent_key) )" );
            stmt.execute(
                "CREATE TABLE CHILD( gen_id INTEGER NOT NULL, child_key INTEGER NOT NULL, value_too VARCHAR(32), PRIMARY KEY(gen_id, child_key), FOREIGN KEY(gen_id) REFERENCES PARENT )" );

            //If I comment out the following line, the program exists successfully, if I don't
            //it hangs because one of the threads is not exiting properly. This is while in in-process mode.
            stmt.execute( "CREATE TRIGGER test_gen_id BEFORE INSERT ON PARENT CALL \"test_gen_id\"" );
        }catch ( Exception cex ) {
            cex.printStackTrace();
        }finally {
            try {
                if ( results != null ) {
                    results.close();
                }

                if ( stmt != null ) {
                    stmt.close();
                }

                if ( conn != null ) {
                    conn.commit();
                    conn.close();
                }
            }catch ( Exception ex ) {
                ex.printStackTrace();
            }
        }
    }


    public static void main(String[] args) {

        test tester;

        tester = new test();
        tester.dowork();
    }
}
