Java Code Examples for org.h2.tools.Server

The following examples show how to use org.h2.tools.Server. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: java-trader   Source File: H2DBStartAction.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public int execute(BeansContainer beansContainer, PrintWriter writer, List<KVPair> options) throws Exception {
    File h2db = new File( TraderHomeUtil.getTraderHome(), "data/h2db");
    h2db.mkdirs();
    statusFile = new File(h2db, "status.ini");

    int h2TcpPort = ConfigUtil.getInt("/BasisService/h2db.tcpPort", 9092);
    Server.main("-ifNotExists", "-web", "-webAllowOthers", "-tcp", "-tcpAllowOthers", "-tcpPort", ""+h2TcpPort,"-baseDir", h2db.getAbsolutePath());

    String text = "[start]\n"
            +"pid="+SystemUtil.getPid()+"\n"
            +"startTime="+DateUtil.date2str(LocalDateTime.now())+"\n"
            +"traderHome="+TraderHomeUtil.getTraderHome().getAbsolutePath()+"\n"
            +"h2TcpPort="+h2TcpPort+"\n";

    FileUtil.save(statusFile, text);
    statusFile.deleteOnExit();
    //tcpServer.start();
    //writer.println(tcpServer.getStatus());
    //tcpServer.setShutdownHandler(this);
    synchronized(statusFile) {
        statusFile.wait();
    }
    return 0;
}
 
Example 2
Source Project: envelope   Source File: TestJdbcOutput.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void beforeClass() throws SQLException, ClassNotFoundException {
  Class.forName("org.h2.Driver");
  server = Server.createTcpServer("-tcp", "-tcpAllowOthers").start();
  Connection connection = DriverManager.getConnection(String.format(JDBC_URL, server.getPort()),
      JDBC_USERNAME, JDBC_PASSWORD);
  Statement stmt = connection.createStatement();
  stmt.executeUpdate("create table if not exists user (firstname varchar(30), lastname varchar(30))");

  Properties properties = new Properties();
  properties.setProperty("url", String.format(JDBC_URL, server.getPort()));
  properties.setProperty("tablename", JDBC_TABLE);
  properties.setProperty("username", JDBC_USERNAME);
  properties.setProperty("password", JDBC_PASSWORD);

  config = ConfigFactory.parseProperties(properties);
}
 
Example 3
Source Project: envelope   Source File: TestJdbcInput.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void beforeClass() throws SQLException, ClassNotFoundException {
  Class.forName("org.h2.Driver");
  server = Server.createTcpServer("-tcp", "-tcpAllowOthers").start();
  Connection connection = DriverManager.getConnection("jdbc:h2:tcp://127.0.0.1:" + server.getPort() +
      "/mem:test;DB_CLOSE_DELAY=-1", "sa", "");
  Statement stmt = connection.createStatement();
  stmt.executeUpdate("create table if not exists user (firstname varchar(30), lastname varchar(30))");
  stmt.executeUpdate("insert into user values ('f1','p1')");
  stmt.executeUpdate("insert into user values ('f2','p1')");
  stmt.executeUpdate("insert into user values ('f3','p1')");

  Properties properties = new Properties();
  properties.setProperty("url", String.format(JDBC_URL, server.getPort()));
  properties.setProperty("tablename", JDBC_TABLE);
  properties.setProperty("username", JDBC_USERNAME);
  properties.setProperty("password", JDBC_PASSWORD);

  config = ConfigFactory.parseProperties(properties);
}
 
Example 4
Source Project: cassandra-reaper   Source File: PostgresStorageTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws SQLException, IOException {
  Server.createTcpServer().start();

  DBI dbi = new DBI(DB_URL);
  Handle handle = dbi.open();
  Connection conn = handle.getConnection();

  // to suppress output of ScriptRunner
  PrintStream tmp = new PrintStream(new OutputStream() {
    @Override
    public void write(int buff) throws IOException {
      // do nothing
    }
  });
  PrintStream console = System.out;
  System.setOut(tmp);

  String cwd = Paths.get("").toAbsolutePath().toString();
  String path = cwd + "/../src/test/resources/db/postgres/V17_0_0__multi_instance.sql";
  ScriptRunner scriptExecutor = new ScriptRunner(conn, false, true);
  Reader reader = new BufferedReader(new FileReader(path));
  scriptExecutor.runScript(reader);

  System.setOut(console);
}
 
