Search in sources :

Example 1 with JsonTypeInfo

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonTypeInfo in project candlepin by candlepin.

the class CandlepinSwaggerModelConverter method resolve.

public Model resolve(Type rawType, ModelConverterContext context, Iterator<ModelConverter> next) {
    if (this.shouldIgnoreClass(rawType)) {
        return null;
    }
    /**
     * See java doc of NestedComplexType. This unwrapping makes sure that a
     * real type of field used throughout the method. At the same time flag
     * 'isNested' helps to indicate later in the method that this type may
     * be introspected as Hateoas enabled field
     */
    boolean isNested = false;
    if (rawType instanceof NestedComplexType) {
        isNested = true;
        NestedComplexType nested = (NestedComplexType) rawType;
        rawType = nested.getOriginalType();
    }
    JavaType type = pMapper.constructType(rawType);
    if (type.isEnumType() || PrimitiveType.fromType(type) != null) {
        // We don't build models for primitive types
        return null;
    }
    final BeanDescription beanDesc = pMapper.getSerializationConfig().introspect(type);
    // Couple of possibilities for defining
    String name = isNested ? "Nested" : "";
    name += pTypeName(type, beanDesc);
    if ("Object".equals(name)) {
        return new ModelImpl();
    }
    final ModelImpl model = new ModelImpl().type(ModelImpl.OBJECT).name(name).description(pDescription(beanDesc.getClassInfo()));
    if (!type.isContainerType()) {
        // define the model here to support self/cyclic referencing of
        // models
        context.defineModel(name, model, type, null);
    }
    if (type.isContainerType()) {
        // We treat collections as primitive types, just need to add models
        // for values (if any)
        context.resolve(type.getContentType());
        return null;
    }
    // if XmlRootElement annotation, construct an Xml object and attach it
    // to the model
    XmlRootElement rootAnnotation = beanDesc.getClassAnnotations().get(XmlRootElement.class);
    if (rootAnnotation != null && !"".equals(rootAnnotation.name()) && !"##default".equals(rootAnnotation.name())) {
        log.debug(rootAnnotation.toString());
        Xml xml = new Xml().name(rootAnnotation.name());
        if (rootAnnotation.namespace() != null && !"".equals(rootAnnotation.namespace()) && !"##default".equals(rootAnnotation.namespace())) {
            xml.namespace(rootAnnotation.namespace());
        }
        model.xml(xml);
    }
    // see if @JsonIgnoreProperties exist
    Set<String> propertiesToIgnore = new HashSet<>();
    JsonIgnoreProperties ignoreProperties = beanDesc.getClassAnnotations().get(JsonIgnoreProperties.class);
    if (ignoreProperties != null) {
        propertiesToIgnore.addAll(Arrays.asList(ignoreProperties.value()));
    }
    final ApiModel apiModel = beanDesc.getClassAnnotations().get(ApiModel.class);
    String disc = (apiModel == null) ? "" : apiModel.discriminator();
    if (apiModel != null && StringUtils.isNotEmpty(apiModel.reference())) {
        model.setReference(apiModel.reference());
    }
    if (disc.isEmpty()) {
        // longer method would involve
        // AnnotationIntrospector.findTypeResolver(...) but:
        JsonTypeInfo typeInfo = beanDesc.getClassAnnotations().get(JsonTypeInfo.class);
        if (typeInfo != null) {
            disc = typeInfo.property();
        }
    }
    if (!disc.isEmpty()) {
        model.setDiscriminator(disc);
    }
    List<Property> props = new ArrayList<>();
    for (BeanPropertyDefinition propDef : beanDesc.findProperties()) {
        parseProperty(context, isNested, beanDesc, propertiesToIgnore, props, propDef);
    }
    Collections.sort(props, getPropertyComparator());
    Map<String, Property> modelProps = new LinkedHashMap<>();
    for (Property prop : props) {
        modelProps.put(prop.getName(), prop);
    }
    model.setProperties(modelProps);
    /**
     * This must be done after model.setProperties so that the model's set
     * of properties is available to filter from any subtypes
     */
    if (!resolveSubtypes(model, beanDesc, context)) {
        model.setDiscriminator(null);
    }
    return model;
}
Also used : XmlRootElement(javax.xml.bind.annotation.XmlRootElement) BeanDescription(com.fasterxml.jackson.databind.BeanDescription) ArrayList(java.util.ArrayList) ApiModel(io.swagger.annotations.ApiModel) JsonTypeInfo(com.fasterxml.jackson.annotation.JsonTypeInfo) JsonIgnoreProperties(com.fasterxml.jackson.annotation.JsonIgnoreProperties) LinkedHashMap(java.util.LinkedHashMap) JavaType(com.fasterxml.jackson.databind.JavaType) Xml(io.swagger.models.Xml) BeanPropertyDefinition(com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition) ModelImpl(io.swagger.models.ModelImpl) JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) StringProperty(io.swagger.models.properties.StringProperty) ArrayProperty(io.swagger.models.properties.ArrayProperty) Property(io.swagger.models.properties.Property) MapProperty(io.swagger.models.properties.MapProperty) UUIDProperty(io.swagger.models.properties.UUIDProperty) ApiModelProperty(io.swagger.annotations.ApiModelProperty) AbstractNumericProperty(io.swagger.models.properties.AbstractNumericProperty) RefProperty(io.swagger.models.properties.RefProperty) IntegerProperty(io.swagger.models.properties.IntegerProperty) HashSet(java.util.HashSet)

