io.vertx.reactivex.core.http.HttpServer Java Examples

The following examples show how to use io.vertx.reactivex.core.http.HttpServer. 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: CrnkVerticle.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Override
public void start() {
    LOGGER.debug("starting");
    HttpServer server = vertx.createHttpServer();

    CrnkVertxHandler handler = new CrnkVertxHandler((boot) -> {
        SimpleModule daggerModule = new SimpleModule("dagger");
        daggerModule.addSecurityProvider(securityProvider);
        modules.forEach(it -> boot.addModule(it));
        repositories.forEach(it -> daggerModule.addRepository(it));
        boot.addModule(daggerModule);
    });
    handler.addInterceptor(securityProvider);

    server.requestStream().toFlowable()
            .flatMap(request -> handler.process(request))
            .subscribe((response) -> LOGGER.debug("delivered response {}", response), error -> LOGGER.debug("error occured", error));
    LOGGER.debug("listen on port={}", port);
    server.listen(port);
    LOGGER.debug("started");
}
 
Example #2
Source File: AuditVerticle.java    From vertx-kubernetes-workshop with Apache License 2.0 6 votes vote down vote up
private Single<HttpServer> configureTheHTTPServer() {

        //TODO
        //----

        Router router = Router.router(vertx);
        router.get("/").handler(this::retrieveOperations);
        router.get("/health").handler(rc -> {
            if (ready) {
                rc.response().end("Ready");
            } else {
                // Service not yet available
                rc.response().setStatusCode(503).end();
            }
        });
        return vertx.createHttpServer().requestHandler(router::accept).rxListen(8080);
        //----

//        return ready;
    }
 
Example #3
Source File: WebClientTest.java    From vertx-rx with Apache License 2.0 6 votes vote down vote up
@Test
public void testGet() {
  int times = 5;
  waitFor(times);
  HttpServer server = vertx.createHttpServer(new HttpServerOptions().setPort(8080));
  server.requestStream().handler(req -> req.response().setChunked(true).end("some_content"));
  try {
    server.listen(ar -> {
      client = WebClient.wrap(vertx.createHttpClient(new HttpClientOptions()));
      Single<HttpResponse<Buffer>> single = client
              .get(8080, "localhost", "/the_uri")
              .as(BodyCodec.buffer())
              .rxSend();
      for (int i = 0; i < times; i++) {
        single.subscribe(resp -> {
          Buffer body = resp.body();
          assertEquals("some_content", body.toString("UTF-8"));
          complete();
        }, this::fail);
      }
    });
    await();
  } finally {
    server.close();
  }
}
 
Example #4
Source File: WebClientTest.java    From vertx-rx with Apache License 2.0 6 votes vote down vote up
@Test
public void testPost() {
  int times = 5;
  waitFor(times);
  HttpServer server = vertx.createHttpServer(new HttpServerOptions().setPort(8080));
  server.requestStream().handler(req -> req.bodyHandler(buff -> {
    assertEquals("onetwothree", buff.toString());
    req.response().end();
  }));
  try {
    server.listen(ar -> {
      client = WebClient.wrap(vertx.createHttpClient(new HttpClientOptions()));
      Observable<Buffer> stream = Observable.just(Buffer.buffer("one"), Buffer.buffer("two"), Buffer.buffer("three"));
      Single<HttpResponse<Buffer>> single = client
              .post(8080, "localhost", "/the_uri")
              .rxSendStream(stream);
      for (int i = 0; i < times; i++) {
        single.subscribe(resp -> complete(), this::fail);
      }
    });
    await();
  } finally {
    server.close();
  }
}
 
Example #5
Source File: WebClientTest.java    From vertx-rx with Apache License 2.0 6 votes vote down vote up
@Test
public void testResponseMissingBody() throws Exception {
  int times = 5;
  waitFor(times);
  HttpServer server = vertx.createHttpServer(new HttpServerOptions().setPort(8080));
  server.requestStream().handler(req -> req.response().setStatusCode(403).end());
  try {
    server.listen(ar -> {
      client = WebClient.wrap(vertx.createHttpClient(new HttpClientOptions()));
      Single<HttpResponse<Buffer>> single = client
              .get(8080, "localhost", "/the_uri")
              .rxSend();
      for (int i = 0; i < times; i++) {
        single.subscribe(resp -> {
          assertEquals(403, resp.statusCode());
          assertNull(resp.body());
          complete();
        }, this::fail);
      }
    });
    await();
  } finally {
    server.close();
  }
}
 
