Search in sources :

Example 1 with ResolvedParameter

use of io.swagger.v3.jaxrs2.ResolvedParameter in project cxf by apache.

the class JaxRs2Extension method extractParameters.

@Override
public ResolvedParameter extractParameters(final List<Annotation> annotations, final Type type, final Set<Type> typesToSkip, final Components components, final Consumes classConsumes, final Consumes methodConsumes, final boolean includeRequestBody, final JsonView jsonViewAnnotation, final Iterator<OpenAPIExtension> chain) {
    if (shouldIgnoreType(type, typesToSkip)) {
        return new ResolvedParameter();
    }
    List<Parameter> parameters = annotations.stream().filter(annotation -> annotation instanceof MatrixParam).map(annotation -> {
        MatrixParam param = (MatrixParam) annotation;
        Parameter mp = new PathParameter().name(param.value());
        mp.setStyle(Parameter.StyleEnum.MATRIX);
        ResolvedSchema resolvedSchema = ModelConverters.getInstance().readAllAsResolvedSchema(type);
        if (resolvedSchema != null) {
            mp.setSchema(resolvedSchema.schema);
        }
        applyBeanValidatorAnnotations(mp, annotations);
        return mp;
    }).collect(Collectors.toList());
    // Only call down to the other items in the chain if no parameters were produced
    if (parameters.isEmpty()) {
        return super.extractParameters(annotations, type, typesToSkip, components, classConsumes, methodConsumes, includeRequestBody, jsonViewAnnotation, chain);
    }
    ResolvedParameter resolved = new ResolvedParameter();
    resolved.parameters = parameters;
    return resolved;
}
Also used : Size(javax.validation.constraints.Size) AbstractOpenAPIExtension(io.swagger.v3.jaxrs2.ext.AbstractOpenAPIExtension) JsonView(com.fasterxml.jackson.annotation.JsonView) ResolvedSchema(io.swagger.v3.core.converter.ResolvedSchema) Parameter(io.swagger.v3.oas.models.parameters.Parameter) DecimalMin(javax.validation.constraints.DecimalMin) HashMap(java.util.HashMap) ResolvedParameter(io.swagger.v3.jaxrs2.ResolvedParameter) BigDecimal(java.math.BigDecimal) Consumes(javax.ws.rs.Consumes) Map(java.util.Map) Max(javax.validation.constraints.Max) Schema(io.swagger.v3.oas.models.media.Schema) Iterator(java.util.Iterator) Set(java.util.Set) Min(javax.validation.constraints.Min) NotNull(javax.validation.constraints.NotNull) Collectors(java.util.stream.Collectors) OpenAPIExtension(io.swagger.v3.jaxrs2.ext.OpenAPIExtension) ModelConverters(io.swagger.v3.core.converter.ModelConverters) List(java.util.List) Type(java.lang.reflect.Type) DecimalMax(javax.validation.constraints.DecimalMax) Annotation(java.lang.annotation.Annotation) Pattern(javax.validation.constraints.Pattern) MatrixParam(javax.ws.rs.MatrixParam) Components(io.swagger.v3.oas.models.Components) PathParameter(io.swagger.v3.oas.models.parameters.PathParameter) MatrixParam(javax.ws.rs.MatrixParam) ResolvedParameter(io.swagger.v3.jaxrs2.ResolvedParameter) Parameter(io.swagger.v3.oas.models.parameters.Parameter) ResolvedParameter(io.swagger.v3.jaxrs2.ResolvedParameter) PathParameter(io.swagger.v3.oas.models.parameters.PathParameter) ResolvedSchema(io.swagger.v3.core.converter.ResolvedSchema) PathParameter(io.swagger.v3.oas.models.parameters.PathParameter)

Example 2 with ResolvedParameter

use of io.swagger.v3.jaxrs2.ResolvedParameter in project swagger-core by swagger-api.

the class DefaultParameterExtension method extractParameters.

