Search in sources :

Example 1 with AnnotatedType

use of io.swagger.v3.core.converter.AnnotatedType 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 AnnotatedType

use of io.swagger.v3.core.converter.AnnotatedType in project swagger-core by swagger-api.

the class EnumPropertyTest method testEnumRefPropertyGlobalNotAffectingNonEnums.

@Test(description = "it should not affect non-enum models when the enumsAsRef property is enabled globally")
public void testEnumRefPropertyGlobalNotAffectingNonEnums() {
    ModelResolver.enumsAsRef = true;
    Schema schema = context.resolve(new AnnotatedType(Model1979.class));
    final Map<String, Schema> models = context.getDefinedModels();
    final String yaml = "Model1979:\n" + "  type: object\n" + "  properties:\n" + "    id:\n" + "      type: string\n" + "      nullable: true";
    SerializationMatchers.assertEqualsToYaml(models, yaml);
    ModelResolver.enumsAsRef = false;
}
Also used : AnnotatedType(io.swagger.v3.core.converter.AnnotatedType) StringSchema(io.swagger.v3.oas.models.media.StringSchema) Schema(io.swagger.v3.oas.models.media.Schema) Model1979(io.swagger.v3.core.oas.models.Model1979) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest)

Example 3 with AnnotatedType

use of io.swagger.v3.core.converter.AnnotatedType in project swagger-core by swagger-api.

the class EnumPropertyTest method testEnumRefPropertyWithFQNTypeNameResolver.

@Test(description = "it should read a model with an enum property as a reference with fqn TypeNameResolver")
public void testEnumRefPropertyWithFQNTypeNameResolver() {
    TypeNameResolver.std.setUseFqn(true);
    Schema schema = context.resolve(new AnnotatedType(ModelWithEnumRefProperty.class));
    final Map<String, Schema> models = context.getDefinedModels();
    final String yaml = "io.swagger.v3.core.oas.models.ModelWithEnumRefProperty:\n" + "  type: object\n" + "  properties:\n" + "    a:\n" + "      $ref: '#/components/schemas/io.swagger.v3.core.oas.models.TestEnum'\n" + "    b:\n" + "      $ref: '#/components/schemas/io.swagger.v3.core.oas.models.TestEnum'\n" + "    c:\n" + "      $ref: '#/components/schemas/io.swagger.v3.core.oas.models.TestSecondEnum'\n" + "    d:\n" + "      type: string\n" + "      enum:\n" + "      - A_PRIVATE\n" + "      - A_PUBLIC\n" + "      - A_SYSTEM\n" + "      - A_INVITE_ONLY\n" + "io.swagger.v3.core.oas.models.TestEnum:\n" + "  type: string\n" + "  enum:\n" + "  - PRIVATE\n" + "  - PUBLIC\n" + "  - SYSTEM\n" + "  - INVITE_ONLY\n" + "io.swagger.v3.core.oas.models.TestSecondEnum:\n" + "  type: string\n" + "  enum:\n" + "  - A_PRIVATE\n" + "  - A_PUBLIC\n" + "  - A_SYSTEM\n" + "  - A_INVITE_ONLY\n";
    TypeNameResolver.std.setUseFqn(false);
    SerializationMatchers.assertEqualsToYaml(models, yaml);
}
Also used : AnnotatedType(io.swagger.v3.core.converter.AnnotatedType) ModelWithEnumRefProperty(io.swagger.v3.core.oas.models.ModelWithEnumRefProperty) StringSchema(io.swagger.v3.oas.models.media.StringSchema) Schema(io.swagger.v3.oas.models.media.Schema) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest)

Example 4 with AnnotatedType

use of io.swagger.v3.core.converter.AnnotatedType in project swagger-core by swagger-api.

the class GericModelConverter method resolve.

@Override
public Schema resolve(AnnotatedType type, ModelConverterContext context, Iterator<ModelConverter> next) {
    if (type.getType() instanceof Class<?>) {
        Class<?> cls = (Class<?>) type.getType();
        if (GenericModel.class.isAssignableFrom(cls)) {
            Schema impl = new Schema();
            impl.title(cls.getSimpleName());
            for (Entry<String, Class<?>> entry : GenericModel.getDeclaredProperties().entrySet()) {
                impl.addProperties(entry.getKey(), context.resolve(new AnnotatedType(entry.getValue())));
            }
            context.defineModel(impl.getTitle(), impl);
            return impl;
        }
    }
    if (next.hasNext()) {
        return next.next().resolve(type, context, next);
    } else {
        return null;
    }
}
Also used : AnnotatedType(io.swagger.v3.core.converter.AnnotatedType) Schema(io.swagger.v3.oas.models.media.Schema)

