io.vertx.reactivex.ext.web.handler.BodyHandler Java Examples

The following examples show how to use io.vertx.reactivex.ext.web.handler.BodyHandler. 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: UserProfileApiVerticle.java    From vertx-in-action with MIT License 6 votes vote down vote up
@Override
public Completable rxStart() {
  mongoClient = MongoClient.createShared(vertx, mongoConfig());

  authProvider = MongoAuthentication.create(mongoClient, new MongoAuthenticationOptions());
  userUtil = MongoUserUtil.create(mongoClient, new MongoAuthenticationOptions(), new MongoAuthorizationOptions());

  Router router = Router.router(vertx);
  BodyHandler bodyHandler = BodyHandler.create();
  router.post().handler(bodyHandler);
  router.put().handler(bodyHandler);
  router.post("/register")
    .handler(this::validateRegistration)
    .handler(this::register);
  router.get("/:username").handler(this::fetchUser);
  router.put("/:username").handler(this::updateUser);
  router.post("/authenticate").handler(this::authenticate);
  router.get("/owns/:deviceId").handler(this::whoOwns);

  return vertx.createHttpServer()
    .requestHandler(router)
    .rxListen(HTTP_PORT)
    .ignoreElement();
}
 
Example #2
Source File: IngesterVerticle.java    From vertx-in-action with MIT License 6 votes vote down vote up
@Override
public Completable rxStart() {
  updateProducer = KafkaProducer.create(vertx, kafkaConfig());

  AmqpClientOptions amqpOptions = amqpConfig();
  AmqpReceiverOptions receiverOptions = new AmqpReceiverOptions()
    .setAutoAcknowledgement(false)
    .setDurable(true);

  AmqpClient.create(vertx, amqpOptions)
    .rxConnect()
    .flatMap(conn -> conn.rxCreateReceiver("step-events", receiverOptions))
    .flatMapPublisher(AmqpReceiver::toFlowable)
    .doOnError(this::logAmqpError)
    .retryWhen(this::retryLater)
    .subscribe(this::handleAmqpMessage);

  Router router = Router.router(vertx);
  router.post().handler(BodyHandler.create());
  router.post("/ingest").handler(this::httpIngest);

  return vertx.createHttpServer()
    .requestHandler(router)
    .rxListen(HTTP_PORT)
    .ignoreElement();
}
 
Example #3
Source File: CurrencyServiceProxy.java    From vertx-kubernetes-workshop with Apache License 2.0 6 votes vote down vote up
@Override
public void start() throws Exception {
    Router router = Router.router(vertx);
    router.get().handler(this::convertPortfolioToEuro);
    router.post().handler(BodyHandler.create());
    router.post().handler(this::delegateWithCircuitBreaker);

    circuit = CircuitBreaker.create("circuit-breaker", vertx,
        new CircuitBreakerOptions()
            .setFallbackOnFailure(true)
            .setMaxFailures(3)
            .setResetTimeout(5000)
            .setTimeout(1000)
    );

    discovery = ServiceDiscovery.create(vertx);


    vertx.createHttpServer()
        .requestHandler(router::accept)
        .listen(8080);
}
 
Example #4
Source File: CurrencyServiceProxy.java    From vertx-kubernetes-workshop with Apache License 2.0 6 votes vote down vote up
@Override
public void start() throws Exception {
    Router router = Router.router(vertx);
    router.get().handler(this::convertPortfolioToEuro);
    router.post().handler(BodyHandler.create());
    router.post().handler(this::delegateWithCircuitBreaker);

    circuit = CircuitBreaker.create("circuit-breaker", vertx,
        new CircuitBreakerOptions()
            .setFallbackOnFailure(true)
            .setMaxFailures(3)
            .setResetTimeout(5000)
            .setTimeout(1000)
    );

    discovery = ServiceDiscovery.create(vertx);


    vertx.createHttpServer()
        .requestHandler(router::accept)
        .listen(8080);
}
 
Example #5
Source File: RxTodoVerticle.java    From vertx-blueprint-todo-backend with Apache License 2.0 6 votes vote down vote up
@Override
public void start(Future<Void> startFuture) throws Exception {
  Router router = Router.router(vertx);
  // Enable HTTP Body parse.
  router.route().handler(BodyHandler.create());
  // Enable CORS.
  enableCorsSupport(router);

  router.get(Constants.API_GET).handler(this::handleGetTodo);
  router.get(Constants.API_LIST_ALL).handler(this::handleGetAll);
  router.post(Constants.API_CREATE).handler(this::handleCreateTodo);
  router.patch(Constants.API_UPDATE).handler(this::handleUpdateTodo);
  router.delete(Constants.API_DELETE).handler(this::handleDeleteOne);
  router.delete(Constants.API_DELETE_ALL).handler(this::handleDeleteAll);

  String host = config().getString("http.address", HOST);
  int port = config().getInteger("http.port", PORT);

  initService().andThen(createHttpServer(router, host, port))
    .subscribe(startFuture::complete, startFuture::fail);
}
 
