Search in sources :

Example 1 with BeanPropertyDefinition

use of com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition in project jackson-databind by FasterXML.

the class BasicExceptionTest method testBadDefinition.

public void testBadDefinition() throws Exception {
    JavaType t = TypeFactory.defaultInstance().constructType(String.class);
    JsonParser p = JSON_F.createParser("[]");
    InvalidDefinitionException e = new InvalidDefinitionException(p, "Testing", t);
    assertEquals("Testing", e.getOriginalMessage());
    assertEquals(String.class, e.getType().getRawClass());
    assertNull(e.getBeanDescription());
    assertNull(e.getProperty());
    assertSame(p, e.getProcessor());
    p.close();
    // and via factory method:
    BeanDescription beanDef = MAPPER.getSerializationConfig().introspectClassAnnotations(getClass());
    e = InvalidDefinitionException.from(p, "Testing", beanDef, (BeanPropertyDefinition) null);
    assertEquals(beanDef.getType(), e.getType());
    assertNotNull(e);
    // and the other constructor too
    JsonGenerator g = JSON_F.createGenerator(new StringWriter());
    e = new InvalidDefinitionException(p, "Testing", t);
    assertEquals("Testing", e.getOriginalMessage());
    assertEquals(String.class, e.getType().getRawClass());
    // and factory
    e = InvalidDefinitionException.from(g, "Testing", beanDef, (BeanPropertyDefinition) null);
    assertEquals(beanDef.getType(), e.getType());
    assertNotNull(e);
    g.close();
}
Also used : StringWriter(java.io.StringWriter) BeanPropertyDefinition(com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition)

Example 2 with BeanPropertyDefinition

use of com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition in project torodb by torodb.

the class AbstractBackendSerializer method acceptJsonFormatVisitor.

@Override
public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType type) throws JsonMappingException {
    if (visitor == null) {
        return;
    }
    JsonObjectFormatVisitor v = visitor.expectObjectFormat(type);
    SerializerProvider prov = visitor.getProvider();
    final SerializationConfig config = prov.getConfig();
    BeanDescription beanDesc = config.introspect(type);
    JsonSubTypes jsonSubTypes;
    if (v != null) {
        for (BeanPropertyDefinition propDef : beanDesc.findProperties()) {
            if (propDef.isExplicitlyIncluded()) {
                jsonSubTypes = propDef.getPrimaryMember().getAnnotation(JsonSubTypes.class);
                if (jsonSubTypes != null) {
                    for (JsonSubTypes.Type jsonSubType : jsonSubTypes.value()) {
                        JavaType subType = TypeFactory.defaultInstance().constructType(jsonSubType.value());
                        depositSchemaProperty(v, jsonSubType.name(), subType);
                    }
                } else {
                    depositSchemaProperty(v, propDef.getName(), propDef.getPrimaryMember().getType(beanDesc.bindingsForBeanType()));
                }
            }
        }
    }
}
Also used : JsonSubTypes(com.fasterxml.jackson.annotation.JsonSubTypes) JavaType(com.fasterxml.jackson.databind.JavaType) JsonObjectFormatVisitor(com.fasterxml.jackson.databind.jsonFormatVisitors.JsonObjectFormatVisitor) SerializationConfig(com.fasterxml.jackson.databind.SerializationConfig) BeanDescription(com.fasterxml.jackson.databind.BeanDescription) BeanPropertyDefinition(com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition) SerializerProvider(com.fasterxml.jackson.databind.SerializerProvider)

Example 3 with BeanPropertyDefinition

