Search in sources :

Example 71 with Parameter

use of io.swagger.v3.oas.models.parameters.Parameter in project swagger-core by swagger-api.

the class OpenAPI3_1SerializationTest method testParameterRefSerialization.

@Test
public void testParameterRefSerialization() {
    OpenAPI openAPI = new OpenAPI().openapi("3.1.0").components(new Components().addParameters("testParameter", new Parameter().in("query"))).path("/test", new PathItem().description("test path item").get(new Operation().operationId("testPathItem").addParametersItem(new Parameter().$ref("#/components/parameters/testParameter").description("test parameter"))));
    SerializationMatchers.assertEqualsToYaml31(openAPI, "openapi: 3.1.0\n" + "paths:\n" + "  /test:\n" + "    description: test path item\n" + "    get:\n" + "      operationId: testPathItem\n" + "      parameters:\n" + "      - description: test parameter\n" + "        $ref: '#/components/parameters/testParameter'\n" + "components:\n" + "  parameters:\n" + "    testParameter:\n" + "      in: query");
    SerializationMatchers.assertEqualsToJson31(openAPI, "{\n" + "  \"openapi\" : \"3.1.0\",\n" + "  \"paths\" : {\n" + "    \"/test\" : {\n" + "      \"description\" : \"test path item\",\n" + "      \"get\" : {\n" + "        \"operationId\" : \"testPathItem\",\n" + "        \"parameters\" : [ {\n" + "          \"description\" : \"test parameter\",\n" + "          \"$ref\" : \"#/components/parameters/testParameter\"\n" + "        } ]\n" + "      }\n" + "    }\n" + "  },\n" + "  \"components\" : {\n" + "    \"parameters\" : {\n" + "      \"testParameter\" : {\n" + "        \"in\" : \"query\"\n" + "      }\n" + "    }\n" + "  }\n" + "}");
}
Also used : Components(io.swagger.v3.oas.models.Components) PathItem(io.swagger.v3.oas.models.PathItem) Parameter(io.swagger.v3.oas.models.parameters.Parameter) Operation(io.swagger.v3.oas.models.Operation) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Test(org.testng.annotations.Test)

Example 72 with Parameter

use of io.swagger.v3.oas.models.parameters.Parameter 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)

Example 73 with Parameter

use of io.swagger.v3.oas.models.parameters.Parameter in project swagger-core by swagger-api.

the class Reader method read.

/**
 * Scans a set of classes for both ReaderListeners and OpenAPI annotations. All found listeners will
 * be instantiated before any of the classes are scanned for OpenAPI annotations - so they can be invoked
 * accordingly.
 *
 * @param classes a set of classes to scan
 * @return the generated OpenAPI definition
 */