Example #6
Source File: WebClientTest.java    From vertx-rx with Apache License 2.0 6 votes vote down vote up
@Test
public void testResponseBodyAsAsJsonMapped() throws Exception {
  JsonObject expected = new JsonObject().put("cheese", "Goat Cheese").put("wine", "Condrieu");
  HttpServer server = vertx.createHttpServer(new HttpServerOptions().setPort(8080));
  server.requestStream().handler(req -> req.response().end(expected.encode()));
  try {
    server.listen(ar -> {
      client = WebClient.wrap(vertx.createHttpClient(new HttpClientOptions()));
      Single<HttpResponse<WineAndCheese>> single = client
              .get(8080, "localhost", "/the_uri")
              .as(BodyCodec.json(WineAndCheese.class))
              .rxSend();
      single.subscribe(resp -> {
        assertEquals(200, resp.statusCode());
        assertEquals(new WineAndCheese().setCheese("Goat Cheese").setWine("Condrieu"), resp.body());
        testComplete();
      }, this::fail);
    });
    await();
  } finally {
    server.close();
  }
}
 
Example #7
Source File: CrnkVerticle.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
@Override
public void start() {
    HttpServer server = vertx.createHttpServer();

    server.requestStream().toFlowable()
            .flatMap(request -> handler.process(request))
            .subscribe((response) -> LOGGER.debug("delivered response {}", response), error -> LOGGER.debug("error occured", error));
    server.listen(port);
}
 
Example #8
Source File: HttpServerVerticle.java    From vertx-postgresql-starter with MIT License 5 votes vote down vote up
@Override
public void start(Future<Void> startFuture) throws Exception {
  HttpServer httpServer = vertx.createHttpServer();

  BookDatabaseService bookDatabaseService = createProxy(vertx.getDelegate(), config().getString(CONFIG_DB_EB_QUEUE));

  Router router = Router.router(vertx);

  router.route().handler(BodyHandler.create());

  router.route().handler(HTTPRequestValidationHandler.create().addExpectedContentType("application/json"));

  router.get(GET_BOOKS).handler(addBookValidationHandler())
    .handler(BookApis.getBooksHandler(bookDatabaseService));

  router.post(ADD_NEW_BOOK).handler(BookApis.addBookHandler(bookDatabaseService));

  router.delete(DELETE_BOOK_BY_ID).handler(deleteBookByIdValidationHandler())
    .handler(BookApis.deleteBookByIdHandler(bookDatabaseService));

  router.get(GET_BOOK_BY_ID).handler(getBookByIdValidationHandler())
    .handler(BookApis.getBookByIdHandler(bookDatabaseService));

  router.put(UPDATE_BOOK_BY_ID).handler(upsertBookByIdValidationHandler())
    .handler(BookApis.upsertBookByIdHandler(bookDatabaseService));

  router.route().failureHandler(new FailureHandler());

  int httpServerPort = config().getInteger(CONFIG_HTTP_SERVER_PORT, 8080);
  httpServer.requestHandler(router::accept)
    .rxListen(httpServerPort)
    .subscribe(server -> {
        LOGGER.info("HTTP server is running on port " + httpServerPort);
        startFuture.complete();
      },
      throwable -> {
        LOGGER.error("Fail to start a HTTP server ", throwable);
        startFuture.fail(throwable);
      });
}
 
Example #9
Source File: AuditVerticle.java    From vertx-kubernetes-workshop with Apache License 2.0 5 votes vote down vote up
/**
 * Starts the verticle asynchronously. The the initialization is completed, it calls
 * `complete()` on the given {@link Future} object. If something wrong happens,
 * `fail` is called.
 *
 * @param future the future to indicate the completion
 */
@Override
public void start(Future<Void> future) {
    // creates the jdbc client.

    ServiceDiscovery.create(vertx, discovery -> {

        // Discover and configure the database.
        Single<JDBCClient> jdbc = JDBCDataSource.rxGetJDBCClient(discovery,
            svc -> svc.getName().equals("audit-database"),
            getDatabaseConfiguration()
        ).doOnSuccess(jdbcClient -> this.jdbc = jdbcClient);

        // TODO
        // ----

        Single<JDBCClient> databaseReady = jdbc
            .flatMap(client -> initializeDatabase(client, true));
        Single<HttpServer> httpServerReady = configureTheHTTPServer();
        Single<MessageConsumer<JsonObject>> messageConsumerReady = retrieveThePortfolioMessageSource();

        Single<MessageConsumer<JsonObject>> readySingle = Single.zip(databaseReady, httpServerReady,
            messageConsumerReady, (db, http, consumer) -> consumer);

        // ----

        // signal a verticle start failure
        readySingle.doOnSuccess(consumer -> {
            // on success we set the handler that will store message in the database
            consumer.handler(message -> storeInDatabase(message.body()));
        }).subscribe(consumer -> {
            // complete the verticle start with a success
            future.complete();
            ready = true;
        }, future::fail);
    });


}
 
