io.vertx.ext.web.api.contract.openapi3.OpenAPI3RouterFactory Java Examples

The following examples show how to use io.vertx.ext.web.api.contract.openapi3.OpenAPI3RouterFactory. 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: OpenAPI3RouterFactoryImpl.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
@Override
public OpenAPI3RouterFactory mountServiceInterface(Class interfaceClass, String address) {
  for (Method m : interfaceClass.getMethods()) {
    if (OpenApi3Utils.serviceProxyMethodIsCompatibleHandler(m)) {
      String methodName = m.getName();
      OperationValue op = Optional
        .ofNullable(this.operations.get(methodName))
        .orElseGet(() ->
          this.operations.entrySet().stream().filter(e -> OpenApi3Utils.sanitizeOperationId(e.getKey()).equals(methodName)).map(Map.Entry::getValue).findFirst().orElseGet(() -> null)
        );
      if (op != null) {
        op.mountRouteToService(address, methodName);
      }
    }
  }
  return this;
}
 
Example #2
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 #3
Source File: OpenAPI3Examples.java    From vertx-web with Apache License 2.0 6 votes vote down vote up
public void addOperationModelKey(OpenAPI3RouterFactory routerFactory, RouterFactoryOptions options) {
  // Configure the operation model key and set options in router factory
  options.setOperationModelKey("operationPOJO");
  routerFactory.setOptions(options);

  // Add an handler that uses the operation model
  routerFactory.addHandlerByOperationId("listPets", routingContext -> {
    io.swagger.v3.oas.models.Operation operation = routingContext.get("operationPOJO");

    routingContext
      .response()
      .setStatusCode(200)
      .setStatusMessage("OK")
      // Write the response with operation id "listPets"
      .end(operation.getOperationId());
  });
}
 
Example #4
Source File: SpaceApi.java    From xyz-hub with Apache License 2.0 5 votes vote down vote up
public SpaceApi(OpenAPI3RouterFactory routerFactory) {
  routerFactory.addHandlerByOperationId("getSpace", this::getSpace);
  routerFactory.addHandlerByOperationId("getSpaces", this::getSpaces);
  routerFactory.addHandlerByOperationId("postSpace", this::postSpace);
  routerFactory.addHandlerByOperationId("patchSpace", this::patchSpace);
  routerFactory.addHandlerByOperationId("deleteSpace", this::deleteSpace);
}
 
Example #5
Source File: OpenAPI3RouterFactoryImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Override
public OpenAPI3RouterFactory mountServicesFromExtensions() {
  for (Map.Entry<String, OperationValue> opEntry : operations.entrySet()) {
    OperationValue operation = opEntry.getValue();
    Object extensionVal = OpenApi3Utils.getAndMergeServiceExtension(OPENAPI_EXTENSION, OPENAPI_EXTENSION_ADDRESS, OPENAPI_EXTENSION_METHOD_NAME, operation.pathModel, operation.operationModel);

    if (extensionVal != null) {
      if (extensionVal instanceof String) {
        operation.mountRouteToService((String) extensionVal, opEntry.getKey());
      } else if (extensionVal instanceof Map) {
        JsonObject extensionMap = new JsonObject((Map<String, Object>) extensionVal);
        String address = extensionMap.getString(OPENAPI_EXTENSION_ADDRESS);
        String methodName = extensionMap.getString(OPENAPI_EXTENSION_METHOD_NAME);
        JsonObject sanitizedMap = OpenApi3Utils.sanitizeDeliveryOptionsExtension(extensionMap);
        if (address == null)
          throw RouterFactoryException.createWrongExtension("Extension " + OPENAPI_EXTENSION + " must define " + OPENAPI_EXTENSION_ADDRESS);
        if (methodName == null)
          operation.mountRouteToService(address, opEntry.getKey());
        else
          operation.mountRouteToService(address, methodName, sanitizedMap);
      } else {
        throw RouterFactoryException.createWrongExtension("Extension " + OPENAPI_EXTENSION + " must be or string or a JsonObject");
      }
    }
  }
  return this;
}
 
Example #6
Source File: OpenAPI3RouterFactoryImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Override
public OpenAPI3RouterFactory mountOperationToEventBus(String operationId, String address) {
  OperationValue op = operations.get(operationId);
  if (op == null) throw RouterFactoryException.createOperationIdNotFoundException(operationId);
  op.mountRouteToService(address, operationId);
  return this;
}
 
Example #7
Source File: OpenAPI3RouterFactoryImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Override
public OpenAPI3RouterFactory mountServiceFromTag(String tag, String address) {
  for (Map.Entry<String, OperationValue> op : operations.entrySet()) {
    if (op.getValue().hasTag(tag))
      op.getValue().mountRouteToService(address);
  }
  return this;
}
 
