Java Code Examples for io.vertx.core.http.HttpServer

The following examples show how to use io.vertx.core.http.HttpServer. 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: vertx-dropwizard-metrics   Source File: MBeansTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testDistinctHttpServerMBeans() throws Exception {
  int port1 = 8080, port2 = 8888;
  CountDownLatch listenLatch = new CountDownLatch(2);
  HttpServer server1 = vertx.createHttpServer()
    .requestHandler(req -> req.response().end())
    .listen(port1, onSuccess(server -> listenLatch.countDown()));
  HttpServer server2 = vertx.createHttpServer()
    .requestHandler(req -> req.response().end())
    .listen(port2, onSuccess(server -> listenLatch.countDown()));
  awaitLatch(listenLatch);

  MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
  assertTrue(mBeanServer.isRegistered(new ObjectName(name.getMethodName(), "name", "\"vertx.http.servers.0.0.0.0:" + port1 + ".requests\"")));
  assertTrue(mBeanServer.isRegistered(new ObjectName(name.getMethodName(), "name", "\"vertx.http.servers.0.0.0.0:" + port2 + ".requests\"")));

  cleanup(server1);
  cleanup(server2);
}
 
Example 2
Source Project: ethsigner   Source File: ClientSideTlsAcceptanceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void ethSignerProvidesSpecifiedClientCertificateToDownStreamServer(@TempDir Path workDir)
    throws Exception {

  final TlsCertificateDefinition serverCert =
      TlsCertificateDefinition.loadFromResource("tls/cert1.pfx", "password");
  final TlsCertificateDefinition ethSignerCert =
      TlsCertificateDefinition.loadFromResource("tls/cert2.pfx", "password2");

  // Note: the HttpServer always responds with a JsonRpcSuccess, result=300.
  final HttpServer web3ProviderHttpServer =
      serverFactory.create(serverCert, ethSignerCert, workDir);

  signer =
      createAndStartSigner(
          ethSignerCert, serverCert, web3ProviderHttpServer.actualPort(), 0, workDir);

  assertThat(signer.accounts().balance("0x123456"))
      .isEqualTo(BigInteger.valueOf(MockBalanceReporter.REPORTED_BALANCE));
}
 
Example 3
Source Project: mewbase   Source File: Main.java    License: MIT License 6 votes vote down vote up
public static void main(String[] args) {
    String resourceBasename = "example.gettingstarted.projectionrest/configuration.conf";
    final Config config = ConfigFactory.load(resourceBasename);

    // create a Vertx web server
    final Vertx vertx = Vertx.vertx();
    final HttpServerOptions options = new HttpServerOptions().setPort(8080);
    final HttpServer httpServer = vertx.createHttpServer(options);
    final BinderStore binderStore = BinderStore.instance(config);
    final Router router = Router.router(vertx);
    router.route().handler(BodyHandler.create());
    httpServer.requestHandler(router::accept);

    /*
    Expose endpoint to retrieve a document from the binder store
     */
    router.route(HttpMethod.GET, "/summary/:product/:date").handler(routingContext -> {
        final String product = routingContext.pathParams().get("product");
        final String date = routingContext.pathParams().get("date");
        final VertxRestServiceActionVisitor actionVisitor = new VertxRestServiceActionVisitor(routingContext);
        actionVisitor.visit(RestServiceAction.retrieveSingleDocument(binderStore, "sales_summary", product + "_" + date));
    });

    httpServer.listen();
}
 
Example 4
@SuppressWarnings("unchecked")
private HttpServer getHttpServer(final boolean startupShouldFail) {

    final HttpServer server = mock(HttpServer.class);
    when(server.actualPort()).thenReturn(0, 8080);
    when(server.requestHandler(any(Handler.class))).thenReturn(server);
    when(server.listen(any(Handler.class))).then(invocation -> {
        final Handler<AsyncResult<HttpServer>> handler = (Handler<AsyncResult<HttpServer>>) invocation
                .getArgument(0);
        if (startupShouldFail) {
            handler.handle(Future.failedFuture("http server intentionally failed to start"));
        } else {
            handler.handle(Future.succeededFuture(server));
        }
        return server;
    });
    return server;
}
 
