Search in sources :

Example 16 with Vertx

use of io.vertx.core.Vertx in project vert.x by eclipse.

the class HttpProxy method start.

/**
   * Start the server.
   * 
   * @param vertx
   *          Vertx instance to use for creating the server and client
   * @param finishedHandler
   *          will be called when the server has started
   */
@Override
public void start(Vertx vertx, Handler<Void> finishedHandler) {
    HttpServerOptions options = new HttpServerOptions();
    options.setHost("localhost").setPort(PORT);
    server = vertx.createHttpServer(options);
    server.requestHandler(request -> {
        HttpMethod method = request.method();
        String uri = request.uri();
        if (username != null) {
            String auth = request.getHeader("Proxy-Authorization");
            String expected = "Basic " + Base64.getEncoder().encodeToString((username + ":" + username).getBytes());
            if (auth == null || !auth.equals(expected)) {
                request.response().setStatusCode(407).end("proxy authentication failed");
                return;
            }
        }
        lastRequestHeaders = MultiMap.caseInsensitiveMultiMap().addAll(request.headers());
        if (error != 0) {
            request.response().setStatusCode(error).end("proxy request failed");
        } else if (method == HttpMethod.CONNECT) {
            if (!uri.contains(":")) {
                request.response().setStatusCode(403).end("invalid request");
            } else {
                lastUri = uri;
                if (forceUri != null) {
                    uri = forceUri;
                }
                String[] split = uri.split(":");
                String host = split[0];
                int port;
                try {
                    port = Integer.parseInt(split[1]);
                } catch (NumberFormatException ex) {
                    port = 443;
                }
                if (port == 8080 || port < 1024 && port != 443) {
                    request.response().setStatusCode(403).end("access to port denied");
                    return;
                }
                NetSocket serverSocket = request.netSocket();
                NetClientOptions netOptions = new NetClientOptions();
                NetClient netClient = vertx.createNetClient(netOptions);
                netClient.connect(port, host, result -> {
                    if (result.succeeded()) {
                        NetSocket clientSocket = result.result();
                        serverSocket.write("HTTP/1.0 200 Connection established\n\n");
                        serverSocket.closeHandler(v -> clientSocket.close());
                        clientSocket.closeHandler(v -> serverSocket.close());
                        Pump.pump(serverSocket, clientSocket).start();
                        Pump.pump(clientSocket, serverSocket).start();
                    } else {
                        request.response().setStatusCode(403).end("request failed");
                    }
                });
            }
        } else if (method == HttpMethod.GET) {
            lastUri = request.uri();
            HttpClient client = vertx.createHttpClient();
            HttpClientRequest clientRequest = client.getAbs(request.uri(), resp -> {
                for (String name : resp.headers().names()) {
                    request.response().putHeader(name, resp.headers().getAll(name));
                }
                resp.bodyHandler(body -> {
                    request.response().end(body);
                });
            });
            for (String name : request.headers().names()) {
                if (!name.equals("Proxy-Authorization")) {
                    clientRequest.putHeader(name, request.headers().getAll(name));
                }
            }
            clientRequest.exceptionHandler(e -> {
                log.debug("exception", e);
                int status;
                if (e instanceof UnknownHostException) {
                    status = 504;
                } else {
                    status = 400;
                }
                request.response().setStatusCode(status).end(e.toString() + " on client request");
            });
            clientRequest.end();
        } else {
            request.response().setStatusCode(405).end("method not supported");
        }
    });
    server.listen(server -> {
        finishedHandler.handle(null);
    });
}
Also used : NetSocket(io.vertx.core.net.NetSocket) HttpServer(io.vertx.core.http.HttpServer) MultiMap(io.vertx.core.MultiMap) Vertx(io.vertx.core.Vertx) UnknownHostException(java.net.UnknownHostException) LoggerFactory(io.vertx.core.logging.LoggerFactory) NetClientOptions(io.vertx.core.net.NetClientOptions) HttpClientRequest(io.vertx.core.http.HttpClientRequest) Base64(java.util.Base64) HttpMethod(io.vertx.core.http.HttpMethod) HttpServerOptions(io.vertx.core.http.HttpServerOptions) Pump(io.vertx.core.streams.Pump) Handler(io.vertx.core.Handler) Logger(io.vertx.core.logging.Logger) NetClient(io.vertx.core.net.NetClient) HttpClient(io.vertx.core.http.HttpClient) NetSocket(io.vertx.core.net.NetSocket) NetClientOptions(io.vertx.core.net.NetClientOptions) HttpClientRequest(io.vertx.core.http.HttpClientRequest) NetClient(io.vertx.core.net.NetClient) UnknownHostException(java.net.UnknownHostException) HttpClient(io.vertx.core.http.HttpClient) HttpServerOptions(io.vertx.core.http.HttpServerOptions) HttpMethod(io.vertx.core.http.HttpMethod)

Example 17 with Vertx

use of io.vertx.core.Vertx in project vert.x by eclipse.

the class NamedWorkerPoolTest method testCloseWorkerPoolsWhenVertxCloses.

