Search in sources :

Example 1 with Example

use of io.swagger.v3.oas.models.examples.Example in project swagger-core by swagger-api.

the class ParameterProcessor method applyAnnotations.

public static Parameter applyAnnotations(Parameter parameter, Type type, List<Annotation> annotations, Components components, String[] classTypes, String[] methodTypes, JsonView jsonViewAnnotation) {
    final AnnotationsHelper helper = new AnnotationsHelper(annotations, type);
    if (helper.isContext()) {
        return null;
    }
    if (parameter == null) {
        // consider it to be body param
        parameter = new Parameter();
    }
    // first handle schema
    List<Annotation> reworkedAnnotations = new ArrayList<>(annotations);
    Annotation paramSchemaOrArrayAnnotation = getParamSchemaAnnotation(annotations);
    if (paramSchemaOrArrayAnnotation != null) {
        reworkedAnnotations.add(paramSchemaOrArrayAnnotation);
    }
    AnnotatedType annotatedType = new AnnotatedType().type(type).resolveAsRef(true).skipOverride(true).jsonViewAnnotation(jsonViewAnnotation).ctxAnnotations(reworkedAnnotations.toArray(new Annotation[reworkedAnnotations.size()]));
    ResolvedSchema resolvedSchema = ModelConverters.getInstance().resolveAsResolvedSchema(annotatedType);
    if (resolvedSchema.schema != null) {
        parameter.setSchema(resolvedSchema.schema);
    }
    resolvedSchema.referencedSchemas.forEach(components::addSchemas);
    // handle first FormParam as it affects Explode resolving
    for (Annotation annotation : annotations) {
        if (annotation.annotationType().getName().equals("javax.ws.rs.FormParam")) {
            try {
                String name = (String) annotation.annotationType().getMethod("value").invoke(annotation);
                if (StringUtils.isNotBlank(name)) {
                    parameter.setName(name);
                }
            } catch (Exception e) {
            }
            // set temporarily to "form" to inform caller that we need to further process along other form parameters
            parameter.setIn("form");
        } else if (annotation.annotationType().getName().endsWith("FormDataParam")) {
            try {
                String name = (String) annotation.annotationType().getMethod("value").invoke(annotation);
                if (StringUtils.isNotBlank(name)) {
                    parameter.setName(name);
                }
            } catch (Exception e) {
            }
            // set temporarily to "form" to inform caller that we need to further process along other form parameters
            parameter.setIn("form");
        }
    }
    for (Annotation annotation : annotations) {
        if (annotation instanceof io.swagger.v3.oas.annotations.Parameter) {
            io.swagger.v3.oas.annotations.Parameter p = (io.swagger.v3.oas.annotations.Parameter) annotation;
            if (p.hidden()) {
                return null;
            }
            if (StringUtils.isNotBlank(p.ref())) {
                parameter = new Parameter().$ref(p.ref());
                return parameter;
            }
            if (StringUtils.isNotBlank(p.description())) {
                parameter.setDescription(p.description());
            }
            if (StringUtils.isNotBlank(p.name())) {
                parameter.setName(p.name());
            }
            if (StringUtils.isNotBlank(p.in().toString())) {
                parameter.setIn(p.in().toString());
            }
            if (StringUtils.isNotBlank(p.example())) {
                try {
                    parameter.setExample(Json.mapper().readTree(p.example()));
                } catch (IOException e) {
                    parameter.setExample(p.example());
                }
            }
            if (p.deprecated()) {
                parameter.setDeprecated(p.deprecated());
            }
            if (p.required()) {
                parameter.setRequired(p.required());
            }
            if (p.allowEmptyValue()) {
                parameter.setAllowEmptyValue(p.allowEmptyValue());
            }
            if (p.allowReserved()) {
                parameter.setAllowReserved(p.allowReserved());
            }
            Map<String, Example> exampleMap = new LinkedHashMap<>();
            if (p.examples().length == 1 && StringUtils.isBlank(p.examples()[0].name())) {
                Optional<Example> exampleOptional = AnnotationsUtils.getExample(p.examples()[0], true);
                if (exampleOptional.isPresent()) {
                    parameter.setExample(exampleOptional.get());
                }
            } else {
                for (ExampleObject exampleObject : p.examples()) {
                    AnnotationsUtils.getExample(exampleObject).ifPresent(example -> exampleMap.put(exampleObject.name(), example));
                }
            }
            if (exampleMap.size() > 0) {
                parameter.setExamples(exampleMap);
            }
            if (p.extensions().length > 0) {
                Map<String, Object> extensionMap = AnnotationsUtils.getExtensions(p.extensions());
                if (extensionMap != null && !extensionMap.isEmpty()) {
                    extensionMap.forEach(parameter::addExtension);
                }
            }
            Optional<Content> content = AnnotationsUtils.getContent(p.content(), classTypes, methodTypes, parameter.getSchema(), null, jsonViewAnnotation);
            if (content.isPresent()) {
                parameter.setContent(content.get());
                parameter.setSchema(null);
            }
            setParameterStyle(parameter, p);
            setParameterExplode(parameter, p);
        } else if (annotation.annotationType().getName().equals("javax.ws.rs.PathParam")) {
            try {
                String name = (String) annotation.annotationType().getMethod("value").invoke(annotation);
                if (StringUtils.isNotBlank(name)) {
                    parameter.setName(name);
                }
            } catch (Exception e) {
            }
        } else if (annotation.annotationType().getName().equals("javax.validation.constraints.Size")) {
            try {
                if (parameter.getSchema() == null) {
                    parameter.setSchema(new ArraySchema());
                }
                if (parameter.getSchema() instanceof ArraySchema) {
                    ArraySchema as = (ArraySchema) parameter.getSchema();
                    Integer min = (Integer) annotation.annotationType().getMethod("min").invoke(annotation);
                    if (min != null) {
                        as.setMinItems(min);
                    }
                    Integer max = (Integer) annotation.annotationType().getMethod("max").invoke(annotation);
                    if (max != null) {
                        as.setMaxItems(max);
                    }
                }
            } catch (Exception e) {
                LOGGER.error("failed on " + annotation.annotationType().getName(), e);
            }
        } else if (ModelResolver.NOT_NULL_ANNOTATIONS.contains(annotation.annotationType().getSimpleName())) {
            parameter.setRequired(true);
        }
    }
    final String defaultValue = helper.getDefaultValue();
    Schema paramSchema = parameter.getSchema();
    if (paramSchema == null) {
        if (parameter.getContent() != null && !parameter.getContent().values().isEmpty()) {
            paramSchema = parameter.getContent().values().iterator().next().getSchema();
        }
    }
    if (paramSchema != null) {
        if (paramSchema instanceof ArraySchema) {
            ArraySchema as = (ArraySchema) paramSchema;
            if (defaultValue != null) {
                as.getItems().setDefault(defaultValue);
            }
        } else {
            if (defaultValue != null) {
                paramSchema.setDefault(defaultValue);
            }
        }
    }
    return parameter;
}
Also used : ExampleObject(io.swagger.v3.oas.annotations.media.ExampleObject) ResolvedSchema(io.swagger.v3.core.converter.ResolvedSchema) ArraySchema(io.swagger.v3.oas.models.media.ArraySchema) Schema(io.swagger.v3.oas.models.media.Schema) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) ArraySchema(io.swagger.v3.oas.models.media.ArraySchema) Example(io.swagger.v3.oas.models.examples.Example) ResolvedSchema(io.swagger.v3.core.converter.ResolvedSchema) IOException(java.io.IOException) Annotation(java.lang.annotation.Annotation) IOException(java.io.IOException) AnnotatedType(io.swagger.v3.core.converter.AnnotatedType) Content(io.swagger.v3.oas.models.media.Content) Parameter(io.swagger.v3.oas.models.parameters.Parameter) ExampleObject(io.swagger.v3.oas.annotations.media.ExampleObject)