Example 5 with AnnotatedType

use of io.swagger.v3.core.converter.AnnotatedType in project swagger-core by swagger-api.

the class InheritedBeanTest method testMultipleInheritedChildBean.

@Test
public void testMultipleInheritedChildBean() throws Exception {
    final Schema subModel = context.resolve(new AnnotatedType(MultipleSub1Bean.class));
    assertNotNull(subModel);
    // make sure child points at parent
    assertTrue(subModel instanceof ComposedSchema);
    ComposedSchema cm = (ComposedSchema) subModel;
    assertEquals(cm.getAllOf().get(0).get$ref(), "#/components/schemas/MultipleBaseBean");
    // make sure parent properties are filtered out of subclass
    assertSub1PropertiesValid(cm.getAllOf().get(1).getProperties());
    final Schema baseModel = context.getDefinedModels().get("MultipleBaseBean");
    assertNotNull(baseModel);
    assertBasePropertiesValid(baseModel.getProperties());
    final Schema sub1Model = context.getDefinedModels().get("MultipleSub1Bean");
    assertNotNull(sub1Model);
    // make sure child points at parent
    assertTrue(sub1Model instanceof ComposedSchema);
    ComposedSchema cm1 = (ComposedSchema) sub1Model;
    assertEquals(cm1.getAllOf().get(0).get$ref(), "#/components/schemas/MultipleBaseBean");
    // make sure parent properties are filtered out of subclass
    assertSub1PropertiesValid(cm1.getAllOf().get(1).getProperties());
    final Schema sub2Model = context.getDefinedModels().get("MultipleSub2Bean");
    assertNotNull(sub2Model);
    assertTrue(sub2Model instanceof ComposedSchema);
    ComposedSchema cm2 = (ComposedSchema) sub2Model;
    assertEquals(cm2.getAllOf().get(0).get$ref(), "#/components/schemas/MultipleBaseBean");
    // make sure parent properties are filtered out of subclass
    assertSub2PropertiesValid(cm2.getAllOf().get(1).getProperties());
}
Also used : AnnotatedType(io.swagger.v3.core.converter.AnnotatedType) ComposedSchema(io.swagger.v3.oas.models.media.ComposedSchema) Schema(io.swagger.v3.oas.models.media.Schema) ComposedSchema(io.swagger.v3.oas.models.media.ComposedSchema) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest)

Aggregations

Schema (io.swagger.v3.oas.models.media.Schema)60 AnnotatedType (io.swagger.v3.core.converter.AnnotatedType)57 Test (org.testng.annotations.Test)47 ModelConverterContextImpl (io.swagger.v3.core.converter.ModelConverterContextImpl)25 ModelResolver (io.swagger.v3.core.jackson.ModelResolver)21 ArraySchema (io.swagger.v3.oas.models.media.ArraySchema)14 ComposedSchema (io.swagger.v3.oas.models.media.ComposedSchema)13 AfterTest (org.testng.annotations.AfterTest)13 StringSchema (io.swagger.v3.oas.models.media.StringSchema)11 ModelConverter (io.swagger.v3.core.converter.ModelConverter)6 IntegerSchema (io.swagger.v3.oas.models.media.IntegerSchema)6 ObjectSchema (io.swagger.v3.oas.models.media.ObjectSchema)6 Annotation (java.lang.annotation.Annotation)6 LinkedHashMap (java.util.LinkedHashMap)5 Map (java.util.Map)5 JavaType (com.fasterxml.jackson.databind.JavaType)4 MapSchema (io.swagger.v3.oas.models.media.MapSchema)4 NumberSchema (io.swagger.v3.oas.models.media.NumberSchema)4 UUIDSchema (io.swagger.v3.oas.models.media.UUIDSchema)4 ArrayList (java.util.ArrayList)4