Search in sources :

Example 41 with Server

use of org.h2.tools.Server in project webpieces by deanhiller.

the class H2DbModule method configure.

@Override
protected void configure() {
    Multibinder<BackendGuiDescriptor> backendBinder = Multibinder.newSetBinder(binder(), BackendGuiDescriptor.class);
    backendBinder.addBinding().to(H2DbGuiDescriptor.class);
    bind(H2DbConfig.class).toInstance(config);
    bind(ServerConfig.class).toInstance(svrConfig);
    try {
        String[] args;
        // if this port1 is 0, server.getPort will get the real port later in this method
        int port1 = config.getPort().get();
        if (config.getConvertDomain() == null) {
            args = new String[] { "-webPort", port1 + "" };
        } else {
            // if we are converting a domain, definitely need to allow other ip addresses in..
            // this is because we are exposing a domain url on the web to hit
            args = new String[] { "-webPort", port1 + "", "-webAllowOthers" };
        }
        log.info("Creating H2 webserver for html GUI interface to serve up as a webpage(for development servers)");
        // start the TCP Server
        Server server = Server.createWebServer(args);
        log.info("Starting H2 webserver");
        server.start();
        int port = server.getPort();
        log.info("H2 webserver started on port=" + port);
        if (config.getConvertDomain() == null) {
            log.info("H2 webserver setting webpage to use=" + port);
            this.svrConfig.setPort(port);
        } else {
            log.info("H2 webserver using the domain converter=" + config.getConvertDomain());
        }
        return;
    } catch (Exception e) {
        throw SneakyThrow.sneak(e);
    }
}
Also used : BackendGuiDescriptor(org.webpieces.plugin.backend.spi.BackendGuiDescriptor) Server(org.h2.tools.Server) SQLException(java.sql.SQLException)

Example 42 with Server

use of org.h2.tools.Server in project ignite by apache.

the class GridReduceQueryExecutor method update.

/**
 * @param schemaName Schema name.
 * @param cacheIds Cache ids.
 * @param selectQry Select query.
 * @param params SQL parameters.
 * @param enforceJoinOrder Enforce join order of tables.
 * @param pageSize Page size.
 * @param timeoutMillis Timeout.
 * @param parts Partitions.
 * @param isReplicatedOnly Whether query uses only replicated caches.
 * @param cancel Cancel state.
 * @return Update result, or {@code null} when some map node doesn't support distributed DML.
 */
@SuppressWarnings("IfMayBeConditional")
public UpdateResult update(String schemaName, List<Integer> cacheIds, String selectQry, Object[] params, boolean enforceJoinOrder, int pageSize, int timeoutMillis, final int[] parts, boolean isReplicatedOnly, GridQueryCancel cancel) {
    AffinityTopologyVersion topVer = h2.readyTopologyVersion();
    ReducePartitionMapResult nodesParts = mapper.nodesForPartitions(cacheIds, topVer, parts, isReplicatedOnly);
    Collection<ClusterNode> nodes = nodesParts.nodes();
    if (F.isEmpty(nodes))
        throw new CacheException("Failed to determine nodes participating in the update. " + "Explanation (Retry update once topology recovers).");
    if (isReplicatedOnly) {
        ClusterNode locNode = ctx.discovery().localNode();
        if (nodes.contains(locNode))
            nodes = singletonList(locNode);
        else
            nodes = singletonList(F.rand(nodes));
    }
    for (ClusterNode n : nodes) {
        if (!n.version().greaterThanEqual(2, 3, 0)) {
            log.warning("Server-side DML optimization is skipped because map node does not support it. " + "Falling back to normal DML. [node=" + n.id() + ", v=" + n.version() + "].");
            return null;
        }
    }
    final long reqId = qryReqIdGen.incrementAndGet();
    h2.runningQueryManager().trackRequestId(reqId);
    final DmlDistributedUpdateRun r = new DmlDistributedUpdateRun(nodes.size());
    int flags = enforceJoinOrder ? GridH2QueryRequest.FLAG_ENFORCE_JOIN_ORDER : 0;
    if (isReplicatedOnly)
        flags |= GridH2QueryRequest.FLAG_REPLICATED;
    GridH2DmlRequest req = new GridH2DmlRequest().requestId(reqId).topologyVersion(topVer).caches(cacheIds).schemaName(schemaName).query(selectQry).pageSize(pageSize).parameters(params).timeout(timeoutMillis).explicitTimeout(true).flags(flags);
    updRuns.put(reqId, r);
    boolean release = false;
    try {
        Map<ClusterNode, IntArray> partsMap = (nodesParts.queryPartitionsMap() != null) ? nodesParts.queryPartitionsMap() : nodesParts.partitionsMap();
        ReducePartitionsSpecializer partsSpec = (parts == null) ? null : new ReducePartitionsSpecializer(partsMap);
        final Collection<ClusterNode> finalNodes = nodes;
        cancel.add(() -> {
            r.future().onCancelled();
            send(finalNodes, new GridQueryCancelRequest(reqId), null, true);
        });
        // send() logs the debug message
        if (send(nodes, req, partsSpec, false))
            return r.future().get();
        throw new CacheException("Failed to send update request to participating nodes.");
    } catch (IgniteCheckedException | RuntimeException e) {
        release = true;
        U.error(log, "Error during update [localNodeId=" + ctx.localNodeId() + "]", e);
        throw new CacheException("Failed to run SQL update query. " + e.getMessage(), e);
    } finally {
        if (release)
            send(nodes, new GridQueryCancelRequest(reqId), null, false);
        if (!updRuns.remove(reqId, r))
            U.warn(log, "Update run was already removed: " + reqId);
    }
}
Also used : ClusterNode(org.apache.ignite.cluster.ClusterNode) GridH2DmlRequest(org.apache.ignite.internal.processors.query.h2.twostep.msg.GridH2DmlRequest) GridQueryCancelRequest(org.apache.ignite.internal.processors.query.h2.twostep.messages.GridQueryCancelRequest) AffinityTopologyVersion(org.apache.ignite.internal.processors.affinity.AffinityTopologyVersion) CacheException(javax.cache.CacheException) DmlDistributedUpdateRun(org.apache.ignite.internal.processors.query.h2.dml.DmlDistributedUpdateRun) IgniteCheckedException(org.apache.ignite.IgniteCheckedException) IntArray(org.h2.util.IntArray)

