@BeforeClass
  public static void startH2Database() throws Exception {
    DeleteDbFiles.execute("", "DroolsFlow", true);
    h2Server = Server.createTcpServer(new String[0]);
    h2Server.start();
    try {
      TMPDIR =
          JPASingleSessionCommandServiceFactoryEnvTest.class
              .getResource("/kb_persistence")
              .getFile();
      log.info("creating: {}", TMPDIR + "/processWorkItems.pkg");
      writePackage(getProcessWorkItems(), new File(TMPDIR + "/processWorkItems.pkg"));

      log.info("creating: {}", TMPDIR + "/processSubProcess.pkg");
      writePackage(getProcessSubProcess(), new File(TMPDIR + "/processSubProcess.pkg"));

      log.info("creating: {}", TMPDIR + "/processTimer.pkg");
      writePackage(getProcessTimer(), new File(TMPDIR + "/processTimer.pkg"));

      log.info("creating: {}", TMPDIR + "/processTimer2.pkg");
      writePackage(getProcessTimer2(), new File(TMPDIR + "/processTimer2.pkg"));
    } catch (Exception e) {
      log.error("can't create packages!", e);
      throw new RuntimeException(e);
    }
  }
 @AfterClass
 public static void exitH2() throws SQLException {
   if (h2Server != null) {
     h2Server.stop();
   }
   DeleteDbFiles.execute("", "JPADroolsFlow", true);
 }
예제 #3
0
 @Override
 protected void finalize() throws Throwable {
   if (realH2Server != null) {
     realH2Server.stop();
   }
   DeleteDbFiles.execute("", "JPADroolsFlow", true);
   super.finalize();
 }
예제 #4
0
  /**
   * Called when ran from command line.
   *
   * @param args ignored
   */
  public static void main(String... args) throws Exception {
    DeleteDbFiles.execute("~", "test", true);

    Class.forName("org.h2.Driver");
    Connection conn = DriverManager.getConnection("jdbc:h2:~/test");
    Statement stat = conn.createStatement();

    stat.execute(
        "create table test_data(id int, user varchar, data varchar, primary key(id, user))");
    stat.execute("create index on test_data(id, user)");

    stat.execute("create view test as select id, data from test_data where user = user()");
    stat.execute(
        "create trigger t_test instead of "
            + "insert, update, delete on test for each row "
            + "call \""
            + RowAccessRights.class.getName()
            + "\"");
    stat.execute("create user a password 'a'");
    stat.execute("create user b password 'b'");
    stat.execute("grant all on test to a");
    stat.execute("grant all on test to b");

    ResultSet rs;

    Connection connA = DriverManager.getConnection("jdbc:h2:~/test", "a", "a");
    Statement statA = connA.createStatement();
    statA.execute("insert into test values(1, 'Hello'), (2, 'World')");
    statA.execute("update test set data = 'Hello!' where id = 1");
    statA.execute("delete from test where id = 2");

    Connection connB = DriverManager.getConnection("jdbc:h2:~/test", "b", "b");
    Statement statB = connB.createStatement();
    statB.execute("insert into test values(1, 'Hallo'), (2, 'Welt')");
    statB.execute("update test set data = 'Hallo!' where id = 1");
    statB.execute("delete from test where id = 2");

    rs = statA.executeQuery("select * from test");
    while (rs.next()) {
      System.out.println("a: " + rs.getInt(1) + "/" + rs.getString(2));
    }

    rs = statB.executeQuery("select * from test");
    while (rs.next()) {
      System.out.println("b: " + rs.getInt(1) + "/" + rs.getString(2));
    }

    connA.close();
    connB.close();

    rs = stat.executeQuery("select * from test_data");
    while (rs.next()) {
      System.out.println(rs.getInt(1) + "/" + rs.getString(2) + "/" + rs.getString(3));
    }
    conn.close();
  }
예제 #5
0
 public void start() {
   if (realH2Server == null || !realH2Server.isRunning(false)) {
     try {
       DeleteDbFiles.execute("", "JPADroolsFlow", true);
       realH2Server = Server.createTcpServer(new String[0]);
       realH2Server.start();
     } catch (SQLException e) {
       throw new RuntimeException("can't start h2 server db", e);
     }
   }
 }
 @BeforeClass
 public static void initH2() {
   try {
     DeleteDbFiles.execute("", "JPADroolsFlow", true);
     h2Server = Server.createTcpServer(new String[0]);
     h2Server.start();
   } catch (final SQLException e) {
     throw new RuntimeException("can't start h2 server db", e);
   }
   DOMConfigurator.configure(SingleSessionCommandServiceTest.class.getResource("/log4j.xml"));
 }
 public void compact() {
   LOGGER.info("Compacting database...");
   PMS.get().getFrame().setStatusLine(Messages.getString("DLNAMediaDatabase.3"));
   String filename = "database/backup.sql";
   try {
     Script.execute(url, "sa", "", filename);
     DeleteDbFiles.execute(dbDir, dbName, true);
     RunScript.execute(url, "sa", "", filename, null, false);
   } catch (SQLException se) {
     LOGGER.error("Error in compacting database: ", se);
   } finally {
     File testsql = new File(filename);
     if (testsql.exists() && !testsql.delete()) {
       testsql.deleteOnExit();
     }
   }
   PMS.get().getFrame().setStatusLine(null);
 }