@Override
public ResolvedParameter extractParameters(List<Annotation> annotations, Type type, Set<Type> typesToSkip, Components components, javax.ws.rs.Consumes classConsumes, javax.ws.rs.Consumes methodConsumes, boolean includeRequestBody, JsonView jsonViewAnnotation, Iterator<OpenAPIExtension> chain) {
    if (shouldIgnoreType(type, typesToSkip)) {
        return new ResolvedParameter();
    }
    Parameter parameter = null;
    for (Annotation annotation : annotations) {
        if (annotation instanceof QueryParam) {
            QueryParam param = (QueryParam) annotation;
            Parameter qp = new Parameter();
            qp.setIn(QUERY_PARAM);
            qp.setName(param.value());
            parameter = qp;
        } else if (annotation instanceof PathParam) {
            PathParam param = (PathParam) annotation;
            Parameter pp = new Parameter();
            pp.setIn(PATH_PARAM);
            pp.setName(param.value());
            parameter = pp;
        } else if (annotation instanceof MatrixParam) {
            MatrixParam param = (MatrixParam) annotation;
            Parameter pp = new Parameter();
            pp.setIn(PATH_PARAM);
            pp.setStyle(Parameter.StyleEnum.MATRIX);
            pp.setName(param.value());
            parameter = pp;
        } else if (annotation instanceof HeaderParam) {
            HeaderParam param = (HeaderParam) annotation;
            Parameter pp = new Parameter();
            pp.setIn(HEADER_PARAM);
            pp.setName(param.value());
            parameter = pp;
        } else if (annotation instanceof CookieParam) {
            CookieParam param = (CookieParam) annotation;
            Parameter pp = new Parameter();
            pp.setIn(COOKIE_PARAM);
            pp.setName(param.value());
            parameter = pp;
        } else if (annotation instanceof io.swagger.v3.oas.annotations.Parameter) {
            if (((io.swagger.v3.oas.annotations.Parameter) annotation).hidden()) {
                return new ResolvedParameter();
            }
            if (parameter == null) {
                parameter = new Parameter();
            }
            if (StringUtils.isNotBlank(((io.swagger.v3.oas.annotations.Parameter) annotation).ref())) {
                parameter.$ref(((io.swagger.v3.oas.annotations.Parameter) annotation).ref());
            }
        } else {
            List<Parameter> formParameters = new ArrayList<>();
            List<Parameter> parameters = new ArrayList<>();
            if (handleAdditionalAnnotation(parameters, formParameters, annotation, type, typesToSkip, classConsumes, methodConsumes, components, includeRequestBody, jsonViewAnnotation)) {
                ResolvedParameter extractParametersResult = new ResolvedParameter();
                extractParametersResult.parameters.addAll(parameters);
                extractParametersResult.formParameters.addAll(formParameters);
                return extractParametersResult;
            }
        }
    }
    List<Parameter> parameters = new ArrayList<>();
    ResolvedParameter extractParametersResult = new ResolvedParameter();
    if (parameter != null && (StringUtils.isNotBlank(parameter.getIn()) || StringUtils.isNotBlank(parameter.get$ref()))) {
        parameters.add(parameter);
    } else if (includeRequestBody) {
        Parameter unknownParameter = ParameterProcessor.applyAnnotations(null, type, annotations, components, classConsumes == null ? new String[0] : classConsumes.value(), methodConsumes == null ? new String[0] : methodConsumes.value(), jsonViewAnnotation);
        if (unknownParameter != null) {
            if (StringUtils.isNotBlank(unknownParameter.getIn()) && !"form".equals(unknownParameter.getIn())) {
                extractParametersResult.parameters.add(unknownParameter);
            } else if ("form".equals(unknownParameter.getIn())) {
                unknownParameter.setIn(null);
                extractParametersResult.formParameters.add(unknownParameter);
            } else {
                // return as request body
                extractParametersResult.requestBody = unknownParameter;
            }
        }
    }
    for (Parameter p : parameters) {
        Parameter processedParameter = ParameterProcessor.applyAnnotations(p, type, annotations, components, classConsumes == null ? new String[0] : classConsumes.value(), methodConsumes == null ? new String[0] : methodConsumes.value(), jsonViewAnnotation);
        if (processedParameter != null) {
            extractParametersResult.parameters.add(processedParameter);
        }
    }
    return extractParametersResult;
}
Also used : MatrixParam(javax.ws.rs.MatrixParam) HeaderParam(javax.ws.rs.HeaderParam) ArrayList(java.util.ArrayList) Annotation(java.lang.annotation.Annotation) CookieParam(javax.ws.rs.CookieParam) QueryParam(javax.ws.rs.QueryParam) Parameter(io.swagger.v3.oas.models.parameters.Parameter) ArrayList(java.util.ArrayList) List(java.util.List) PathParam(javax.ws.rs.PathParam)

Example 3 with ResolvedParameter

use of io.swagger.v3.jaxrs2.ResolvedParameter in project swagger-core by swagger-api.

the class Reader method read.

