/* Example for setup and environment variables (database pool):

### Vorbereitungen auf dbpraktikum:

### Setup for Java: (am besten in .bash_profile eintragen)
export PATH=/usr/local/java/bin:$PATH

### CLASSPATH setting:
### For the connection to the Oracle JDBC database the following
### classes are needed:
###   $ORACLE_HOME/jdbc/lib/classes12.zip for java 1.2+
### in the following circumstances:
### * At compile time, if the method
###   DriverManager.registerDriver is used directly without
###   method Class.forName.
### * The program/applet is not run as .jar/.zip file that contains
###   also the above classes.
### (am besten in .bash_profile eintragen)
export CLASSPATH=.:$ORACLE_HOME/jdbc/lib/classes12.zip

*/

/* Example for compiling and running:

### Compiling:
javac <name>.java

### Running as application:
java <name>

### Running as applet by appletviewer:
### Now it will be a little more complicated :-)

### The appletviewer does not evaluate the setting of the
### environment variable CLASSPATH, when it runs Java on
### the applet. There are two methods to deal with this
### situation.
###
### a) The official one, see "Packaging Applets":
###   http://www.dbis.informatik.uni-goettingen.de/
###       Teaching/DBP/orajdbc/advanc.htm#1003944
###    Example, your class is called frame and frame.class
###    is in current directory:
unzip $ORACLE_HOME/jdbc/lib/classes12 -d emptydir
cp frame.class emptydir/
cd emptydir
jar cf ../frame.jar *
cd ..
### Then, the file frame.html has to be changed:
###    The jar file is added in the APPLET tag of the HTML page:
<APPLET CODE="frame" ARCHIVE="frame.jar" WIDTH=600 HEIGHT=400>
</APPLET>
### Next, read the section "Security issues"

### b) Quick and dirty: The CLASSPATH can be given as option
###    in the call of appletviewer:
### Do not forget to read and include the "Security Issues" below!
appletviewer -J-classpath -J$ORACLE_HOME/jdbc/lib/classes12.zip frame.html

### Security issues
### Because of applet security restrictions, an applet cannot
### connect to a server other than the host where the web server
### is running. The JDBC documentation describes two methods,
### running the Oracle8 Connection Manager on the web server
### or using signed applets.
### See: http://www.dbis.informatik.uni-goettingen.de/
###            Teaching/DBP/orajdbc/advanc.htm#1003752
###
### Other method: Customized policy file
###    Create a policy file "mypolicy":
grant {
  permission java.net.SocketPermission
             "134.76.81.14:1521", "connect, resolve";
};
###    Finally, the appletviewer can be called
###     telling it to use the policy file:
appletviewer \
    -J-Djava.security.manager \
    -J-Djava.security.policy=mypolicy \
    frame.html
###    (The backslash tells the shell to continue the line on the
###    next one, alternatively all can be written in one line
###    without the backslashes.)
*/

// Import the java classes used in applets
import java.awt.*;
import java.awt.event.*;
/*
  You are not restricted to the AWT classes,
  also Swing may be used.
*/

// Import the JDBC classes
import java.sql.*;

public class frame extends Frame implements ActionListener {

    public static void main (String[] args) {
        new frame();
    }

    // The connection to the database
    private Connection conn = null;

    // Input area
    private TextField input = new TextField(60);

    // The button to push for executing the query
    private Button submitQuery = new Button("submitQuery");

    // The place where to dump the query result
    private TextArea output = new TextArea();

    // For managing the layout
    private GridBagConstraints gbc = new GridBagConstraints();

    public frame () {
        super("Rahmen zu JDBC");
        try {

            // Syntax for ORACLE driver:
            // "jdbc:oracle:thin:<USERNAME>/<PASSWORD>@
            //         <IP-Address of DB Server>:<Port>:<SID>"

            // The JDBC driver to load
            // a) DriverManager.registerDriver can be called directly:
            // DriverManager.registerDriver(
            //        new oracle.jdbc.driver.OracleDriver());
            // or
            // b) Class.forName can be used, then
            // * class oracle.jdbc.driver.OracleDriver has not to
            //   known at compile time,
            // * DriverManager.registerDriver is called automatically,
            // * but ClassNotFoundException has to be catched.
            Class.forName("oracle.jdbc.driver.OracleDriver");

            // connect string

            // Replace "jdbc_x/jdbc_x" by your group account.
            // Example for group 8: "jdbc_8/jdbc_8"
            String account = "jdbc_x/jdbc_x";

            // Server: s4.ifi.informatik.uni-goettingen.de
            String server = "s4.ifi.informatik.uni-goettingen.de:1521";

            // If you are behind a firewall that blocks this port,
            // you can use a tunneling application (stunnel, ...)
            // or use local forwarding by ssh.
            // Example for user "foo" that logins into "dbpraktikum":
            //   ssh -L 1521:134.76.81.14:1521 foo@dbpraktikum.ifi.informatik.uni-goettingen.de
            // Then the server string contains the port on the
            // local machine:
            //   String server = "127.0.0.1:1521";

            String url = "jdbc:oracle:thin:" + account + "@"
                         + server + ":dbis";
            conn = DriverManager.getConnection(url);
        }
        catch (ClassNotFoundException e) {
            System.out.println("!!! Error: Class '" + e.getMessage()
                    + "' not found!");
            System.exit(1);
        }
        catch (SQLException e) {
            System.out.println("!!! Error: Connection failed:");
            System.out.println(e.getMessage());
            System.exit(1);
        }

        // Layout
        setLayout(new GridBagLayout());
        input.addActionListener(this);
        submitQuery.addActionListener(this);

        // add components
        gbc.gridx = 0;
        gbc.gridy = 0;
        add(input, gbc);
        gbc.gridy = 1;
        add(output, gbc);
        gbc.gridx = 1;
        gbc.gridy = 0;
        add(submitQuery, gbc);

        addWindowListener(new WindowAdapter() {
            public void windowClosing (WindowEvent e) {
                System.exit(0);
            }
        });
        pack();
        setVisible(true);
    }

    public void actionPerformed (ActionEvent e) {
        Object origin = e.getSource();
        // The compiler generates an error, if a method is used
        // that throws a SQLException, e.g. dispResult()!
        try {
            Statement stmt = conn.createStatement ();
            if ( origin == submitQuery ) {
                String query = input.getText();
                // execute the query ...
                // ... and print the result with the help of dispResult
                // Execute the query
                output.append ("Executing query " + query + "\n\n");
                ResultSet rset = stmt.executeQuery (query);

                // Write the result set

                dispResult(rset);
                rset.close();

                return;
            }

            // Treatment of the remaining exercises
            // (for instance, one button per exercise)

            // if ( origin == execJob ) {
                // execute exercise X ...
                // ... and print the result by displayResult
                // here the method is called that has to be written
                // doJob();
                // return;
            // }
        }
        catch (SQLException exc) {
            output.setText("Error while executing the command:\n"
                    + exc.getMessage());
        }
    }

    // ******************************************************
    // * dispResult                                         *
    // * Display all the columns and rows of the result set *
    // ******************************************************

    private void dispResult (ResultSet rs)
      throws SQLException {

      // This method must be implemented.
    }
}