Example 5
Source Project: quarkus-http   Source File: VertxUndertowEngine.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void start(Future<Void> startFuture) throws Exception {

    server = vertx.createHttpServer(options);

    server.requestHandler(request -> {
        VertxHttpExchange delegate = new VertxHttpExchange(request, allocator, blockingExecutor, null, null);
        rootHandler.handle(delegate);
    });

    server.listen(port, host, new Handler<AsyncResult<HttpServer>>() {
        @Override
        public void handle(AsyncResult<HttpServer> event) {
            if (event.failed()) {
                startFuture.fail(event.cause());
            } else {
                startFuture.complete();
            }
        }
    });
}
 
Example 6
Source Project: generator-jvm   Source File: App.java    License: MIT License 6 votes vote down vote up
public static void main(String[] args) {

    final HttpServer server = Vertx.vertx().createHttpServer();

    server.requestHandler(event -> {

      log.info("hendling request");

      final Map<String, String> o = HashMap.of("hello", "world",
                                               "ololo", "trololo")
                                           .toJavaMap();
      final String json = Try.of(() -> mapper.writeValueAsString(o))
                             .getOrElseGet(throwable -> "{}");
      event.response()
           .putHeader("Content-Type", "application/json")
           .end(json);
    });

    server.listen(port, event -> log.info("listening {} port.", port));
  }
 
Example 7
Source Project: jdk-source-analysis   Source File: VertTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
    public void test() {
        Vertx vertx = Vertx.vertx();
//        request.response().putHeader("Content-Type", "text/plain").write("some text").end();
        vertx.setPeriodic(1000, id -> {
            System.out.println(id);
        });
        vertx.executeBlocking(promise -> {

        }, asyncResult -> {

        });

        HttpServer server = vertx.createHttpServer();
        Handler<HttpServerRequest> requestHandler = server.requestHandler();
    }
 
Example 8
@Test
public void testMatch1(TestContext should) {
  final Async test = should.async();

  final HttpServer server = rule.vertx().createHttpServer();
  server.requestHandler(request -> {
    User user = User.create(new JsonObject().put("username", "dummy user"));
    user.authorizations().add("providerId", PermissionBasedAuthorization.create("p1").setResource("r1"));
    AuthorizationContext context = new AuthorizationContextImpl(user, request.params());
    should.assertEquals(true, PermissionBasedAuthorization.create("p1").setResource("{variable1}").match(context));
    request.response().end();
  }).listen(0, "localhost", listen -> {
    if (listen.failed()) {
      should.fail(listen.cause());
      return;
    }

    rule.vertx().createHttpClient().get(listen.result().actualPort(), "localhost", "/?variable1=r1", res -> {
      if (res.failed()) {
        should.fail(res.cause());
        return;
      }
      server.close(close -> test.complete());
    });
  });
}
 
Example 9
Source Project: strimzi-kafka-operator   Source File: Session.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Start an HTTP health server
 */
private HttpServer startHealthServer() {

    return this.vertx.createHttpServer()
            .requestHandler(request -> {

                if (request.path().equals("/healthy")) {
                    request.response().setStatusCode(200).end();
                } else if (request.path().equals("/ready")) {
                    request.response().setStatusCode(200).end();
                } else if (request.path().equals("/metrics")) {
                    request.response().setStatusCode(200).end(metricsRegistry.scrape());
                }
            })
            .listen(HEALTH_SERVER_PORT);
}
 
Example 10
@SuppressWarnings("deprecation")
// TODO: vert.x 3.8.3 does not update startListen to promise, so we keep use deprecated API now. update in newer version.
private void startListen(HttpServer server, Future<Void> startFuture) {
  server.listen(endpointObject.getPort(), endpointObject.getHostOrIp(), ar -> {
    if (ar.succeeded()) {
      LOGGER.info("rest listen success. address={}:{}",
          endpointObject.getHostOrIp(),
          ar.result().actualPort());
      startFuture.complete();
      return;
    }

    String msg = String.format("rest listen failed, address=%s:%d",
        endpointObject.getHostOrIp(),
        endpointObject.getPort());
    LOGGER.error(msg, ar.cause());
    startFuture.fail(ar.cause());
  });
}
 
