Java Code Examples for io.vertx.ext.web.api.contract.openapi3.OpenAPI3RouterFactory#create()

The following examples show how to use io.vertx.ext.web.api.contract.openapi3.OpenAPI3RouterFactory#create() . 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: OpenAPI3Examples.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
public void constructRouterFactoryFromUrlWithAuthenticationHeader(Vertx vertx) {
  AuthorizationValue authorizationValue = new AuthorizationValue()
    .type("header")
    .keyName("Authorization")
    .value("Bearer xx.yy.zz");
  List<JsonObject> authorizations = Collections.singletonList(JsonObject.mapFrom(authorizationValue));
  OpenAPI3RouterFactory.create(
    vertx,
    "https://raw.githubusercontent.com/OAI/OpenAPI-Specification/master/examples/v3.0/petstore.yaml",
    authorizations,
    ar -> {
      if (ar.succeeded()) {
        // Spec loaded with success
        OpenAPI3RouterFactory routerFactory = ar.result();
      } else {
        // Something went wrong during router factory initialization
        Throwable exception = ar.cause();
      }
    });
}
 
Example 2
Source File: XYZHubRESTVerticle.java    From xyz-hub with Apache License 2.0 5 votes vote down vote up
@Override
public void start(Future<Void> fut) {
  OpenAPI3RouterFactory.create(vertx, CONTRACT_LOCATION, ar -> {
    if (ar.succeeded()) {
      //Add the handlers
      final OpenAPI3RouterFactory routerFactory = ar.result();
      routerFactory.setOptions(new RouterFactoryOptions());
      featureApi = new FeatureApi(routerFactory);
      featureQueryApi = new FeatureQueryApi(routerFactory);
      spaceApi = new SpaceApi(routerFactory);

      final AuthHandler jwtHandler = createJWTHandler();
      routerFactory.addSecurityHandler("authToken", jwtHandler);

      final Router router = routerFactory.getRouter();
      //Add additional handler to the router
      router.route().failureHandler(XYZHubRESTVerticle::failureHandler);
      router.route().order(0)
          .handler(this::onRequestReceived)
          .handler(createCorsHandler());

      this.healthApi = new HealthApi(vertx, router);
      this.adminApi = new AdminApi(vertx, router, jwtHandler);

      //OpenAPI resources
      router.route("/hub/static/openapi/*").handler(createCorsHandler()).handler((routingContext -> {
        final HttpServerResponse res = routingContext.response();
        final String path = routingContext.request().path();
        if (path.endsWith("full.yaml")) {
          res.headers().add(CONTENT_LENGTH, String.valueOf(FULL_API.getBytes().length));
          res.write(FULL_API);
        } else if (path.endsWith("stable.yaml")) {
          res.headers().add(CONTENT_LENGTH, String.valueOf(STABLE_API.getBytes().length));
          res.write(STABLE_API);
        } else if (path.endsWith("experimental.yaml")) {
          res.headers().add(CONTENT_LENGTH, String.valueOf(EXPERIMENTAL_API.getBytes().length));
          res.write(EXPERIMENTAL_API);
        } else if (path.endsWith("contract.yaml")) {
          res.headers().add(CONTENT_LENGTH, String.valueOf(CONTRACT_API.getBytes().length));
          res.write(CONTRACT_API);
        } else {
          res.setStatusCode(HttpResponseStatus.NOT_FOUND.code());
        }

        res.end();
      }));

      //Static resources
      router.route("/hub/static/*").handler(StaticHandler.create().setIndexPage("index.html")).handler(createCorsHandler());
      if (Service.configuration.FS_WEB_ROOT != null) {
        logger.debug("Serving extra web-root folder in file-system with location: {}", Service.configuration.FS_WEB_ROOT);
        //noinspection ResultOfMethodCallIgnored
        new File(Service.configuration.FS_WEB_ROOT).mkdirs();
        router.route("/hub/static/*")
            .handler(StaticHandler.create(Service.configuration.FS_WEB_ROOT).setIndexPage("index.html"));
      }

      //Default NotFound handler
      router.route().last().handler(XYZHubRESTVerticle::notFoundHandler);

      vertx.createHttpServer(SERVER_OPTIONS)
          .requestHandler(router)
          .listen(
              Service.configuration.HTTP_PORT, result -> {
                if (result.succeeded()) {
                  createMessageServer(router, fut);
                } else {
                  logger.error("An error occurred, during the initialization of the server.", result.cause());
                  fut.fail(result.cause());
                }
              });
    } else {
      logger.error("An error occurred, during the creation of the router from the Open API specification file.", ar.cause());
    }
  });
}
 
