Exemplo n.º 1
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();
    }
  }
Exemplo n.º 2
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();
    }
  }
Exemplo n.º 3
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();
  }
Exemplo n.º 4
0
 private void testTransfer() throws Exception {
   Server server = new Server();
   server.setOut(new PrintStream(new ByteArrayOutputStream()));
   server.runTool("-web", "-webPort", "8182", "-properties", "null");
   File transfer = new File("transfer");
   transfer.mkdirs();
   try {
     FileOutputStream f = new FileOutputStream("transfer/test.txt");
     f.write("Hello World".getBytes());
     f.close();
     WebClient client = new WebClient();
     String url = "http://localhost:8182";
     String result = client.get(url);
     client.readSessionId(result);
     String test = client.get(url, "transfer/test.txt");
     assertEquals("Hello World", test);
     new File("transfer/testUpload.txt").delete();
     client.upload(
         url + "/transfer/testUpload.txt",
         "testUpload.txt",
         new ByteArrayInputStream("Hallo Welt".getBytes()));
     byte[] d = IOUtils.readBytesAndClose(new FileInputStream("transfer/testUpload.txt"), -1);
     assertEquals("Hallo Welt", new String(d));
     new File("transfer/testUpload.txt").delete();
   } finally {
     server.shutdown();
     FileUtils.deleteRecursive("transfer", true);
   }
 }
  @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);
    }
  }
Exemplo n.º 6
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);
   }
 }
Exemplo n.º 7
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"));
 }
  @Action(
      value = "h2-db-web-console-tab-content",
      results = {@Result(name = "tab", location = "h2-db-web-console-tab-content.jsp")})
  @SkipValidation
  public String tab() throws Exception {
    Server server = (Server) application.get("h2DbWebServer");
    if (server != null && server.isRunning(false)) {
      h2DbWebServerRunning = true;
    } else {
      h2DbWebServerRunning = false;
    }

    return "tab";
  }
Exemplo n.º 10
0
  @Action(
      value = "h2-db-web-console-stop",
      results = {@Result(name = "sucess", location = "h2-db-web-console-start.jsp")})
  @SkipValidation
  public String stop() throws Exception {
    synchronized (lock) {
      Server server = (Server) application.get("h2DbWebServer");
      if (server != null && server.isRunning(false)) {
        server.stop();
      }
    }

    return "sucess";
  }
Exemplo n.º 11
0
 private void testAlreadyRunning() throws Exception {
   Server server = Server.createWebServer("-webPort", "8182", "-properties", "null");
   server.start();
   assertTrue(server.getStatus().indexOf("server running") >= 0);
   Server server2 = Server.createWebServer("-webPort", "8182", "-properties", "null");
   assertEquals("Not started", server2.getStatus());
   try {
     server2.start();
     fail();
   } catch (Exception e) {
     assertTrue(e.toString().indexOf("port may be in use") >= 0);
     assertTrue(server2.getStatus().indexOf("could not be started") >= 0);
   }
   server.stop();
 }
 @AfterClass
 public static void exitH2() throws SQLException {
   if (h2Server != null) {
     h2Server.stop();
   }
   DeleteDbFiles.execute("", "JPADroolsFlow", true);
 }
 public TestPersistenceUnit(int port) {
   try {
     tcpServer = Server.createTcpServer("-tcpPort", "" + port);
   } catch (SQLException e) {
     throw new IllegalStateException(e);
   }
 }
 public void stopService() {
   try {
     Server.shutdownTcpServer("tcp://localhost", "", true, false);
   } catch (SQLException e) {
     throw new RuntimeException(e);
   }
 }
Exemplo n.º 15
0
 @Override
 public void terminate() {
   log.debug("termination signal received");
   if (server != null) {
     server.stop();
   }
 }
Exemplo n.º 16
0
 /** 启动H2数据库 */
 public void start() {
   try {
     server = Server.createTcpServer().start();
     log.info("h2 DB start..");
   } catch (Exception e) {
     log.error("h2 DB start error!", e);
   }
 }
Exemplo n.º 17
0
  @Override
  public boolean rawInvocation(Request request, Response response) throws Exception {
    if (Play.mode.isDev() && request.path.equals("/@db")) {
      response.status = Http.StatusCode.MOVED;

      // For H2 embeded database, we'll also start the Web console
      if (h2Server != null) {
        h2Server.stop();
      }
      h2Server = org.h2.tools.Server.createWebServer();
      h2Server.start();

      response.setHeader("Location", "http://localhost:8082/");
      return true;
    }
    return false;
  }