use of com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition 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 void handleAdditionalAnnotation(List<Parameter> parameters, Annotation annotation, final Type type, Set<Type> typesToSkip) {
    if (CLASS_BEAN_PARAM != null && CLASS_BEAN_PARAM.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<Annotation>();
            final Iterator<SwaggerExtension> extensions = SwaggerExtensions.chain();
            Type paramType = null;
            // Gather the field's details
            if (field != null) {
                paramType = field.getRawType();
                for (final Annotation fieldAnnotation : field.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 = setter.getRawParameterTypes() != null ? setter.getRawParameterTypes()[0] : null;
                }
                for (final Annotation fieldAnnotation : setter.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.getRawReturnType();
                }
                for (final Annotation fieldAnnotation : getter.annotations()) {
                    if (!paramAnnotations.contains(fieldAnnotation)) {
                        paramAnnotations.add(fieldAnnotation);
                    }
                }
            }
            if (paramType == null) {
                continue;
            }
            // Re-process all Bean fields and let the default swagger-jaxrs/swagger-jersey-jaxrs processors do their thing
            List<Parameter> extracted = extensions.next().extractParameters(paramAnnotations, paramType, typesToSkip, extensions);
            // since downstream processors won't know how to introspect @BeanParam, process here
            for (Parameter param : extracted) {
                if (ParameterProcessor.applyAnnotations(null, param, paramType, paramAnnotations) != null) {
                    parameters.add(param);
                }
            }
        }
    }
}
Also used : AnnotatedMethod(com.fasterxml.jackson.databind.introspect.AnnotatedMethod) BeanDescription(com.fasterxml.jackson.databind.BeanDescription) ArrayList(java.util.ArrayList) Annotation(java.lang.annotation.Annotation) Type(java.lang.reflect.Type) AbstractSwaggerExtension(io.swagger.jaxrs.ext.AbstractSwaggerExtension) SwaggerExtension(io.swagger.jaxrs.ext.SwaggerExtension) BeanPropertyDefinition(com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition) HeaderParameter(io.swagger.models.parameters.HeaderParameter) CookieParameter(io.swagger.models.parameters.CookieParameter) FormParameter(io.swagger.models.parameters.FormParameter) PathParameter(io.swagger.models.parameters.PathParameter) Parameter(io.swagger.models.parameters.Parameter) QueryParameter(io.swagger.models.parameters.QueryParameter) AnnotatedField(com.fasterxml.jackson.databind.introspect.AnnotatedField)

Example 4 with BeanPropertyDefinition

use of com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition in project Gaffer by gchq.

the class GraphConfigurationService method getSerialisedFields.

@SuppressFBWarnings(value = "REC_CATCH_EXCEPTION", justification = "Need to wrap all runtime exceptions before they are given to the user")
@Override
public Set<String> getSerialisedFields(final String className) {
    final Class<?> clazz;
    try {
        clazz = Class.forName(className);
    } catch (final Exception e) {
        throw new IllegalArgumentException("Class name was not recognised: " + className, e);
    }
    final ObjectMapper mapper = new ObjectMapper();
    final JavaType type = mapper.getTypeFactory().constructType(clazz);
    final BeanDescription introspection = mapper.getSerializationConfig().introspect(type);
    final List<BeanPropertyDefinition> properties = introspection.findProperties();
    final Set<String> fields = new HashSet<>();
    for (final BeanPropertyDefinition property : properties) {
        fields.add(property.getName());
    }
    return fields;
}
Also used : JavaType(com.fasterxml.jackson.databind.JavaType) BeanDescription(com.fasterxml.jackson.databind.BeanDescription) BeanPropertyDefinition(com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HashSet(java.util.HashSet) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Example 5 with BeanPropertyDefinition

use of com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition 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)

Aggregations

BeanPropertyDefinition (com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition)24 BeanDescription (com.fasterxml.jackson.databind.BeanDescription)19 JavaType (com.fasterxml.jackson.databind.JavaType)16 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)8 ArrayList (java.util.ArrayList)8 Annotation (java.lang.annotation.Annotation)7 HashSet (java.util.HashSet)6 JsonProperty (com.fasterxml.jackson.annotation.JsonProperty)5 AnnotatedMethod (com.fasterxml.jackson.databind.introspect.AnnotatedMethod)5 Type (java.lang.reflect.Type)4 JsonIgnoreProperties (com.fasterxml.jackson.annotation.JsonIgnoreProperties)3 JsonTypeInfo (com.fasterxml.jackson.annotation.JsonTypeInfo)3 AnnotatedField (com.fasterxml.jackson.databind.introspect.AnnotatedField)3 POJOPropertyBuilder (com.fasterxml.jackson.databind.introspect.POJOPropertyBuilder)3 SuppressFBWarnings (edu.umd.cs.findbugs.annotations.SuppressFBWarnings)3 ArrayProperty (io.swagger.models.properties.ArrayProperty)3 Property (io.swagger.models.properties.Property)3 RefProperty (io.swagger.models.properties.RefProperty)3 StringProperty (io.swagger.models.properties.StringProperty)3 JsonIdentityInfo (com.fasterxml.jackson.annotation.JsonIdentityInfo)2