Example 11
Source Project: gae   Source File: GaeHttpServer.java    License: MIT License 6 votes vote down vote up
@Override
public void start() {
    HttpServer server = vertx.createHttpServer();

    Router router = Router.router(vertx);
    router.route().handler(BodyHandler.create());
    router.route().handler(ResponseTimeHandler.create());
    router.route("/")
            .handler(jsonHandlerVertx)
            .handler(authHandlerVertx)
            // .blockingHandler(bidHandlerVertx, false)
            .handler(bidHandlerVertx)
            .failureHandler(errorHandlerVertx);

    server.requestHandler(router::accept).listen(serverProps.getPort());
}
 
Example 12
@Test
public void testApiDetectionOpenshift(VertxTestContext context) throws InterruptedException {
    List<String> apis = new ArrayList<>();
    apis.add("/apis/route.openshift.io/v1");
    apis.add("/apis/build.openshift.io/v1");
    apis.add("/apis/apps.openshift.io/v1");
    apis.add("/apis/image.openshift.io/v1");

    HttpServer mockHttp = startMockApi(context, apis);

    KubernetesClient client = new DefaultKubernetesClient("127.0.0.1:" + mockHttp.actualPort());

    Checkpoint async = context.checkpoint();

    PlatformFeaturesAvailability.create(vertx, client).onComplete(context.succeeding(pfa -> context.verify(() -> {
        assertThat(pfa.hasRoutes(), is(true));
        assertThat(pfa.hasBuilds(), is(true));
        assertThat(pfa.hasImages(), is(true));
        assertThat(pfa.hasApps(), is(true));
        stopMockApi(context, mockHttp);
        async.flag();
    })));
}
 
Example 13
Source Project: excelastic   Source File: Website.java    License: MIT License 6 votes vote down vote up
private HttpServer setupStatusService() {
    return vertx.createHttpServer().websocketHandler(websock -> {
        websock.writeFinalTextFrame(new JsonObject().put("message", getStatusServiceWelcomeMessage()).encode());

        AtomicReference<String> uploadId = new AtomicReference<>("");

        // sets up an event bus consumer to listen for import progress.
        MessageConsumer<JsonObject> consumer = vertx.eventBus().consumer(IMPORT_PROGRESS, data -> {
            try {
                if (uploadId.get().equals(data.body().getString(UPLOAD_ID))) {
                    websock.writeFinalTextFrame(data.body().encode());
                }
            } catch (Throwable e) {
                websock.close();
            }
        });
        // we only support one message from the client - to set the upload ID to listen to.
        websock.handler(handler -> uploadId.set(handler.toJsonObject().getString(UPLOAD_ID)));

        // when the websocket is closed we should stop listening for status messages.
        websock.closeHandler(closed -> consumer.unregister());

        // when the websocket excepts we should also stop listening for status messages.
        websock.exceptionHandler(sock -> consumer.unregister());
    });
}
 
Example 14
@Test
public void testMatch1(TestContext should) {
  final Async test = should.async();
  final HttpServer server = rule.vertx().createHttpServer();
  server.requestHandler(request -> {
    User user = User.create(new JsonObject().put("username", "dummy user"));
    user.authorizations().add("providerId", WildcardPermissionBasedAuthorization.create("p1").setResource("r1"));
    AuthorizationContext context = new AuthorizationContextImpl(user, request.params());
    should.assertTrue(WildcardPermissionBasedAuthorization.create("p1").setResource("{variable1}").match(context));
    request.response().end();
  }).listen(0, "localhost", listen -> {
    if (listen.failed()) {
      should.fail(listen.cause());
      return;
    }
    rule.vertx().createHttpClient().get(listen.result().actualPort(), "localhost", "/?variable1=r1", res -> {
      if (res.failed()) {
        should.fail(res.cause());
        return;
      }
      server.close(close -> test.complete());
    });
  });
}
 
