Search in sources :

Example 1 with RouteImpl

use of io.vertx.ext.web.impl.RouteImpl in project vertx-web by vert-x3.

the class OpenAPI3RouterFactoryImpl method getRouter.

@Override
public Router getRouter() {
    Router router = Router.router(vertx);
    Route globalRoute = router.route();
    globalRoute.handler(this.getBodyHandler());
    List<Handler<RoutingContext>> globalHandlers = this.getGlobalHandlers();
    for (Handler<RoutingContext> globalHandler : globalHandlers) {
        globalRoute.handler(globalHandler);
    }
    List<Handler<RoutingContext>> globalSecurityHandlers = securityHandlers.solveSecurityHandlers(spec.getSecurity(), this.getOptions().isRequireSecurityHandlers());
    for (OperationValue operation : operations.values()) {
        // If user don't want 501 handlers and the operation is not configured, skip it
        if (!options.isMountNotImplementedHandler() && !operation.isConfigured())
            continue;
        List<Handler> handlersToLoad = new ArrayList<>();
        List<Handler> failureHandlersToLoad = new ArrayList<>();
        // Operation specific security requirement overrides global security requirement, even if local security requirement is an empty array
        if (operation.getOperationModel().getSecurity() != null) {
            handlersToLoad.addAll(securityHandlers.solveSecurityHandlers(operation.getOperationModel().getSecurity(), this.getOptions().isRequireSecurityHandlers()));
        } else {
            handlersToLoad.addAll(globalSecurityHandlers);
        }
        // Generate ValidationHandler
        OpenAPI3RequestValidationHandlerImpl validationHandler = new OpenAPI3RequestValidationHandlerImpl(operation.getOperationModel(), operation.getParameters(), this.spec, refsCache);
        handlersToLoad.add(validationHandler);
        // Check if path is set by user
        if (operation.isConfigured()) {
            handlersToLoad.addAll(operation.getUserHandlers());
            failureHandlersToLoad.addAll(operation.getUserFailureHandlers());
            if (operation.mustMountRouteToService()) {
                handlersToLoad.add((operation.getEbServiceDeliveryOptions() != null) ? RouteToEBServiceHandler.build(vertx.eventBus(), operation.getEbServiceAddress(), operation.getEbServiceMethodName(), operation.getEbServiceDeliveryOptions(), this.getExtraOperationContextPayloadMapper()) : RouteToEBServiceHandler.build(vertx.eventBus(), operation.getEbServiceAddress(), operation.getEbServiceMethodName(), this.getExtraOperationContextPayloadMapper()));
            }
        } else {
            // Check if not implemented or method not allowed
            List<HttpMethod> configuredMethodsForThisPath = operations.values().stream().filter(ov -> operation.path.equals(ov.path)).filter(OperationValue::isConfigured).map(OperationValue::getMethod).collect(Collectors.toList());
            if (!configuredMethodsForThisPath.isEmpty())
                handlersToLoad.add(generateNotAllowedHandler(configuredMethodsForThisPath));
            else
                handlersToLoad.add(NOT_IMPLEMENTED_HANDLER);
        }
        // Now add all handlers to route
        OpenAPI3PathResolver pathResolver = new OpenAPI3PathResolver(operation.getPath(), operation.getParameters());
        Route route = pathResolver.solve().map(solvedRegex -> router.routeWithRegex(operation.getMethod(), solvedRegex.toString())).orElseGet(() -> router.route(operation.getMethod(), operation.getPath()));
        String exposeConfigurationKey = this.getOptions().getOperationModelKey();
        if (exposeConfigurationKey != null)
            route.handler(context -> context.put(exposeConfigurationKey, operation.getOperationModel()).next());
        // Set produces/consumes
        Set<String> consumes = new HashSet<>();
        Set<String> produces = new HashSet<>();
        if (operation.getOperationModel().getRequestBody() != null && operation.getOperationModel().getRequestBody().getContent() != null)
            consumes.addAll(operation.getOperationModel().getRequestBody().getContent().keySet());
        if (operation.getOperationModel().getResponses() != null)
            for (ApiResponse response : operation.getOperationModel().getResponses().values()) if (response.getContent() != null)
                produces.addAll(response.getContent().keySet());
        for (String ct : consumes) route.consumes(ct);
        for (String ct : produces) route.produces(ct);
        if (!consumes.isEmpty())
            ((RouteImpl) route).setEmptyBodyPermittedWithConsumes(!validationHandler.isBodyRequired());
        if (options.isMountResponseContentTypeHandler() && produces.size() != 0)
            route.handler(ResponseContentTypeHandler.create());
        route.setRegexGroupsNames(new ArrayList<>(pathResolver.getMappedGroups().values()));
        for (Handler handler : handlersToLoad) route.handler(handler);
        for (Handler failureHandler : failureHandlersToLoad) route.failureHandler(failureHandler);
    }
    // Check validation failure handler
    if (this.options.isMountValidationFailureHandler())
        router.errorHandler(400, this.getValidationFailureHandler());
    if (this.options.isMountNotImplementedHandler())
        router.errorHandler(501, this.getNotImplementedFailureHandler());
    return router;
}
Also used : RouteToEBServiceHandler(io.vertx.ext.web.api.contract.impl.RouteToEBServiceHandler) LoggerFactory(io.vertx.core.impl.logging.LoggerFactory) Parameter(io.swagger.v3.oas.models.parameters.Parameter) ResolverCache(io.swagger.v3.parser.ResolverCache) Router(io.vertx.ext.web.Router) Operation(io.swagger.v3.oas.models.Operation) RoutingContext(io.vertx.ext.web.RoutingContext) BaseRouterFactory(io.vertx.ext.web.api.contract.impl.BaseRouterFactory) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Map(java.util.Map) JsonObject(io.vertx.core.json.JsonObject) OpenAPI3RouterFactory(io.vertx.ext.web.api.contract.openapi3.OpenAPI3RouterFactory) Method(java.lang.reflect.Method) Logger(io.vertx.core.impl.logging.Logger) Route(io.vertx.ext.web.Route) ApiResponse(io.swagger.v3.oas.models.responses.ApiResponse) PathItem(io.swagger.v3.oas.models.PathItem) Vertx(io.vertx.core.Vertx) Set(java.util.Set) RouterFactoryException(io.vertx.ext.web.api.contract.RouterFactoryException) Collectors(java.util.stream.Collectors) List(java.util.List) HttpMethod(io.vertx.core.http.HttpMethod) Optional(java.util.Optional) ResponseContentTypeHandler(io.vertx.ext.web.handler.ResponseContentTypeHandler) RouteImpl(io.vertx.ext.web.impl.RouteImpl) Handler(io.vertx.core.Handler) ArrayList(java.util.ArrayList) Router(io.vertx.ext.web.Router) RouteToEBServiceHandler(io.vertx.ext.web.api.contract.impl.RouteToEBServiceHandler) ResponseContentTypeHandler(io.vertx.ext.web.handler.ResponseContentTypeHandler) Handler(io.vertx.core.Handler) ApiResponse(io.swagger.v3.oas.models.responses.ApiResponse) RoutingContext(io.vertx.ext.web.RoutingContext) Route(io.vertx.ext.web.Route) HttpMethod(io.vertx.core.http.HttpMethod) HashSet(java.util.HashSet)