Example 2 with JsonTypeInfo

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonTypeInfo in project typescript-generator by vojtechhabarta.

the class Jackson2Parser method parseBean.

private BeanModel parseBean(SourceType<Class<?>> sourceClass) {
    final List<PropertyModel> properties = new ArrayList<>();
    final BeanHelper beanHelper = getBeanHelper(sourceClass.type);
    if (beanHelper != null) {
        for (final BeanPropertyWriter beanPropertyWriter : beanHelper.getProperties()) {
            final Member propertyMember = beanPropertyWriter.getMember().getMember();
            checkMember(propertyMember, beanPropertyWriter.getName(), sourceClass.type);
            Type propertyType = getGenericType(propertyMember);
            if (propertyType == JsonNode.class) {
                propertyType = Object.class;
            }
            boolean isInAnnotationFilter = settings.includePropertyAnnotations.isEmpty();
            if (!isInAnnotationFilter) {
                for (Class<? extends Annotation> optionalAnnotation : settings.includePropertyAnnotations) {
                    if (beanPropertyWriter.getAnnotation(optionalAnnotation) != null) {
                        isInAnnotationFilter = true;
                        break;
                    }
                }
                if (!isInAnnotationFilter) {
                    System.out.println("Skipping " + sourceClass.type + "." + beanPropertyWriter.getName() + " because it is missing an annotation from includePropertyAnnotations!");
                    continue;
                }
            }
            final boolean optional = settings.optionalProperties == OptionalProperties.useLibraryDefinition ? !beanPropertyWriter.isRequired() : isAnnotatedPropertyOptional(new AnnotatedProperty() {

                @Override
                public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
                    return beanPropertyWriter.getAnnotation(annotationClass);
                }
            });
            // @JsonUnwrapped
            PropertyModel.PullProperties pullProperties = null;
            final Member originalMember = beanPropertyWriter.getMember().getMember();
            if (originalMember instanceof AccessibleObject) {
                final AccessibleObject accessibleObject = (AccessibleObject) originalMember;
                final JsonUnwrapped annotation = accessibleObject.getAnnotation(JsonUnwrapped.class);
                if (annotation != null && annotation.enabled()) {
                    pullProperties = new PropertyModel.PullProperties(annotation.prefix(), annotation.suffix());
                }
            }
            properties.add(processTypeAndCreateProperty(beanPropertyWriter.getName(), propertyType, optional, sourceClass.type, originalMember, pullProperties));
        }
    }
    if (sourceClass.type.isEnum()) {
        return new BeanModel(sourceClass.type, null, null, null, null, null, properties, null);
    }
    final String discriminantProperty;
    final String discriminantLiteral;
    final JsonTypeInfo jsonTypeInfo = sourceClass.type.getAnnotation(JsonTypeInfo.class);
    final JsonTypeInfo parentJsonTypeInfo;
    if (isSupported(jsonTypeInfo)) {
        // this is parent
        discriminantProperty = getDiscriminantPropertyName(jsonTypeInfo);
        discriminantLiteral = null;
    } else if (isSupported(parentJsonTypeInfo = getAnnotationRecursive(sourceClass.type, JsonTypeInfo.class))) {
        // this is child class
        discriminantProperty = getDiscriminantPropertyName(parentJsonTypeInfo);
        discriminantLiteral = getTypeName(parentJsonTypeInfo, sourceClass.type);
    } else {
        // not part of explicit hierarchy
        discriminantProperty = null;
        discriminantLiteral = null;
    }
    final List<Class<?>> taggedUnionClasses;
    final JsonSubTypes jsonSubTypes = sourceClass.type.getAnnotation(JsonSubTypes.class);
    if (jsonSubTypes != null) {
        taggedUnionClasses = new ArrayList<>();
        for (JsonSubTypes.Type type : jsonSubTypes.value()) {
            addBeanToQueue(new SourceType<>(type.value(), sourceClass.type, "<subClass>"));
            taggedUnionClasses.add(type.value());
        }
    } else {
        taggedUnionClasses = null;
    }
    final Type superclass = sourceClass.type.getGenericSuperclass() == Object.class ? null : sourceClass.type.getGenericSuperclass();
    if (superclass != null) {
        addBeanToQueue(new SourceType<>(superclass, sourceClass.type, "<superClass>"));
    }
    final List<Type> interfaces = Arrays.asList(sourceClass.type.getGenericInterfaces());
    for (Type aInterface : interfaces) {
        addBeanToQueue(new SourceType<>(aInterface, sourceClass.type, "<interface>"));
    }
    return new BeanModel(sourceClass.type, superclass, taggedUnionClasses, discriminantProperty, discriminantLiteral, interfaces, properties, null);
}
Also used : AccessibleObject(java.lang.reflect.AccessibleObject) JsonUnwrapped(com.fasterxml.jackson.annotation.JsonUnwrapped) Member(java.lang.reflect.Member) JsonSubTypes(com.fasterxml.jackson.annotation.JsonSubTypes) JsonTypeInfo(com.fasterxml.jackson.annotation.JsonTypeInfo) Annotation(java.lang.annotation.Annotation) Type(java.lang.reflect.Type) AccessibleObject(java.lang.reflect.AccessibleObject)