Example 15
Source Project: vertx-auth   Source File: RoleBasedAuthorizationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMatch2(TestContext should) {
  final Async test = should.async();

  final HttpServer server = rule.vertx().createHttpServer();
  server.requestHandler(request -> {
    User user = User.create(new JsonObject().put("username", "dummy user"));
    user.authorizations().add("providerId", RoleBasedAuthorization.create("p1").setResource("r1"));
    AuthorizationContext context = new AuthorizationContextImpl(user, request.params());
    should.assertFalse(RoleBasedAuthorization.create("p1").setResource("{variable1}").match(context));
    request.response().end();
  }).listen(0, "localhost", listen -> {
    if (listen.failed()) {
      should.fail(listen.cause());
      return;
    }

    rule.vertx().createHttpClient().get(listen.result().actualPort(), "localhost", "/?variable1=r2", res -> {
      if (res.failed()) {
        should.fail(res.cause());
        return;
      }
      server.close(close -> test.complete());
    });
  });
}
 
Example 16
Source Project: vert.x-microservice   Source File: ServiceEntryPoint.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * start the server, attach the route matcher
 */
private void initHTTPConnector() {
    HttpServer server = vertx.createHttpServer(new HttpServerOptions().setHost(host)
            .setPort(port));
    registerWebSocketHandler(server);
    // TODO provide a WebSocket and a EventBus access to ServiceInfo ... this must be routed through the Router to enrich the service info with metadata from the router
    routeMatcher.matchMethod(HttpMethod.GET, serviceInfoPath, request -> fetchRegitryAndUpdateMetadata((serviceInfo -> {
        request.response().putHeader("content-type", "text/json");
        request.response().end(serviceInfo.encodePrettily());
    })));
    routeMatcher.matchMethod(HttpMethod.GET,"/metrics",req -> {
        MetricsService metricsService = MetricsService.create(vertx);
        JsonObject metrics = metricsService.getMetricsSnapshot(vertx);
        req.response().putHeader("content-type", "text/json");
        req.response().end(metrics.encodePrettily());
    }) ;
    routeMatcher.noMatch(handler -> handler.response().end("no route found"));
    server.requestHandler(routeMatcher::accept).listen(res -> {

    });


}
 
Example 17
Source Project: examples   Source File: WebsiteMain.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    System.out.println("done waiting");

    Vertx vertx = Vertx.vertx();

    // Deploy
    DeploymentOptions options = new DeploymentOptions().setWorker(true);
    ZookeeperVerticle zkv = new ZookeeperVerticle();
    vertx.deployVerticle(zkv, options);

    HttpServer server = vertx.createHttpServer();
    server.requestHandler(request -> {
        HttpServerResponse response = request.response();
        response.putHeader("content-type", "application/json");
        JsonObject responseJson;
        synchronized (WebsiteMain.jsonObject) {
            responseJson = WebsiteMain.jsonObject.copy();
        }
        response.end(responseJson.encodePrettily());
    });
    server.listen(8080);
}
 
Example 18
/**
 * Create an HTTP Server and return a future for the startup result
 * @return Future for handling the serve open event
 */
protected Future<HttpServer> createServer() {
  Future<HttpServer> ret = Future.future();

  HttpServerOptions serverOptions =
      new HttpServerOptions()
          .setLogActivity(true)
          .setPort(8091)
          .setSsl(false);

  httpServer = this.vertx.createHttpServer(serverOptions);

  // Simple 200 handler
  httpServer.requestHandler( req -> req.response().setStatusCode(200).end("Success!") );

  // Listen! delegating to the future
  httpServer.listen( ret.completer() );

  return ret;
}
 
