@Override public void start(Future<Void> startFuture) throws Exception { super.start(); // 如果本地未配置地址,则表示不必监听,只需要作为客户端使用即可 if (endpointObject == null) { LOGGER.warn("rest listen address is not configured, will not start."); startFuture.complete(); return; } Router mainRouter = Router.router(vertx); mountAccessLogHandler(mainRouter); initDispatcher(mainRouter); HttpServer httpServer = createHttpServer(); httpServer.requestHandler(mainRouter::accept); startListen(httpServer, startFuture); }
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()); }); }
@Test public void testSyncAndWaitFiveSecondsForTimeOut() throws Exception { // Create a server that will take a long time to reply to a request. final HttpServer timeOutHttpServer = vertx.createHttpServer(); timeOutHttpServer.requestHandler( e -> { try { Thread.sleep(100000); } catch (InterruptedException ex) { ex.printStackTrace(); } }); timeOutHttpServer.listen(TIMEOUT_SERVER_PORT); // Send a request synchronously and wait 5 seconds for a response. doSync(e -> vertx.createHttpClient().getNow(TIMEOUT_SERVER_PORT, HOST, URI, e::complete), 5); }
@Override public void start(final Future<Void> startFuture) throws Exception { HttpServer http = vertx.createHttpServer(); Router router = Router.router(vertx); router.get("/hello").handler(ctx -> ctx.response().end("World " + System.currentTimeMillis())); http.requestHandler(router::accept).listen(11011, result -> { if(result.succeeded()){ System.out.println("Listening on port 11011"); } else { throw new RuntimeException("Server start failed"); } }); }
public MetricsFacade(Vertx vertx, HttpServer httpServer, int publicationPeriodInMillis) { this.httpServer = httpServer; this.metricsService = MetricsService.create(vertx); logger.info("Scheduling metrics publication every {}ms", publicationPeriodInMillis); // ensure that the metrics publication does *not* happen on an event loop thread vertx.setPeriodic( publicationPeriodInMillis, event -> vertx.executeBlocking( event1 -> { JsonObject metrics = metricsService.getMetricsSnapshot(httpServer); if (metrics != null) { metricsLogger.info(metrics.encode()); } event1.complete(); }, (Handler<AsyncResult<Void>>) event12 -> { // no-op })); }
private Future<Void> startHttpServer() { Future<Void> future = Future.future(); HttpServer server = vertx.createHttpServer(); // <1> Router router = Router.router(vertx); // <2> router.get("/").handler(this::indexHandler); router.get("/wiki/:page").handler(this::pageRenderingHandler); // <3> router.post().handler(BodyHandler.create()); // <4> router.post("/save").handler(this::pageUpdateHandler); router.post("/create").handler(this::pageCreateHandler); router.post("/delete").handler(this::pageDeletionHandler); server .requestHandler(router::accept) // <5> .listen(8080, ar -> { // <6> if (ar.succeeded()) { LOGGER.info("HTTP server running on port 8080"); future.complete(); } else { LOGGER.error("Could not start a HTTP server", ar.cause()); future.fail(ar.cause()); } }); return future; }
@Override public void start() throws Exception { final Router router = Router.router(vertx); final HttpServerOptions httpServerOptions = new HttpServerOptions(); httpServerOptions.setPort(8900); final HttpServer http = vertx.createHttpServer(httpServerOptions); SwaggerHandler.registerToRouter(router, MyApp.class); final JaxRsRouter jaxRsRouter = new JaxRsRouter(); final SpringJaxRsHandler handler = new SpringJaxRsHandler(MyApp.class); jaxRsRouter.register(MyApp.class, router, handler, handler); ManifestHandler.registerToRouter(router); http.requestHandler(req -> router.accept(req)).listen(res -> { if (res.failed()) { res.cause().printStackTrace(); vertx.close(); } }); }
public static void main(String[] args) { long time = System.currentTimeMillis(); Json.mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); Vertx vertx = Vertx.vertx(); Router router = Router.router(vertx); HelloResource helloResource = new HelloResource(); router.get("/vertx/hello").produces("application/json").handler(helloResource::hello); router.route("/vertx/hello").method(HttpMethod.POST).handler(BodyHandler.create()); router.post("/vertx/hello") .consumes("application/json") .handler(helloResource::createMessage); HttpServerOptions serverOptions = new HttpServerOptions() .setPort(8085); HttpServer server = vertx.createHttpServer(serverOptions); server.requestHandler(router::accept).listen(); System.out.println("started in " + (System.currentTimeMillis() - time) + " ms"); }
private Future<HttpServer> configureTheHTTPServer() { Future<HttpServer> future = Future.future(); // Use a Vert.x Web router for this REST API. Router router = Router.router(vertx); router.get(config.getString("http.root")).handler(context -> { Future<List<JsonObject>> jdbcFuture = retrieveOperations(); jdbcFuture.setHandler(jdbc -> { if (jdbc.succeeded()) { context.response() .putHeader("Content-Type", "application/json") .setStatusCode(200) .end(Json.encodePrettily(jdbcFuture.result())); } else { context.response().setStatusCode(500).end(jdbc.cause().toString()); } }); }); vertx.createHttpServer() .requestHandler(router::accept) .listen(config.getInt("http.port"), future.completer()); return future; }
private Future<HttpServer> startHttpServer() { Future<HttpServer> webServerFuture = Future.future(); Future<Void> routerFuture = Future.future(); Router router = configureRouter(routerFuture); routerFuture.compose(i -> { HttpServerOptions httpOptions = configureWebServer(); int port = config.getPort(); LOG.info("Starting web server on port {}", port); server = vertx.createHttpServer(httpOptions) .requestHandler(router::accept) .listen(port, webServerFuture); }, webServerFuture); return webServerFuture; }
@Test public void testValidJWT(TestContext context) throws URISyntaxException { HttpServer openIdMockServer = this.createOpenIdMockServer(CERTS_VALID); Async openIdStarted = context.async(); openIdMockServer.listen(TestConfig.OPENID_PORT, context.asyncAssertSuccess(i -> openIdStarted.complete())); openIdStarted.awaitSuccess(5000); JsonObject config = TestConfig.getApiConfig(); config.getJsonObject("auth").put("enable", true); deployApiVerticle(context, config); createSslRequest("/api/v1.0/pr/latest") .putHeader("Authorization", "Bearer " + JWT_TOKEN) .send(context.asyncAssertSuccess(res -> context.assertEquals(200, res.statusCode()) )); openIdMockServer.close(context.asyncAssertSuccess()); }
private Future<HttpServer> bindSecureHttpServer(final Router router) { if (isSecurePortEnabled()) { Future<HttpServer> result = Future.future(); final String bindAddress = server == null ? getConfig().getBindAddress() : "?"; if (server == null) { server = vertx.createHttpServer(getHttpServerOptions()); } server.requestHandler(router::accept).listen(done -> { if (done.succeeded()) { LOG.info("secure http server listening on {}:{}", bindAddress, server.actualPort()); result.complete(done.result()); } else { LOG.error("error while starting up secure http server", done.cause()); result.fail(done.cause()); } }); return result; } else { return Future.succeededFuture(); } }
private Future<HttpServer> bindInsecureHttpServer(final Router router) { if (isInsecurePortEnabled()) { Future<HttpServer> result = Future.future(); final String bindAddress = insecureServer == null ? getConfig().getInsecurePortBindAddress() : "?"; if (insecureServer == null) { insecureServer = vertx.createHttpServer(getInsecureHttpServerOptions()); } insecureServer.requestHandler(router::accept).listen(done -> { if (done.succeeded()) { LOG.info("insecure http server listening on {}:{}", bindAddress, insecureServer.actualPort()); result.complete(done.result()); } else { LOG.error("error while starting up insecure http server", done.cause()); result.fail(done.cause()); } }); return result; } else { return Future.succeededFuture(); } }
/** * Verifies that a client provided http server is started instead of creating and starting a new http server. * * @param ctx The helper to use for running async tests on vertx. * @throws Exception if the test fails. */ @SuppressWarnings("unchecked") @Test public void testStartUsesClientProvidedHttpServer(final TestContext ctx) throws Exception { // GIVEN an adapter with a client provided http server HttpServer server = getHttpServer(false); AbstractVertxBasedHttpProtocolAdapter<HttpProtocolAdapterProperties> adapter = getAdapter(server, null); adapter.setCredentialsAuthProvider(credentialsAuthProvider); // WHEN starting the adapter Async startup = ctx.async(); Future<Void> startupTracker = Future.future(); startupTracker.setHandler(ctx.asyncAssertSuccess(s -> { startup.complete(); })); adapter.start(startupTracker); // THEN the client provided http server has been configured and started startup.await(); verify(server).requestHandler(any(Handler.class)); verify(server).listen(any(Handler.class)); verify(messagingClient).connect(any(ProtonClientOptions.class), any(Handler.class), any(Handler.class)); verify(registrationClient).connect(any(ProtonClientOptions.class), any(Handler.class), any(Handler.class)); }
/** * Verifies that the <me>onStartupSuccess</em> method is invoked if the http server has been started successfully. * * @param ctx The helper to use for running async tests on vertx. * @throws Exception if the test fails. */ @Test public void testStartInvokesOnStartupSuccess(final TestContext ctx) throws Exception { // GIVEN an adapter with a client provided http server HttpServer server = getHttpServer(false); Async onStartupSuccess = ctx.async(); AbstractVertxBasedHttpProtocolAdapter<HttpProtocolAdapterProperties> adapter = getAdapter(server, s -> onStartupSuccess.complete()); adapter.setCredentialsAuthProvider(credentialsAuthProvider); adapter.setMetrics(mock(HttpAdapterMetrics.class)); // WHEN starting the adapter Async startup = ctx.async(); Future<Void> startupTracker = Future.future(); startupTracker.setHandler(ctx.asyncAssertSuccess(s -> { startup.complete(); })); adapter.start(startupTracker); // THEN the onStartupSuccess method has been invoked startup.await(); onStartupSuccess.await(); }
/** * Verifies that the <me>onStartupSuccess</em> method is not invoked if no credentials authentication provider is set. * * @param ctx The helper to use for running async tests on vertx. */ @Test public void testStartUpFailsIfCredentialsAuthProviderIsNotSet(final TestContext ctx) { // GIVEN an adapter with a client provided http server HttpServer server = getHttpServer(false); AbstractVertxBasedHttpProtocolAdapter<HttpProtocolAdapterProperties> adapter = getAdapter(server, s -> ctx.fail("should not have invoked onStartupSuccess")); // WHEN starting the adapter Async startup = ctx.async(); Future<Void> startupTracker = Future.future(); startupTracker.setHandler(ctx.asyncAssertFailure(s -> { startup.complete(); })); adapter.start(startupTracker); // THEN the onStartupSuccess method has been invoked startup.await(); }
/** * Verifies that the adapter waits for an event being settled and accepted * by a downstream peer before responding with a 202 status to the device. */ @Test public void testUploadEventWaitsForAcceptedOutcome() { // GIVEN an adapter with a downstream event consumer attached final Future<ProtonDelivery> outcome = Future.future(); givenAnEventSenderForOutcome(outcome); HttpServer server = getHttpServer(false); AbstractVertxBasedHttpProtocolAdapter<HttpProtocolAdapterProperties> adapter = getAdapter(server, null); // WHEN a device publishes an event final Buffer payload = Buffer.buffer("some payload"); final HttpServerResponse response = mock(HttpServerResponse.class); final RoutingContext ctx = newRoutingContext(payload, response); adapter.uploadEventMessage(ctx, "tenant", "device", payload, "application/text"); // THEN the device does not get a response verify(response, never()).end(); // until the event has been accepted outcome.complete(mock(ProtonDelivery.class)); verify(response).setStatusCode(202); verify(response).end(); }
/** * Verifies that the adapter fails the upload of an event with a 400 * result if it is rejected by the downstream peer. */ @Test public void testUploadEventFailsForRejectedOutcome() { // GIVEN an adapter with a downstream event consumer attached final Future<ProtonDelivery> outcome = Future.future(); givenAnEventSenderForOutcome(outcome); HttpServer server = getHttpServer(false); AbstractVertxBasedHttpProtocolAdapter<HttpProtocolAdapterProperties> adapter = getAdapter(server, null); // WHEN a device publishes an event that is not accepted by the peer final Buffer payload = Buffer.buffer("some payload"); final RoutingContext ctx = newRoutingContext(payload); adapter.uploadEventMessage(ctx, "tenant", "device", payload, "application/text"); outcome.fail(new ClientErrorException(HttpURLConnection.HTTP_BAD_REQUEST, "malformed message")); // THEN the device gets a 400 verify(ctx).fail(HttpURLConnection.HTTP_BAD_REQUEST); }
/** * Verifies that the adapter does not wait for a telemetry message being settled and accepted * by a downstream peer before responding with a 202 status to the device. */ @Test public void testUploadTelemetryDoesNotWaitForAcceptedOutcome() { // GIVEN an adapter with a downstream telemetry consumer attached final Future<ProtonDelivery> outcome = Future.succeededFuture(mock(ProtonDelivery.class)); givenATelemetrySenderForOutcome(outcome); HttpServer server = getHttpServer(false); AbstractVertxBasedHttpProtocolAdapter<HttpProtocolAdapterProperties> adapter = getAdapter(server, null); // WHEN a device publishes a telemetry message final Buffer payload = Buffer.buffer("some payload"); final HttpServerResponse response = mock(HttpServerResponse.class); final RoutingContext ctx = newRoutingContext(payload, response); adapter.uploadTelemetryMessage(ctx, "tenant", "device", payload, "application/text"); // THEN the device receives a 202 response immediately verify(response).setStatusCode(202); verify(response).end(); }
@SuppressWarnings("unchecked") private HttpServer getHttpServer(final boolean startupShouldFail) { 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 -> { Handler<AsyncResult<HttpServer>> handler = (Handler<AsyncResult<HttpServer>>) invocation.getArgumentAt(0, Handler.class); if (startupShouldFail) { handler.handle(Future.failedFuture("http server intentionally failed to start")); } else { handler.handle(Future.succeededFuture(server)); } return server; }); return server; }
@Override public void start() { boolean debug = true; // Serve the javascript for figwheely (and turn it on too) Router router = Router.router(vertx); if (debug) { router.get(FigWheelyClient.urlJavascript).handler(FigWheelyServer.create()); } // The main compiled js router.get("/*").handler(VertxUI.with(ExampleClient.class, "/", debug, true)); // Start the server HttpServer server = vertx.createHttpServer(new HttpServerOptions().setCompressionSupported(true)); server.requestHandler(router::accept).listen(80, listenHandler -> { if (listenHandler.failed()) { log.log(Level.SEVERE, "Startup error", listenHandler.cause()); System.exit(0);// stop on startup error } log.info("Initialised:" + router.getRoutes().stream().map(a -> { return "\n\thttp://localhost:" + server.actualPort() + a.getPath(); }).distinct().collect(Collectors.joining())); }); }
public static void start(Class<?> classs, Router router, HttpServer httpServer) { boolean debug = true; // Serve the javascript for figwheely (and turn it on too) if (debug) { router.get(FigWheelyClient.urlJavascript).handler(FigWheelyServer.create()); } // The main compiled js router.get("/*").handler(VertxUI.with(classs, "/", debug, true)); // Start the server httpServer.requestHandler(router::accept).listen(8088, listenHandler -> { if (listenHandler.failed()) { log.log(Level.SEVERE, "Startup error", listenHandler.cause()); System.exit(0);// stop on startup error } log.info("Initialised:" + router.getRoutes().stream().map(a -> { return "\n\thttp://localhost:" + httpServer.actualPort() + a.getPath(); }).distinct().collect(Collectors.joining())); }); }
@Override public void start() throws Exception { VERSION = Utils.readFileToString(vertx, "version"); HttpServerOptions serverOptions = new HttpServerOptions(); serverOptions.setCompressionSupported(true); HttpServer httpServer = vertx.createHttpServer(serverOptions); Router router = Router.router(vertx); new SpeechDropApplication(vertx, config(), Utils.readFileToString(vertx, "main.html"), Utils.readFileToString(vertx, "room.html"), Utils.readFileToString(vertx, "about.html") ).mount(router); httpServer.requestHandler(router::accept).listen(config().getInteger("port"), config().getString("host")); }
void listen(int port, Handler<AsyncResult<HttpServer>> listenHandler) { log.debug("listen(port={0}, listenHandler)", port); runnerServer = vertx.createHttpServer(); Router router = Router.router(vertx); router.get().handler(request -> { if (postgresRuns) { get(request); } else { getRequests.add(request); } }); router.post().handler(request -> { if (postgresRuns) { post(request); undeploy(); } else { postRequests.add(request); } }); runnerServer.requestHandler(router::accept).listen(port, listenHandler); }
/** * Instantiates a new transporter. * * @param name the name * @param port the port * @param vertx the vertx * @param httpServer the http server * @param router the router * @param source4conventions the source 4 conventions * @param httpServerOptions the http server options * @param routes the routes * @param handlers the handlers * @param routeHandlerClass the route handler * @param ignoreBodyHandler the ignore body handler * @param bodyHandler the body handler * @param defaultBodyEndHandlers the default body end handlers * @param authProvider the auth provider */ public Transporter(String name, int port, Vertx vertx, HttpServer httpServer, Router router, Object source4conventions, HttpServerOptions httpServerOptions, List<Class<?>> routes, List<Handler<RoutingContext>> handlers, Class<? extends Handler<RoutingContext>> routeHandlerClass, boolean ignoreBodyHandler, Handler<RoutingContext> bodyHandler, List<BodyEndHandler> defaultBodyEndHandlers, AuthProvider authProvider) { super(); this.name = name; this.port = port; this.vertx = vertx; this.httpServer = httpServer; this.router = router; this.source4conventions = source4conventions; this.httpServerOptions = httpServerOptions; this.routes = routes; this.handlers = handlers; this.routeHandlerClass = routeHandlerClass; this.ignoreBodyHandler = ignoreBodyHandler; this.bodyHandler = bodyHandler; this.defaultBodyEndHandlers = defaultBodyEndHandlers; this.authProvider = authProvider; build(); }
@PostConstruct public void start() throws InterruptedException, ExecutionException, TimeoutException { // Create two instances if (env.containsProperty("serve")) { log.info("Server started http://{}:{}/", address, port); contextRunner.executeBlocking(2, (Handler<AsyncResult<HttpServer>> handler) -> vertx.createHttpServer() .requestHandler(router::accept) .listen(port, address, handler), 1, TimeUnit.MINUTES); } else { log.info("Not starting web server. User --serve coommand line parameter."); } }
@Before public void setUp() { vertx = Vertx.vertx(); AsyncLock<HttpServer> httpLock = new AsyncLock<>(); AsyncLock<StompServer> stompLock = new AsyncLock<>(); vertx = Vertx.vertx(); server = StompServer.create(vertx, new StompServerOptions().setWebsocketBridge(true)) .handler(StompServerHandler.create(vertx) .bridge(new BridgeOptions() .addInboundPermitted(new PermittedOptions().setAddressRegex(".*")) .addOutboundPermitted(new PermittedOptions().setAddressRegex(".*"))) ) .listen(stompLock.handler()); stompLock.waitForSuccess(); HttpServerOptions httpOptions = new HttpServerOptions() .setMaxWebsocketFrameSize(MAX_WEBSOCKET_FRAME_SIZE) .setMaxWebsocketMessageSize(2048); http = vertx.createHttpServer(httpOptions).websocketHandler(server.webSocketHandler()).listen(8080, httpLock.handler()); httpLock.waitForSuccess(); }
public static void async_05(TestContext context, Vertx vertx, Handler<HttpServerRequest> requestHandler) { Async async = context.async(2); HttpServer server = vertx.createHttpServer(); server.requestHandler(requestHandler); server.listen(8080, ar -> { context.assertTrue(ar.succeeded()); async.countDown(); }); vertx.setTimer(1000, id -> { async.complete(); }); // Wait until completion of the timer and the http request async.awaitSuccess(); // Do something else }
public static void vertxInteg3(Vertx vertx, TestSuite suite) throws Exception { suite.before(testContext -> { // Report uncaught exceptions as Vert.x Unit failures vertx.exceptionHandler(testContext.exceptionHandler()); }); suite.test("test-server", testContext -> { HttpServer server = vertx.createHttpServer().requestHandler(req -> { if (req.path().equals("/somepath")) { throw new AssertionError("Wrong path!"); } req.response().end(); }); }); }
private void testRedirect(TestContext context, int responseStatus) { vertx = Vertx.vertx(); HttpServer redirectServer = vertx.createHttpServer(); redirectServer.requestHandler(req -> { HttpServerResponse resp = req.response(); resp.setStatusCode(responseStatus); resp.putHeader("Location", "http://localhost:8080/the_verticle.zip"); resp.end(); }); HttpServer server = new RepoBuilder().setVerticle(verticleWithMain).build(); redirectServer.listen(8081, context.asyncAssertSuccess(r -> { server.listen( 8080, context.asyncAssertSuccess(s -> { vertx.deployVerticle("http://localhost:8081/the_verticle.zip", context.asyncAssertSuccess()); }) ); })); }
@Test public void testDeployFromAuthenticatedRepo(TestContext context) { System.setProperty(HttpServiceFactory.AUTH_USERNAME_PROPERTY, "the_username"); System.setProperty(HttpServiceFactory.AUTH_PASSWORD_PROPERTY, "the_password"); vertx = Vertx.vertx(); HttpServer server = new RepoBuilder().setVerticle(verticleWithMain).setAuthenticated(true).build(); Async async = context.async(); server.listen( 8080, context.asyncAssertSuccess(s -> { vertx.deployVerticle("http://localhost:8080/the_verticle.zip", ar -> { context.assertTrue(ar.failed()); async.complete(); }); }) ); }
private void launch() { System.out.println("Launching web socket server..."); HttpServer server = vertx.createHttpServer(); server.websocketHandler(webSocket -> { // String test: webSocket.frameHandler(frame -> handleStringFrame(webSocket, frame)); }).listen(8000); server = vertx.createHttpServer(); server.websocketHandler(webSocket -> { // JSON test: webSocket.frameHandler(frame -> handleJsonFrame(webSocket, frame)); }).listen(8001); server = vertx.createHttpServer(); server.websocketHandler(webSocket -> { // Serialization test: webSocket.frameHandler(frame -> handleSerializationFrame(webSocket, frame)); }).listen(8002); }
@Override public void start(Future<Void> future) { server = vertx.createHttpServer(); Router router = Router.router(vertx); router.get("/").handler(rc -> rc.reroute("/static/index.html")); router.get("/static/*").handler(staticFiles); sse.connectHandler(connection -> { connection.forward(EB_ADDRESS); }); router.get("/iss/position").handler(sse); vertx.setPeriodic(10000, this::fetchISSPosition); server.requestHandler(router::accept); server.listen(PORT, future.<HttpServer>map(v -> null).completer()); }
/** * 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 -> { }); }
@Override public void start() throws Exception { HttpServer server = vertx.createHttpServer(); server.requestHandler(request -> { LOG.info("Web request arrived"); if (request.path().endsWith("index.html")) { request.response().putHeader("content-type", "text/html"); request.response().sendFile("src/main/webroot/index.html"); } else { request.response().setChunked(true); request.response().putHeader("content-type", "text/plain"); request.response().write("No such file!!"); request.response().setStatusCode(404); request.response().end(); } }); server.listen(); super.start(); }
@Test public void testNamedHttpClientMetrics() throws Exception { String name = TestUtils.randomAlphaString(10); HttpClient client = vertx.createHttpClient(new HttpClientOptions().setMetricsName(name)); HttpServer server = vertx.createHttpServer(new HttpServerOptions().setHost("localhost").setPort(8080)).requestHandler(req -> { req.response().end(); }).listen(ar -> { assertTrue(ar.succeeded()); client.request(HttpMethod.GET, 8080, "localhost", "/file", resp -> { resp.bodyHandler(buff -> { testComplete(); }); }).end(); }); await(); String baseName = "vertx.http.clients." + name; JsonObject metrics = metricsService.getMetricsSnapshot(baseName); assertCount(metrics.getJsonObject(baseName + ".bytes-read"), 1L); cleanup(client); cleanup(server); }
@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); }
@Override public void start() throws Exception { //TODO: Fix a better way of configuration other than system properties? Integer port = Integer.getInteger("websocket.port", 5556); ObservableFuture<HttpServer> httpServerObservable = RxHelper.observableFuture(); HttpServer httpServer = vertx.createHttpServer(new HttpServerOptions().setPort(port)); httpServerObservable.subscribe( a -> log.info("Starting web socket listener..."), e -> log.error("Could not start web socket listener at port " + port, e), () -> log.info("Started web socket listener on port " + port) ); Observable<Tup2<ServerWebSocket, Func1<Event, Boolean>>> eventObservable = EventObservable.convertFromWebSocketObservable(RxHelper.toObservable(httpServer.websocketStream())); eventObservable.subscribe(new EventToJsonAction(Riemann.getEvents(vertx), WebSocketFrameImpl::new), e -> { log.error(e); //TODO: Fix proper error handling }); httpServer.listen(httpServerObservable.asHandler()); }