Example 3 with JsonTypeInfo

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonTypeInfo in project jsonschema2pojo by joelittlejohn.

the class IncludeTypeInfoIT method defaultWithSchemaProperty.

@Test
public void defaultWithSchemaProperty() throws ClassNotFoundException {
    ClassLoader classLoader = schemaRule.generateAndCompile("/schema/typeInfo/typeInfoWithSchemaProperty.json", "com.example");
    Class<?> classWithTypeInfo = classLoader.loadClass("com.example.TypeInfoWithSchemaProperty");
    assertNotNull(classWithTypeInfo.getAnnotation(JsonTypeInfo.class));
    JsonTypeInfo jsonTypeInfo = classWithTypeInfo.getAnnotation(JsonTypeInfo.class);
    assertThat(jsonTypeInfo.use(), is(JsonTypeInfo.Id.CLASS));
    assertThat(jsonTypeInfo.include(), is(JsonTypeInfo.As.PROPERTY));
    assertThat(jsonTypeInfo.property(), is("@clazz"));
}
Also used : JsonTypeInfo(com.fasterxml.jackson.annotation.JsonTypeInfo) Test(org.junit.Test)

Example 4 with JsonTypeInfo

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonTypeInfo in project jsonschema2pojo by joelittlejohn.

the class IncludeTypeInfoIT method enabled.