Example 5
public void start(String connectString, String userName, String pwd, Map<String, String> params) throws OpenAS2Exception {
    createConnectionPool(connectString, userName, pwd);
    String isStartSrvr = params.get(PARAM_TCP_SERVER_START);
    if (isStartSrvr == null || "true".equalsIgnoreCase(isStartSrvr)) {
        String tcpPort = params.get(PARAM_TCP_SERVER_PORT);
        if (tcpPort == null || tcpPort.length() < 1) {
            tcpPort = "9092";
        }
        String tcpPwd = params.get(PARAM_TCP_SERVER_PWD);
        if (tcpPwd == null || tcpPwd.length() < 1) {
            tcpPwd = "OpenAS2";
        }
        String dbDirectory = params.get(PARAM_DB_DIRECTORY);
        if (dbDirectory == null || dbDirectory.length() < 1) {
            throw new OpenAS2Exception("TCP server requireds parameter: " + PARAM_DB_DIRECTORY);
        }

        try {
            server = Server.createTcpServer("-tcpPort", tcpPort, "-tcpPassword", tcpPwd, "-baseDir", dbDirectory, "-tcpAllowOthers").start();
        } catch (SQLException e) {
            throw new OpenAS2Exception("Failed to start TCP server", e);
        }
    }
}
 
Example 6
Source Project: ignite   Source File: H2CacheStoreStrategy.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @throws IgniteCheckedException If failed.
 */
public H2CacheStoreStrategy() throws IgniteCheckedException {
    Server srv = null;

    try {
        srv = Server.createTcpServer().start();

        port = srv.getPort();

        dataSrc = H2CacheStoreSessionListenerFactory.createDataSource(port);

        try (Connection conn = connection()) {
            RunScript.execute(conn, new StringReader(CREATE_CACHE_TABLE));
            RunScript.execute(conn, new StringReader(CREATE_STATS_TABLES));
            RunScript.execute(conn, new StringReader(POPULATE_STATS_TABLE));
        }
    }
    catch (SQLException e) {
        throw new IgniteCheckedException("Failed to set up cache store strategy" +
            (srv == null ? "" : ": " + srv.getStatus()), e);
    }
}
 
Example 7
Source Project: spring-cloud-task   Source File: JpaApplicationTests.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
	DriverManagerDataSource dataSource = new DriverManagerDataSource();
	dataSource.setDriverClassName(DATASOURCE_DRIVER_CLASS_NAME);
	dataSource.setUrl(DATASOURCE_URL);
	dataSource.setUsername(DATASOURCE_USER_NAME);
	dataSource.setPassword(DATASOURCE_USER_PASSWORD);
	this.dataSource = dataSource;
	try {
		this.server = Server
			.createTcpServer("-tcp", "-ifNotExists", "-tcpAllowOthers", "-tcpPort", String
				.valueOf(randomPort))
			.start();
	}
	catch (SQLException e) {
		throw new IllegalStateException(e);
	}
}
 
Example 8
Source Project: spring-cloud-task   Source File: TaskStartTests.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
public Server initH2TCPServer() {
	Server server = null;
	try {
		if (defaultServer == null) {
			server = Server.createTcpServer("-ifNotExists", "-tcp",
					"-tcpAllowOthers", "-tcpPort", String.valueOf(randomPort))
					.start();
			defaultServer = server;
		}
	}
	catch (SQLException e) {
		throw new IllegalStateException(e);
	}
	return defaultServer;
}
 
Example 9
Source Project: spring-cloud-task   Source File: TaskInitializerTests.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
public Server initH2TCPServer() {
	Server server = null;
	try {
		if (defaultServer == null) {
			server = Server.createTcpServer("-ifNotExists", "-tcp",
					"-tcpAllowOthers", "-tcpPort", String.valueOf(randomPort))
					.start();
			defaultServer = server;
		}
	}
	catch (SQLException e) {
		throw new IllegalStateException(e);
	}
	return defaultServer;
}
 
Example 10
Source Project: hortonmachine   Source File: H2GisServer.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Start the web server mode.
 * 
 * @param port the optional port to use.
 * @param doSSL if <code>true</code>, ssl is used.
 * @param ifExists is <code>true</code>, the database to connect to has to exist.
 * @param baseDir an optional basedir into which it is allowed to connect.
 * @return
 * @throws SQLException
 */