Example #10
Source File: Exercise1Verticle.java    From vertx-kubernetes-workshop with Apache License 2.0 5 votes vote down vote up
private Single<Record> publish(HttpServer server) {
    // 1 - Create a service record using `io.vertx.reactivex.servicediscovery.types.HttpEndpoint.createRecord`.
    // This record define the service name ("greetings"), the host ("localhost"), the server port and the root ("/")
    // TODO

    // 2 - Call the rxPublish method with the created record and return the resulting single
    // TODO
    return null; // To be removed
}
 
Example #11
Source File: RestQuoteAPIVerticle.java    From vertx-kubernetes-workshop with Apache License 2.0 5 votes vote down vote up
@Override
public void start(Future<Void> future) throws Exception {
    // Get the stream of messages sent on the "market" address
    vertx.eventBus().<JsonObject>consumer(GeneratorConfigVerticle.ADDRESS).toFlowable()
        // TODO Extract the body of the message using `.map(msg -> {})`
        // ----
        //
        // ----
        // TODO For each message, populate the `quotes` map with the received quote. Use `.doOnNext(json -> {})`
        // Quotes are json objects you can retrieve from the message body
        // The map is structured as follows: name -> quote
        // ----
        //
        // ----
        .subscribe();

    HttpServer server = vertx.createHttpServer();
    server.requestStream().toFlowable()
        .doOnNext(request -> {
            HttpServerResponse response = request.response()
                .putHeader("content-type", "application/json");

            // TODO Handle the HTTP request
            // The request handler returns a specific quote if the `name` parameter is set, or the whole map if none.
            // To write the response use: `response.end(content)`
            // If the name is set but not found, you should return 404 (use response.setStatusCode(404)).
            // To encode a Json object, use the `encorePrettily` method
            // ----

            // Remove this line
            response.end(Json.encodePrettily(quotes));
            
            // ----
        })
    .subscribe();

    server.rxListen(config().getInteger("http.port", 8080))
        .toCompletable()
        .subscribe(CompletableHelper.toObserver(future));
}
 
Example #12
Source File: RxWebApiContractExamples.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
public void mainExample(Vertx vertx, Handler<RoutingContext> myValidationFailureHandler, JWTAuth jwtAuth) {
  OpenAPI3RouterFactory
    .rxCreate(vertx, "src/main/resources/petstore.yaml")
    .flatMap(routerFactory -> {
      // Spec loaded with success. router factory contains OpenAPI3RouterFactory
      // Set router factory options.
      RouterFactoryOptions options = new RouterFactoryOptions().setOperationModelKey("openapi_model");
      // Mount the options
      routerFactory.setOptions(options);
      // Add an handler with operationId
      routerFactory.addHandlerByOperationId("listPets", routingContext -> {
        // Handle listPets operation
        routingContext.response().setStatusMessage("Called listPets").end();
      });

      // Add a security handler
      routerFactory.addSecurityHandler("api_key", JWTAuthHandler.create(jwtAuth));

      // Now you have to generate the router
      Router router = routerFactory.getRouter();

      // Now you can use your Router instance
      HttpServer server = vertx.createHttpServer(new HttpServerOptions().setPort(8080).setHost("localhost"));
      return server.requestHandler(router).rxListen();
    })
    .subscribe(httpServer -> {
      // Server up and running
    }, throwable -> {
      // Error during router factory instantiation or http server start
    });
}
 
Example #13
Source File: RestQuoteAPIVerticle.java    From vertx-kubernetes-workshop with Apache License 2.0 4 votes vote down vote up
@Override
public void start(Future<Void> future) throws Exception {
    // Get the stream of messages sent on the "market" address
    vertx.eventBus().<JsonObject>consumer(GeneratorConfigVerticle.ADDRESS).toFlowable()
        // TODO Extract the body of the message using `.map(msg -> {})`
        // ----
        .map(Message::body)
        // ----
        // TODO For each message, populate the `quotes` map with the received quote. Use `.doOnNext(json -> {})`
        // Quotes are json objects you can retrieve from the message body
        // The map is structured as follows: name -> quote
        // ----
        .doOnNext(json -> {
            quotes.put(json.getString("name"), json); // 2
        })
        // ----
        .subscribe();

    HttpServer server = vertx.createHttpServer();
    server.requestStream().toFlowable()
        .doOnNext(request -> {
            HttpServerResponse response = request.response()
                .putHeader("content-type", "application/json");

            // TODO Handle the HTTP request
            // The request handler returns a specific quote if the `name` parameter is set, or the whole map if none.
            // To write the response use: `response.end(content)`
            // If the name is set but not found, you should return 404 (use response.setStatusCode(404)).
            // To encode a Json object, use the `encorePrettily` method
            // ----
            
            String company = request.getParam("name");
            if (company == null) {
                String content = Json.encodePrettily(quotes);
                response.end(content);
            } else {
                JsonObject quote = quotes.get(company);
                if (quote == null) {
                    response.setStatusCode(404).end();
                } else {
                    response.end(quote.encodePrettily());
                }
            }
            // ----
        })
        .subscribe();

    server.rxListen(config().getInteger("http.port", 8080))
        .toCompletable()
        .subscribe(CompletableHelper.toObserver(future));
}
 