Example 2 with RouteImpl

use of io.vertx.ext.web.impl.RouteImpl in project vertx-web by vert-x3.

the class OpenAPI3RouterBuilderImpl method createRouter.

@Override
public Router createRouter() {
    Router router = Router.router(vertx);
    Route globalRoute = router.route();
    if (bodyHandler != null) {
        globalRoute.handler(bodyHandler);
    }
    globalHandlers.forEach(globalRoute::handler);
    // sort paths by number of patterned fields so /pets/mine is matched first
    // when there is a choice between /pets/{petId} and /pets/mine
    List<ResolvedOpenAPI3Path> resolvedPaths = operations.values().stream().map(it -> new ResolvedOpenAPI3Path(it, openapi)).sorted().collect(Collectors.toList());
    for (ResolvedOpenAPI3Path resolvedPath : resolvedPaths) {
        OperationImpl operation = resolvedPath.operation;
        // If user don't want 501 handlers and the operation is not configured, skip it
        if (!options.isMountNotImplementedHandler() && !operation.isConfigured())
            continue;
        List<Handler<RoutingContext>> handlersToLoad = new ArrayList<>();
        List<Handler<RoutingContext>> failureHandlersToLoad = new ArrayList<>();
        // Authentication Handler
        AuthenticationHandler authnHandler = this.securityHandlers.solveAuthenticationHandler(OpenAPI3Utils.mergeSecurityRequirements(this.openapi.getOpenAPI().getJsonArray("security"), operation.getOperationModel().getJsonArray("security")), this.options.isRequireSecurityHandlers());
        if (authnHandler != null) {
            handlersToLoad.add(authnHandler);
        }
        // Generate ValidationHandler
        ValidationHandlerImpl validationHandler = validationHandlerGenerator.create(operation);
        handlersToLoad.add(validationHandler);
        // Check if path is set by user
        if (operation.isConfigured()) {
            handlersToLoad.addAll(operation.getUserHandlers());
            failureHandlersToLoad.addAll(operation.getUserFailureHandlers());
            if (operation.mustMountRouteToService()) {
                try {
                    io.vertx.ext.web.api.service.RouteToEBServiceHandler routeToEBServiceHandler = (operation.getEbServiceDeliveryOptions() != null) ? io.vertx.ext.web.api.service.RouteToEBServiceHandler.build(vertx.eventBus(), operation.getEbServiceAddress(), operation.getEbServiceMethodName(), operation.getEbServiceDeliveryOptions()) : io.vertx.ext.web.api.service.RouteToEBServiceHandler.build(vertx.eventBus(), operation.getEbServiceAddress(), operation.getEbServiceMethodName());
                    routeToEBServiceHandler.extraPayloadMapper(serviceExtraPayloadMapper);
                    handlersToLoad.add(routeToEBServiceHandler);
                } catch (NoClassDefFoundError exception) {
                    throw new IllegalStateException("You're trying to use api service without adding it to your classpath. " + "Check you have included vertx-web-api-service in your dependencies", exception);
                }
            }
        } else {
            // Check if not implemented or method not allowed
            List<HttpMethod> configuredMethodsForThisPath = operations.values().stream().filter(ov -> operation.getOpenAPIPath().equals(ov.getOpenAPIPath())).filter(OperationImpl::isConfigured).map(OperationImpl::getHttpMethod).collect(Collectors.toList());
            if (!configuredMethodsForThisPath.isEmpty())
                handlersToLoad.add(generateNotAllowedHandler(configuredMethodsForThisPath));
            else
                handlersToLoad.add(NOT_IMPLEMENTED_HANDLER);
        }
        // Now add all handlers to route
        Route route = resolvedPath.optionalPattern.map(solvedRegex -> router.routeWithRegex(operation.getHttpMethod(), solvedRegex.toString())).orElseGet(() -> router.route(operation.getHttpMethod(), operation.getOpenAPIPath())).setName(options.getRouteNamingStrategy().apply(operation));
        String exposeConfigurationKey = this.getOptions().getOperationModelKey();
        if (exposeConfigurationKey != null)
            route.handler(context -> context.put(exposeConfigurationKey, operation.getOperationModel()).next());
        // Set produces/consumes
        Set<String> consumes = ((JsonObject) JsonPointer.from("/requestBody/content").queryJsonOrDefault(operation.getOperationModel(), new JsonObject())).fieldNames();
        Set<String> produces = operation.getOperationModel().getJsonObject("responses", new JsonObject()).stream().map(Map.Entry::getValue).map(j -> (JsonObject) j).flatMap(j -> j.getJsonObject("content", new JsonObject()).fieldNames().stream()).collect(Collectors.toSet());
        for (String ct : produces) route.produces(ct);
        if (!consumes.isEmpty())
            ((RouteImpl) route).setEmptyBodyPermittedWithConsumes(!validationHandler.isBodyRequired());
        if (options.isMountResponseContentTypeHandler() && produces.size() != 0)
            route.handler(ResponseContentTypeHandler.create());
        route.setRegexGroupsNames(new ArrayList<>(resolvedPath.resolver.getMappedGroups().values()));
        for (Handler<RoutingContext> handler : handlersToLoad) route.handler(handler);
        for (Handler<RoutingContext> failureHandler : failureHandlersToLoad) route.failureHandler(failureHandler);
    }
    if (this.options.getContractEndpoint() != null) {
        router.get(this.options.getContractEndpoint()).handler(ContractEndpointHandler.create(this.openapi));
    }
    return router;
}
Also used : DeliveryOptions(io.vertx.core.eventbus.DeliveryOptions) java.util(java.util) LoggerFactory(io.vertx.core.impl.logging.LoggerFactory) OpenAPI3SchemaParser(io.vertx.json.schema.openapi3.OpenAPI3SchemaParser) AuthenticationHandler(io.vertx.ext.web.handler.AuthenticationHandler) Router(io.vertx.ext.web.Router) RoutingContext(io.vertx.ext.web.RoutingContext) BodyHandler(io.vertx.ext.web.handler.BodyHandler) Function(java.util.function.Function) ValidationHandlerImpl(io.vertx.ext.web.validation.impl.ValidationHandlerImpl) io.vertx.ext.web.openapi(io.vertx.ext.web.openapi) JsonObject(io.vertx.core.json.JsonObject) Method(java.lang.reflect.Method) Logger(io.vertx.core.impl.logging.Logger) Route(io.vertx.ext.web.Route) Vertx(io.vertx.core.Vertx) SchemaParser(io.vertx.json.schema.SchemaParser) SchemaRouter(io.vertx.json.schema.SchemaRouter) Collectors(java.util.stream.Collectors) Stream(java.util.stream.Stream) HttpMethod(io.vertx.core.http.HttpMethod) ResponseContentTypeHandler(io.vertx.ext.web.handler.ResponseContentTypeHandler) RouteImpl(io.vertx.ext.web.impl.RouteImpl) Pattern(java.util.regex.Pattern) Handler(io.vertx.core.Handler) JsonPointer(io.vertx.core.json.pointer.JsonPointer) HttpClient(io.vertx.core.http.HttpClient) JsonObject(io.vertx.core.json.JsonObject) ValidationHandlerImpl(io.vertx.ext.web.validation.impl.ValidationHandlerImpl) RoutingContext(io.vertx.ext.web.RoutingContext) AuthenticationHandler(io.vertx.ext.web.handler.AuthenticationHandler) Route(io.vertx.ext.web.Route) Router(io.vertx.ext.web.Router) SchemaRouter(io.vertx.json.schema.SchemaRouter) AuthenticationHandler(io.vertx.ext.web.handler.AuthenticationHandler) BodyHandler(io.vertx.ext.web.handler.BodyHandler) ResponseContentTypeHandler(io.vertx.ext.web.handler.ResponseContentTypeHandler) Handler(io.vertx.core.Handler) HttpMethod(io.vertx.core.http.HttpMethod)