public OpenAPI read(Class<?> cls, String parentPath, String parentMethod, boolean isSubresource, RequestBody parentRequestBody, ApiResponses parentResponses, Set<String> parentTags, List<Parameter> parentParameters, Set<Class<?>> scannedResources) {
    Hidden hidden = cls.getAnnotation(Hidden.class);
    // class path
    final javax.ws.rs.Path apiPath = ReflectionUtils.getAnnotation(cls, javax.ws.rs.Path.class);
    if (hidden != null) {
        // || (apiPath == null && !isSubresource)) {
        return openAPI;
    }
    io.swagger.v3.oas.annotations.responses.ApiResponse[] classResponses = ReflectionUtils.getRepeatableAnnotationsArray(cls, io.swagger.v3.oas.annotations.responses.ApiResponse.class);
    List<io.swagger.v3.oas.annotations.security.SecurityScheme> apiSecurityScheme = ReflectionUtils.getRepeatableAnnotations(cls, io.swagger.v3.oas.annotations.security.SecurityScheme.class);
    List<io.swagger.v3.oas.annotations.security.SecurityRequirement> apiSecurityRequirements = ReflectionUtils.getRepeatableAnnotations(cls, io.swagger.v3.oas.annotations.security.SecurityRequirement.class);
    ExternalDocumentation apiExternalDocs = ReflectionUtils.getAnnotation(cls, ExternalDocumentation.class);
    io.swagger.v3.oas.annotations.tags.Tag[] apiTags = ReflectionUtils.getRepeatableAnnotationsArray(cls, io.swagger.v3.oas.annotations.tags.Tag.class);
    io.swagger.v3.oas.annotations.servers.Server[] apiServers = ReflectionUtils.getRepeatableAnnotationsArray(cls, io.swagger.v3.oas.annotations.servers.Server.class);
    javax.ws.rs.Consumes classConsumes = ReflectionUtils.getAnnotation(cls, javax.ws.rs.Consumes.class);
    javax.ws.rs.Produces classProduces = ReflectionUtils.getAnnotation(cls, javax.ws.rs.Produces.class);
    boolean classDeprecated = ReflectionUtils.getAnnotation(cls, Deprecated.class) != null;
    // OpenApiDefinition
    OpenAPIDefinition openAPIDefinition = ReflectionUtils.getAnnotation(cls, OpenAPIDefinition.class);
    if (openAPIDefinition != null) {
        // info
        AnnotationsUtils.getInfo(openAPIDefinition.info()).ifPresent(info -> openAPI.setInfo(info));
        // OpenApiDefinition security requirements
        SecurityParser.getSecurityRequirements(openAPIDefinition.security()).ifPresent(s -> openAPI.setSecurity(s));
        // 
        // OpenApiDefinition external docs
        AnnotationsUtils.getExternalDocumentation(openAPIDefinition.externalDocs()).ifPresent(docs -> openAPI.setExternalDocs(docs));
        // OpenApiDefinition tags
        AnnotationsUtils.getTags(openAPIDefinition.tags(), false).ifPresent(tags -> openApiTags.addAll(tags));
        // OpenApiDefinition servers
        AnnotationsUtils.getServers(openAPIDefinition.servers()).ifPresent(servers -> openAPI.setServers(servers));
        // OpenApiDefinition extensions
        if (openAPIDefinition.extensions().length > 0) {
            openAPI.setExtensions(AnnotationsUtils.getExtensions(openAPIDefinition.extensions()));
        }
    }
    // class security schemes
    if (apiSecurityScheme != null) {
        for (io.swagger.v3.oas.annotations.security.SecurityScheme securitySchemeAnnotation : apiSecurityScheme) {
            Optional<SecurityParser.SecuritySchemePair> securityScheme = SecurityParser.getSecurityScheme(securitySchemeAnnotation);
            if (securityScheme.isPresent()) {
                Map<String, SecurityScheme> securitySchemeMap = new HashMap<>();
                if (StringUtils.isNotBlank(securityScheme.get().key)) {
                    securitySchemeMap.put(securityScheme.get().key, securityScheme.get().securityScheme);
                    if (components.getSecuritySchemes() != null && components.getSecuritySchemes().size() != 0) {
                        components.getSecuritySchemes().putAll(securitySchemeMap);
                    } else {
                        components.setSecuritySchemes(securitySchemeMap);
                    }
                }
            }
        }
    }
    // class security requirements
    List<SecurityRequirement> classSecurityRequirements = new ArrayList<>();
    if (apiSecurityRequirements != null) {
        Optional<List<SecurityRequirement>> requirementsObject = SecurityParser.getSecurityRequirements(apiSecurityRequirements.toArray(new io.swagger.v3.oas.annotations.security.SecurityRequirement[apiSecurityRequirements.size()]));
        if (requirementsObject.isPresent()) {
            classSecurityRequirements = requirementsObject.get();
        }
    }
    // class tags, consider only name to add to class operations
    final Set<String> classTags = new LinkedHashSet<>();
    if (apiTags != null) {
        AnnotationsUtils.getTags(apiTags, false).ifPresent(tags -> tags.stream().map(Tag::getName).forEach(classTags::add));
    }
    // parent tags
    if (isSubresource) {
        if (parentTags != null) {
            classTags.addAll(parentTags);
        }
    }
    // servers
    final List<io.swagger.v3.oas.models.servers.Server> classServers = new ArrayList<>();
    if (apiServers != null) {
        AnnotationsUtils.getServers(apiServers).ifPresent(classServers::addAll);
    }
    // class external docs
    Optional<io.swagger.v3.oas.models.ExternalDocumentation> classExternalDocumentation = AnnotationsUtils.getExternalDocumentation(apiExternalDocs);
    JavaType classType = TypeFactory.defaultInstance().constructType(cls);
    BeanDescription bd = Json.mapper().getSerializationConfig().introspect(classType);
    final List<Parameter> globalParameters = new ArrayList<>();
    // look for constructor-level annotated properties
    globalParameters.addAll(ReaderUtils.collectConstructorParameters(cls, components, classConsumes, null));
    // look for field-level annotated properties
    globalParameters.addAll(ReaderUtils.collectFieldParameters(cls, components, classConsumes, null));
    // Make sure that the class methods are sorted for deterministic order
    // See https://docs.oracle.com/javase/8/docs/api/java/lang/Class.html#getMethods--
    final List<Method> methods = Arrays.stream(cls.getMethods()).sorted(new MethodComparator()).collect(Collectors.toList());
    // iterate class methods
    for (Method method : methods) {
        if (isOperationHidden(method)) {
            continue;
        }
        AnnotatedMethod annotatedMethod = bd.findMethod(method.getName(), method.getParameterTypes());
        javax.ws.rs.Produces methodProduces = ReflectionUtils.getAnnotation(method, javax.ws.rs.Produces.class);
        javax.ws.rs.Consumes methodConsumes = ReflectionUtils.getAnnotation(method, javax.ws.rs.Consumes.class);
        if (isMethodOverridden(method, cls)) {
            continue;
        }
        boolean methodDeprecated = ReflectionUtils.getAnnotation(method, Deprecated.class) != null;
        javax.ws.rs.Path methodPath = ReflectionUtils.getAnnotation(method, javax.ws.rs.Path.class);
        String operationPath = ReaderUtils.getPath(apiPath, methodPath, parentPath, isSubresource);
        // extending resource config.
        if (ignoreOperationPath(operationPath, parentPath) && !isSubresource) {
            continue;
        }
        Map<String, String> regexMap = new LinkedHashMap<>();
        operationPath = PathUtils.parsePath(operationPath, regexMap);
        if (operationPath != null) {
            if (config != null && ReaderUtils.isIgnored(operationPath, config)) {
                continue;
            }
            final Class<?> subResource = getSubResourceWithJaxRsSubresourceLocatorSpecs(method);
            String httpMethod = ReaderUtils.extractOperationMethod(method, OpenAPIExtensions.chain());
            httpMethod = (httpMethod == null && isSubresource) ? parentMethod : httpMethod;
            if (StringUtils.isBlank(httpMethod) && subResource == null) {
                continue;
            } else if (StringUtils.isBlank(httpMethod) && subResource != null) {
                Type returnType = method.getGenericReturnType();
                if (annotatedMethod != null && annotatedMethod.getType() != null) {
                    returnType = annotatedMethod.getType();
                }
                if (shouldIgnoreClass(returnType.getTypeName()) && !method.getGenericReturnType().equals(subResource)) {
                    continue;
                }
            }
            io.swagger.v3.oas.annotations.Operation apiOperation = ReflectionUtils.getAnnotation(method, io.swagger.v3.oas.annotations.Operation.class);
            JsonView jsonViewAnnotation;
            JsonView jsonViewAnnotationForRequestBody;
            if (apiOperation != null && apiOperation.ignoreJsonView()) {
                jsonViewAnnotation = null;
                jsonViewAnnotationForRequestBody = null;
            } else {
                jsonViewAnnotation = ReflectionUtils.getAnnotation(method, JsonView.class);
                /* If one and only one exists, use the @JsonView annotation from the method parameter annotated
                       with @RequestBody. Otherwise fall back to the @JsonView annotation for the method itself. */
                jsonViewAnnotationForRequestBody = (JsonView) Arrays.stream(ReflectionUtils.getParameterAnnotations(method)).filter(arr -> Arrays.stream(arr).anyMatch(annotation -> annotation.annotationType().equals(io.swagger.v3.oas.annotations.parameters.RequestBody.class))).flatMap(Arrays::stream).filter(annotation -> annotation.annotationType().equals(JsonView.class)).reduce((a, b) -> null).orElse(jsonViewAnnotation);
            }
            Operation operation = parseMethod(method, globalParameters, methodProduces, classProduces, methodConsumes, classConsumes, classSecurityRequirements, classExternalDocumentation, classTags, classServers, isSubresource, parentRequestBody, parentResponses, jsonViewAnnotation, classResponses, annotatedMethod);
            if (operation != null) {
                if (classDeprecated || methodDeprecated) {
                    operation.setDeprecated(true);
                }
                List<Parameter> operationParameters = new ArrayList<>();
                List<Parameter> formParameters = new ArrayList<>();
                Annotation[][] paramAnnotations = ReflectionUtils.getParameterAnnotations(method);
                if (annotatedMethod == null) {
                    // annotatedMethod not null only when method with 0-2 parameters
                    Type[] genericParameterTypes = method.getGenericParameterTypes();
                    for (int i = 0; i < genericParameterTypes.length; i++) {
                        final Type type = TypeFactory.defaultInstance().constructType(genericParameterTypes[i], cls);
                        io.swagger.v3.oas.annotations.Parameter paramAnnotation = AnnotationsUtils.getAnnotation(io.swagger.v3.oas.annotations.Parameter.class, paramAnnotations[i]);
                        Type paramType = ParameterProcessor.getParameterType(paramAnnotation, true);
                        if (paramType == null) {
                            paramType = type;
                        } else {
                            if (!(paramType instanceof Class)) {
                                paramType = type;
                            }
                        }
                        ResolvedParameter resolvedParameter = getParameters(paramType, Arrays.asList(paramAnnotations[i]), operation, classConsumes, methodConsumes, jsonViewAnnotation);
                        operationParameters.addAll(resolvedParameter.parameters);
                        // collect params to use together as request Body
                        formParameters.addAll(resolvedParameter.formParameters);
                        if (resolvedParameter.requestBody != null) {
                            processRequestBody(resolvedParameter.requestBody, operation, methodConsumes, classConsumes, operationParameters, paramAnnotations[i], type, jsonViewAnnotationForRequestBody, null);
                        }
                    }
                } else {
                    for (int i = 0; i < annotatedMethod.getParameterCount(); i++) {
                        AnnotatedParameter param = annotatedMethod.getParameter(i);
                        final Type type = TypeFactory.defaultInstance().constructType(param.getParameterType(), cls);
                        io.swagger.v3.oas.annotations.Parameter paramAnnotation = AnnotationsUtils.getAnnotation(io.swagger.v3.oas.annotations.Parameter.class, paramAnnotations[i]);
                        Type paramType = ParameterProcessor.getParameterType(paramAnnotation, true);
                        if (paramType == null) {
                            paramType = type;
                        } else {
                            if (!(paramType instanceof Class)) {
                                paramType = type;
                            }
                        }
                        ResolvedParameter resolvedParameter = getParameters(paramType, Arrays.asList(paramAnnotations[i]), operation, classConsumes, methodConsumes, jsonViewAnnotation);
                        operationParameters.addAll(resolvedParameter.parameters);
                        // collect params to use together as request Body
                        formParameters.addAll(resolvedParameter.formParameters);
                        if (resolvedParameter.requestBody != null) {
                            processRequestBody(resolvedParameter.requestBody, operation, methodConsumes, classConsumes, operationParameters, paramAnnotations[i], type, jsonViewAnnotationForRequestBody, null);
                        }
                    }
                }
                // if we have form parameters, need to merge them into single schema and use as request body..
                if (!formParameters.isEmpty()) {
                    Schema mergedSchema = new ObjectSchema();
                    Map<String, Encoding> encoding = new LinkedHashMap<>();
                    for (Parameter formParam : formParameters) {
                        if (formParam.getExplode() != null || (formParam.getStyle() != null) && Encoding.StyleEnum.fromString(formParam.getStyle().toString()) != null) {
                            Encoding e = new Encoding();
                            if (formParam.getExplode() != null) {
                                e.explode(formParam.getExplode());
                            }
                            if (formParam.getStyle() != null && Encoding.StyleEnum.fromString(formParam.getStyle().toString()) != null) {
                                e.style(Encoding.StyleEnum.fromString(formParam.getStyle().toString()));
                            }
                            encoding.put(formParam.getName(), e);
                        }
                        mergedSchema.addProperties(formParam.getName(), formParam.getSchema());
                        if (formParam.getSchema() != null && StringUtils.isNotBlank(formParam.getDescription()) && StringUtils.isBlank(formParam.getSchema().getDescription())) {
                            formParam.getSchema().description(formParam.getDescription());
                        }
                        if (null != formParam.getRequired() && formParam.getRequired()) {
                            mergedSchema.addRequiredItem(formParam.getName());
                        }
                    }
                    Parameter merged = new Parameter().schema(mergedSchema);
                    processRequestBody(merged, operation, methodConsumes, classConsumes, operationParameters, new Annotation[0], null, jsonViewAnnotationForRequestBody, encoding);
                }
                if (!operationParameters.isEmpty()) {
                    for (Parameter operationParameter : operationParameters) {
                        operation.addParametersItem(operationParameter);
                    }
                }
                // if subresource, merge parent parameters
                if (parentParameters != null) {
                    for (Parameter parentParameter : parentParameters) {
                        operation.addParametersItem(parentParameter);
                    }
                }
                if (subResource != null && !scannedResources.contains(subResource)) {
                    scannedResources.add(subResource);
                    read(subResource, operationPath, httpMethod, true, operation.getRequestBody(), operation.getResponses(), classTags, operation.getParameters(), scannedResources);
                    // remove the sub resource so that it can visit it later in another path
                    // but we have a room for optimization in the future to reuse the scanned result
                    // by caching the scanned resources in the reader instance to avoid actual scanning
                    // the the resources again
                    scannedResources.remove(subResource);
                    // don't proceed with root resource operation, as it's handled by subresource
                    continue;
                }
                final Iterator<OpenAPIExtension> chain = OpenAPIExtensions.chain();
                if (chain.hasNext()) {
                    final OpenAPIExtension extension = chain.next();
                    extension.decorateOperation(operation, method, chain);
                }
                PathItem pathItemObject;
                if (openAPI.getPaths() != null && openAPI.getPaths().get(operationPath) != null) {
                    pathItemObject = openAPI.getPaths().get(operationPath);
                } else {
                    pathItemObject = new PathItem();
                }
                if (StringUtils.isBlank(httpMethod)) {
                    continue;
                }
                setPathItemOperation(pathItemObject, httpMethod, operation);
                paths.addPathItem(operationPath, pathItemObject);
                if (openAPI.getPaths() != null) {
                    this.paths.putAll(openAPI.getPaths());
                }
                openAPI.setPaths(this.paths);
            }
        }
    }
    // if no components object is defined in openApi instance passed by client, set openAPI.components to resolved components (if not empty)
    if (!isEmptyComponents(components) && openAPI.getComponents() == null) {
        openAPI.setComponents(components);
    }
    // add tags from class to definition tags
    AnnotationsUtils.getTags(apiTags, true).ifPresent(tags -> openApiTags.addAll(tags));
    if (!openApiTags.isEmpty()) {
        Set<Tag> tagsSet = new LinkedHashSet<>();
        if (openAPI.getTags() != null) {
            for (Tag tag : openAPI.getTags()) {
                if (tagsSet.stream().noneMatch(t -> t.getName().equals(tag.getName()))) {
                    tagsSet.add(tag);
                }
            }
        }
        for (Tag tag : openApiTags) {
            if (tagsSet.stream().noneMatch(t -> t.getName().equals(tag.getName()))) {
                tagsSet.add(tag);
            }
        }
        openAPI.setTags(new ArrayList<>(tagsSet));
    }
    return openAPI;
}
Also used : LinkedHashSet(java.util.LinkedHashSet) Arrays(java.util.Arrays) JsonView(com.fasterxml.jackson.annotation.JsonView) OpenAPIExtensions(io.swagger.v3.jaxrs2.ext.OpenAPIExtensions) Produces(javax.ws.rs.Produces) ResolvedSchema(io.swagger.v3.core.converter.ResolvedSchema) Parameter(io.swagger.v3.oas.models.parameters.Parameter) LoggerFactory(org.slf4j.LoggerFactory) OpenAPIConfiguration(io.swagger.v3.oas.integration.api.OpenAPIConfiguration) SecurityRequirement(io.swagger.v3.oas.models.security.SecurityRequirement) Operation(io.swagger.v3.oas.models.Operation) Application(javax.ws.rs.core.Application) StringUtils(org.apache.commons.lang3.StringUtils) AnnotationsUtils(io.swagger.v3.core.util.AnnotationsUtils) PathUtils(io.swagger.v3.core.util.PathUtils) Consumes(javax.ws.rs.Consumes) TypeFactory(com.fasterxml.jackson.databind.type.TypeFactory) Map(java.util.Map) OpenApiReader(io.swagger.v3.oas.integration.api.OpenApiReader) BeanDescription(com.fasterxml.jackson.databind.BeanDescription) Tag(io.swagger.v3.oas.models.tags.Tag) Method(java.lang.reflect.Method) ApiResponse(io.swagger.v3.oas.models.responses.ApiResponse) SecurityScheme(io.swagger.v3.oas.models.security.SecurityScheme) Content(io.swagger.v3.oas.models.media.Content) Hidden(io.swagger.v3.oas.annotations.Hidden) MediaType(io.swagger.v3.oas.models.media.MediaType) Set(java.util.Set) RequestBody(io.swagger.v3.oas.models.parameters.RequestBody) ReaderUtils(io.swagger.v3.jaxrs2.util.ReaderUtils) Paths(io.swagger.v3.oas.models.Paths) Collectors(java.util.stream.Collectors) AnnotatedType(io.swagger.v3.core.converter.AnnotatedType) OpenAPIExtension(io.swagger.v3.jaxrs2.ext.OpenAPIExtension) ModelConverters(io.swagger.v3.core.converter.ModelConverters) List(java.util.List) OpenAPIDefinition(io.swagger.v3.oas.annotations.OpenAPIDefinition) Type(java.lang.reflect.Type) Annotation(java.lang.annotation.Annotation) Server(io.swagger.v3.oas.annotations.servers.Server) Optional(java.util.Optional) ObjectSchema(io.swagger.v3.oas.models.media.ObjectSchema) Json(io.swagger.v3.core.util.Json) ExternalDocumentation(io.swagger.v3.oas.annotations.ExternalDocumentation) HashMap(java.util.HashMap) TreeSet(java.util.TreeSet) ParameterProcessor(io.swagger.v3.core.util.ParameterProcessor) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Schema(io.swagger.v3.oas.models.media.Schema) JavaType(com.fasterxml.jackson.databind.JavaType) AnnotatedMethod(com.fasterxml.jackson.databind.introspect.AnnotatedMethod) LinkedHashSet(java.util.LinkedHashSet) ApiResponses(io.swagger.v3.oas.models.responses.ApiResponses) Logger(org.slf4j.Logger) AnnotatedParameter(com.fasterxml.jackson.databind.introspect.AnnotatedParameter) Iterator(java.util.Iterator) PathItem(io.swagger.v3.oas.models.PathItem) ApplicationPath(javax.ws.rs.ApplicationPath) ContextUtils(io.swagger.v3.oas.integration.ContextUtils) Callback(io.swagger.v3.oas.models.callbacks.Callback) SwaggerConfiguration(io.swagger.v3.oas.integration.SwaggerConfiguration) ReflectionUtils(io.swagger.v3.core.util.ReflectionUtils) ParameterizedType(java.lang.reflect.ParameterizedType) Components(io.swagger.v3.oas.models.Components) Encoding(io.swagger.v3.oas.models.media.Encoding) Comparator(java.util.Comparator) Collections(java.util.Collections) Server(io.swagger.v3.oas.annotations.servers.Server) Produces(javax.ws.rs.Produces) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ResolvedSchema(io.swagger.v3.core.converter.ResolvedSchema) ObjectSchema(io.swagger.v3.oas.models.media.ObjectSchema) Schema(io.swagger.v3.oas.models.media.Schema) ArrayList(java.util.ArrayList) OpenAPIExtension(io.swagger.v3.jaxrs2.ext.OpenAPIExtension) ApiResponse(io.swagger.v3.oas.models.responses.ApiResponse) LinkedHashMap(java.util.LinkedHashMap) PathItem(io.swagger.v3.oas.models.PathItem) ExternalDocumentation(io.swagger.v3.oas.annotations.ExternalDocumentation) Consumes(javax.ws.rs.Consumes) ObjectSchema(io.swagger.v3.oas.models.media.ObjectSchema) Hidden(io.swagger.v3.oas.annotations.Hidden) List(java.util.List) ArrayList(java.util.ArrayList) SecurityScheme(io.swagger.v3.oas.models.security.SecurityScheme) BeanDescription(com.fasterxml.jackson.databind.BeanDescription) Encoding(io.swagger.v3.oas.models.media.Encoding) Method(java.lang.reflect.Method) AnnotatedMethod(com.fasterxml.jackson.databind.introspect.AnnotatedMethod) JavaType(com.fasterxml.jackson.databind.JavaType) OpenAPIDefinition(io.swagger.v3.oas.annotations.OpenAPIDefinition) Collectors(java.util.stream.Collectors) ModelConverters(io.swagger.v3.core.converter.ModelConverters) AnnotatedMethod(com.fasterxml.jackson.databind.introspect.AnnotatedMethod) AnnotatedParameter(com.fasterxml.jackson.databind.introspect.AnnotatedParameter) Operation(io.swagger.v3.oas.models.Operation) JsonView(com.fasterxml.jackson.annotation.JsonView) MediaType(io.swagger.v3.oas.models.media.MediaType) AnnotatedType(io.swagger.v3.core.converter.AnnotatedType) Type(java.lang.reflect.Type) JavaType(com.fasterxml.jackson.databind.JavaType) ParameterizedType(java.lang.reflect.ParameterizedType) Parameter(io.swagger.v3.oas.models.parameters.Parameter) AnnotatedParameter(com.fasterxml.jackson.databind.introspect.AnnotatedParameter) Tag(io.swagger.v3.oas.models.tags.Tag) SecurityRequirement(io.swagger.v3.oas.models.security.SecurityRequirement)

