@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);
    }
  }
Esempio n. 2
0
  private void runH2Server(final String fileName, final int port, final char[] password) {
    org.h2.tools.Server server = null;

    stop = false;

    try {
      final List<String> serverArgs = new ArrayList<>();

      serverArgs.add("-tcpPort");
      serverArgs.add(String.valueOf(port));
      serverArgs.add("-tcpAllowOthers");

      /*boolean useSSL = Boolean.parseBoolean(System.getProperties().getProperty(EncryptionManager.ENCRYPTION_FLAG));

      if (useSSL) {
          serverArgs.add("-tcpSSL");
      }*/

      server =
          org.h2.tools.Server.createTcpServer(serverArgs.toArray(new String[serverArgs.size()]));
      server.start();

    } catch (SQLException e) {
      Logger.getLogger(JpaNetworkServer.class.getName()).log(Level.SEVERE, e.getMessage(), e);
    }

    // Start the message server and engine, this should block until closed
    if (!run(DataStoreType.H2_DATABASE, fileName, port, password)) {
      Logger.getLogger(JpaNetworkServer.class.getName()).severe("Failed to start the server");
    }

    if (server != null) {
      server.stop();
    }
  }
 public TestPersistenceUnit(int port) {
   try {
     tcpServer = Server.createTcpServer("-tcpPort", "" + port);
   } catch (SQLException e) {
     throw new IllegalStateException(e);
   }
 }
Esempio n. 4
0
  /**
   * 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 {

    // start the server, allows to access the database remotely
    Server server = Server.createTcpServer("-tcpPort", "9081");
    server.start();
    System.out.println("You can access the database remotely now, using the URL:");
    System.out.println("jdbc:h2:tcp://localhost:9081/~/test (user: sa, password: sa)");

    // now use the database in your application in embedded mode
    Class.forName("org.h2.Driver");
    Connection conn = DriverManager.getConnection("jdbc:h2:~/test", "sa", "sa");

    // some simple 'business usage'
    Statement stat = conn.createStatement();
    stat.execute("DROP TABLE TIMER IF EXISTS");
    stat.execute("CREATE TABLE TIMER(ID INT PRIMARY KEY, TIME VARCHAR)");
    System.out.println("Execute this a few times: " + "SELECT TIME FROM TIMER");
    System.out.println("To stop this application " + "(and the server), run: DROP TABLE TIMER");
    try {
      while (true) {
        // runs forever, except if you drop the table remotely
        stat.execute("MERGE INTO TIMER VALUES(1, NOW())");
        Thread.sleep(1000);
      }
    } catch (SQLException e) {
      System.out.println("Error: " + e.toString());
    }
    conn.close();

    // stop the server
    server.stop();
  }
Esempio n. 5
0
  public void contextInitialized(ServletContextEvent servletContextEvent) {
    try {
      org.h2.Driver.load();

      // This will get the setting from a context-param in web.xml if defined:
      ServletContext servletContext = servletContextEvent.getServletContext();
      String url = getParameter(servletContext, "db.url", "jdbc:h2:~/test");
      String user = getParameter(servletContext, "db.user", "sa");
      String password = getParameter(servletContext, "db.password", "sa");

      // Start the server if configured to do so
      String serverParams = getParameter(servletContext, "db.tcpServer", null);
      if (serverParams != null) {
        String[] params = StringUtils.arraySplit(serverParams, ' ', true);
        server = Server.createTcpServer(params);
        server.start();
      }

      // To access the database in server mode, use the database URL:
      // jdbc:h2:tcp://localhost/~/test
      conn = DriverManager.getConnection(url, user, password);
      servletContext.setAttribute("connection", conn);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 /** 启动H2数据库 */
 public void start() {
   try {
     server = Server.createTcpServer().start();
     log.info("h2 DB start..");
   } catch (Exception e) {
     log.error("h2 DB start error!", e);
   }
 }
 @Override
 public void run() {
   log.debug("H2DatabaseServer stared");
   try {
     String[] assembleCommandLine = assembleCommandLine();
     server = Server.createTcpServer(assembleCommandLine).start();
   } catch (SQLException e) {
     throw new TechnicalException(e);
   }
 }
Esempio n. 8
0
 public static Server startH2Server() {
   try {
     // start h2 in memory database
     Server server = Server.createTcpServer(new String[0]);
     server.start();
     return server;
   } catch (Throwable t) {
     throw new RuntimeException("Could not start H2 server", t);
   }
 }
