Search in sources :

Example 26 with Operation

use of io.swagger.v3.oas.annotations.Operation in project cxf by apache.

the class OpenApiCustomizedResource method getOpenApi.

@GET
@Produces({ MediaType.APPLICATION_JSON, "application/yaml" })
@Operation(hidden = true)
public Response getOpenApi(@Context ServletConfig config, @Context HttpHeaders headers, @Context UriInfo uriInfo, @PathParam("type") String type) throws Exception {
    if (customizer != null) {
        final OpenAPIConfiguration configuration = customizer.customize(getOpenApiConfiguration());
        setOpenApiConfiguration(configuration);
        // By default, the OpenApiContext instance is cached. It means that the configuration
        // changes won't be taken into account (due to the deep copying rather than reference
        // passing). In order to reflect any changes which customization may do, we have to
        // update reader's configuration directly.
        final String ctxId = ServletConfigContextUtils.getContextIdFromServletConfig(config);
        final OpenApiContext ctx = OpenApiContextLocator.getInstance().getOpenApiContext(ctxId);
        if (ctx instanceof GenericOpenApiContext<?>) {
            ((GenericOpenApiContext<?>) ctx).getOpenApiReader().setConfiguration(configuration);
            customizer.customize(ctx.read());
        }
    }
    return super.getOpenApi(headers, uriInfo, type);
}
Also used : OpenAPIConfiguration(io.swagger.v3.oas.integration.api.OpenAPIConfiguration) GenericOpenApiContext(io.swagger.v3.oas.integration.GenericOpenApiContext) GenericOpenApiContext(io.swagger.v3.oas.integration.GenericOpenApiContext) OpenApiContext(io.swagger.v3.oas.integration.api.OpenApiContext) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET) Operation(io.swagger.v3.oas.annotations.Operation)

Example 27 with Operation

use of io.swagger.v3.oas.annotations.Operation in project cxf by apache.

the class OpenApiCustomizer method customize.

public void customize(final OpenAPI oas) {
    if (replaceTags || javadocProvider != null) {
        Map<String, ClassResourceInfo> operations = new HashMap<>();
        Map<Pair<String, String>, OperationResourceInfo> methods = new HashMap<>();
        cris.forEach(cri -> {
            cri.getMethodDispatcher().getOperationResourceInfos().forEach(ori -> {
                String normalizedPath = getNormalizedPath(cri.getURITemplate().getValue(), ori.getURITemplate().getValue());
                operations.put(normalizedPath, cri);
                methods.put(Pair.of(ori.getHttpMethod(), normalizedPath), ori);
            });
        });
        List<Tag> tags = new ArrayList<>();
        oas.getPaths().forEach((pathKey, pathItem) -> {
            Tag tag = null;
            if (replaceTags && operations.containsKey(pathKey)) {
                ClassResourceInfo cri = operations.get(pathKey);
                tag = new Tag();
                tag.setName(cri.getURITemplate().getValue().replaceAll("/", "_"));
                if (javadocProvider != null) {
                    tag.setDescription(javadocProvider.getClassDoc(cri));
                }
                if (!tags.contains(tag)) {
                    tags.add(tag);
                }
            }
            for (Map.Entry<HttpMethod, Operation> subentry : pathItem.readOperationsMap().entrySet()) {
                if (replaceTags && tag != null) {
                    subentry.getValue().setTags(Collections.singletonList(tag.getName()));
                }
                Pair<String, String> key = Pair.of(subentry.getKey().name(), pathKey);
                if (methods.containsKey(key) && javadocProvider != null) {
                    OperationResourceInfo ori = methods.get(key);
                    if (StringUtils.isBlank(subentry.getValue().getSummary())) {
                        subentry.getValue().setSummary(javadocProvider.getMethodDoc(ori));
                    }
                    if (subentry.getValue().getParameters() == null) {
                        List<Parameter> parameters = new ArrayList<>();
                        addParameters(parameters);
                        subentry.getValue().setParameters(parameters);
                    } else {
                        for (int i = 0; i < subentry.getValue().getParameters().size(); i++) {
                            if (StringUtils.isBlank(subentry.getValue().getParameters().get(i).getDescription())) {
                                subentry.getValue().getParameters().get(i).setDescription(javadocProvider.getMethodParameterDoc(ori, i));
                            }
                        }
                        addParameters(subentry.getValue().getParameters());
                    }
                    if (subentry.getValue().getResponses() != null && !subentry.getValue().getResponses().isEmpty()) {
                        ApiResponse response = subentry.getValue().getResponses().entrySet().iterator().next().getValue();
                        if (StringUtils.isBlank(response.getDescription())) {
                            response.setDescription(javadocProvider.getMethodResponseDoc(ori));
                        }
                    }
                }
            }
        });
        if (replaceTags && oas.getTags() != null) {
            oas.setTags(tags);
        }
    }
}
Also used : HashMap(java.util.HashMap) ClassResourceInfo(org.apache.cxf.jaxrs.model.ClassResourceInfo) ArrayList(java.util.ArrayList) Operation(io.swagger.v3.oas.models.Operation) ApiResponse(io.swagger.v3.oas.models.responses.ApiResponse) Parameter(io.swagger.v3.oas.models.parameters.Parameter) OperationResourceInfo(org.apache.cxf.jaxrs.model.OperationResourceInfo) Tag(io.swagger.v3.oas.models.tags.Tag) HashMap(java.util.HashMap) Map(java.util.Map) HttpMethod(io.swagger.v3.oas.models.PathItem.HttpMethod) Pair(org.apache.commons.lang3.tuple.Pair)