Example 4 with ResolvedParameter

use of io.swagger.v3.jaxrs2.ResolvedParameter in project swagger-core by swagger-api.

the class Reader method getParameters.

protected ResolvedParameter getParameters(Type type, List<Annotation> annotations, Operation operation, javax.ws.rs.Consumes classConsumes, javax.ws.rs.Consumes methodConsumes, JsonView jsonViewAnnotation) {
    final Iterator<OpenAPIExtension> chain = OpenAPIExtensions.chain();
    if (!chain.hasNext()) {
        return new ResolvedParameter();
    }
    LOGGER.debug("getParameters for {}", type);
    Set<Type> typesToSkip = new HashSet<>();
    final OpenAPIExtension extension = chain.next();
    LOGGER.debug("trying extension {}", extension);
    return extension.extractParameters(annotations, type, typesToSkip, components, classConsumes, methodConsumes, true, jsonViewAnnotation, chain);
}
Also used : MediaType(io.swagger.v3.oas.models.media.MediaType) AnnotatedType(io.swagger.v3.core.converter.AnnotatedType) Type(java.lang.reflect.Type) JavaType(com.fasterxml.jackson.databind.JavaType) ParameterizedType(java.lang.reflect.ParameterizedType) OpenAPIExtension(io.swagger.v3.jaxrs2.ext.OpenAPIExtension) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 5 with ResolvedParameter

