import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DerbySimpleOpenClose {
  private static final String DERBY_SHUTDOWN_OK_SQLSTATE="08006";
  private static final String DB_PATH = "/testDBHome/simpleDerbyTest";

  public static void main(String[] args) throws Exception {
    // start up the embedded db engine
    //
    System.out.println("Starting up embedded engine");
    Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
    System.out.println("Done loading embedded engine");

    // open the db the first time creating if necessary then close
    //
    openDB(DB_PATH);
    shutdownDB(DB_PATH);

    // prompt to continue to clear/start dtrace
    //
    System.out.println("press enter to open/close db again...");
    System.in.read();

    // open the db the first time creating if necessary then close
    //
    openDB(DB_PATH);
    shutdownDB(DB_PATH);

  }

  static void openDB(String dbPath) throws SQLException {
    System.out.println("opening database '" + dbPath + "'");
    String jdbcUrl = "jdbc:derby:" + dbPath + ";create=true";
    final long startNS = System.nanoTime();
    Connection con = DriverManager.getConnection(jdbcUrl);
    final long timeMS = (System.nanoTime() - startNS) / 1000000;
    System.out.println("opened db - time (ms): " + timeMS);
    con.close();
  }

  static void shutdownDB(String path) throws SQLException {
    System.out.println("shutting down db '" + path + "'");
    // Derby throws an exception to show that it is shutdown
    final long startNS = System.nanoTime();
    try {
      DriverManager.getConnection("jdbc:derby:" + path + ";shutdown=true;");
    } catch (SQLException e) {
      if (!DERBY_SHUTDOWN_OK_SQLSTATE.equals(e.getSQLState())) {
        throw e;
      }
    }
    final long timeMS = (System.nanoTime() - startNS) / 1000000;
    System.out.println("database shutdown, time (ms): " + timeMS);
  }

}
