/**
 *      sample2 JDBC sample applet
 *
 *      Sep 24 1997 JP
 *
 *      This simple JDBC applet does the following using
 *      Solid native JDBC driver. 
 *  
 *  1. Registers the driver using JDBC driver manager services
 *  2. Connects to Solid Server using the driver.
 *     Used url is read from sample2.html
 *  3. Executes given SQL statements
 *
 *  To build and run the application 
 *
 *  1. Make sure you have a working Java Development environment
 *  2. Install and start Solid Server to connect. Ensure that the Server 
 *     is up and running.
 *  3. Append SolidDriver.zip into the CLASSPATH definition used 
 *     by your development/running environment. 
 *  4. Create a java project based on the file sample2.java. 
 *  5. Build and run the application. Check that sample2.html
 *     defines valid url to your environment.
 * 
 *  For more information read the readme.htm file contained by
 *  SOLID JDBC Driver package.
 *
 */

import java.util.*;
import java.awt.*;
import java.applet.Applet;
import java.net.URL;
import java.sql.*;

public class sample2 extends Applet {
    TextField textField;
    static TextArea textArea;

    String url = null;
    Connection con = null;

    public void init() {
        // a valid value for url could be
        // url = "jdbc:solid://localhost:1313/dba/dba";
	
        url = getParameter("url");

        textField = new TextField(40);
        textArea = new TextArea(10, 40);
        textArea.setEditable(false);

        Font font = textArea.getFont();
        Font newfont = new Font("Monospaced", font.PLAIN, 12);
        textArea.setFont(newfont);

        // Add Components to the Applet. 
        GridBagLayout gridBag = new GridBagLayout();
        setLayout(gridBag);
        GridBagConstraints c = new GridBagConstraints();
        c.gridwidth = GridBagConstraints.REMAINDER;

        c.fill = GridBagConstraints.HORIZONTAL;
        gridBag.setConstraints(textField, c);
        add(textField);

        c.fill = GridBagConstraints.BOTH;
        c.weightx = 1.0;
        c.weighty = 1.0;
        gridBag.setConstraints(textArea, c);
        add(textArea);

        validate();

        try {
            // Load the SOLID JDBC Driver
            Driver d = (Driver)Class.forName ("solid.jdbc.SolidDriver").newInstance();

            // Attempt to connect to a driver.
            con = DriverManager.getConnection (url);

            // If we were unable to connect, an exception
            // would have been thrown.  So, if we get here,
            // we are successfully connected to the url

            // Check for, and display and warnings generated
            // by the connect.
            checkForWarning (con.getWarnings ());

            // Get the DatabaseMetaData object and display
            // some information about the connection
            DatabaseMetaData dma = con.getMetaData ();

            textArea.appendText("Connected to " + dma.getURL() + "\n");
            textArea.appendText("Driver       " + dma.getDriverName() + "\n");
            textArea.appendText("Version      " + dma.getDriverVersion() + "\n");
        }
        catch (SQLException ex) {
            printSQLException(ex);
        }
        catch (Exception e) {
            textArea.appendText("Exception:  " + e + "\n");
        }
    }

    public void destroy() {
        if (con != null) {
            try {
                con.close();
            }
            catch (SQLException ex) {
                printSQLException(ex);
            }
            catch (Exception e) {
                textArea.appendText("Exception:  " + e + "\n");
            }
        }
    }

    public boolean action(Event evt, Object arg) {
        if (con != null) {
            String sqlstmt = textField.getText();
            textArea.setText("");
            try {
                // Create a Statement object so we can submit
                // SQL statements to the driver
                Statement stmt = con.createStatement ();
                // set row limit
                stmt.setMaxRows(50);
                // Submit a query, creating a ResultSet object
                ResultSet rs = stmt.executeQuery (sqlstmt);

                // Display all columns and rows from the result set
                textArea.setVisible(false);
                dispResultSet (stmt,rs);
                textArea.setVisible(true);

                // Close the result set
                rs.close();

                // Close the statement
                stmt.close();
            }
            catch (SQLException ex) {
                printSQLException(ex);
            }
            catch (Exception e) {
                textArea.appendText("Exception:  " + e + "\n");
            }
            textField.selectAll();
        }
        return true;
    }

    //-------------------------------------------------------------------
    // checkForWarning
    // Checks for and displays warnings.  Returns true if a warning
    // existed
    //-------------------------------------------------------------------

    private static boolean checkForWarning (SQLWarning warn)
            throws SQLException
    {
        boolean rc = false;

        // If a SQLWarning object was given, display the
        // warning messages.  Note that there could be
        // multiple warnings chained together

        if (warn != null) {
            textArea.appendText("\n*** Warning ***\n");
            rc = true;
            while (warn != null) {
                textArea.appendText("SQLState: " +
                    warn.getSQLState () + "\n");
                textArea.appendText("Message:  " +
                    warn.getMessage () + "\n");
                textArea.appendText("Vendor:   " +
                    warn.getErrorCode () + "\n");
                textArea.appendText("\n");
                warn = warn.getNextWarning ();
            }
        }
        return rc;
    }

    //-------------------------------------------------------------------
    // dispResultSet
    // Displays all columns and rows in the given result set
    //-------------------------------------------------------------------

    private static void dispResultSet (Statement sta, ResultSet rs)
        throws SQLException
    {
        int i;

        // Get the ResultSetMetaData.  This will be used for
        // the column headings
        ResultSetMetaData rsmd = rs.getMetaData ();

        // Get the number of columns in the result set
        int numCols = rsmd.getColumnCount ();
        if (numCols == 0) {
            textArea.appendText("Updatecount is "+sta.getUpdateCount());
            return;
        }

        // Display column headings
        for (i=1; i<=numCols; i++) {
            if (i > 1) {
                textArea.appendText("\t");
            }
            try {
                textArea.appendText(rsmd.getColumnLabel(i));
            }
            catch(NullPointerException ex) {
                textArea.appendText("null");
            }
        }
        textArea.appendText("\n");
        
        // Display data, fetching until end of the result set
        boolean more = rs.next ();
        while (more) {

            // Loop through each column, get the 
            // column datza and display it
            for (i=1; i<=numCols; i++) {
                if (i > 1) {
                    textArea.appendText("\t");
                }
                try {
                    textArea.appendText(rs.getString(i));
                }
                catch(NullPointerException ex) {
                    textArea.appendText("null");
                }
            }
            textArea.appendText("\n");

            // Fetch the next result set row
            more = rs.next ();
        }
    }

    private static void printSQLException(SQLException ex)
    {
            // A SQLException was generated.  Catch it and
            // display the error information.  Note that there
            // could be multiple error objects chained
            // together

            textArea.appendText("\n*** SQLException caught ***\n");

            while (ex != null) {
                textArea.appendText("SQLState: " +
                    ex.getSQLState () + "\n");
                textArea.appendText("Message:  " +
                    ex.getMessage () + "\n");
                textArea.appendText("Vendor:   " +
                    ex.getErrorCode () + "\n");
                textArea.appendText("\n");
                ex = ex.getNextException ();
            }
    }
}

