Java Code Examples for io.vertx.core.http.HttpServer#listen()

The following examples show how to use io.vertx.core.http.HttpServer#listen() . 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 File: RestServerVerticle.java    From servicecomb-java-chassis with Apache License 2.0 7 votes vote down vote up
@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 2
Source File: AdminVerticle.java    From quarantyne with Apache License 2.0 6 votes vote down vote up
public void start() {
  this.metricsService = MetricsService.create(vertx);

  HttpServer httpServer = vertx.createHttpServer();
  httpServer.requestHandler(req -> {
    if (req.path().equals(HEALTH_PATH)) {
      req.response().end("ok");
    } else if (req.path().equals(METRICS_PATH)) {
      publishMetricsSnapshot(req.response());
    } else {
      req.response().setStatusCode(404).end("HTTP 404");
    }
  });
  // we don't start this verticle unless this was defined
  httpServer.listen(ipPort.getPort(), ipPort.getIp(), h -> {
    if (h.failed()) {
      log.info("failed to start admin service", h.cause());
    }
  });
}
 
Example 3
Source File: App.java    From generator-jvm with 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 4
Source File: Examples.java    From vertx-unit with Apache License 2.0 6 votes vote down vote up
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
}
 
Example 5
Source File: Main.java    From mewbase with 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 6
Source File: WebsiteMain.java    From examples with 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 7
Source File: TestVertxMetersInitializer.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Override
@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.
public void start(Future<Void> startFuture) {
  Router mainRouter = Router.router(vertx);
  mainRouter.route("/").handler(context -> {
    context.response().end(context.getBody());
  });

  HttpServer server = vertx.createHttpServer();
  server.requestHandler(mainRouter);
  server.listen(0, "0.0.0.0", ar -> {
    if (ar.succeeded()) {
      port = ar.result().actualPort();
      startFuture.complete();
      return;
    }

    startFuture.fail(ar.cause());
  });
}
 
Example 8
Source File: WebServerVerticle.java    From chuidiang-ejemplos with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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();
}
 
Example 9
Source File: WhitelistNodeClientTest.java    From orion with Apache License 2.0 5 votes vote down vote up
private static void startServer(final HttpServer server) throws Exception {
  final CompletableAsyncCompletion completion = AsyncCompletion.incomplete();
  server.listen(getFreePort(), result -> {
    if (result.succeeded()) {
      completion.complete();
    } else {
      completion.completeExceptionally(result.cause());
    }
  });
  completion.join();
}
 
Example 10
Source File: HttpTermServerSubRouterTest.java    From vertx-shell with Apache License 2.0 5 votes vote down vote up
@Override
protected TermServer createServer(TestContext context, HttpTermOptions options) {
  HttpServer httpServer = vertx.createHttpServer(new HttpServerOptions().setPort(8080));
  Router router = Router.router(vertx);
  Router subRouter = Router.router(vertx);
  router.mountSubRouter("/sub", subRouter);
  httpServer.requestHandler(router);
  Async async = context.async();
  httpServer.listen(8080, context.asyncAssertSuccess(s -> {
    async.complete();
  }));
  async.awaitSuccess(20000);
  return TermServer.createHttpTermServer(vertx, subRouter, options);
}
 
Example 11
Source File: SimpleWebsiteMain.java    From examples with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    Vertx vertx = Vertx.vertx();
    HttpServer server = vertx.createHttpServer();
    server.requestHandler(request -> {
        HttpServerResponse response = request.response();
        response.putHeader("content-type", "application/json");
        JsonObject responseJson = SimpleWebsiteMain.jsonObject.copy();
        response.end(responseJson.encodePrettily());
    });
    server.listen(8080);
}
 
Example 12
Source File: SecurityTestUtils.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
static void startServer(HttpServer server) {
  CompletableFuture<Boolean> future = new CompletableFuture<>();
  server.listen(0, result -> {
    if (result.succeeded()) {
      future.complete(true);
    } else {
      future.completeExceptionally(result.cause());
    }
  });
  future.join();
}
 
Example 13
Source File: Examples.java    From vertx-unit with Apache License 2.0 5 votes vote down vote up
public static void async_04(TestContext context, Vertx vertx, Handler<HttpServerRequest> requestHandler) {
  Async async = context.async();
  HttpServer server = vertx.createHttpServer();
  server.requestHandler(requestHandler);
  server.listen(8080, ar -> {
    context.assertTrue(ar.succeeded());
    async.complete();
  });

  // Wait until completion
  async.awaitSuccess();

  // Do something else
}
 
Example 14
Source File: CertificateAuthorityNodeClientTest.java    From orion with Apache License 2.0 5 votes vote down vote up
private static void startServer(final HttpServer server) throws Exception {
  final CompletableAsyncCompletion completion = AsyncCompletion.incomplete();
  server.listen(getFreePort(), result -> {
    if (result.succeeded()) {
      completion.complete();
    } else {
      completion.completeExceptionally(result.cause());
    }
  });
  completion.join();
}
 