예제 #8
0
  public static void main(String[] args) throws ClassNotFoundException, SQLException {
    // delete the database named 'test' in the user home directory
    DeleteDbFiles.execute("~", "test", true);

    Class.forName("org.h2.Driver");
    Connection conn = DriverManager.getConnection("jdbc:h2:~/test");
    Statement stat = conn.createStatement();

    // this line would initialize the database
    // from the SQL script file 'init.sql'
    // stat.execute("runscript from 'init.sql'");

    stat.execute("create table test(id int primary key, name varchar(255))");
    stat.execute("insert into test values(1, 'Hello')");
    ResultSet rs;
    rs = stat.executeQuery("select * from test");
    while (rs.next()) {
      System.out.println(rs.getString("name"));
    }
    stat.close();
  }
 private static void test() throws SQLException {
   DeleteDbFiles.execute("data", "test", true);
   Connection conn = DriverManager.getConnection("jdbc:h2:data/test");
   Statement stat = conn.createStatement();
   stat.execute("set max_operation_memory 100");
   stat.execute("set max_memory_undo 100");
   stat.execute("create table test(id identity, name varchar)");
   conn.setAutoCommit(false);
   PreparedStatement prep =
       conn.prepareStatement("insert into test(name) values(space(1024*1024))");
   long time = System.currentTimeMillis();
   for (int i = 0; i < 2500; i++) {
     prep.execute();
     long now = System.currentTimeMillis();
     if (now > time + 5000) {
       System.out.println(i);
       time = now + 5000;
     }
   }
   conn.rollback();
   conn.close();
 }
  /**
   * This method is called when executing this sample application from the command line.
   *
   * @param args the command line parameters
   */
  public static void main(String... args) throws Exception {

    // delete all files in this directory
    FileUtils.deleteRecursive("~/temp", false);

    Connection conn;
    Class.forName("org.h2.Driver");

    // create a database where the database file is split into
    // multiple small files, 4 MB each (2^22). The larger the
    // parts, the faster opening the database, but also the
    // more files. 4 MB seems to be a good compromise, so
    // the prefix split:22: is used, which means each part is
    // 2^22 bytes long
    conn = DriverManager.getConnection("jdbc:h2:split:22:~/temp/test");

    System.out.println("adding test data...");
    Statement stat = conn.createStatement();
    stat.execute(
        "create table test(id int primary key, name varchar) "
            + "as select x, space(1000) from system_range(1, 2000)");

    System.out.println("defrag to reduce random access...");
    stat.execute("shutdown defrag");
    conn.close();

    System.out.println("create the zip file...");
    Backup.execute("~/temp/test.zip", "~/temp", "", true);

    // delete the old database files
    DeleteDbFiles.execute("split:~/temp", "test", true);

    System.out.println("open the database from the zip file...");
    conn = DriverManager.getConnection("jdbc:h2:split:zip:~/temp/test.zip!/test");
    // the database can now be used
    conn.close();
  }
예제 #11
0
 @AfterClass
 public static void destroy() throws Exception {
   ctx.close();
   DeleteDbFiles.execute(".", "geoserver", false);
 }
예제 #12
0
 private void deleteFiles() throws SQLException {
   DeleteDbFiles.main("-dir", getBaseDir() + "/node1", "-quiet");
   DeleteDbFiles.main("-dir", getBaseDir() + "/node2", "-quiet");
   IOUtils.delete(getBaseDir() + "/node1");
   IOUtils.delete(getBaseDir() + "/node2");
 }