Aggregations

Handler (io.vertx.core.Handler)2 Vertx (io.vertx.core.Vertx)2 HttpMethod (io.vertx.core.http.HttpMethod)2 Logger (io.vertx.core.impl.logging.Logger)2 LoggerFactory (io.vertx.core.impl.logging.LoggerFactory)2 JsonObject (io.vertx.core.json.JsonObject)2 Route (io.vertx.ext.web.Route)2 Router (io.vertx.ext.web.Router)2 RoutingContext (io.vertx.ext.web.RoutingContext)2 ResponseContentTypeHandler (io.vertx.ext.web.handler.ResponseContentTypeHandler)2 RouteImpl (io.vertx.ext.web.impl.RouteImpl)2 Method (java.lang.reflect.Method)2 Collectors (java.util.stream.Collectors)2 OpenAPI (io.swagger.v3.oas.models.OpenAPI)1 Operation (io.swagger.v3.oas.models.Operation)1 PathItem (io.swagger.v3.oas.models.PathItem)1 Parameter (io.swagger.v3.oas.models.parameters.Parameter)1 ApiResponse (io.swagger.v3.oas.models.responses.ApiResponse)1 ResolverCache (io.swagger.v3.parser.ResolverCache)1 DeliveryOptions (io.vertx.core.eventbus.DeliveryOptions)1