Exemplo n.º 18
0
 @Override
 protected void finalize() throws Throwable {
   if (realH2Server != null) {
     realH2Server.stop();
   }
   DeleteDbFiles.execute("", "JPADroolsFlow", true);
   super.finalize();
 }
Exemplo n.º 19
0
 private void test(String dir) throws Exception {
   Server server = FtpServer.createFtpServer("-ftpDir", dir, "-ftpPort", "8121").start();
   FtpServer ftp = (FtpServer) server.getService();
   ftp.setEventListener(this);
   FtpClient client = FtpClient.open("localhost:8121");
   client.login("sa", "sa");
   client.makeDirectory("test");
   client.changeWorkingDirectory("test");
   assertEquals("CWD", lastEvent.getCommand());
   client.makeDirectory("hello");
   client.changeWorkingDirectory("hello");
   client.changeDirectoryUp();
   assertEquals("CDUP", lastEvent.getCommand());
   client.nameList("hello");
   client.removeDirectory("hello");
   client.close();
   server.stop();
 }
Exemplo n.º 20
0
 @Override
 public void run() {
   log.debug("H2DatabaseServer stared");
   try {
     String[] assembleCommandLine = assembleCommandLine();
     server = Server.createTcpServer(assembleCommandLine).start();
   } catch (SQLException e) {
     throw new TechnicalException(e);
   }
 }
 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();
 }
Exemplo n.º 22
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");
 }
Exemplo n.º 23
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);
  }
Exemplo n.º 24
0
  @Action(
      value = "h2-db-web-console-start",
      results = {@Result(name = "sucess", location = "h2-db-web-console-stop.jsp")})
  public String start() throws Exception {
    synchronized (lock) {
      Server server = (Server) application.get("h2DbWebServer");
      if (server != null && server.isRunning(false)) {
        URL urlObj = new URL(ServletActionContext.getRequest().getRequestURL().toString());
        StringBuffer sb = new StringBuffer();
        sb.append(urlObj.getProtocol())
            .append("://")
            .append(urlObj.getHost())
            .append(":")
            .append(server.getPort())
            .append("/");
        url = sb.toString();
      } else {
        server =
            Server.createWebServer(
                "-webPort", port.toString(), "-baseDir", ".", "-webAllowOthers", "-webDaemon");
        server.start();
        application.put("h2DbWebServer", server);

        URL urlObj = new URL(ServletActionContext.getRequest().getRequestURL().toString());
        StringBuffer sb = new StringBuffer();
        sb.append(urlObj.getProtocol())
            .append("://")
            .append(urlObj.getHost())
            .append(":")
            .append(port)
            .append("/");
        url = sb.toString();
      }
    }

    return "sucess";
  }
  @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();
    }
  }
Exemplo n.º 26
0
 public void contextDestroyed(ServletContextEvent servletContextEvent) {
   try {
     Statement stat = conn.createStatement();
     stat.execute("SHUTDOWN");
     stat.close();
   } catch (Exception e) {
     e.printStackTrace();
   }
   try {
     conn.close();
   } catch (Exception e) {
     e.printStackTrace();
   }
   if (server != null) {
     server.stop();
     server = null;
   }
 }
Exemplo n.º 27
0
 private void testStartWebServerWithConnection() throws Exception {
   String old = System.getProperty(SysProperties.H2_BROWSER);
   try {
     System.setProperty(
         SysProperties.H2_BROWSER, "call:" + TestWeb.class.getName() + ".openBrowser");
     Server.openBrowser("testUrl");
     assertEquals("testUrl", lastUrl);
     String oldUrl = lastUrl;
     final Connection conn = getConnection("testWeb");
     Task t =
         new Task() {
           public void call() throws Exception {
             Server.startWebServer(conn);
           }
         };
     t.execute();
     for (int i = 0; lastUrl == oldUrl; i++) {
       if (i > 100) {
         throw new Exception("Browser not started");
       }
       Thread.sleep(100);
     }
     String url = lastUrl;
     WebClient client = new WebClient();
     client.readSessionId(url);
     url = client.getBaseUrl(url);
     try {
       client.get(url, "logout.do");
     } catch (Exception e) {
       // the server stops on logout
     }
     t.get();
   } finally {
     if (old != null) {
       System.setProperty(SysProperties.H2_BROWSER, old);
     } else {
       System.clearProperty(SysProperties.H2_BROWSER);
     }
     deleteDb("testWeb");
   }
 }
Exemplo n.º 28
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();
 }
 /** 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");
 }
Exemplo n.º 30
0
 private void startServer() throws SQLException {
   h2Server = Server.createTcpServer().start();
 }