Search in sources :

Example 1 with ArraySchema

use of io.swagger.v3.oas.models.media.ArraySchema 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 ArraySchema

use of io.swagger.v3.oas.models.media.ArraySchema in project swagger-core by swagger-api.

the class ModelConverterTest method serializeParameterizedType.

@Test(description = "it should serialize a parameterized type per 606")
public void serializeParameterizedType() {
    final Map<String, Schema> schemas = readAll(Employee.class);
    final Schema employee = (Schema) schemas.get("employee").getProperties().get("employee");
    final Map<String, Schema> props = employee.getProperties();
    final Iterator<String> et = props.keySet().iterator();
    final Schema id = props.get(et.next());
    assertTrue(id instanceof IntegerSchema);
    final Schema firstName = props.get(et.next());
    assertTrue(firstName instanceof StringSchema);
    final Schema lastName = props.get(et.next());
    assertTrue(lastName instanceof StringSchema);
    final Schema department = props.get(et.next());
    assertNotNull(department.get$ref());
    final Schema manager = props.get(et.next());
    assertNotNull(manager.get$ref());
    final Schema team = props.get(et.next());
    assertTrue(team instanceof ArraySchema);
    final ArraySchema ap = (ArraySchema) team;
    assertTrue(ap.getUniqueItems());
    assertNotNull(employee.getXml());
    assertEquals(employee.getXml().getName(), "employee");
}
Also used : ArraySchema(io.swagger.v3.oas.models.media.ArraySchema) IntegerSchema(io.swagger.v3.oas.models.media.IntegerSchema) StringSchema(io.swagger.v3.oas.models.media.StringSchema) ArraySchema(io.swagger.v3.oas.models.media.ArraySchema) NumberSchema(io.swagger.v3.oas.models.media.NumberSchema) Schema(io.swagger.v3.oas.models.media.Schema) MapSchema(io.swagger.v3.oas.models.media.MapSchema) IntegerSchema(io.swagger.v3.oas.models.media.IntegerSchema) StringSchema(io.swagger.v3.oas.models.media.StringSchema) Test(org.testng.annotations.Test)

Example 3 with ArraySchema

use of io.swagger.v3.oas.models.media.ArraySchema in project swagger-core by swagger-api.

the class ModelConverterTest method processModelWithPairProperties.

@Test(description = "it should process a model with org.apache.commons.lang3.tuple.Pair properties")
public void processModelWithPairProperties() {
    final ModelWithTuple2.TupleAsMapPropertyConverter asPropertyConverter = new ModelWithTuple2.TupleAsMapPropertyConverter(Json.mapper());
    ModelConverters.getInstance().addConverter(asPropertyConverter);
    final Map<String, Schema> asProperty = readAll(ModelWithTuple2.class);
    ModelConverters.getInstance().removeConverter(asPropertyConverter);
    // assertEquals(asProperty.size(), 2);
    Map<String, Schema> values = asProperty.get("ModelWithTuple2").getProperties();
    Yaml.prettyPrint(values);
    for (Map.Entry<String, Schema> entry : values.entrySet()) {
        String name = entry.getKey();
        Schema property = entry.getValue();
        if ("timesheetStates".equals(name)) {
            assertEquals(property.getClass(), MapSchema.class);
        } else if ("manyPairs".equals(name)) {
            assertEquals(property.getClass(), ArraySchema.class);
            Schema items = ((ArraySchema) property).getItems();
            assertNotNull(items);
            assertEquals(items.getClass(), MapSchema.class);
            Schema stringProperty = (Schema) ((MapSchema) items).getAdditionalProperties();
            assertNotNull(stringProperty);
            assertEquals(stringProperty.getClass(), StringSchema.class);
        } else if ("complexLeft".equals(name)) {
            assertEquals(property.getClass(), ArraySchema.class);
            Schema items = ((ArraySchema) property).getItems();
            assertNotNull(items);
            assertEquals(items.getClass(), MapSchema.class);
            Schema additionalProperty = (Schema) ((MapSchema) items).getAdditionalProperties();
            assertNotNull(additionalProperty);
            assertNotNull(additionalProperty.get$ref());
            assertEquals(additionalProperty.get$ref(), "#/components/schemas/ComplexLeft");
        } else {
            fail(String.format("Unexpected property: %s", name));
        }
    }
}
Also used : ArraySchema(io.swagger.v3.oas.models.media.ArraySchema) ModelWithTuple2(io.swagger.v3.core.oas.models.ModelWithTuple2) IntegerSchema(io.swagger.v3.oas.models.media.IntegerSchema) StringSchema(io.swagger.v3.oas.models.media.StringSchema) ArraySchema(io.swagger.v3.oas.models.media.ArraySchema) NumberSchema(io.swagger.v3.oas.models.media.NumberSchema) Schema(io.swagger.v3.oas.models.media.Schema) MapSchema(io.swagger.v3.oas.models.media.MapSchema) MapSchema(io.swagger.v3.oas.models.media.MapSchema) StringSchema(io.swagger.v3.oas.models.media.StringSchema) Map(java.util.Map) Test(org.testng.annotations.Test)