Esempio n. 9
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 startService() {
   try {
     Server.createTcpServer(new String[] {"-tcpAllowOthers"}).start();
   } catch (SQLException e) {
     e.printStackTrace();
   }
   processEngine = ProcessEngines.getDefaultProcessEngine();
   processEngine
       .getRepositoryService()
       .createDeployment()
       .addClasspathResource("process/activiti/humanTask.xml.bpmn20.xml")
       .deploy();
 }
Esempio n. 12
0
 private void testReadOnlyInZip() throws SQLException {
   if (config.cipher != null) {
     return;
   }
   deleteDb("readonlyInZip");
   String dir = getBaseDir();
   Connection conn = getConnection("readonlyInZip");
   Statement stat = conn.createStatement();
   stat.execute("CREATE TABLE TEST(ID INT) AS " + "SELECT X FROM SYSTEM_RANGE(1, 20)");
   conn.close();
   Backup.execute(dir + "/readonly.zip", dir, "readonlyInZip", true);
   conn =
       getConnection(
           "jdbc:h2:zip:" + dir + "/readonly.zip!/readonlyInZip", getUser(), getPassword());
   conn.createStatement().execute("select * from test where id=1");
   conn.close();
   Server server = Server.createTcpServer("-tcpPort", "9081", "-baseDir", dir);
   server.start();
   try {
     conn =
         getConnection(
             "jdbc:h2:tcp://localhost:9081/zip:readonly.zip!/readonlyInZip",
             getUser(),
             getPassword());
     conn.createStatement().execute("select * from test where id=1");
     conn.close();
     FilePathZip2.register();
     conn =
         getConnection(
             "jdbc:h2:tcp://localhost:9081/zip2:readonly.zip!/readonlyInZip",
             getUser(),
             getPassword());
     conn.createStatement().execute("select * from test where id=1");
     conn.close();
   } finally {
     server.stop();
   }
   deleteDb("readonlyInZip");
 }
Esempio n. 13
0
 private void testServer() throws Exception {
   Server server = new Server();
   server.setOut(new PrintStream(new ByteArrayOutputStream()));
   server.runTool("-web", "-webPort", "8182", "-properties", "null", "-tcp", "-tcpPort", "9101");
   try {
     String url = "http://localhost:8182";
     WebClient client;
     String result;
     client = new WebClient();
     client.setAcceptLanguage("de-de,de;q=0.5");
     result = client.get(url);
     client.readSessionId(result);
     result = client.get(url, "login.jsp");
     assertEquals("text/html", client.getContentType());
     assertContains(result, "Einstellung");
     client.get(url, "favicon.ico");
     assertEquals("image/x-icon", client.getContentType());
     client.get(url, "ico_ok.gif");
     assertEquals("image/gif", client.getContentType());
     client.get(url, "tree.js");
     assertEquals("text/javascript", client.getContentType());
     client.get(url, "stylesheet.css");
     assertEquals("text/css", client.getContentType());
     client.get(url, "admin.do");
     try {
       client.get(url, "adminShutdown.do");
     } catch (IOException e) {
       // expected
       Thread.sleep(1000);
     }
   } finally {
     server.shutdown();
   }
   // it should be stopped now
   server = Server.createTcpServer("-tcpPort", "9101");
   server.start();
   server.stop();
 }