Example 2 with Example

use of io.swagger.v3.oas.models.examples.Example in project swagger-core by swagger-api.

the class MapPropertyDeserializerTest method testIssue1261InlineSchemaExample.

@Test(description = "it should read an example within an inlined schema")
public void testIssue1261InlineSchemaExample() throws Exception {
    Operation operation = Yaml.mapper().readValue("      responses:\n" + "        \"200\":\n" + "          content:\n" + "            '*/*':\n" + "              description: OK\n" + "              schema:\n" + "                type: object\n" + "                properties:\n" + "                  id:\n" + "                    type: integer\n" + "                    format: int32\n" + "                  name:\n" + "                    type: string\n" + "                required: [id, name]\n" + "                example: ok", Operation.class);
    ApiResponse response = operation.getResponses().get("200");
    assertNotNull(response);
    Schema schema = response.getContent().get("*/*").getSchema();
    Object example = schema.getExample();
    assertNotNull(example);
    assertTrue(example instanceof String);
    assertEquals(example, "ok");
}
Also used : MapSchema(io.swagger.v3.oas.models.media.MapSchema) IntegerSchema(io.swagger.v3.oas.models.media.IntegerSchema) ObjectSchema(io.swagger.v3.oas.models.media.ObjectSchema) Schema(io.swagger.v3.oas.models.media.Schema) Operation(io.swagger.v3.oas.models.Operation) ApiResponse(io.swagger.v3.oas.models.responses.ApiResponse) Test(org.testng.annotations.Test)