Example 28 with Operation

use of io.swagger.v3.oas.annotations.Operation in project vertx-web by vert-x3.

the class OpenAPI3RouterFactoryImpl method resolveOperationId.

private String resolveOperationId(HttpMethod method, String path) {
    // I assume the user give path in openapi style
    PathItem pathObject = this.spec.getPaths().get(path);
    if (pathObject == null) {
        throw RouterFactoryException.createPathNotFoundException(path);
    }
    Operation operation;
    switch(method) {
        case GET:
            operation = pathObject.getGet();
            break;
        case PUT:
            operation = pathObject.getPut();
            break;
        case HEAD:
            operation = pathObject.getHead();
            break;
        case DELETE:
            operation = pathObject.getDelete();
            break;
        case PATCH:
            operation = pathObject.getPatch();
            break;
        case POST:
            operation = pathObject.getPost();
            break;
        case OPTIONS:
            operation = pathObject.getOptions();
            break;
        case TRACE:
            operation = pathObject.getTrace();
            break;
        case OTHER:
        case CONNECT:
        default:
            throw RouterFactoryException.createPathNotFoundException(path);
    }
    return operation.getOperationId();
}
Also used : PathItem(io.swagger.v3.oas.models.PathItem) Operation(io.swagger.v3.oas.models.Operation)

Example 29 with Operation

use of io.swagger.v3.oas.annotations.Operation in project vertx-web by vert-x3.

the class OpenAPI3RouterFactoryImpl method getRouter.