Esempio n. 14
0
  private void testOldClientNewServer() throws Exception {
    Server server = org.h2.tools.Server.createTcpServer("-tcpPort", "9001");
    server.start();
    assertThrows(ErrorCode.DRIVER_VERSION_ERROR_2, driver)
        .connect("jdbc:h2:tcp://localhost:9001/mem:test", null);
    server.stop();

    Class<?> serverClass = cl.loadClass("org.h2.tools.Server");
    Method m;
    m = serverClass.getMethod("createTcpServer", String[].class);
    Object serverOld = m.invoke(null, new Object[] {new String[] {"-tcpPort", "9001"}});
    m = serverOld.getClass().getMethod("start");
    m.invoke(serverOld);
    Connection conn;
    conn = org.h2.Driver.load().connect("jdbc:h2:mem:", null);
    Statement stat = conn.createStatement();
    ResultSet rs = stat.executeQuery("call 1");
    rs.next();
    assertEquals(1, rs.getInt(1));
    conn.close();
    m = serverOld.getClass().getMethod("stop");
    m.invoke(serverOld);
  }
  @Test
  public void submitJob() throws Exception {
    org.h2.tools.Server h2 = org.h2.tools.Server.createTcpServer();
    Server server = new Server();
    Connector connector = new SelectChannelConnector();
    connector.setPort(8081);
    connector.setHost("127.0.0.1");
    server.addConnector(connector);

    WebAppContext wac = new WebAppContext();
    wac.setContextPath("/springbatchadmin");
    wac.setWar("./src/main/webapp");
    server.setHandler(wac);
    server.setStopAtShutdown(true);

    try {
      h2.start();
      server.start();
      assertTrue(restTemplate.getForObject(BASE_URL + "jobs.json", String.class).contains(JOB));
    } finally {
      server.stop();
      h2.stop();
    }
  }
 /** Open the TCP port for the H2 database, so it is available remotely. */
 @Bean(initMethod = "start", destroyMethod = "stop")
 public Server h2TCPServer() throws SQLException {
   return Server.createTcpServer("-tcp", "-tcpAllowOthers");
 }
  // @BeforeClass
  public static void startDb() throws SQLException {
    System.out.println("Starting DB server");

    server = Server.createTcpServer(null).start();
  }
