Java Code Examples for io.vertx.reactivex.ext.web.Router#router()

The following examples show how to use io.vertx.reactivex.ext.web.Router#router() . 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: 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 3
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 4
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 5
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 6
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 7
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 8
Source File: DiscoveryProvider.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
private void startDiscovery() {
    final Router discoveryRouter = Router.router(vertx);

    // UMA Provider configuration information endpoint
    Handler<RoutingContext> providerConfigurationEndpoint = new ProviderConfigurationEndpoint();
    ((ProviderConfigurationEndpoint) providerConfigurationEndpoint).setDiscoveryService(discoveryService);
    discoveryRouter.route().handler(corsHandler);
    discoveryRouter.get().handler(providerConfigurationEndpoint);

    // error handler
    discoveryRouter.route().failureHandler(new ErrorHandler());

    router.mountSubRouter(path(), discoveryRouter);
}
 
Example 9
Source File: UsersProvider.java    From graviteeio-access-management with Apache License 2.0 5 votes vote down vote up
@Override
protected void doStart() throws Exception {
    super.doStart();

    // Create the Users router
    final Router usersRouter = Router.router(vertx);

    final UserConsentsEndpointHandler userConsentsHandler = new UserConsentsEndpointHandler(userService, clientSyncService, domain);
    final UserConsentEndpointHandler userConsentHandler = new UserConsentEndpointHandler(userService, clientSyncService, domain);
    final OAuth2AuthHandler oAuth2AuthHandler = OAuth2AuthHandler.create(oAuth2AuthProvider, "consent_admin");
    oAuth2AuthHandler.extractToken(true);
    oAuth2AuthHandler.selfResource(true, "userId");

    // user consent routes
    usersRouter.routeWithRegex(".*consents.*")
            .pathRegex("\\/(?<userId>[^\\/]+)\\/([^\\/]+)")
            .handler(oAuth2AuthHandler);
    usersRouter.get("/:userId/consents")
            .handler(userConsentsHandler::list);
    usersRouter.delete("/:userId/consents")
            .handler(userConsentsHandler::revoke);
    usersRouter.get("/:userId/consents/:consentId")
            .handler(userConsentHandler::get);
    usersRouter.delete("/:userId/consents/:consentId")
            .handler(userConsentHandler::revoke);

    // error handler
    usersRouter.route().failureHandler(new ErrorHandler());

    router.mountSubRouter(path(), usersRouter);
}
 
Example 10
Source File: DashboardWebAppVerticle.java    From vertx-in-action with MIT License 5 votes vote down vote up
@Override
public Completable rxStart() {
  Router router = Router.router(vertx);

  KafkaConsumer.<String, JsonObject>create(vertx, KafkaConfig.consumerConfig("dashboard-webapp-throughput"))
    .subscribe("event-stats.throughput")
    .toFlowable()
    .subscribe(record -> forwardKafkaRecord(record, "client.updates.throughput"));

  KafkaConsumer.<String, JsonObject>create(vertx, KafkaConfig.consumerConfig("dashboard-webapp-city-trend"))
    .subscribe("event-stats.city-trend.updates")
    .toFlowable()
    .subscribe(record -> forwardKafkaRecord(record, "client.updates.city-trend"));

  KafkaConsumer.<String, JsonObject>create(vertx, KafkaConfig.consumerConfig("dashboard-webapp-ranking"))
    .subscribe("event-stats.user-activity.updates")
    .toFlowable()
    .filter(record -> record.value().getBoolean("makePublic"))
    .buffer(5, TimeUnit.SECONDS, RxHelper.scheduler(vertx))
    .subscribe(this::updatePublicRanking);

  hydrate();

  SockJSHandler sockJSHandler = SockJSHandler.create(vertx);
  SockJSBridgeOptions bridgeOptions = new SockJSBridgeOptions()
    .addInboundPermitted(new PermittedOptions().setAddressRegex("client.updates.*"))
    .addOutboundPermitted(new PermittedOptions().setAddressRegex("client.updates.*"));
  sockJSHandler.bridge(bridgeOptions);
  router.route("/eventbus/*").handler(sockJSHandler);

  router.get("/").handler(ctx -> ctx.reroute("/index.html"));
  router.route().handler(StaticHandler.create("webroot/assets"));

  return vertx.createHttpServer()
    .requestHandler(router)
    .rxListen(HTTP_PORT)
    .ignoreElement();
}
 