Example 3 with Example

use of io.swagger.v3.oas.models.examples.Example in project swagger-core by swagger-api.

the class JsonDeserializationTest method testNullExampleDeserialization.

@Test
public void testNullExampleDeserialization() throws Exception {
    String yamlNull = "openapi: 3.0.1\n" + "paths:\n" + "  /:\n" + "    get:\n" + "      description: Operation Description\n" + "      operationId: operationId\n" + "components:\n" + "  schemas:\n" + "    UserStatus:\n" + "      type: string\n" + "      example: null\n";
    String yamlMissing = "openapi: 3.0.1\n" + "paths:\n" + "  /:\n" + "    get:\n" + "      description: Operation Description\n" + "      operationId: operationId\n" + "components:\n" + "  schemas:\n" + "    UserStatus:\n" + "      type: string\n";
    OpenAPI oas = Yaml.mapper().readValue(yamlNull, OpenAPI.class);
    Yaml.prettyPrint(oas);
    assertNull(oas.getComponents().getSchemas().get("UserStatus").getExample());
    assertTrue(oas.getComponents().getSchemas().get("UserStatus").getExampleSetFlag());
    oas = Yaml.mapper().readValue(yamlMissing, OpenAPI.class);
    Yaml.prettyPrint(oas);
    assertNull(oas.getComponents().getSchemas().get("UserStatus").getExample());
    assertFalse(oas.getComponents().getSchemas().get("UserStatus").getExampleSetFlag());
    Yaml.prettyPrint(oas);
}
Also used : OpenAPI(io.swagger.v3.oas.models.OpenAPI) Test(org.testng.annotations.Test)

Example 4 with Example

use of io.swagger.v3.oas.models.examples.Example in project swagger-core by swagger-api.

the class SwaggerSerializerTest method convertSpec.