Example 43 with Server

use of org.h2.tools.Server in project traccar by tananaev.

the class ConsoleServlet method init.

@Override
public void init() {
    super.init();
    try {
        Field field = WebServlet.class.getDeclaredField("server");
        field.setAccessible(true);
        org.h2.server.web.WebServer server = (org.h2.server.web.WebServer) field.get(this);
        ConnectionInfo connectionInfo = new ConnectionInfo("Traccar|" + Context.getConfig().getString(Keys.DATABASE_DRIVER) + "|" + Context.getConfig().getString(Keys.DATABASE_URL) + "|" + Context.getConfig().getString(Keys.DATABASE_USER));
        Method method;
        method = org.h2.server.web.WebServer.class.getDeclaredMethod("updateSetting", ConnectionInfo.class);
        method.setAccessible(true);
        method.invoke(server, connectionInfo);
        method = org.h2.server.web.WebServer.class.getDeclaredMethod("setAllowOthers", boolean.class);
        method.setAccessible(true);
        method.invoke(server, true);
    } catch (NoSuchFieldException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
        LOGGER.warn("Console reflection error", e);
    }
}
Also used : Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) Field(java.lang.reflect.Field) ConnectionInfo(org.h2.server.web.ConnectionInfo)

Example 44 with Server

use of org.h2.tools.Server in project spf4j by zolyfarkas.

the class PooledDataSourceTest method testConnectionPool.

@Test
public void testConnectionPool() throws SQLException, ObjectCreationException, IOException {
    Server server = Server.createTcpServer(new String[] { "-tcpPort", "9123", "-ifNotExists" }).start();
    try {
        File tempDB = File.createTempFile("test", "h2db");
        String connStr = "jdbc:h2:tcp://localhost:9123/nio:" + tempDB.getAbsolutePath() + ";AUTO_SERVER=TRUE";
        PooledDataSource pds = new PooledDataSource(1, 2, new JdbcConnectionFactory("org.h2.Driver", connStr, "sa", "sa"));
        try (Connection conn = pds.getConnection()) {
            Assert.assertTrue(conn.isValid(10));
        }
    } finally {
        server.shutdown();
    }
}
Also used : Server(org.h2.tools.Server) Connection(java.sql.Connection) File(java.io.File) Test(org.junit.Test)

Example 45 with Server

use of org.h2.tools.Server in project spf4j by zolyfarkas.

the class JdbcSemaphoreTest method testPerformance.

@Test
@Ignore
public void testPerformance() throws SQLException, IOException, InterruptedException, ExecutionException, TimeoutException {
    int port = PORT.getAndIncrement();
    Server server = Server.createTcpServer(new String[] { "-tcpPort", Integer.toString(port), "-ifNotExists" }).start();
    try {
        File tempDB = File.createTempFile("test", "h2db");
        tempDB.deleteOnExit();
        String connStr = "jdbc:h2:tcp://localhost:" + port + "/nio:" + tempDB.getAbsolutePath() + ";AUTO_SERVER=TRUE";
        JdbcDataSource ds = new JdbcDataSource();
        ds.setURL(connStr);
        ds.setUser("sa");
        ds.setPassword("sa");
        createSchemaObjects(ds);
        JdbcSemaphore semaphore = new JdbcSemaphore(ds, "test_sem2", 1, true);
        Sampler s = new Sampler(5, 5000);
        s.registerJmx();
        s.start();
        LOG.info("started sampling");
        long deadline = TimeSource.nanoTime() + TimeUnit.SECONDS.toNanos(10);
        do {
            semaphore.acquire(1, 1, TimeUnit.SECONDS);
            semaphore.release();
        } while (deadline > TimeSource.nanoTime());
        semaphore.close();
        s.stop();
        LOG.debug("dumped samples to {}", s.dumpToFile());
    } finally {
        JdbcHeartBeat.stopHeartBeats();
        server.shutdown();
    }
}
Also used : Server(org.h2.tools.Server) JdbcDataSource(org.h2.jdbcx.JdbcDataSource) Sampler(org.spf4j.stackmonitor.Sampler) File(java.io.File) Ignore(org.junit.Ignore) Test(org.junit.Test)

Aggregations

Server (org.h2.tools.Server)47 Connection (java.sql.Connection)27 SQLException (java.sql.SQLException)22 Statement (java.sql.Statement)17 PreparedStatement (java.sql.PreparedStatement)15 IOException (java.io.IOException)13 ResultSet (java.sql.ResultSet)10 DbException (org.h2.message.DbException)9 Socket (java.net.Socket)8 Test (org.junit.Test)8 Properties (java.util.Properties)7 ByteArrayOutputStream (java.io.ByteArrayOutputStream)6 File (java.io.File)6 ServerSocket (java.net.ServerSocket)6 PrintStream (java.io.PrintStream)5 JdbcDataSource (org.h2.jdbcx.JdbcDataSource)5 Task (org.h2.util.Task)5 TcpServer (org.h2.server.TcpServer)4 PgServer (org.h2.server.pg.PgServer)4 WebServer (org.h2.server.web.WebServer)4