예제 #13
0
  private void testStartStopCluster() throws SQLException {
    if (config.memory || config.networked || config.cipher != null) {
      return;
    }
    int port1 = 9193, port2 = 9194;
    String serverList = "localhost:" + port1 + ",localhost:" + port2;
    deleteFiles();

    // initialize the database
    Connection conn;
    org.h2.Driver.load();

    String urlNode1 = getURL("node1/test", true);
    String urlNode2 = getURL("node2/test", true);
    String user = getUser(), password = getPassword();
    conn = DriverManager.getConnection(urlNode1, user, password);
    Statement stat;
    stat = conn.createStatement();
    stat.execute("DROP TABLE IF EXISTS TEST");
    stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))");
    PreparedStatement prep = conn.prepareStatement("INSERT INTO TEST VALUES(?, ?)");
    int len = getSize(10, 1000);
    for (int i = 0; i < len; i++) {
      prep.setInt(1, i);
      prep.setString(2, "Data" + i);
      prep.executeUpdate();
    }
    check(conn, len, "''");
    conn.close();

    // copy the database and initialize the cluster
    CreateCluster.main(
        "-urlSource",
        urlNode1,
        "-urlTarget",
        urlNode2,
        "-user",
        user,
        "-password",
        password,
        "-serverList",
        serverList);

    // start both servers
    Server n1 =
        org.h2.tools.Server.createTcpServer(
                "-tcpPort", "" + port1, "-baseDir", getBaseDir() + "/node1")
            .start();
    Server n2 =
        org.h2.tools.Server.createTcpServer(
                "-tcpPort", "" + port2, "-baseDir", getBaseDir() + "/node2")
            .start();

    // try to connect in standalone mode - should fail
    try {
      conn =
          DriverManager.getConnection("jdbc:h2:tcp://localhost:" + port1 + "/test", user, password);
      fail("should not be able to connect in standalone mode");
    } catch (SQLException e) {
      assertKnownException(e);
    }
    try {
      DriverManager.getConnection("jdbc:h2:tcp://localhost:" + port2 + "/test", user, password);
      fail("should not be able to connect in standalone mode");
    } catch (SQLException e) {
      assertKnownException(e);
    }

    // test a cluster connection
    conn = DriverManager.getConnection("jdbc:h2:tcp://" + serverList + "/test", user, password);
    check(conn, len, "'" + serverList + "'");
    conn.close();

    // stop server 2, and test if only one server is available
    n2.stop();
    conn = DriverManager.getConnection("jdbc:h2:tcp://" + serverList + "/test", user, password);
    check(conn, len, "''");
    conn.close();
    conn = DriverManager.getConnection("jdbc:h2:tcp://" + serverList + "/test", user, password);
    check(conn, len, "''");
    conn.close();

    // disable the cluster
    conn =
        DriverManager.getConnection(
            "jdbc:h2:tcp://localhost:" + port1 + "/test;CLUSTER=''", user, password);
    conn.close();
    n1.stop();

    // re-create the cluster
    DeleteDbFiles.main("-dir", getBaseDir() + "/node2", "-quiet");
    CreateCluster.main(
        "-urlSource",
        urlNode1,
        "-urlTarget",
        urlNode2,
        "-user",
        user,
        "-password",
        password,
        "-serverList",
        serverList);
    n1 =
        org.h2.tools.Server.createTcpServer(
                "-tcpPort", "" + port1, "-baseDir", getBaseDir() + "/node1")
            .start();
    n2 =
        org.h2.tools.Server.createTcpServer(
                "-tcpPort", "" + port2, "-baseDir", getBaseDir() + "/node2")
            .start();

    conn = DriverManager.getConnection("jdbc:h2:tcp://" + serverList + "/test", user, password);
    stat = conn.createStatement();
    stat.execute("CREATE TABLE BOTH(ID INT)");

    n1.stop();

    stat.execute("CREATE TABLE A(ID INT)");
    conn.close();
    n2.stop();

    n1 =
        org.h2.tools.Server.createTcpServer(
                "-tcpPort", "" + port1, "-baseDir", getBaseDir() + "/node1")
            .start();
    conn =
        DriverManager.getConnection(
            "jdbc:h2:tcp://localhost:" + port1 + "/test;CLUSTER=''", user, password);
    check(conn, len, "''");
    conn.close();
    n1.stop();

    n2 =
        org.h2.tools.Server.createTcpServer(
                "-tcpPort", "" + port2, "-baseDir", getBaseDir() + "/node2")
            .start();
    conn =
        DriverManager.getConnection(
            "jdbc:h2:tcp://localhost:" + port2 + "/test;CLUSTER=''", user, password);
    check(conn, len, "''");
    conn.createStatement().execute("SELECT * FROM A");
    conn.close();
    n2.stop();
    deleteFiles();
  }
  private SymfonyDbFactory() throws Exception {
    try {
      Class.forName("org.h2.Driver");
    } catch (ClassNotFoundException e) {
      Logger.logException(e);
    }

    IPath dbPath = SymfonyIndex.getDefault().getStateLocation();

    String connString = getConnectionString(dbPath);

    pool = JdbcConnectionPool.create(connString, DB_USER, DB_PASS);

    Schema schema = new Schema();
    boolean initializeSchema = false;

    int tries = 2; // Tries for opening database
    Connection connection = null;
    do {
      try {
        connection = pool.getConnection();
        try {
          Statement statement = connection.createStatement();
          try {
            statement.executeQuery("SELECT COUNT(*) FROM SERVICES WHERE 1=0;");
            initializeSchema = !schema.isCompatible();

          } catch (SQLException e) {
            // Basic table doesn't exist
            initializeSchema = true;
          } finally {
            statement.close();
          }

          if (initializeSchema) {
            connection.close();
            pool.dispose();
            // Destroy schema by removing DB (if exists)
            DeleteDbFiles.execute(dbPath.toOSString(), DB_NAME, true);

            pool = JdbcConnectionPool.create(connString, DB_USER, DB_PASS);
            connection = pool.getConnection();
            schema.initialize(connection);
          }
        } finally {
          if (connection != null) {
            connection.close();
          }
        }
      } catch (SQLException e) {

        Logger.logException(e);

        // remove corrupted DB
        try {
          DeleteDbFiles.execute(dbPath.toOSString(), DB_NAME, true);

        } catch (Exception e1) {

          Logger.logException(e1);
          throw e1;
        }
      }
    } while (connection == null && --tries > 0);
  }