@Test(description = "it should convert a spec")
public void convertSpec() throws IOException {
    final Schema personModel = ModelConverters.getInstance().read(Person.class).get("Person");
    final Schema errorModel = ModelConverters.getInstance().read(Error.class).get("Error");
    final Info info = new Info().version("1.0.0").title("Swagger Petstore");
    final Contact contact = new Contact().name("Swagger API Team").email("foo@bar.baz").url("http://swagger.io");
    info.setContact(contact);
    final Map<String, Object> map = new HashMap<String, Object>();
    map.put("name", "value");
    info.addExtension("x-test2", map);
    info.addExtension("x-test", "value");
    final OpenAPI swagger = new OpenAPI().info(info).addServersItem(new Server().url("http://petstore.swagger.io")).schema("Person", personModel).schema("Error", errorModel);
    final Operation get = new Operation().summary("finds pets in the system").description("a longer description").addTagsItem("Pet Operations").operationId("get pet by id").deprecated(true);
    get.addParametersItem(new Parameter().in("query").name("tags").description("tags to filter by").required(false).schema(new StringSchema()));
    get.addParametersItem(new Parameter().in("path").name("petId").description("pet to fetch").schema(new IntegerSchema().format("int64")));
    final ApiResponse response = new ApiResponse().description("pets returned").content(new Content().addMediaType("application/json", new MediaType().schema(new Schema().$ref("Person")).example("fun")));
    final ApiResponse errorResponse = new ApiResponse().description("error response").addLink("myLink", new Link().description("a link").operationId("theLinkedOperationId").addParameter("userId", "gah")).content(new Content().addMediaType("application/json", new MediaType().schema(new Schema().$ref("Error"))));
    get.responses(new ApiResponses().addApiResponse("200", response).addApiResponse("default", errorResponse));
    final Operation post = new Operation().summary("adds a new pet").description("you can add a new pet this way").addTagsItem("Pet Operations").operationId("add pet").responses(new ApiResponses().addApiResponse("default", errorResponse)).requestBody(new RequestBody().description("the pet to add").content(new Content().addMediaType("*/*", new MediaType().schema(new Schema().$ref("Person")))));
    swagger.paths(new Paths().addPathItem("/pets", new PathItem().get(get).post(post)));
    final String swaggerJson = Json.mapper().writeValueAsString(swagger);
    Json.prettyPrint(swagger);
    final OpenAPI rebuilt = Json.mapper().readValue(swaggerJson, OpenAPI.class);
    SerializationMatchers.assertEqualsToJson(rebuilt, swaggerJson);
}
Also used : Server(io.swagger.v3.oas.models.servers.Server) HashMap(java.util.HashMap) Schema(io.swagger.v3.oas.models.media.Schema) IntegerSchema(io.swagger.v3.oas.models.media.IntegerSchema) StringSchema(io.swagger.v3.oas.models.media.StringSchema) IntegerSchema(io.swagger.v3.oas.models.media.IntegerSchema) Operation(io.swagger.v3.oas.models.Operation) Info(io.swagger.v3.oas.models.info.Info) ApiResponse(io.swagger.v3.oas.models.responses.ApiResponse) Contact(io.swagger.v3.oas.models.info.Contact) PathItem(io.swagger.v3.oas.models.PathItem) Content(io.swagger.v3.oas.models.media.Content) Parameter(io.swagger.v3.oas.models.parameters.Parameter) QueryParameter(io.swagger.v3.oas.models.parameters.QueryParameter) MediaType(io.swagger.v3.oas.models.media.MediaType) StringSchema(io.swagger.v3.oas.models.media.StringSchema) Paths(io.swagger.v3.oas.models.Paths) Person(io.swagger.v3.core.oas.models.Person) OpenAPI(io.swagger.v3.oas.models.OpenAPI) Link(io.swagger.v3.oas.models.links.Link) ApiResponses(io.swagger.v3.oas.models.responses.ApiResponses) RequestBody(io.swagger.v3.oas.models.parameters.RequestBody) Test(org.testng.annotations.Test)

Example 5 with Example

use of io.swagger.v3.oas.models.examples.Example in project swagger-core by swagger-api.

the class OpenAPI3_1DeserializationTest method testRefDeserializationOnOAS31.