Example 3
Source File: OpenAPI3Examples.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
public void constructRouterFactory(Vertx vertx) {
  OpenAPI3RouterFactory.create(vertx, "src/main/resources/petstore.yaml", ar -> {
    if (ar.succeeded()) {
      // Spec loaded with success
      OpenAPI3RouterFactory routerFactory = ar.result();
    } else {
      // Something went wrong during router factory initialization
      Throwable exception = ar.cause();
    }
  });
}
 
Example 4
Source File: OpenAPI3Examples.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
public void constructRouterFactoryFromUrl(Vertx vertx) {
  OpenAPI3RouterFactory.create(
    vertx,
    "https://raw.githubusercontent.com/OAI/OpenAPI-Specification/master/examples/v3.0/petstore.yaml",
    ar -> {
      if (ar.succeeded()) {
        // Spec loaded with success
        OpenAPI3RouterFactory routerFactory = ar.result();
      } else {
        // Something went wrong during router factory initialization
        Throwable exception = ar.cause();
      }
    });
}
 
Example 5
Source File: HttpBridge.java    From strimzi-kafka-bridge with Apache License 2.0 4 votes vote down vote up
@Override
public void start(Promise<Void> startPromise) {

    OpenAPI3RouterFactory.create(vertx, "openapi.json", ar -> {
        if (ar.succeeded()) {
            OpenAPI3RouterFactory routerFactory = ar.result();
            routerFactory.addHandlerByOperationId(this.SEND.getOperationId().toString(), this.SEND);
            routerFactory.addHandlerByOperationId(this.SEND_TO_PARTITION.getOperationId().toString(), this.SEND_TO_PARTITION);
            routerFactory.addHandlerByOperationId(this.CREATE_CONSUMER.getOperationId().toString(), this.CREATE_CONSUMER);
            routerFactory.addHandlerByOperationId(this.DELETE_CONSUMER.getOperationId().toString(), this.DELETE_CONSUMER);
            routerFactory.addHandlerByOperationId(this.SUBSCRIBE.getOperationId().toString(), this.SUBSCRIBE);
            routerFactory.addHandlerByOperationId(this.UNSUBSCRIBE.getOperationId().toString(), this.UNSUBSCRIBE);
            routerFactory.addHandlerByOperationId(this.LIST_SUBSCRIPTIONS.getOperationId().toString(), this.LIST_SUBSCRIPTIONS);
            routerFactory.addHandlerByOperationId(this.ASSIGN.getOperationId().toString(), this.ASSIGN);
            routerFactory.addHandlerByOperationId(this.POLL.getOperationId().toString(), this.POLL);
            routerFactory.addHandlerByOperationId(this.COMMIT.getOperationId().toString(), this.COMMIT);
            routerFactory.addHandlerByOperationId(this.SEEK.getOperationId().toString(), this.SEEK);
            routerFactory.addHandlerByOperationId(this.SEEK_TO_BEGINNING.getOperationId().toString(), this.SEEK_TO_BEGINNING);
            routerFactory.addHandlerByOperationId(this.SEEK_TO_END.getOperationId().toString(), this.SEEK_TO_END);
            routerFactory.addHandlerByOperationId(this.LIST_TOPICS.getOperationId().toString(), this.LIST_TOPICS);
            routerFactory.addHandlerByOperationId(this.GET_TOPIC.getOperationId().toString(), this.GET_TOPIC);
            routerFactory.addHandlerByOperationId(this.HEALTHY.getOperationId().toString(), this.HEALTHY);
            routerFactory.addHandlerByOperationId(this.READY.getOperationId().toString(), this.READY);
            routerFactory.addHandlerByOperationId(this.OPENAPI.getOperationId().toString(), this.OPENAPI);
            routerFactory.addHandlerByOperationId(this.INFO.getOperationId().toString(), this.INFO);

            this.router = routerFactory.getRouter();

            // handling validation errors and not existing endpoints
            this.router.errorHandler(HttpResponseStatus.BAD_REQUEST.code(), this::errorHandler);
            this.router.errorHandler(HttpResponseStatus.NOT_FOUND.code(), this::errorHandler);

            this.router.route("/metrics").handler(this::metricsHandler);

            //enable cors
            if (this.bridgeConfig.getHttpConfig().isCorsEnabled()) {
                Set<String> allowedHeaders = new HashSet<>();
                //set predefined headers
                allowedHeaders.add("x-requested-with");
                allowedHeaders.add(ACCESS_CONTROL_ALLOW_ORIGIN.toString());
                allowedHeaders.add(ACCESS_CONTROL_ALLOW_METHODS.toString());
                allowedHeaders.add(ORIGIN.toString());
                allowedHeaders.add(CONTENT_TYPE.toString());
                allowedHeaders.add(ACCEPT.toString());

                //set allowed methods from property http.cors.allowedMethods
                Set<HttpMethod> allowedMethods = new HashSet<>();
                String configAllowedMethods = this.bridgeConfig.getHttpConfig().getCorsAllowedMethods();
                String[] configAllowedMethodsArray = configAllowedMethods.split(",");
                for (String method: configAllowedMethodsArray)
                    allowedMethods.add(HttpMethod.valueOf(method));

                //set allowed origins from property http.cors.allowedOrigins
                String allowedOrigins = this.bridgeConfig.getHttpConfig().getCorsAllowedOrigins();

                log.info("Allowed origins for Cors: {}", allowedOrigins);

                this.router.route().handler(CorsHandler.create(allowedOrigins)
                        .allowedHeaders(allowedHeaders)
                        .allowedMethods(allowedMethods));
            }

            log.info("Starting HTTP-Kafka bridge verticle...");
            this.httpBridgeContext = new HttpBridgeContext<>();
            AdminClientEndpoint adminClientEndpoint = new HttpAdminClientEndpoint(this.vertx, this.bridgeConfig, this.httpBridgeContext);
            this.httpBridgeContext.setAdminClientEndpoint(adminClientEndpoint);
            adminClientEndpoint.open();
            this.bindHttpServer(startPromise);
        } else {
            log.error("Failed to create OpenAPI router factory");
            startPromise.fail(ar.cause());
        }
    });
}
 