Example #6
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 #7
Source File: RestApiTestBase.java    From vertx-postgresql-starter with MIT License 5 votes vote down vote up
protected void mockServer(int port, HttpMethod httpMethod, String routingPath, Handler<RoutingContext> handler, TestContext testContext) {
  vertx = new Vertx(rule.vertx());
  router = Router.router(vertx);

  if (httpMethod.equals(HttpMethod.POST) || httpMethod.equals(HttpMethod.PUT)) {
    router.route().handler(BodyHandler.create());
  }

  router.route(httpMethod, routingPath).handler(handler);

  vertx.createHttpServer().requestHandler(router::accept).listen(port, testContext.asyncAssertSuccess());
}
 
Example #8
Source File: CreateUserEndpointHandlerTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public void setUp() throws Exception {
    super.setUp();

    // object mapper
    when(objectWriter.writeValueAsString(any())).thenReturn("UserObject");
    when(objectMapper.writerWithDefaultPrettyPrinter()).thenReturn(objectWriter);

    router.route()
            .handler(BodyHandler.create())
            .failureHandler(new ErrorHandler());
}
 
Example #9
Source File: UpdateUserEndpointHandlerTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public void setUp() throws Exception {
    super.setUp();

    // object mapper
    when(objectWriter.writeValueAsString(any())).thenReturn("UserObject");
    when(objectMapper.writerWithDefaultPrettyPrinter()).thenReturn(objectWriter);

    router.route()
            .handler(BodyHandler.create())
            .failureHandler(new ErrorHandler());
}
 
Example #10
Source File: PasswordPolicyRequestParseHandlerTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
public void setUp() throws Exception {
    super.setUp();

    router.route()
            .handler(BodyHandler.create())
            .failureHandler(new ErrorHandler());
}
 
Example #11
Source File: UserInfoEndpointHandlerTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotInvokeUserEndpoint_noBearerToken_post() throws Exception {
    router.route().order(-1)
            .handler(BodyHandler.create())
            .handler(createOAuth2AuthHandler(oAuth2AuthProvider()));

    testRequest(
            HttpMethod.POST, "/userinfo",
            HttpStatusCode.UNAUTHORIZED_401, "Unauthorized");
}
 
Example #12
Source File: UserInfoEndpointHandlerTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldNotInvokeUserEndpoint_invalidToken_jwtDecode_post() throws Exception {
    router.route().order(-1)
            .handler(BodyHandler.create())
            .handler(createOAuth2AuthHandler(oAuth2AuthProvider(new ServerErrorException())));

    testRequest(
            HttpMethod.POST, "/userinfo", req -> {
                final String body = "access_token=test-token";
                req.putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED);
                req.putHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(body.length()));
                req.write(Buffer.buffer(body));
            },
            HttpStatusCode.BAD_REQUEST_400, "Bad Request", null);
}
 
Example #13
Source File: UserInfoEndpointHandlerTest.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldInvokeUserEndpoint_post() throws Exception {
    User user = new User();
    user.setAdditionalInformation(Collections.singletonMap("sub", "user"));

    JWT jwt = new JWT();
    jwt.setJti("id-token");
    jwt.setAud("client-id");
    jwt.setSub("id-subject");
    jwt.setScope("openid");

    Client client = new Client();
    client.setId("client-id");
    client.setClientId("client-id");

    router.route().order(-1)
            .handler(BodyHandler.create())
            .handler(createOAuth2AuthHandler(oAuth2AuthProvider(jwt, client)));

    when(userService.findById(anyString())).thenReturn(Maybe.just(user));

    testRequest(
            HttpMethod.POST, "/userinfo", req ->
            {
                final String body = "access_token=test-token";
                req.putHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED);
                req.putHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(body.length()));
                req.write(Buffer.buffer(body));
            },
            HttpStatusCode.OK_200, "OK", null);
}
 
