/**
 * Client application that fetches random fortunes.
 */

import java.sql.*;
public class Fortune {      
  public static void main (String[] args) {

    try {
      Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
      Connection conn = DriverManager.getConnection("jdbc:derby:fortunes");

      /* Create a statement to execute SQL commands.  */
      Statement s = conn.createStatement();

      /* Execute a query.  */

      ResultSet rs = s.executeQuery("SELECT src, fortune FROM fortunes " 
		+ "WHERE id = tutRand("
		+ "(select min(id) from fortunes), "
		+ "(select max(id) from fortunes))"
		);

      String cookie, fortune;

      /* Step through the results. */
      while (rs.next()) {
	cookie = rs.getString(1);
	fortune = rs.getString(2);
	System.out.println("fortune category=" + cookie);
	System.out.println(fortune);
      }

      /* Explicitly close all objects. */
      rs.close();
      s.close();
      conn.close();
    }

    catch (Throwable e) {
      System.out.println("exception thrown:");
      errorPrint(e);
    }

    try {
	DriverManager.getConnection("jdbc:derby:;shutdown=true");
    } 
    catch (SQLException se) {
              // Successful shutdown produces exception XJ015, which we
	      // can safely ignore.
	      if( ((se).getSQLState()).equals("XJ015") != true)
                   SQLExceptionPrint((SQLException)se);
    }
  }

  static void errorPrint(Throwable e) {
      if (e instanceof SQLException) 
	SQLExceptionPrint((SQLException)e);
      else
	System.out.println("A non SQL error occurred.");
        e.printStackTrace();
  }

  static void SQLExceptionPrint(SQLException sqle) {
      while (sqle != null) {
	System.out.println("\n---SQLException Caught---\n");
	System.out.println("SQLState:   " + (sqle).getSQLState());
	System.out.println("Severity: " + (sqle).getErrorCode());
	System.out.println("Message:  " + (sqle).getMessage()); 
	sqle.printStackTrace();  
	sqle = sqle.getNextException();
      }
  }
}