Example 6
Source File: OpenAPI3Examples.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
public void mainExample(Vertx vertx) {
  // Load the api spec. This operation is asynchronous
  OpenAPI3RouterFactory.create(vertx, "src/main/resources/petstore.yaml",
    openAPI3RouterFactoryAsyncResult -> {
    if (openAPI3RouterFactoryAsyncResult.succeeded()) {
      // Spec loaded with success, retrieve the router
      OpenAPI3RouterFactory routerFactory = openAPI3RouterFactoryAsyncResult.result();
      // You can enable or disable different features of router factory through mounting RouterFactoryOptions
      // For example you can enable or disable the default failure handler for ValidationException
      RouterFactoryOptions options = new RouterFactoryOptions()
        .setMountValidationFailureHandler(false);
      // 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 failure handler to the same operationId
      routerFactory.addFailureHandlerByOperationId("listPets", routingContext -> {
        // This is the failure handler
        Throwable failure = routingContext.failure();
        if (failure instanceof ValidationException)
          // Handle Validation Exception
          routingContext.response().setStatusCode(400).setStatusMessage("ValidationException thrown! " + (
            (ValidationException) failure).type().name()).end();
      });

      // Add a security handler
      // Handle security here
      routerFactory.addSecurityHandler("api_key", RoutingContext::next);

      // 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"));
      server.requestHandler(router).listen();

    } else {
      // Something went wrong during router factory initialization
      Throwable exception = openAPI3RouterFactoryAsyncResult.cause();
    }
  });
}