use of io.swagger.v3.jaxrs2.ResolvedParameter in project swagger-core by swagger-api.

the class DefaultParameterExtension method handleAdditionalAnnotation.

/**
 * Adds additional annotation processing support
 *
 * @param parameters
 * @param annotation
 * @param type
 * @param typesToSkip
 */
private boolean handleAdditionalAnnotation(List<Parameter> parameters, List<Parameter> formParameters, Annotation annotation, final Type type, Set<Type> typesToSkip, javax.ws.rs.Consumes classConsumes, javax.ws.rs.Consumes methodConsumes, Components components, boolean includeRequestBody, JsonView jsonViewAnnotation) {
    boolean processed = false;
    if (BeanParam.class.isAssignableFrom(annotation.getClass())) {
        // Use Jackson's logic for processing Beans
        final BeanDescription beanDesc = mapper.getSerializationConfig().introspect(constructType(type));
        final List<BeanPropertyDefinition> properties = beanDesc.findProperties();
        for (final BeanPropertyDefinition propDef : properties) {
            final AnnotatedField field = propDef.getField();
            final AnnotatedMethod setter = propDef.getSetter();
            final AnnotatedMethod getter = propDef.getGetter();
            final List<Annotation> paramAnnotations = new ArrayList<>();
            final Iterator<OpenAPIExtension> extensions = OpenAPIExtensions.chain();
            Type paramType = null;
            // Gather the field's details
            if (field != null) {
                paramType = field.getType();
                AnnotationMap annotationMap = field.getAllAnnotations();
                if (annotationMap != null) {
                    for (final Annotation fieldAnnotation : annotationMap.annotations()) {
                        if (!paramAnnotations.contains(fieldAnnotation)) {
                            paramAnnotations.add(fieldAnnotation);
                        }
                    }
                }
            }
            // Gather the setter's details but only the ones we need
            if (setter != null) {
                // Do not set the param class/type from the setter if the values are already identified
                if (paramType == null) {
                    // paramType will stay null if there is no parameter
                    paramType = setter.getParameterType(0);
                }
                AnnotationMap annotationMap = setter.getAllAnnotations();
                if (annotationMap != null) {
                    for (final Annotation fieldAnnotation : annotationMap.annotations()) {
                        if (!paramAnnotations.contains(fieldAnnotation)) {
                            paramAnnotations.add(fieldAnnotation);
                        }
                    }
                }
            }
            // Gather the getter's details but only the ones we need
            if (getter != null) {
                // Do not set the param class/type from the getter if the values are already identified
                if (paramType == null) {
                    paramType = getter.getType();
                }
                AnnotationMap annotationMap = getter.getAllAnnotations();
                if (annotationMap != null) {
                    for (final Annotation fieldAnnotation : annotationMap.annotations()) {
                        if (!paramAnnotations.contains(fieldAnnotation)) {
                            paramAnnotations.add(fieldAnnotation);
                        }
                    }
                }
            }
            if (paramType == null) {
                continue;
            }
            // skip hidden properties
            boolean hidden = false;
            for (Annotation a : paramAnnotations) {
                if (a instanceof io.swagger.v3.oas.annotations.media.Schema) {
                    if (((io.swagger.v3.oas.annotations.media.Schema) a).hidden()) {
                        hidden = true;
                        break;
                    }
                    ;
                } else if (a instanceof Hidden) {
                    hidden = true;
                    break;
                }
            }
            if (hidden) {
                continue;
            }
            // Re-process all Bean fields and let the default swagger-jaxrs/swagger-jersey-jaxrs processors do their thing
            ResolvedParameter resolvedParameter = extensions.next().extractParameters(paramAnnotations, paramType, typesToSkip, components, classConsumes, methodConsumes, includeRequestBody, jsonViewAnnotation, extensions);
            List<Parameter> extractedParameters = resolvedParameter.parameters;
            for (Parameter p : extractedParameters) {
                Parameter processedParam = ParameterProcessor.applyAnnotations(p, paramType, paramAnnotations, components, classConsumes == null ? new String[0] : classConsumes.value(), methodConsumes == null ? new String[0] : methodConsumes.value(), jsonViewAnnotation);
                if (processedParam != null) {
                    parameters.add(processedParam);
                }
            }
            List<Parameter> extractedFormParameters = resolvedParameter.formParameters;
            for (Parameter p : extractedFormParameters) {
                Parameter processedParam = ParameterProcessor.applyAnnotations(p, paramType, paramAnnotations, components, classConsumes == null ? new String[0] : classConsumes.value(), methodConsumes == null ? new String[0] : methodConsumes.value(), jsonViewAnnotation);
                if (processedParam != null) {
                    formParameters.add(processedParam);
                }
            }
            processed = true;
        }
    }
    return processed;
}
Also used : AnnotatedMethod(com.fasterxml.jackson.databind.introspect.AnnotatedMethod) BeanDescription(com.fasterxml.jackson.databind.BeanDescription) ArrayList(java.util.ArrayList) AbstractOpenAPIExtension(io.swagger.v3.jaxrs2.ext.AbstractOpenAPIExtension) OpenAPIExtension(io.swagger.v3.jaxrs2.ext.OpenAPIExtension) Annotation(java.lang.annotation.Annotation) Type(java.lang.reflect.Type) AnnotationMap(com.fasterxml.jackson.databind.introspect.AnnotationMap) BeanPropertyDefinition(com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition) Hidden(io.swagger.v3.oas.annotations.Hidden) Parameter(io.swagger.v3.oas.models.parameters.Parameter) AnnotatedField(com.fasterxml.jackson.databind.introspect.AnnotatedField)