@Test
public void testRefDeserializationOnOAS31() throws IOException {
    final String jsonString = ResourceUtils.loadClassResource(getClass(), "specFiles/3.1.0/petstore-3.1_refs_siblings.yaml");
    OpenAPI openAPI = Yaml31.mapper().readValue(jsonString, OpenAPI.class);
    assertEquals(openAPI.getPaths().get("/ref_pet").get$ref(), "#/components/pathItems/pet");
    assertEquals(openAPI.getPaths().get("/ref_pet").getDescription(), "ref pathItem description");
    assertEquals(openAPI.getPaths().get("/ref_pet").getSummary(), "ref pathItem summary");
    assertEquals(openAPI.getPaths().get("/pets").getPost().getParameters().get(0).get$ref(), "#/components/parameters/testParameter");
    assertEquals(openAPI.getPaths().get("/pets").getPost().getParameters().get(0).getDescription(), "ref parameter description");
    assertEquals(openAPI.getPaths().get("/pets").getPost().getParameters().get(1).getName(), "randomParam");
    assertEquals(openAPI.getPaths().get("/pets").getPost().getParameters().get(1).getIn(), "query");
    assertEquals(openAPI.getPaths().get("/pets").getPost().getParameters().get(1).getExamples().get("refExample").get$ref(), "#/components/examples/testExample");
    assertEquals(openAPI.getPaths().get("/pets").getPost().getParameters().get(1).getExamples().get("refExample").getDescription(), "ref example description");
    assertEquals(openAPI.getPaths().get("/pets").getPost().getParameters().get(1).getExamples().get("refExample").getSummary(), "ref example summary");
    assertEquals(openAPI.getPaths().get("/pets").getPost().getCallbacks().get("callIt").get$ref(), "#/components/callbacks/TestCallback");
    assertEquals(openAPI.getPaths().get("/pets").getPost().getRequestBody().get$ref(), "#/components/requestBodies/body");
    assertEquals(openAPI.getPaths().get("/pets").getPost().getRequestBody().getDescription(), "ref request body description");
    assertEquals(openAPI.getPaths().get("/pets").getPost().getResponses().get("201").get$ref(), "#/components/responses/okResponse");
    assertEquals(openAPI.getPaths().get("/pets").getPost().getResponses().get("201").getDescription(), "ref response description");
    assertEquals(openAPI.getPaths().get("/pets").getPost().getResponses().get("default").getHeaders().get("head").get$ref(), "#/components/headers/head");
    assertEquals(openAPI.getPaths().get("/pets").getPost().getResponses().get("default").getHeaders().get("head").getDescription(), "ref header description");
}
Also used : OpenAPI(io.swagger.v3.oas.models.OpenAPI) Test(org.testng.annotations.Test)

Aggregations

Test (org.testng.annotations.Test)28 OpenAPI (io.swagger.v3.oas.models.OpenAPI)20 Schema (io.swagger.v3.oas.models.media.Schema)12 Components (io.swagger.v3.oas.models.Components)9 IntegerSchema (io.swagger.v3.oas.models.media.IntegerSchema)9 Info (io.swagger.v3.oas.models.info.Info)8 StringSchema (io.swagger.v3.oas.models.media.StringSchema)7 Example (io.swagger.v3.oas.models.examples.Example)6 Content (io.swagger.v3.oas.models.media.Content)6 MediaType (io.swagger.v3.oas.models.media.MediaType)6 Parameter (io.swagger.v3.oas.models.parameters.Parameter)6 ApiResponse (io.swagger.v3.oas.models.responses.ApiResponse)6 Operation (io.swagger.v3.oas.models.Operation)5 ObjectSchema (io.swagger.v3.oas.models.media.ObjectSchema)5 ArraySchema (io.swagger.v3.oas.models.media.ArraySchema)4 AnnotatedType (io.swagger.v3.core.converter.AnnotatedType)3 ExampleObject (io.swagger.v3.oas.annotations.media.ExampleObject)3 PathItem (io.swagger.v3.oas.models.PathItem)3 Link (io.swagger.v3.oas.models.links.Link)3 ApiResponses (io.swagger.v3.oas.models.responses.ApiResponses)3