@Test
public void testCloseWorkerPoolsWhenVertxCloses() {
    Vertx vertx = Vertx.vertx();
    WorkerExecutor exec = vertx.createSharedWorkerExecutor("vert.x-123");
    vertx.close(v -> {
        try {
            vertx.executeBlocking(fut -> fail(), ar -> fail());
            fail();
        } catch (RejectedExecutionException ignore) {
        }
        try {
            exec.executeBlocking(fut -> fail(), ar -> fail());
            fail();
        } catch (RejectedExecutionException ignore) {
        }
        exec.close();
        testComplete();
    });
    await();
}
Also used : WorkerExecutor(io.vertx.core.WorkerExecutor) Vertx(io.vertx.core.Vertx) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) Test(org.junit.Test)

Example 18 with Vertx

use of io.vertx.core.Vertx in project camel by apache.

the class VertxComponent method doStart.

@Override
protected void doStart() throws Exception {
    super.doStart();
    if (vertx == null) {
        if (vertxFactory == null) {
            vertxFactory = new VertxFactoryImpl();
        }
        if (vertxOptions == null) {
            vertxOptions = new VertxOptions();
            if (ObjectHelper.isNotEmpty(host)) {
                vertxOptions.setClusterHost(host);
                vertxOptions.setClustered(true);
            }
            if (port > 0) {
                vertxOptions.setClusterPort(port);
                vertxOptions.setClustered(true);
            }
        }
        // we are creating vertx so we should handle its lifecycle
        createdVertx = true;
        final CountDownLatch latch = new CountDownLatch(1);
        // lets using a host / port if a host name is specified
        if (vertxOptions.isClustered()) {
            LOG.info("Creating Clustered Vertx {}:{}", vertxOptions.getClusterHost(), vertxOptions.getClusterPort());
            // use the async api as we want to wait for the eventbus to be ready before we are in started state
            vertxFactory.clusteredVertx(vertxOptions, new Handler<AsyncResult<Vertx>>() {

                @Override
                public void handle(AsyncResult<Vertx> event) {
                    if (event.cause() != null) {
                        LOG.warn("Error creating Clustered Vertx " + host + ":" + port + " due " + event.cause().getMessage(), event.cause());
                    } else if (event.succeeded()) {
                        vertx = event.result();
                        LOG.info("EventBus is ready: {}", vertx);
                    }
                    latch.countDown();
                }
            });
        } else {
            LOG.info("Creating Non-Clustered Vertx");
            vertx = vertxFactory.vertx();
            LOG.info("EventBus is ready: {}", vertx);
            latch.countDown();
        }
        if (latch.getCount() > 0) {
            LOG.info("Waiting for EventBus to be ready using {} sec as timeout", timeout);
            latch.await(timeout, TimeUnit.SECONDS);
        }
    } else {
        LOG.debug("Using Vert.x instance set on the component level.");
    }
}
Also used : CountDownLatch(java.util.concurrent.CountDownLatch) Vertx(io.vertx.core.Vertx) VertxOptions(io.vertx.core.VertxOptions) AsyncResult(io.vertx.core.AsyncResult) VertxFactoryImpl(io.vertx.core.impl.VertxFactoryImpl)

Example 19 with Vertx

use of io.vertx.core.Vertx in project java-chassis by ServiceComb.

the class PerfClient method main.

public static void main(String[] args) throws Exception {
    PojoClient.init();
    System.out.println("mode:" + Config.getMode());
    if ("reactive".equals(Config.getMode())) {
        Vertx vertx = VertxUtils.getOrCreateVertxByName("perfClient", null);
        VertxUtils.deployVerticle(vertx, ClientVerticle.class, Config.getClientThread());
        return;
    }
    for (int idx = 0; idx < Config.getClientThread(); idx++) {
        new ClientThread().start();
    }
}
Also used : Vertx(io.vertx.core.Vertx)

Example 20 with Vertx

use of io.vertx.core.Vertx in project java-chassis by ServiceComb.

the class VertxUtils method getOrCreateVertxByName.

public static Vertx getOrCreateVertxByName(String name, VertxOptions vertxOptions) {
    Vertx vertx = getVertxByName(name);
    if (vertx == null) {
        synchronized (VertxUtils.class) {
            vertx = getVertxByName(name);
            if (vertx == null) {
                vertx = init(vertxOptions);
                vertxMap.put(name, vertx);
            }
        }
    }
    return vertx;
}
Also used : Vertx(io.vertx.core.Vertx)

Aggregations

Vertx (io.vertx.core.Vertx)43 Test (org.junit.Test)17 VertxOptions (io.vertx.core.VertxOptions)11 Buffer (io.vertx.core.buffer.Buffer)10 Handler (io.vertx.core.Handler)8 NetSocket (io.vertx.core.net.NetSocket)7 Pump (io.vertx.core.streams.Pump)7 CountDownLatch (java.util.concurrent.CountDownLatch)7 DeploymentOptions (io.vertx.core.DeploymentOptions)6 VertxInternal (io.vertx.core.impl.VertxInternal)6 NetServer (io.vertx.core.net.NetServer)6 NetServerOptions (io.vertx.core.net.NetServerOptions)6 JsonObject (io.vertx.core.json.JsonObject)5 Launcher (io.vertx.core.Launcher)4 RunCommandTest (io.vertx.core.impl.launcher.commands.RunCommandTest)4 IOException (java.io.IOException)4 ArrayList (java.util.ArrayList)4 AtomicReference (java.util.concurrent.atomic.AtomicReference)4 AbstractVerticle (io.vertx.core.AbstractVerticle)3 AsyncResult (io.vertx.core.AsyncResult)3