Aggregations

OpenAPIExtension (io.swagger.v3.jaxrs2.ext.OpenAPIExtension)4 Parameter (io.swagger.v3.oas.models.parameters.Parameter)4 Annotation (java.lang.annotation.Annotation)4 Type (java.lang.reflect.Type)4 ArrayList (java.util.ArrayList)3 List (java.util.List)3 JsonView (com.fasterxml.jackson.annotation.JsonView)2 BeanDescription (com.fasterxml.jackson.databind.BeanDescription)2 JavaType (com.fasterxml.jackson.databind.JavaType)2 AnnotatedMethod (com.fasterxml.jackson.databind.introspect.AnnotatedMethod)2 AnnotatedType (io.swagger.v3.core.converter.AnnotatedType)2 ModelConverters (io.swagger.v3.core.converter.ModelConverters)2 ResolvedSchema (io.swagger.v3.core.converter.ResolvedSchema)2 AbstractOpenAPIExtension (io.swagger.v3.jaxrs2.ext.AbstractOpenAPIExtension)2 Hidden (io.swagger.v3.oas.annotations.Hidden)2 Components (io.swagger.v3.oas.models.Components)2 MediaType (io.swagger.v3.oas.models.media.MediaType)2 Schema (io.swagger.v3.oas.models.media.Schema)2 ParameterizedType (java.lang.reflect.ParameterizedType)2 HashMap (java.util.HashMap)2