Example 19
@Test
public void testVersionDetectionOpenShift39(VertxTestContext context) throws InterruptedException {
    String version = "{\n" +
            "  \"major\": \"1\",\n" +
            "  \"minor\": \"9\",\n" +
            "  \"gitVersion\": \"v1.9.1+a0ce1bc657\",\n" +
            "  \"gitCommit\": \"a0ce1bc\",\n" +
            "  \"gitTreeState\": \"clean\",\n" +
            "  \"buildDate\": \"2018-06-24T01:54:00Z\",\n" +
            "  \"goVersion\": \"go1.9\",\n" +
            "  \"compiler\": \"gc\",\n" +
            "  \"platform\": \"linux/amd64\"\n" +
            "}";

    HttpServer mockHttp = startMockApi(context, version, Collections.EMPTY_LIST);

    KubernetesClient client = new DefaultKubernetesClient("127.0.0.1:" + mockHttp.actualPort());

    Checkpoint a = context.checkpoint();

    PlatformFeaturesAvailability.create(vertx, client).onComplete(context.succeeding(pfa -> context.verify(() -> {
        assertThat("Versions are not equal", pfa.getKubernetesVersion(), is(KubernetesVersion.V1_9));
        stopMockApi(context, mockHttp);
        a.flag();
    })));
}
 
Example 20
Source Project: ethsigner   Source File: ClientSideTlsAcceptanceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void ethSignerDoesNotConnectToServerNotSpecifiedInTrustStore(@TempDir Path workDir)
    throws Exception {
  final TlsCertificateDefinition serverPresentedCert =
      TlsCertificateDefinition.loadFromResource("tls/cert1.pfx", "password");
  final TlsCertificateDefinition ethSignerCert =
      TlsCertificateDefinition.loadFromResource("tls/cert2.pfx", "password2");
  final TlsCertificateDefinition ethSignerExpectedServerCert =
      TlsCertificateDefinition.loadFromResource("tls/cert2.pfx", "password2");

  final HttpServer web3ProviderHttpServer =
      serverFactory.create(serverPresentedCert, ethSignerCert, workDir);

  signer =
      createAndStartSigner(
          ethSignerCert,
          ethSignerExpectedServerCert,
          web3ProviderHttpServer.actualPort(),
          0,
          workDir);

  assertThatThrownBy(() -> signer.accounts().balance("0x123456"))
      .isInstanceOf(ClientConnectionException.class)
      .hasMessageContaining(String.valueOf(BAD_GATEWAY.code()));

  // ensure submitting a transaction results in the same behaviour
  final Transaction transaction =
      Transaction.createEtherTransaction(
          signer.accounts().richBenefactor().address(),
          null,
          GAS_PRICE,
          INTRINSIC_GAS,
          "0x1b00ba00ca00bb00aa00bc00be00ac00ca00da00",
          Convert.toWei("1.75", Unit.ETHER).toBigIntegerExact());

  assertThatThrownBy(() -> signer.transactions().submit(transaction))
      .isInstanceOf(ClientConnectionException.class)
      .hasMessageContaining(String.valueOf(BAD_GATEWAY.code()));
}
 
Example 21
Source Project: djl-demo   Source File: WebVerticle.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void start() {
	HttpServer server = vertx.createHttpServer();
	Router router = Router.router(vertx);
	router.route().handler(BodyHandler.create());

	SockJSHandler sockJSHandler = SockJSHandler.create(vertx);
	BridgeOptions options = new BridgeOptions();

	options.addInboundPermitted(new PermittedOptions().setAddress(ADDRESS_TRAINER_REQUEST));

	options.addOutboundPermitted(new PermittedOptions().setAddress(ADDRESS_TRAINER));

	// Event bus
	router.mountSubRouter("/api/eventbus", sockJSHandler.bridge(options));

	// Static content (UI)
	router.route("/*").handler(StaticHandler.create());
	router.route("/*").handler(rc -> {
		if (!rc.currentRoute().getPath().startsWith("/api")) {
			rc.reroute("/index.html");
		}
	});

	server.requestHandler(router).listen(port, http -> {
		if (http.succeeded()) {
			LOGGER.info("HTTP server started: http://localhost:{0}", String.valueOf(port));
		} else {
			LOGGER.info("HTTP server failed on port {0}", String.valueOf(port));
		}
	});
}
 