Example #14
Source File: PublicApiVerticle.java    From vertx-in-action with MIT License 4 votes vote down vote up
@Override
public Completable rxStart() {

  String publicKey;
  String privateKey;
  try {
    publicKey = CryptoHelper.publicKey();
    privateKey = CryptoHelper.privateKey();
  } catch (IOException e) {
    return Completable.error(e);
  }

  jwtAuth = JWTAuth.create(vertx, new JWTAuthOptions()
    .addPubSecKey(new PubSecKeyOptions()
      .setAlgorithm("RS256")
      .setBuffer(publicKey))
    .addPubSecKey(new PubSecKeyOptions()
      .setAlgorithm("RS256")
      .setBuffer(privateKey)));

  Router router = Router.router(vertx);

  Set<String> allowedHeaders = new HashSet<>();
  allowedHeaders.add("x-requested-with");
  allowedHeaders.add("Access-Control-Allow-Origin");
  allowedHeaders.add("origin");
  allowedHeaders.add("Content-Type");
  allowedHeaders.add("accept");
  allowedHeaders.add("Authorization");

  Set<HttpMethod> allowedMethods = new HashSet<>();
  allowedMethods.add(HttpMethod.GET);
  allowedMethods.add(HttpMethod.POST);
  allowedMethods.add(HttpMethod.OPTIONS);
  allowedMethods.add(HttpMethod.PUT);

  router.route().handler(CorsHandler
    .create("*")
    .allowedHeaders(allowedHeaders)
    .allowedMethods(allowedMethods));

  BodyHandler bodyHandler = BodyHandler.create();
  router.post().handler(bodyHandler);
  router.put().handler(bodyHandler);

  String prefix = "/api/v1";
  JWTAuthHandler jwtHandler = JWTAuthHandler.create(jwtAuth);

  // Account
  router.post(prefix + "/register").handler(this::register);
  router.post(prefix + "/token").handler(this::token);

  // Profile
  router.get(prefix + "/:username").handler(jwtHandler).handler(this::checkUser).handler(this::fetchUser);
  router.put(prefix + "/:username").handler(jwtHandler).handler(this::checkUser).handler(this::updateUser);

  // Data
  router.get(prefix + "/:username/total").handler(jwtHandler).handler(this::checkUser).handler(this::totalSteps);
  router.get(prefix + "/:username/:year/:month").handler(jwtHandler).handler(this::checkUser).handler(this::monthlySteps);
  router.get(prefix + "/:username/:year/:month/:day").handler(jwtHandler).handler(this::checkUser).handler(this::dailySteps);

  webClient = WebClient.create(vertx);

  return vertx.createHttpServer()
    .requestHandler(router)
    .rxListen(HTTP_PORT)
    .ignoreElement();
}
 
Example #15
Source File: MyFirstVerticle.java    From introduction-to-eclipse-vertx with Apache License 2.0 4 votes vote down vote up
@Override
public void start(Future<Void> fut) {

    // Create a router object.
    Router router = Router.router(vertx);

    // Bind "/" to our hello message - so we are still compatible.
    router.route("/").handler(routingContext -> {
        HttpServerResponse response = routingContext.response();
        response
            .putHeader("content-type", "text/html")
            .end("<h1>Hello from my first Vert.x 3 application</h1>");
    });

    // Serve static resources from the /assets directory
    router.route("/assets/*").handler(StaticHandler.create("assets"));
    router.get("/api/articles").handler(this::getAll);
    router.get("/api/articles/:id").handler(this::getOne);
    router.route("/api/articles*").handler(BodyHandler.create());
    router.post("/api/articles").handler(this::addOne);
    router.delete("/api/articles/:id").handler(this::deleteOne);
    router.put("/api/articles/:id").handler(this::updateOne);

    ConfigRetriever retriever = ConfigRetriever.create(vertx);

    // Start sequence:
    // 1 - Retrieve the configuration
    //      |- 2 - Create the JDBC client
    //      |- 3 - Connect to the database (retrieve a connection)
    //              |- 4 - Create table if needed
    //                   |- 5 - Add some data if needed
    //                          |- 6 - Close connection when done
    //              |- 7 - Start HTTP server
    //      |- 9 - we are done!

    retriever.rxGetConfig()
        .doOnSuccess(config ->
            jdbc = JDBCClient.createShared(vertx, config, "My-Reading-List"))
        .flatMap(config ->
            connect()
                .flatMap(connection ->
                    this.createTableIfNeeded(connection)
                        .flatMap(this::createSomeDataIfNone)
                        .doAfterTerminate(connection::close)
                )
                .map(x -> config)
        )
        .flatMapCompletable(config -> createHttpServer(config, router))
        .subscribe(CompletableHelper.toObserver(fut));

}