Example #8
Source File: OpenAPI3RouterFactoryImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Override
public OpenAPI3RouterFactory addFailureHandlerByOperationId(String operationId, Handler<RoutingContext> failureHandler) {
  if (failureHandler != null) {
    OperationValue op = operations.get(operationId);
    if (op == null) throw RouterFactoryException.createOperationIdNotFoundException(operationId);
    op.addUserFailureHandler(failureHandler);
  }
  return this;
}
 
Example #9
Source File: OpenAPI3RouterFactoryImpl.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
@Override
public OpenAPI3RouterFactory addHandlerByOperationId(String operationId, Handler<RoutingContext> handler) {
  if (handler != null) {
    OperationValue op = operations.get(operationId);
    if (op == null) throw RouterFactoryException.createOperationIdNotFoundException(operationId);
    op.addUserHandler(handler);
  }
  return this;
}
 
Example #10
Source File: OpenAPI3Examples.java    From vertx-web with Apache License 2.0 5 votes vote down vote up
public void addRoute(Vertx vertx, OpenAPI3RouterFactory routerFactory) {
  routerFactory.addHandlerByOperationId("awesomeOperation", routingContext -> {
    RequestParameters params = routingContext.get("parsedParameters");
    RequestParameter body = params.body();
    JsonObject jsonBody = body.getJsonObject();
    // Do something with body
  });
  routerFactory.addFailureHandlerByOperationId("awesomeOperation", routingContext -> {
    // Handle failure
  });
}
 
Example #11
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 #12
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 #13
Source File: FeatureQueryApi.java    From xyz-hub with Apache License 2.0 5 votes vote down vote up
public FeatureQueryApi(OpenAPI3RouterFactory routerFactory) {
  routerFactory.addHandlerByOperationId("getFeaturesBySpatial", this::getFeaturesBySpatial);
  routerFactory.addHandlerByOperationId("getFeaturesBySpatialPost", this::getFeaturesBySpatial);
  routerFactory.addHandlerByOperationId("getFeaturesByBBox", this::getFeaturesByBBox);
  routerFactory.addHandlerByOperationId("getFeaturesByTile", this::getFeaturesByTile);
  routerFactory.addHandlerByOperationId("getFeaturesCount", this::getFeaturesCount);
  routerFactory.addHandlerByOperationId("getStatistics", this::getStatistics);
  routerFactory.addHandlerByOperationId("iterateFeatures", this::iterateFeatures);
  routerFactory.addHandlerByOperationId("searchForFeatures", this::searchForFeatures);
}
 
Example #14
Source File: FeatureApi.java    From xyz-hub with Apache License 2.0 5 votes vote down vote up
public FeatureApi(OpenAPI3RouterFactory routerFactory) {
  routerFactory.addHandlerByOperationId("getFeature", this::getFeature);
  routerFactory.addHandlerByOperationId("getFeatures", this::getFeatures);
  routerFactory.addHandlerByOperationId("putFeature", this::putFeature);
  routerFactory.addHandlerByOperationId("putFeatures", this::putFeatures);
  routerFactory.addHandlerByOperationId("postFeatures", this::postFeatures);
  routerFactory.addHandlerByOperationId("patchFeature", this::patchFeature);
  routerFactory.addHandlerByOperationId("deleteFeature", this::deleteFeature);
  routerFactory.addHandlerByOperationId("deleteFeatures", this::deleteFeatures);
}
 
Example #15
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 #16
Source File: OpenAPI3Examples.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
public void addSecurityHandler(OpenAPI3RouterFactory routerFactory, Handler securityHandler) {
  routerFactory.addSecurityHandler("security_scheme_name", securityHandler);
}
 
Example #17
Source File: OpenAPI3Examples.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
public void addJWT(OpenAPI3RouterFactory routerFactory, JWTAuth jwtAuthProvider) {
  routerFactory.addSecurityHandler("jwt_auth", JWTAuthHandler.create(jwtAuthProvider));
}
 
Example #18
Source File: OpenAPI3Examples.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
public void generateRouter(Vertx vertx, OpenAPI3RouterFactory routerFactory) {
  Router router = routerFactory.getRouter();

  HttpServer server = vertx.createHttpServer(new HttpServerOptions().setPort(8080).setHost("localhost"));
  server.requestHandler(router).listen();
}
 
Example #19
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();
    }
  });
}
 
Example #20
Source File: OpenAPI3RouterFactoryImpl.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
@Override
public OpenAPI3RouterFactory addSecuritySchemaScopeValidator(String securitySchemaName, String scopeName, Handler
  handler) {
  securityHandlers.addSecurityRequirement(securitySchemaName, scopeName, handler);
  return this;
}
 
Example #21
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 #22
Source File: OpenAPI3RouterFactoryImpl.java    From vertx-web with Apache License 2.0 4 votes vote down vote up
@Override
public OpenAPI3RouterFactory addSecurityHandler(String securitySchemaName, Handler handler) {
  securityHandlers.addSecurityRequirement(securitySchemaName, handler);
  return this;
}