public OpenAPI read(Set<Class<?>> classes) {
    Set<Class<?>> sortedClasses = new TreeSet<>((class1, class2) -> {
        if (class1.equals(class2)) {
            return 0;
        } else if (class1.isAssignableFrom(class2)) {
            return -1;
        } else if (class2.isAssignableFrom(class1)) {
            return 1;
        }
        return class1.getName().compareTo(class2.getName());
    });
    sortedClasses.addAll(classes);
    Map<Class<?>, ReaderListener> listeners = new HashMap<>();
    String appPath = "";
    for (Class<?> cls : sortedClasses) {
        if (ReaderListener.class.isAssignableFrom(cls) && !listeners.containsKey(cls)) {
            try {
                listeners.put(cls, (ReaderListener) cls.newInstance());
            } catch (Exception e) {
                LOGGER.error("Failed to create ReaderListener", e);
            }
        }
        if (config != null && Boolean.TRUE.equals(config.isAlwaysResolveAppPath())) {
            if (Application.class.isAssignableFrom(cls)) {
                ApplicationPath appPathAnnotation = ReflectionUtils.getAnnotation(cls, ApplicationPath.class);
                if (appPathAnnotation != null) {
                    appPath = appPathAnnotation.value();
                }
            }
        }
    }
    for (ReaderListener listener : listeners.values()) {
        try {
            listener.beforeScan(this, openAPI);
        } catch (Exception e) {
            LOGGER.error("Unexpected error invoking beforeScan listener [" + listener.getClass().getName() + "]", e);
        }
    }
    String appPathRuntime = resolveApplicationPath();
    if (StringUtils.isNotBlank(appPathRuntime)) {
        appPath = appPathRuntime;
    }
    for (Class<?> cls : sortedClasses) {
        read(cls, appPath, null, false, null, null, new LinkedHashSet<String>(), new ArrayList<Parameter>(), new HashSet<Class<?>>());
    }
    for (ReaderListener listener : listeners.values()) {
        try {
            listener.afterScan(this, openAPI);
        } catch (Exception e) {
            LOGGER.error("Unexpected error invoking afterScan listener [" + listener.getClass().getName() + "]", e);
        }
    }
    return openAPI;
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ApplicationPath(javax.ws.rs.ApplicationPath) TreeSet(java.util.TreeSet) Parameter(io.swagger.v3.oas.models.parameters.Parameter) AnnotatedParameter(com.fasterxml.jackson.databind.introspect.AnnotatedParameter)

Example 74 with Parameter

use of io.swagger.v3.oas.models.parameters.Parameter in project swagger-core by swagger-api.

the class ReaderTest method testParameterExtensions.

@Test(description = "ParameterExtensions Tests")
public void testParameterExtensions() {
    Reader reader = new Reader(new OpenAPI());
    OpenAPI openAPI = reader.read(ParameterExtensionsResource.class);
    assertNotNull(openAPI);
    Map<String, Object> extensions = openAPI.getPaths().get("/").getGet().getParameters().get(0).getExtensions();
    assertNotNull(extensions);
    assertEquals(1, extensions.size());
    assertNotNull(extensions.get("x-parameter"));
}
Also used : OpenAPI(io.swagger.v3.oas.models.OpenAPI) Test(org.testng.annotations.Test)

Example 75 with Parameter

use of io.swagger.v3.oas.models.parameters.Parameter in project swagger-core by swagger-api.

the class ReaderTest method testTicket3029.

@Test(description = "Parameter with ref")
public void testTicket3029() {
    Components components = new Components();
    components.addParameters("id", new Parameter().description("Id Description").schema(new IntegerSchema()).in(ParameterIn.QUERY.toString()).example(1).required(true));
    OpenAPI oas = new OpenAPI().info(new Info().description("info")).components(components);
    Reader reader = new Reader(oas);
    OpenAPI openAPI = reader.read(RefParameter3029Resource.class);
    String yaml = "openapi: 3.0.1\n" + "info:\n" + "  description: info\n" + "paths:\n" + "  /2:\n" + "    get:\n" + "      summary: Simple get operation\n" + "      operationId: sendPayload2\n" + "      parameters:\n" + "      - $ref: '#/components/parameters/id'\n" + "      responses:\n" + "        default:\n" + "          description: default response\n" + "          content:\n" + "            '*/*': {}\n" + "  /1:\n" + "    get:\n" + "      summary: Simple get operation\n" + "      operationId: sendPayload1\n" + "      parameters:\n" + "      - $ref: '#/components/parameters/id'\n" + "      responses:\n" + "        default:\n" + "          description: default response\n" + "          content:\n" + "            '*/*': {}\n" + "components:\n" + "  parameters:\n" + "    id:\n" + "      in: query\n" + "      description: Id Description\n" + "      required: true\n" + "      schema:\n" + "        type: integer\n" + "        format: int32\n" + "      example: 1\n";
    SerializationMatchers.assertEqualsToYaml(openAPI, yaml);
}
Also used : Components(io.swagger.v3.oas.models.Components) IntegerSchema(io.swagger.v3.oas.models.media.IntegerSchema) Parameter(io.swagger.v3.oas.models.parameters.Parameter) Info(io.swagger.v3.oas.models.info.Info) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Test(org.testng.annotations.Test)

Aggregations

Parameter (io.swagger.v3.oas.models.parameters.Parameter)48 Test (org.testng.annotations.Test)39 Operation (io.swagger.v3.oas.models.Operation)28 Operation (io.swagger.v3.oas.annotations.Operation)27 lombok.val (lombok.val)26 OpenAPI (io.swagger.v3.oas.models.OpenAPI)20 Map (java.util.Map)17 ArrayList (java.util.ArrayList)16 ReadOperation (org.springframework.boot.actuate.endpoint.annotation.ReadOperation)15 OpenAPI3RequestValidationHandlerImpl (io.vertx.ext.web.api.contract.openapi3.impl.OpenAPI3RequestValidationHandlerImpl)14 Test (org.junit.Test)14 PathItem (io.swagger.v3.oas.models.PathItem)13 QueryParameter (io.swagger.v3.oas.models.parameters.QueryParameter)13 StringUtils (org.apache.commons.lang3.StringUtils)13 StringSchema (io.swagger.v3.oas.models.media.StringSchema)12 LinkedHashMap (java.util.LinkedHashMap)12 Parameter (io.swagger.v3.oas.annotations.Parameter)11 RequestParameters (io.vertx.ext.web.api.RequestParameters)11 HashMap (java.util.HashMap)11 Schema (io.swagger.v3.oas.models.media.Schema)10