Example 11
Source File: SuperHeroesService.java    From rxjava2-lab with Apache License 2.0 5 votes vote down vote up
public Completable start() {
    Vertx vertx = Vertx.vertx();

    Router router = Router.router(vertx);
    router.get("/heroes").handler(this::getAllHeroes);
    router.get("/villains").handler(this::getAllVillains);
    router.get("/heroes/random").handler(this::getRandomHero);
    router.get("/heroes/:id").handler(this::getHeroById);
    router.get("/villains/random").handler(this::getRandomVillain);
    router.get("/villains/:id").handler(this::getVillainById);

    return vertx.fileSystem().rxReadFile("src/main/resources/characters.json")
        .map(buffer -> buffer.toJsonArray().stream().map(o -> new Character((JsonObject) o)).collect(Collectors.toList()))
        .doOnSuccess(list -> {
            if (verbose) {
                System.out.println("Loaded " + list.size() + " heroes and villains");
            }
        })
        .doOnSuccess(list -> {
            this.villains = list.stream().filter(Character::isVillain).collect(
                HashMap::new, (map, superStuff) -> map.put(superStuff.getId(), superStuff), HashMap::putAll);
            this.heroes = list.stream().filter(e -> ! e.isVillain()).collect(
                HashMap::new, (map, superStuff) -> map.put(superStuff.getId(), superStuff), HashMap::putAll);
        })
        .flatMap(x -> vertx.createHttpServer()
            .requestHandler(router::accept)
            .rxListen(8080))
        .toCompletable();

}
 
Example 12
Source File: FakeUserService.java    From vertx-in-action with MIT License 5 votes vote down vote up
@Override
public Completable rxStart() {
  Router router = Router.router(vertx);
  router.get("/owns/:deviceId").handler(this::owns);
  router.get("/:username").handler(this::username);
  return vertx.createHttpServer()
    .requestHandler(router)
    .rxListen(3000)
    .ignoreElement();
}
 
Example 13
Source File: ActivityApiVerticle.java    From vertx-in-action with MIT License 5 votes vote down vote up
@Override
public Completable rxStart() {
  pgPool = PgPool.pool(vertx, PgConfig.pgConnectOpts(), new PoolOptions());

  Router router = Router.router(vertx);
  router.get("/:deviceId/total").handler(this::totalSteps);
  router.get("/:deviceId/:year/:month").handler(this::stepsOnMonth);
  router.get("/:deviceId/:year/:month/:day").handler(this::stepsOnDay);
  router.get("/ranking-last-24-hours").handler(this::ranking);

  return vertx.createHttpServer()
    .requestHandler(router)
    .rxListen(HTTP_PORT)
    .ignoreElement();
}
 
Example 14
Source File: UserWebAppVerticle.java    From vertx-in-action with MIT License 5 votes vote down vote up
@Override
public Completable rxStart() {
  Router router = Router.router(vertx);
  router.get("/").handler(ctx -> ctx.reroute("/index.html"));
  router.route().handler(StaticHandler.create("webroot/assets"));
  return vertx.createHttpServer()
    .requestHandler(router)
    .rxListen(HTTP_PORT)
    .ignoreElement();
}
 
Example 15
Source File: RxWebTestBase.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
protected Router router() {
    return Router.router(vertx);
}
 
Example 16
Source File: DefaultReactor.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
@Override
public void afterPropertiesSet() {
    router = Router.router(vertx);
    router.route().handler(transactionHandlerFactory.create());
    router.route().last().handler(context -> sendNotFound(context.response()));
}
 
Example 17
Source File: HandlerConfiguration.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
@Bean
public Router router() {
    return Router.router(vertx);
}
 