Example 15
Source File: InsecureNodeClientTest.java    From orion with Apache License 2.0 5 votes vote down vote up
private static void startServer(final HttpServer server) throws Exception {
  final CompletableAsyncCompletion completion = AsyncCompletion.incomplete();
  server.listen(getFreePort(), result -> {
    if (result.succeeded()) {
      completion.complete();
    } else {
      completion.completeExceptionally(result.cause());
    }
  });
  completion.join();
}
 
Example 16
Source File: VertxHttpRecorder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private void setupTcpHttpServer(HttpServer httpServer, HttpServerOptions options, boolean https,
        Future<Void> startFuture, AtomicInteger remainingCount) {
    httpServer.listen(options.getPort(), options.getHost(), event -> {
        if (event.cause() != null) {
            startFuture.fail(event.cause());
        } else {
            // Port may be random, so set the actual port
            int actualPort = event.result().actualPort();
            if (actualPort != options.getPort()) {
                // Override quarkus.http(s)?.(test-)?port
                String schema;
                if (https) {
                    clearHttpsProperty = true;
                    schema = "https";
                } else {
                    clearHttpProperty = true;
                    schema = "http";
                }
                System.setProperty(
                        launchMode == LaunchMode.TEST ? "quarkus." + schema + ".test-port"
                                : "quarkus." + schema + ".port",
                        String.valueOf(actualPort));
                // Set in HttpOptions to output the port in the Timing class
                options.setPort(actualPort);
            }
            if (remainingCount.decrementAndGet() == 0) {
                startFuture.complete(null);
            }
        }
    });
}
 
Example 17
Source File: VertxHttpRecorder.java    From quarkus with Apache License 2.0 5 votes vote down vote up
private void setupUnixDomainSocketHttpServer(HttpServer httpServer, HttpServerOptions options, Future<Void> startFuture,
        AtomicInteger remainingCount) {
    httpServer.listen(SocketAddress.domainSocketAddress(options.getHost()), event -> {
        if (event.succeeded()) {
            if (remainingCount.decrementAndGet() == 0) {
                startFuture.complete(null);
            }
        } else {
            startFuture.fail(event.cause());
        }
    });
}
 
Example 18
Source File: HealthServiceIntegrationTest.java    From cassandra-sidecar with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example 19
Source File: SecurityTestUtils.java    From cava with Apache License 2.0 5 votes vote down vote up
static void startServer(HttpServer server) {
  CompletableFuture<Boolean> future = new CompletableFuture<>();
  server.listen(0, result -> {
    if (result.succeeded()) {
      future.complete(true);
    } else {
      future.completeExceptionally(result.cause());
    }
  });
  future.join();
}
 
Example 20
Source File: FigWheelyServer.java    From vertxui with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void start() {
	HttpServer server = vertx.createHttpServer();
	server.websocketHandler(webSocket -> {
		if (!webSocket.path().equals("/" + urlSocket)) {
			webSocket.reject();
			return;
		}
		final String id = webSocket.textHandlerID();
		// log.info("welcoming " + id);
		vertx.sharedData().getLocalMap(browserIds).put(id, "whatever");
		webSocket.closeHandler(data -> {
			vertx.sharedData().getLocalMap(browserIds).remove(id);
		});
		webSocket.handler(buffer -> {
			log.info(buffer.toString());
		});
	});
	server.listen(portSocket, listenHandler -> {
		if (listenHandler.failed()) {
			log.log(Level.SEVERE, "Startup error", listenHandler.cause());
			System.exit(0); // stop on startup error
		}
	});

	// Ensure that even outside this class people can push messages to the
	// browser
	vertx.eventBus().consumer(figNotify, message -> {
		for (Object obj : vertx.sharedData().getLocalMap(browserIds).keySet()) {
			vertx.eventBus().send((String) obj, message.body());
		}
	});

	vertx.setPeriodic(250, id -> {
		if (VertxUI.isCompiling()) {
			return;
		}
		for (Watchable watchable : watchables) {
			String currentState = watchable.getCurrentState();
			if (watchable.lastState.equals(currentState)) {
				continue;
			}
			log.info("Changed: " + watchable.root);
			watchable.lastState = currentState;
			if (watchable.handler == null) {
				log.info("Skipping recompile, no handler found.");
			} else {
				// Recompile
				boolean succeeded = watchable.handler.translate();
				if (succeeded == false) {
					vertx.eventBus().publish(figNotify,
							"unsuccessfull rebuild for url=" + watchable.url + " root=" + watchable.root);
				}
			}
			vertx.eventBus().publish(figNotify, "reload: " + watchable.url);
		}
	});
}