@Test
public void enabled() throws ClassNotFoundException {
    ClassLoader classLoader = schemaRule.generateAndCompile("/schema/typeInfo/typeInfo.json", "com.example", config("includeTypeInfo", true));
    Class<?> classWithTypeInfo = classLoader.loadClass("com.example.TypeInfo");
    assertNotNull(classWithTypeInfo.getAnnotation(JsonTypeInfo.class));
    JsonTypeInfo jsonTypeInfo = classWithTypeInfo.getAnnotation(JsonTypeInfo.class);
    assertThat(jsonTypeInfo.use(), is(JsonTypeInfo.Id.CLASS));
    assertThat(jsonTypeInfo.include(), is(JsonTypeInfo.As.PROPERTY));
    assertThat(jsonTypeInfo.property(), is("@class"));
}
Also used : JsonTypeInfo(com.fasterxml.jackson.annotation.JsonTypeInfo) Test(org.junit.Test)

Example 5 with JsonTypeInfo

use of org.apache.flink.shaded.jackson2.com.fasterxml.jackson.annotation.JsonTypeInfo in project swagger-core by swagger-api.

the class ModelResolver method resolveDiscriminator.

protected Discriminator resolveDiscriminator(JavaType type, ModelConverterContext context) {
    io.swagger.v3.oas.annotations.media.Schema declaredSchemaAnnotation = AnnotationsUtils.getSchemaDeclaredAnnotation(type.getRawClass());
    String disc = (declaredSchemaAnnotation == null) ? "" : declaredSchemaAnnotation.discriminatorProperty();
    if (disc.isEmpty()) {
        // longer method would involve AnnotationIntrospector.findTypeResolver(...) but:
        JsonTypeInfo typeInfo = type.getRawClass().getDeclaredAnnotation(JsonTypeInfo.class);
        if (typeInfo != null) {
            disc = typeInfo.property();
        }
    }
    if (!disc.isEmpty()) {
        Discriminator discriminator = new Discriminator().propertyName(disc);
        if (declaredSchemaAnnotation != null) {
            DiscriminatorMapping[] mappings = declaredSchemaAnnotation.discriminatorMapping();
            if (mappings != null && mappings.length > 0) {
                for (DiscriminatorMapping mapping : mappings) {
                    if (!mapping.value().isEmpty() && !mapping.schema().equals(Void.class)) {
                        discriminator.mapping(mapping.value(), constructRef(context.resolve(new AnnotatedType().type(mapping.schema())).getName()));
                    }
                }
            }
        }
        return discriminator;
    }
    return null;
}
Also used : DiscriminatorMapping(io.swagger.v3.oas.annotations.media.DiscriminatorMapping) AnnotatedType(io.swagger.v3.core.converter.AnnotatedType) JsonTypeInfo(com.fasterxml.jackson.annotation.JsonTypeInfo) Discriminator(io.swagger.v3.oas.models.media.Discriminator)

Aggregations

JsonTypeInfo (com.fasterxml.jackson.annotation.JsonTypeInfo)12 Test (org.junit.Test)4 ArrayList (java.util.ArrayList)3 JsonIgnoreProperties (com.fasterxml.jackson.annotation.JsonIgnoreProperties)2 JsonProperty (com.fasterxml.jackson.annotation.JsonProperty)2 JsonSubTypes (com.fasterxml.jackson.annotation.JsonSubTypes)2 JsonUnwrapped (com.fasterxml.jackson.annotation.JsonUnwrapped)2 BeanDescription (com.fasterxml.jackson.databind.BeanDescription)2 JavaType (com.fasterxml.jackson.databind.JavaType)2 BeanPropertyDefinition (com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition)2 ApiModel (io.swagger.annotations.ApiModel)2 ApiModelProperty (io.swagger.annotations.ApiModelProperty)2 ModelImpl (io.swagger.models.ModelImpl)2 ArraySchema (io.swagger.v3.oas.models.media.ArraySchema)2 ComposedSchema (io.swagger.v3.oas.models.media.ComposedSchema)2 IntegerSchema (io.swagger.v3.oas.models.media.IntegerSchema)2 MapSchema (io.swagger.v3.oas.models.media.MapSchema)2 NumberSchema (io.swagger.v3.oas.models.media.NumberSchema)2 ObjectSchema (io.swagger.v3.oas.models.media.ObjectSchema)2 Schema (io.swagger.v3.oas.models.media.Schema)2