예제 #15
0
 private static void dropDB() {
   DeleteDbFiles.execute("~", "test", true);
 }
 @AfterClass
 public static void stopH2Database() throws Exception {
   log.info("stopping database");
   h2Server.stop();
   DeleteDbFiles.execute("", "DroolsFlow", true);
 }
예제 #17
0
  /**
   * Run one test. The controller starts the process, waits, kills the process, and checks if
   * everything is ok.
   */
  void controllerTest() throws Exception {
    traceOperation("delete database -----------------------------");
    DeleteDbFiles.execute(getBaseDir(), DATABASE_NAME, true);
    new File(getBaseDir() + "/" + TRACE_FILE_NAME).delete();

    connect();
    controllerInit();
    disconnect();
    for (int i = 0; i < 10; i++) {
      traceOperation("backing up " + sequenceId);
      Backup.execute(getBaseDir() + "/haltSeq" + sequenceId + ".zip", getBaseDir(), null, true);
      sequenceId++;
      // int operations = OP_INSERT;
      // OP_DELETE = 1, OP_UPDATE = 2, OP_SELECT = 4;
      // int flags = FLAG_NODELAY;
      // FLAG_NO_DELAY = 1, FLAG_AUTO_COMMIT = 2, FLAG_SMALL_CACHE = 4;
      int testValue = random.nextInt(1000);
      // for Derby and HSQLDB
      // String classPath = "-cp
      // .;D:/data/java/hsqldb.jar;D:/data/java/derby.jar";
      String selfDestruct = SelfDestructor.getPropertyString(60);
      String[] procDef = {
        "java",
        selfDestruct,
        "-cp",
        getClassPath(),
        getClass().getName(),
        "" + operations,
        "" + flags,
        "" + testValue
      };
      traceOperation("start: " + StringUtils.arrayCombine(procDef, ' '));
      Process p = Runtime.getRuntime().exec(procDef);
      InputStream in = p.getInputStream();
      OutputCatcher catcher = new OutputCatcher(in);
      catcher.start();
      String s = catcher.readLine(5 * 60 * 1000);
      if (s == null) {
        throw new IOException(
            "No reply from process, command: " + StringUtils.arrayCombine(procDef, ' '));
      } else if (s.startsWith("READY")) {
        traceOperation("got reply: " + s);
      }
      controllerWaitAfterAppStart();
      p.destroy();
      p.waitFor();
      try {
        traceOperation("backing up " + sequenceId);
        Backup.execute(getBaseDir() + "/haltSeq" + sequenceId + ".zip", getBaseDir(), null, true);
        // new File(BASE_DIR + "/haltSeq" + (sequenceId-20) +
        // ".zip").delete();
        connect();
        controllerCheckAfterCrash();
      } catch (Exception e) {
        File zip = new File(getBaseDir() + "/haltSeq" + sequenceId + ".zip");
        File zipId = new File(getBaseDir() + "/haltSeq" + sequenceId + "-" + errorId + ".zip");
        zip.renameTo(zipId);
        printTime("ERROR: " + sequenceId + " " + errorId + " " + e.toString());
        e.printStackTrace();
        errorId++;
      } finally {
        sequenceId++;
        disconnect();
      }
    }
  }
 @BeforeClass
 public static void startH2Database() throws Exception {
   DeleteDbFiles.execute("", "DroolsFlow", true);
   h2Server = Server.createTcpServer(new String[0]);
   h2Server.start();
 }