Example 22
Source Project: vxms   Source File: VxmsEndpoint.java    License: Apache License 2.0 5 votes vote down vote up
private static void initWebSocketExtensions(HttpServer server,
                                            AbstractVerticle registrationObject, VxmsShared vxmsShared) {
    // check for websocket extension
    final Vertx vertx = vxmsShared.getVertx();
    final JsonObject config = vertx.getOrCreateContext().config();
    Optional.
            ofNullable(getWebSocketSPI()).
            ifPresent(webSockethandlerSPI -> StreamUtils.asStream(webSockethandlerSPI).forEach(spi -> {
                spi
                        .registerWebSocketHandler(server, vertx, config, registrationObject);
                log("start websocket extension: " + spi.getClass().getCanonicalName());
            }));
}
 
Example 23
Source Project: vertx-unit   Source File: Examples.java    License: Apache License 2.0 5 votes vote down vote up
public static void vertxInteg2(Vertx vertx, TestSuite suite) throws Exception {
  suite.test("test-server", testContext -> {
    HttpServer server = vertx.createHttpServer().requestHandler(req -> {
      if (req.path().equals("/somepath")) {
        throw new AssertionError("Wrong path!");
      }
      req.response().end();
    });
  });
}
 
Example 24
public void stopMockApi(VertxTestContext context, HttpServer server) throws InterruptedException {
    Checkpoint async = context.checkpoint();

    server.close(res -> {
        if (res.succeeded())    {
            async.flag();
        } else {
            throw new RuntimeException("Failed to stop Mock HTTP server");
        }
    });

    if (!context.awaitCompletion(60, TimeUnit.SECONDS)) {
        context.failNow(new Throwable("Test timeout"));
    }
}
 
Example 25
Source Project: vertx-rx   Source File: NativeExamples.java    License: Apache License 2.0 5 votes vote down vote up
public void observableToHandler() {
  Observer<HttpServer> observer = new Observer<HttpServer>() {
    @Override
    public void onNext(HttpServer o) {
    }
    @Override
    public void onError(Throwable e) {
    }
    @Override
    public void onCompleted() {
    }
  };
  Handler<AsyncResult<HttpServer>> handler = RxHelper.toFuture(observer);
}
 
Example 26
Source Project: joyqueue   Source File: VertTest.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    Vertx vertx = Vertx.vertx();
    HttpServer server = vertx.createHttpServer();
    Router router = Router.router(vertx);
    router.get("/hello").handler(routingContext -> {
        HttpServerRequest request = routingContext.request();
        System.out.println(request.params().toString());
        routingContext.response().end("helloworld");
    });
    server.requestHandler(request -> router.accept(request)).listen(8080);
    server.close();
}
 
Example 27
Source Project: vertx-vaadin   Source File: VaadinVerticle.java    License: MIT License 5 votes vote down vote up
private Future<Router> startupHttpServer(VertxVaadin vertxVaadin) {
    String mountPoint = vertxVaadin.config().mountPoint();
    HttpServerOptions serverOptions = new HttpServerOptions().setCompressionSupported(true);

    Router router = Router.router(vertx);
    router.mountSubRouter(mountPoint, vertxVaadin.router());

    httpServer = vertx.createHttpServer(serverOptions).requestHandler(router);
    Promise<HttpServer> promise = Promise.promise();
    Future<HttpServer> future = promise.future();
    future.setHandler(event -> {
        if (event.succeeded()) {
            log.info("Started vaadin verticle " + getClass().getName() + " on port " + event.result().actualPort());
        } else {
            log.error("Cannot start http server", event.cause());
        }
    });

    httpPort().setHandler(event -> {
        if (event.succeeded()) {
            httpServer.listen(event.result(), promise);
        } else {
            promise.fail(event.cause());
        }
    });

    return future.map(router);
}
 