Example 18
Source File: OAuth2Provider.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
private void initRouter() {
    // Create the OAuth 2.0 router
    final Router oauth2Router = Router.router(vertx);

    // client auth handler
    final Handler<RoutingContext> clientAuthHandler = ClientAuthHandler.create(clientSyncService, clientAssertionService, jwkService);

    // static handler
    staticHandler(oauth2Router);

    // session cookie handler
    sessionAndCookieHandler(oauth2Router);

    // CSRF handler
    csrfHandler(oauth2Router);

    // Authorization endpoint
    oauth2Router.route(HttpMethod.GET,"/authorize")
            .handler(new AuthorizationRequestParseRequiredParametersHandler(openIDDiscoveryService))
            .handler(new AuthorizationRequestParseClientHandler(clientSyncService))
            .handler(new AuthorizationRequestParseRequestObjectHandler(requestObjectService))
            .handler(new AuthorizationRequestParseParametersHandler(domain))
            .handler(new AuthorizationRequestValidateParametersHandler(domain))
            .handler(authenticationFlowHandler.create())
            .handler(new AuthorizationRequestResolveHandler())
            .handler(new AuthorizationRequestEndUserConsentHandler(userConsentService, domain))
            .handler(new AuthorizationEndpoint(flow))
            .failureHandler(new AuthorizationRequestFailureHandler(domain, openIDDiscoveryService, jwtService, jweService));

    // Authorization consent endpoint
    Handler<RoutingContext> userConsentPrepareContextHandler = new UserConsentPrepareContextHandler(clientSyncService);
    oauth2Router.route(HttpMethod.GET, "/consent")
            .handler(userConsentPrepareContextHandler)
            .handler(policyChainHandler.create(ExtensionPoint.PRE_CONSENT))
            .handler(new UserConsentEndpoint(userConsentService, thymeleafTemplateEngine));
    oauth2Router.route(HttpMethod.POST, "/consent")
            .handler(userConsentPrepareContextHandler)
            .handler(new UserConsentProcessHandler(userConsentService, domain))
            .handler(policyChainHandler.create(ExtensionPoint.POST_CONSENT))
            .handler(new UserConsentPostEndpoint());
    oauth2Router.route("/consent")
            .failureHandler(new UserConsentFailureHandler(domain));

    // Token endpoint
    oauth2Router.route(HttpMethod.OPTIONS, "/token")
            .handler(corsHandler);
    oauth2Router.route(HttpMethod.POST, "/token")
            .handler(corsHandler)
            .handler(new TokenRequestParseHandler())
            .handler(clientAuthHandler)
            .handler(new TokenEndpoint(tokenGranter));

    // Introspection endpoint
    oauth2Router.route(HttpMethod.POST, "/introspect")
            .consumes(MediaType.APPLICATION_FORM_URLENCODED)
            .handler(clientAuthHandler)
            .handler(new IntrospectionEndpoint(introspectionService));

    // Revocation endpoint
    oauth2Router.route(HttpMethod.OPTIONS, "/revoke")
            .handler(corsHandler);
    oauth2Router.route(HttpMethod.POST, "/revoke")
            .consumes(MediaType.APPLICATION_FORM_URLENCODED)
            .handler(corsHandler)
            .handler(clientAuthHandler)
            .handler(new RevocationTokenEndpoint(revocationTokenService));

    // Error endpoint
    oauth2Router.route(HttpMethod.GET, "/error")
            .handler(new ErrorEndpoint(domain.getId(), thymeleafTemplateEngine, clientSyncService));

    // error handler
    errorHandler(oauth2Router);

    // mount OAuth 2.0 router
    router.mountSubRouter(path(), oauth2Router);
}
 
Example 19
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 20
Source File: SCIMProvider.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
@Override
protected void doStart() throws Exception {
    super.doStart();

    if (isSCIMEnabled()) {
        // Create the SCIM router
        final Router scimRouter = Router.router(vertx);

        // CORS handler
        scimRouter.route().handler(corsHandler);

        // Declare SCIM routes
        // see <a href="https://tools.ietf.org/html/rfc7644#section-3.2">3.2. SCIM Endpoints and HTTP Methods</a>

        // Service Provider configuration
        ServiceProviderConfigurationEndpointHandler serviceProviderConfigurationEndpointHandler = ServiceProviderConfigurationEndpointHandler.create(serviceProviderConfigService);
        serviceProviderConfigurationEndpointHandler.setObjectMapper(objectMapper);
        scimRouter.get("/ServiceProviderConfig").handler(serviceProviderConfigurationEndpointHandler);

        // SCIM resources routes are OAuth 2.0 secured
        scimRouter.route().handler(OAuth2AuthHandler.create(oAuth2AuthProvider, "scim"));

        // Users resource
        UsersEndpoint usersEndpoint = new UsersEndpoint(userService, objectMapper, passwordValidator);
        UserEndpoint userEndpoint = new UserEndpoint(userService, objectMapper, passwordValidator);

        scimRouter.get("/Users").handler(usersEndpoint::list);
        scimRouter.get("/Users/:id").handler(userEndpoint::get);
        scimRouter.post("/Users").handler(usersEndpoint::create);
        scimRouter.put("/Users/:id").handler(userEndpoint::update);
        scimRouter.delete("/Users/:id").handler(userEndpoint::delete);

        // Groups resource
        GroupsEndpoint groupsEndpoint = new GroupsEndpoint(groupService, objectMapper);
        GroupEndpoint groupEndpoint = new GroupEndpoint(groupService, objectMapper);

        scimRouter.get("/Groups").handler(groupsEndpoint::list);
        scimRouter.get("/Groups/:id").handler(groupEndpoint::get);
        scimRouter.post("/Groups").handler(groupsEndpoint::create);
        scimRouter.put("/Groups/:id").handler(groupEndpoint::update);
        scimRouter.delete("/Groups/:id").handler(groupEndpoint::delete);

        // error handler
        scimRouter.route().failureHandler(new ErrorHandler());

        // mount SCIM router
        router.mountSubRouter(path(), scimRouter);
    }
}