@Override
public Router getRouter() {
    Router router = Router.router(vertx);
    router.route().handler(options.getBodyHandler());
    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<>();
        // Resolve security handlers
        handlersToLoad.addAll(globalSecurityHandlers);
        handlersToLoad.addAll(securityHandlers.solveSecurityHandlers(operation.getOperationModel().getSecurity(), this.getOptions().isRequireSecurityHandlers()));
        // Generate ValidationHandler
        Handler<RoutingContext> validationHandler = new OpenAPI3RequestValidationHandlerImpl(operation.getOperationModel(), operation.getParameters(), this.spec);
        handlersToLoad.add(validationHandler);
        // Check validation failure handler
        if (this.options.isMountValidationFailureHandler())
            failureHandlersToLoad.add(this.options.getValidationFailureHandler());
        // Check if path is set by user
        if (operation.isConfigured()) {
            handlersToLoad.addAll(operation.getUserHandlers());
            failureHandlersToLoad.addAll(operation.getUserFailureHandlers());
        } else {
            handlersToLoad.add(this.options.getNotImplementedFailureHandler());
        }
        // Now add all handlers to route
        OpenAPI3PathResolver pathResolver = new OpenAPI3PathResolver(operation.getPath(), operation.getParameters());
        Route route = router.routeWithRegex(operation.getMethod(), pathResolver.solve().toString());
        // 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 (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);
    }
    return router;
}
Also used : Router(io.vertx.ext.web.Router) BodyHandler(io.vertx.ext.web.handler.BodyHandler) 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)

Example 30 with Operation

use of io.swagger.v3.oas.annotations.Operation in project vertx-web by vert-x3.

the class OpenAPI3ValidationTest method testQueryParameterArrayDefaultStyle.

@Test
public void testQueryParameterArrayDefaultStyle() throws Exception {
    Operation op = testSpec.getPaths().get("/queryTests/arrayTests/default").getGet();
    OpenAPI3RequestValidationHandler validationHandler = new OpenAPI3RequestValidationHandlerImpl(op, op.getParameters(), testSpec);
    loadHandlers("/queryTests/arrayTests/default", HttpMethod.GET, false, validationHandler, (routingContext) -> {
        RequestParameters params = routingContext.get("parsedParameters");
        List<String> result = new ArrayList<>();
        for (RequestParameter r : params.queryParameter("parameter").getArray()) result.add(r.getInteger().toString());
        routingContext.response().setStatusMessage(serializeInCSVStringArray(result)).end();
    });
    List<String> values = new ArrayList<>();
    values.add("4");
    values.add("2");
    values.add("26");
    testRequest(HttpMethod.GET, "/queryTests/arrayTests/default?parameter=" + serializeInCSVStringArray(values), 200, serializeInCSVStringArray(values));
}
Also used : OpenAPI3RequestValidationHandlerImpl(io.vertx.ext.web.api.contract.openapi3.impl.OpenAPI3RequestValidationHandlerImpl) RequestParameter(io.vertx.ext.web.api.RequestParameter) ArrayList(java.util.ArrayList) Operation(io.swagger.v3.oas.models.Operation) RequestParameters(io.vertx.ext.web.api.RequestParameters) Test(org.junit.Test)

Aggregations

Operation (io.swagger.v3.oas.models.Operation)31 OpenAPI3RequestValidationHandlerImpl (io.vertx.ext.web.api.contract.openapi3.impl.OpenAPI3RequestValidationHandlerImpl)28 Test (org.junit.Test)28 RequestParameters (io.vertx.ext.web.api.RequestParameters)21 ArrayList (java.util.ArrayList)12 JsonObject (io.vertx.core.json.JsonObject)7 RequestParameter (io.vertx.ext.web.api.RequestParameter)7 Operation (io.swagger.v3.oas.annotations.Operation)6 MultiMap (io.vertx.core.MultiMap)5 ApiResponse (io.swagger.v3.oas.models.responses.ApiResponse)3 Produces (javax.ws.rs.Produces)3 Charsets (com.google.common.base.Charsets)2 OpenAPIConfiguration (io.swagger.v3.oas.integration.api.OpenAPIConfiguration)2 OpenAPI (io.swagger.v3.oas.models.OpenAPI)2 HttpMethod (io.swagger.v3.oas.models.PathItem.HttpMethod)2 Parameter (io.swagger.v3.oas.models.parameters.Parameter)2 Tag (io.swagger.v3.oas.models.tags.Tag)2 List (java.util.List)2 Consumes (javax.ws.rs.Consumes)2 POST (javax.ws.rs.POST)2