Example 28
Source Project: hono   Source File: HttpServiceBase.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private Future<HttpServer> bindInsecureHttpServer(final Router router) {

        if (isInsecurePortEnabled()) {
            final Promise<HttpServer> result = Promise.promise();
            final String bindAddress = insecureServer == null ? getConfig().getInsecurePortBindAddress() : "?";
            if (insecureServer == null) {
                insecureServer = vertx.createHttpServer(getInsecureHttpServerOptions());
            }
            insecureServer.requestHandler(router).listen(bindAttempt -> {
                if (bindAttempt.succeeded()) {
                    if (getInsecurePort() == getInsecurePortDefaultValue()) {
                        log.info("server listens on standard insecure port [{}:{}]", bindAddress, insecureServer.actualPort());
                    } else {
                        log.warn("server listens on non-standard insecure port [{}:{}], default is {}", bindAddress,
                                insecureServer.actualPort(), getInsecurePortDefaultValue());
                    }
                    result.complete(bindAttempt.result());
                } else {
                    log.error("cannot bind to insecure port", bindAttempt.cause());
                    result.fail(bindAttempt.cause());
                }
            });
            return result.future();
        } else {
            return Future.succeededFuture();
        }
    }
 
Example 29
Source Project: quarantyne   Source File: ProxyVerticle.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void start(Future<Void> startFuture) {
  this.bouncer = new Bouncer(vertx, configSupplier, configArgs);
  // proxy server (this server)
  HttpServerOptions httpServerOptions = new HttpServerOptions();
  httpServerOptions.setHost(configArgs.getIngress().getIp());
  httpServerOptions.setUsePooledBuffers(true);
  HttpServer httpServer = vertx.createHttpServer(httpServerOptions);

  // http client to remote
  HttpClientOptions httpClientOptions = new HttpClientOptions();
  httpClientOptions.setKeepAlive(true);
  httpClientOptions.setLogActivity(true);

  if (configArgs.getEgress().isSsl()) {
    httpClientOptions.setSsl(true);
  }
  httpClientOptions.setDefaultHost(configArgs.getEgress().getHost());
  httpClientOptions.setDefaultPort(configArgs.getEgress().getPort());

  this.httpClient = vertx.createHttpClient(httpClientOptions);

  httpServer.requestHandler(frontReq -> {
    if (frontReq.method().equals(HttpMethod.POST) || frontReq.method().equals(HttpMethod.PUT)) {
      frontReq.bodyHandler(reqBody -> {
        proxiedRequestHandler(frontReq, reqBody);
      });
    } else {
      proxiedRequestHandler(frontReq, null);
    }
  }).exceptionHandler(ex -> {
    log.error("HTTP server error", ex);
  }).listen(configArgs.getIngress().getPort(), configArgs.getIngress().getIp(), h -> {
    if (h.failed()) {
      log.error("proxy failed to start", h.cause());
      startFuture.fail(h.cause());
    }
  });
}
 
Example 30
@BeforeEach
void setUp() throws InterruptedException
{
    AtomicBoolean failedToListen = new AtomicBoolean(false);

    do
    {
        injector = Guice.createInjector(Modules.override(new MainModule())
                                               .with(new IntegrationTestModule(1, sessions)));
        vertx = injector.getInstance(Vertx.class);
        HttpServer httpServer = injector.getInstance(HttpServer.class);
        Configuration config = injector.getInstance(Configuration.class);
        port = config.getPort();

        CountDownLatch waitLatch = new CountDownLatch(1);
        httpServer.listen(port, res ->
        {
            if (res.succeeded())
            {
                logger.info("Succeeded to listen on port " + port);
            }
            else
            {
                logger.error("Failed to listen on port " + port + " " + res.cause());
                failedToListen.set(true);
            }
            waitLatch.countDown();
        });

        if (waitLatch.await(60, TimeUnit.SECONDS))
            logger.info("Listen complete before timeout.");
        else
            logger.error("Listen complete timed out.");

        if (failedToListen.get())
            closeClusters();
    } while(failedToListen.get());
}