Esempio n. 18
0
  public static void main(String[] args) {
    try {
      File dataDir = new File("target/h2");
      String url = "jdbc:h2:tcp://localhost:9092/apiman";

      if (dataDir.exists()) {
        FileUtils.deleteDirectory(dataDir);
      }
      dataDir.mkdirs();

      Server.createTcpServer(
              "-tcpPassword",
              "sa",
              "-baseDir",
              dataDir.getAbsolutePath(),
              "-tcpPort",
              "9092",
              "-tcpAllowOthers")
          .start();
      Class.forName("org.h2.Driver");

      try (Connection connection = DriverManager.getConnection(url, "sa", "")) {
        System.out.println(
            "Connection Established: "
                + connection.getMetaData().getDatabaseProductName()
                + "/"
                + connection.getCatalog());
        executeUpdate(
            connection,
            "CREATE TABLE users ( username varchar(255) NOT NULL, password varchar(255) NOT NULL, PRIMARY KEY (username))");
        executeUpdate(
            connection,
            "INSERT INTO users (username, password) VALUES ('bwayne', 'ae2efd698aefdf366736a4eda1bc5241f9fbfec7')");
        executeUpdate(
            connection,
            "INSERT INTO users (username, password) VALUES ('ckent', 'ea59f7ca52a2087c99374caba0ff29be1b2dcdbf')");
        executeUpdate(
            connection,
            "INSERT INTO users (username, password) VALUES ('ballen', 'ea59f7ca52a2087c99374caba0ff29be1b2dcdbf')");
        executeUpdate(
            connection,
            "CREATE TABLE roles (rolename varchar(255) NOT NULL, username varchar(255) NOT NULL)");
        executeUpdate(
            connection, "INSERT INTO roles (rolename, username) VALUES ('user', 'bwayne')");
        executeUpdate(
            connection, "INSERT INTO roles (rolename, username) VALUES ('admin', 'bwayne')");
        executeUpdate(
            connection, "INSERT INTO roles (rolename, username) VALUES ('ckent', 'user')");
        executeUpdate(
            connection, "INSERT INTO roles (rolename, username) VALUES ('ballen', 'user')");
      }

      System.out.println("======================================================");
      System.out.println("JDBC (H2) server started successfully.");
      System.out.println("");
      System.out.println("  Data: " + dataDir.getAbsolutePath());
      System.out.println("  JDBC URL: " + url);
      System.out.println("  JDBC User: sa");
      System.out.println("  JDBC Password: "******"  Authentication Query:   SELECT * FROM users u WHERE u.username = ? AND u.password = ?");
      System.out.println(
          "  Authorization Query:    SELECT r.rolename FROM roles r WHERE r.username = ?");
      System.out.println("======================================================");
      System.out.println("");
      System.out.println("");
      System.out.println("Press Enter to stop the JDBC server.");
      new BufferedReader(new InputStreamReader(System.in)).readLine();

      System.out.println("Shutting down the JDBC server...");

      Server.shutdownTcpServer("tcp://localhost:9092", "", true, true);

      System.out.println("Done!");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Esempio n. 19
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();
  }
Esempio n. 20
0
  private void testCreateClusterAtRuntime() throws SQLException {
    if (config.memory || config.networked || config.cipher != null) {
      return;
    }
    int port1 = 9191, port2 = 9192;
    String serverList = "localhost:" + port1 + ",localhost:" + port2;
    deleteFiles();

    org.h2.Driver.load();
    String user = getUser(), password = getPassword();
    Connection conn;
    Statement stat;
    String url1 = "jdbc:h2:tcp://localhost:" + port1 + "/test";
    String url2 = "jdbc:h2:tcp://localhost:" + port2 + "/test";
    String urlCluster = "jdbc:h2:tcp://" + serverList + "/test";
    int len = 10;

    // initialize the database
    Server n1 =
        org.h2.tools.Server.createTcpServer(
                "-tcpPort", "" + port1, "-baseDir", getBaseDir() + "/node1")
            .start();
    conn = DriverManager.getConnection(url1, user, password);
    stat = conn.createStatement();
    stat.execute(
        "create table test(id int primary key, name varchar) as "
            + "select x, 'Data' || x from system_range(0, "
            + (len - 1)
            + ")");
    stat.execute("create user test password 'test'");
    stat.execute("grant all on test to test");

    // start the second server
    Server n2 =
        org.h2.tools.Server.createTcpServer(
                "-tcpPort", "" + port2, "-baseDir", getBaseDir() + "/node2")
            .start();

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

    // check the original connection is closed
    try {
      stat.execute("select * from test");
      fail();
    } catch (SQLException e) {
      // expected
      JdbcUtils.closeSilently(conn);
    }

    // test the cluster connection
    Connection connApp =
        DriverManager.getConnection(urlCluster + ";AUTO_RECONNECT=TRUE", user, password);
    check(connApp, len, "'" + serverList + "'");

    // delete the rows, but don't commit
    connApp.setAutoCommit(false);
    connApp.createStatement().execute("delete from test");

    // stop server 2, and test if only one server is available
    n2.stop();

    // rollback the transaction
    connApp.createStatement().executeQuery("select count(*) from test");
    connApp.rollback();
    check(connApp, len, "''");
    connApp.setAutoCommit(true);

    // re-create the cluster
    n2 =
        org.h2.tools.Server.createTcpServer(
                "-tcpPort", "" + port2, "-baseDir", getBaseDir() + "/node2")
            .start();
    CreateCluster.main(
        "-urlSource",
        url1,
        "-urlTarget",
        url2,
        "-user",
        user,
        "-password",
        password,
        "-serverList",
        serverList);

    // test the cluster connection
    check(connApp, len, "'" + serverList + "'");

    // test a non-admin user
    String user2 = "test", password2 = getPassword("test");
    connApp = DriverManager.getConnection(urlCluster, user2, password2);
    check(connApp, len, "'" + serverList + "'");

    n1.stop();

    // test non-admin cluster connection if only one server runs
    Connection connApp2 =
        DriverManager.getConnection(urlCluster + ";AUTO_RECONNECT=TRUE", user2, password2);
    check(connApp2, len, "''");
    connApp2.close();
    // test non-admin cluster connection if only one server runs
    connApp2 = DriverManager.getConnection(urlCluster + ";AUTO_RECONNECT=TRUE", user2, password2);
    check(connApp2, len, "''");
    connApp2.close();

    n2.stop();
    deleteFiles();
  }
 private void startServer() throws SQLException {
   h2Server = Server.createTcpServer().start();
 }
Esempio n. 22
0
 /** Open the TCP port for the H2 database, so it is available remotely. */
 @Bean(initMethod = "start", destroyMethod = "stop")
 @Profile(Constants.SPRING_PROFILE_DEVELOPMENT)
 public Server h2TCPServer() throws SQLException {
   return Server.createTcpServer("-tcp", "-tcpAllowOthers");
 }
 @BeforeClass
 public static void startH2Database() throws Exception {
   DeleteDbFiles.execute("", "DroolsFlow", true);
   h2Server = Server.createTcpServer(new String[0]);
   h2Server.start();
 }
 @Bean(initMethod = "start", destroyMethod = "stop")
 public Server embeddedDatabase() throws SQLException {
   return Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpShutdownForce");
 }