public static Server startWebServerMode( String port, boolean doSSL, boolean ifExists, String baseDir ) throws SQLException {
    List<String> params = new ArrayList<>();
    params.add("-webAllowOthers");
    if (port != null) {
        params.add("-webPort");
        params.add(port);
    }

    if (doSSL) {
        params.add("-webSSL");
    }

    if (ifExists) {
        params.add("-ifExists");
    }

    if (baseDir != null) {
        params.add("-baseDir");
        params.add(baseDir);
    }

    Server server = Server.createWebServer(params.toArray(new String[0])).start();
    return server;
}
 
Example 11
Source Project: we-cmdb   Source File: TestConfig.java    License: Apache License 2.0 5 votes vote down vote up
@Bean(name = "h2server", destroyMethod = "stop")
public Server getH2Server() {
    Server h2Server;
    try {
        h2Server = Server.createWebServer("-web", "-webAllowOthers", "-webPort", "8082");
        h2Server.start();
        return h2Server;
    } catch (SQLException e) {
        logger.info("Fail to start H2 server.", e);
    }
    return null;
}
 
Example 12
Source Project: quarkus-in-prod   Source File: H2DatabaseTestResource.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, String> start() {

    try {
        tcpServer = Server.createTcpServer();
        tcpServer.start();
        System.out.println("[INFO] H2 database started in TCP server mode on port " + tcpServer.getPort());
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
    return emptyMap();
}
 
Example 13
Source Project: quarkus-in-prod   Source File: H2DatabaseTestResource.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, String> start() {

    try {
        tcpServer = Server.createTcpServer();
        tcpServer.start();
        System.out.println("[INFO] H2 database started in TCP server mode on port " + tcpServer.getPort());
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
    return emptyMap();
}
 
Example 14
Source Project: java-starthere   Source File: H2ServerConfiguration.java    License: MIT License 5 votes vote down vote up
/**
 * TCP connection to connect with SQL clients to the embedded h2 database.
 * <p>
 * Connect to "jdbc:h2:tcp://localhost:9092/mem:testdb", username "sa", password empty.
 */
@Bean
@ConditionalOnExpression("${h2.tcp.enabled:true}")
public Server h2TcpServer() throws SQLException
{
    return Server.createTcpServer("-tcp",
                                  "-tcpAllowOthers",
                                  "-tcpPort",
                                  h2TcpPort)
                 .start();
}
 
Example 15
Source Project: java-starthere   Source File: H2ServerConfiguration.java    License: MIT License 5 votes vote down vote up
/**
 * Web console for the embedded h2 database.
 * <p>
 * Go to http://localhost:8082 and connect to the database "jdbc:h2:mem:testdb", username "sa", password empty.
 */
@Bean
@ConditionalOnExpression("${h2.web.enabled:true}")
public Server h2WebServer() throws SQLException
{
    return Server.createWebServer("-web",
                                  "-webAllowOthers",
                                  "-webPort",
                                  h2WebPort)
                 .start();
}
 
Example 16
Source Project: joyqueue   Source File: H2DBServer.java    License: Apache License 2.0 5 votes vote down vote up
public void start(String url) {
    try {
        String baseDir = getBaseDir(url);
        // tcp server 启动
        if (tcpServer == null) {
            logger.info("begin to create h2 database tcp server...");
            tcpServer = Server.createTcpServer(new String[]{"-tcp", "-tcpAllowOthers", "-tcpPort", getTcpPort(url), "-baseDir", baseDir}).start();
            logger.info(String.format("h2 database tcp server is started on port %s", TCP_PORT));
        } else if (!tcpServer.isRunning(true)) {
            logger.info("begin to start h2 database tcp server...");
            tcpServer.start();
            logger.info(String.format("h2 database tcp server is started on port %s", TCP_PORT));
        } else {
            logger.info("h2 database tcp server is already running");
        }
        // web console 启动
        if (webServer == null) {
            logger.info("begin to create h2 database web server...");
            webServer = Server.createWebServer(new String[]{"-web", "-webAllowOthers", "-webPort", String.valueOf(WEB_PORT), "-baseDir", baseDir}).start();
            logger.info(String.format("h2 database web server is started on port %s", WEB_PORT));
        } else if (!webServer.isRunning(true)) {
            logger.info("begin to start h2 database web server...");
            webServer.start();
            logger.info(String.format("h2 database web server is started on port %s", WEB_PORT));
        }else {
            logger.info("h2 database web server is already running.");
        }
    } catch (SQLException e) {
        logger.error("start h2 dabase server error", e);
    }
}
 
Example 17
Source Project: quarkus   Source File: H2DatabaseTestResource.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Map<String, String> start() {

    try {
        tcpServer = Server.createTcpServer();
        tcpServer.start();
        System.out.println("[INFO] H2 database started in TCP server mode; server status: " + tcpServer.getStatus());
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
    return Collections.emptyMap();
}
 
Example 18
Source Project: Alpine   Source File: PersistenceInitializer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Starts the H2 database engine if the database mode is set to 'server'
 */
private void startDbServer() {
    final String mode = Config.getInstance().getProperty(Config.AlpineKey.DATABASE_MODE);
    final int port = Config.getInstance().getPropertyAsInt(Config.AlpineKey.DATABASE_PORT);

    if (StringUtils.isEmpty(mode) || !("server".equals(mode) || "embedded".equals(mode) || "external".equals(mode))) {
        LOGGER.error("Database mode not specified. Expected values are 'server', 'embedded', or 'external'");
    }

    if (dbServer != null || "embedded".equals(mode) || "external".equals(mode)) {
        return;
    }
    final String[] args = new String[] {
            "-tcp",
            "-tcpPort", String.valueOf(port),
            "-tcpAllowOthers",
            "-ifNotExists"
    };
    try {
        LOGGER.info("Attempting to start database service");
        dbServer = Server.createTcpServer(args).start();
        LOGGER.info("Database service started");
    } catch (SQLException e) {
        LOGGER.error("Unable to start database service: " + e.getMessage());
        stopDbServer();
    }
}
 
Example 19
Source Project: ace   Source File: TestH2.java    License: Apache License 2.0 5 votes vote down vote up
public void startServer() {
    try {
        System.out.println("正在启动h2...");
        server = Server.createTcpServer(
                new String[]{"-tcpPort", port}).start();
    } catch (SQLException e) {
        System.out.println("启动h2出错:" + e.toString());
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}
 
Example 20
Source Project: o2oa   Source File: DataServerTools.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
public static DataTcpWebServer start(DataServer dataServer) throws Exception {
	File dataBaseDir = new File(Config.base(), "local/repository/data");
	FileUtils.forceMkdir(dataBaseDir);
	Server tcpServer = null;
	Server webServer = null;
	String password = Config.token().getPassword();
	String[] tcps = new String[9];
	tcps[0] = "-tcp";
	tcps[1] = "-tcpAllowOthers";
	tcps[2] = "-tcpPort";
	tcps[3] = dataServer.getTcpPort().toString();
	tcps[4] = "-baseDir";
	tcps[5] = dataBaseDir.getAbsolutePath();
	tcps[6] = "-tcpPassword";
	tcps[7] = password;
	tcps[8] = "-ifNotExists";
	tcpServer = Server.createTcpServer(tcps).start();
	Integer webPort = dataServer.getWebPort();
	if ((null != webPort) && (webPort > 0)) {
		String webs[] = new String[4];
		webs[0] = "-web";
		webs[1] = "-webAllowOthers";
		webs[2] = "-webPort";
		webs[3] = webPort.toString();
		webServer = Server.createWebServer(webs).start();
	}
	System.out.println("****************************************");
	System.out.println("* data server start completed.");
	System.out.println("* port: " + dataServer.getTcpPort() + ".");
	System.out.println("* web console port: " + dataServer.getWebPort() + ".");
	System.out.println("****************************************");
	return new DataTcpWebServer(tcpServer, webServer);
}
 
Example 21
public void start() {
    if (realH2Server == null || !realH2Server.isRunning(false)) {
        try {
            realH2Server = Server.createTcpServer(new String[0]);
            realH2Server.start();
            System.out.println("Started H2 Server...");
        } catch (SQLException e) {
            throw new RuntimeException("can't start h2 server db",
                                       e);
        }
    }
}
 
Example 22
Source Project: jbpm-work-items   Source File: JPAWorkItemHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
public void start() {
    if (realH2Server == null || !realH2Server.isRunning(false)) {
        try {
            realH2Server = Server.createTcpServer(new String[0]);
            realH2Server.start();
            System.out.println("Started H2 Server...");
        } catch (SQLException e) {
            throw new RuntimeException("can't start h2 server db",
                                       e);
        }
    }
}
 
Example 23
public static void main(String... args) throws Exception {
  SpringApplication.run(TripBookinApplication.class, args);

  // do default setup of platform (everything is only applied if not yet there)
  ProcessEngine engine = BpmPlatform.getDefaultProcessEngine();
  
  // start a Saga right away
  engine.getRuntimeService().startProcessInstanceByKey(
      "trip", 
      Variables.putValue("someVariableToPass", "someValue"));
  
  // Start H2 server to be able to connect to database from the outside
  Server.createTcpServer(new String[] { "-tcpPort", "8092", "-tcpAllowOthers" }).start();
}
 
Example 24
@Bean(destroyMethod = "stop")
public Server initH2TCPServer() {
	Server server = null;
	logger.info("Starting H2 Server with URL: " + dataSourceUrl);
	try {
		server = Server.createTcpServer("-tcp", "-tcpAllowOthers", "-tcpPort",
				getH2Port(dataSourceUrl)).start();
	} catch (SQLException e) {
		throw new IllegalStateException(e);
	}
	return server;
}
 
Example 25
Source Project: jwala   Source File: H2WebServerServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Server createServer(final String [] serverParams) throws DbServerServiceException {
    try {
        return Server.createWebServer(serverParams);
    } catch (final SQLException e) {
        LOGGER.log(Level.SEVERE, "Failed to create H2 Web Server!", e);
        throw new DbServerServiceException(e);
    }
}
 
Example 26
Source Project: jwala   Source File: H2TcpServerServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Server createServer(final String [] serverParams) throws DbServerServiceException {
    try {
        return Server.createTcpServer(serverParams);
    } catch (final SQLException e) {
        LOGGER.log(Level.SEVERE, "Failed to create H2 TCP Server!", e);
        throw new DbServerServiceException(e);
    }
}
 
Example 27
Source Project: jwala   Source File: H2TcpServerServiceImplTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateServer() {
    String[] params = new String[0];
    Server result = service.createServer(params);
    assertNotNull(result.getPort());
    assertEquals("default status", "Not started", result.getStatus());
    // default URL is created using the IP address of the running machine so just test for not null
    assertNotNull("default URL", result.getURL());
    assertNotNull("default service", result.getService());
}
 
Example 28
Source Project: jwala   Source File: H2WebServerServiceImplTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateServer() {
    String[] params = new String[0];
    Server result = service.createServer(params);
    assertNotNull(result.getPort());
    assertEquals("default status", "Not started", result.getStatus());
    // default URL is created using the IP address of the running machine so just test for not null
    assertNotNull("default URL", result.getURL());
    assertNotNull("default service", result.getService());
}
 
Example 29
Source Project: morf   Source File: H2DatabaseInspector.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @see org.alfasoftware.morf.diagnostics.DatabaseInspector#inspect()
 */
@Override
public void inspect() {
  if (connectionResources instanceof AbstractConnectionResources &&
      "H2".equals(connectionResources.getDatabaseType())) {
    try {
      log.info("Launching H2 database inspector...");
      Server.startWebServer(connectionResources.getDataSource().getConnection());
    } catch (SQLException e) {
      throw new IllegalStateException("Failed to start the H2 Database Inspector web server", e);
    }
  }
}
 
Example 30
Source Project: sample-boot-micro   Source File: MicroRegistry.java    License: MIT License 5 votes vote down vote up
/** テスト用途のメモリDBサーバ  */
@Bean(initMethod="start", destroyMethod = "stop")
@ConditionalOnProperty(prefix = "extension.test.db", name = "enabled", matchIfMissing = false)
Server h2Server() {
    try {
        return Server.createTcpServer("-tcpAllowOthers", "-ifNotExists", "-tcpPort", "9092");
    } catch (SQLException e) {
        throw new IllegalStateException(e);
    }
}