Example #14
Source File: VertxHttpServerFactory.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
@Override
public HttpServer getObject() throws Exception {
    HttpServerOptions options = new HttpServerOptions();

    // Binding port
    options.setPort(httpServerConfiguration.getPort());
    options.setHost(httpServerConfiguration.getHost());

    // Netty pool buffers must be enabled by default
    options.setUsePooledBuffers(true);

    if (httpServerConfiguration.isSecured()) {
        options.setSsl(httpServerConfiguration.isSecured());
        options.setUseAlpn(httpServerConfiguration.isAlpn());

        if (httpServerConfiguration.getClientAuth() == VertxHttpServerConfiguration.ClientAuthMode.NONE) {
            options.setClientAuth(ClientAuth.NONE);
        } else if (httpServerConfiguration.getClientAuth() == VertxHttpServerConfiguration.ClientAuthMode.REQUEST) {
            options.setClientAuth(ClientAuth.REQUEST);
        } else if (httpServerConfiguration.getClientAuth() == VertxHttpServerConfiguration.ClientAuthMode.REQUIRED) {
            options.setClientAuth(ClientAuth.REQUIRED);
        }

        if (httpServerConfiguration.getTrustStorePath() != null) {
            if (httpServerConfiguration.getTrustStoreType() == null || httpServerConfiguration.getTrustStoreType().isEmpty() ||
                    httpServerConfiguration.getTrustStoreType().equalsIgnoreCase(CERTIFICATE_FORMAT_JKS)) {
                options.setTrustStoreOptions(new JksOptions()
                        .setPath(httpServerConfiguration.getTrustStorePath())
                        .setPassword(httpServerConfiguration.getTrustStorePassword()));
            } else if (httpServerConfiguration.getTrustStoreType().equalsIgnoreCase(CERTIFICATE_FORMAT_PEM)) {
                options.setPemTrustOptions(new PemTrustOptions()
                        .addCertPath(httpServerConfiguration.getTrustStorePath()));
            } else if (httpServerConfiguration.getTrustStoreType().equalsIgnoreCase(CERTIFICATE_FORMAT_PKCS12)) {
                options.setPfxTrustOptions(new PfxOptions()
                        .setPath(httpServerConfiguration.getTrustStorePath())
                        .setPassword(httpServerConfiguration.getTrustStorePassword()));
            }
        }

        if (httpServerConfiguration.getKeyStorePath() != null) {
            if (httpServerConfiguration.getKeyStoreType() == null || httpServerConfiguration.getKeyStoreType().isEmpty() ||
                    httpServerConfiguration.getKeyStoreType().equalsIgnoreCase(CERTIFICATE_FORMAT_JKS)) {
                options.setKeyStoreOptions(new JksOptions()
                        .setPath(httpServerConfiguration.getKeyStorePath())
                        .setPassword(httpServerConfiguration.getKeyStorePassword()));
            } else if (httpServerConfiguration.getKeyStoreType().equalsIgnoreCase(CERTIFICATE_FORMAT_PEM)) {
                options.setPemKeyCertOptions(new PemKeyCertOptions()
                        .addCertPath(httpServerConfiguration.getKeyStorePath()));
            } else if (httpServerConfiguration.getKeyStoreType().equalsIgnoreCase(CERTIFICATE_FORMAT_PKCS12)) {
                options.setPfxKeyCertOptions(new PfxOptions()
                        .setPath(httpServerConfiguration.getKeyStorePath())
                        .setPassword(httpServerConfiguration.getKeyStorePassword()));
            }
        }
    }

    // Customizable configuration
    options.setCompressionSupported(httpServerConfiguration.isCompressionSupported());
    options.setIdleTimeout(httpServerConfiguration.getIdleTimeout());
    options.setTcpKeepAlive(httpServerConfiguration.isTcpKeepAlive());

    return vertx.createHttpServer(options);
}
 
Example #15
Source File: VertxHttpServerFactory.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
@Override
public Class<?> getObjectType() {
    return HttpServer.class;
}
 
Example #16
Source File: AuditVerticle.java    From vertx-kubernetes-workshop with Apache License 2.0 3 votes vote down vote up
private Single<HttpServer> configureTheHTTPServer() {

        //TODO
        //----

        return Single
            .error(new UnsupportedOperationException("Not implemented yet"));
        //----

    }