Example 4 with ArraySchema

use of io.swagger.v3.oas.models.media.ArraySchema in project swagger-core by swagger-api.

the class ParameterDeSerializationTest method deserializeNumberEnumPathParameter.

@Test(description = "it should deserialize a number path parameter with enum")
public void deserializeNumberEnumPathParameter() throws IOException {
    final String json = "{" + "   \"in\":\"path\"," + "   \"required\":true," + "   \"schema\":{" + "     \"type\":\"array\"," + "     \"items\":{" + "        \"type\":\"integer\"," + "        \"format\":\"int32\"," + "        \"enum\":[1,2,3]" + "     }" + "   }" + "}";
    final Parameter p = m.readValue(json, Parameter.class);
    SerializationMatchers.assertEqualsToJson(p, json);
    assertEquals(((IntegerSchema) ((ArraySchema) p.getSchema()).getItems()).getEnum(), Arrays.asList(1, 2, 3));
}
Also used : ArraySchema(io.swagger.v3.oas.models.media.ArraySchema) Parameter(io.swagger.v3.oas.models.parameters.Parameter) Test(org.testng.annotations.Test)

Example 5 with ArraySchema

use of io.swagger.v3.oas.models.media.ArraySchema in project swagger-core by swagger-api.

the class ByteConverterTest method testReadOnlyByteArray.

@Test
public void testReadOnlyByteArray() {
    Schema model = new Schema().addProperties("byteArray", new ArraySchema().items(new BinarySchema()).readOnly(true));
    assertEquals(Json.pretty(model), "{" + NEWLINE + "  \"properties\" : {" + NEWLINE + "    \"byteArray\" : {" + NEWLINE + "      \"type\" : \"array\"," + NEWLINE + "      \"readOnly\" : true," + NEWLINE + "      \"items\" : {" + NEWLINE + "        \"type\" : \"string\"," + NEWLINE + "        \"format\" : \"binary\"" + NEWLINE + "      }" + NEWLINE + "    }" + NEWLINE + "  }" + NEWLINE + "}");
}
Also used : ByteArraySchema(io.swagger.v3.oas.models.media.ByteArraySchema) ArraySchema(io.swagger.v3.oas.models.media.ArraySchema) BinarySchema(io.swagger.v3.oas.models.media.BinarySchema) BinarySchema(io.swagger.v3.oas.models.media.BinarySchema) Schema(io.swagger.v3.oas.models.media.Schema) ByteArraySchema(io.swagger.v3.oas.models.media.ByteArraySchema) ArraySchema(io.swagger.v3.oas.models.media.ArraySchema) Test(org.testng.annotations.Test)

Aggregations

ArraySchema (io.swagger.v3.oas.models.media.ArraySchema)32 Test (org.testng.annotations.Test)28 Schema (io.swagger.v3.oas.models.media.Schema)23 StringSchema (io.swagger.v3.oas.models.media.StringSchema)18 IntegerSchema (io.swagger.v3.oas.models.media.IntegerSchema)12 MapSchema (io.swagger.v3.oas.models.media.MapSchema)8 Parameter (io.swagger.v3.oas.models.parameters.Parameter)8 NumberSchema (io.swagger.v3.oas.models.media.NumberSchema)7 AnnotatedType (io.swagger.v3.core.converter.AnnotatedType)4 OpenAPI (io.swagger.v3.oas.models.OpenAPI)4 HeaderParameter (io.swagger.v3.oas.models.parameters.HeaderParameter)4 PathParameter (io.swagger.v3.oas.models.parameters.PathParameter)4 QueryParameter (io.swagger.v3.oas.models.parameters.QueryParameter)4 LinkedHashMap (java.util.LinkedHashMap)4 Operation (io.swagger.v3.oas.models.Operation)3 BooleanSchema (io.swagger.v3.oas.models.media.BooleanSchema)3 ComposedSchema (io.swagger.v3.oas.models.media.ComposedSchema)3 Annotation (java.lang.annotation.Annotation)3 BigDecimal (java.math.BigDecimal)3 Map (java.util.Map)3