Example usage for com.fasterxml.jackson.databind.introspect BeanPropertyDefinition getField

List of usage examples for com.fasterxml.jackson.databind.introspect BeanPropertyDefinition getField

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind.introspect BeanPropertyDefinition getField.

Prototype

public abstract AnnotatedField getField();

Source Link

Usage

From source file:springfox.bean.validators.plugins.Validators.java

private static Optional<Field> extractFieldFromPropertyDefinition(BeanPropertyDefinition propertyDefinition) {
    if (propertyDefinition.getField() != null) {
        return Optional.fromNullable(propertyDefinition.getField().getAnnotated());
    }//from w  w  w  .j a va 2s . c  o m
    return Optional.absent();
}

From source file:springfox.documentation.schema.Annotations.java

@SuppressWarnings("PMD")
private static <A extends Annotation> Optional<A> tryGetFieldAnnotation(
        BeanPropertyDefinition beanPropertyDefinition, Class<A> annotationClass) {
    if (beanPropertyDefinition.hasField()) {
        return Optional.fromNullable(beanPropertyDefinition.getField().getAnnotation(annotationClass));
    }//from   w  ww. ja v  a2  s .com
    return Optional.absent();
}

From source file:com.github.jonpeterson.jackson.module.versioning.VersionedModelUtils.java

public static BeanPropertyDefinition getSerializeToVersionProperty(BeanDescription beanDescription)
        throws RuntimeException {
    BeanPropertyDefinition serializeToVersionProperty = null;
    for (BeanPropertyDefinition definition : beanDescription.findProperties()) {

        // merge field and accessor annotations
        if (definition instanceof POJOPropertyBuilder)
            ((POJOPropertyBuilder) definition).mergeAnnotations(true);

        AnnotatedMember accessor = definition.getAccessor();
        if (accessor != null && accessor.hasAnnotation(JsonSerializeToVersion.class)) {
            if (serializeToVersionProperty != null)
                throw new RuntimeException("@" + JsonSerializeToVersion.class.getSimpleName()
                        + " must be present on at most one field or method");
            if (accessor.getRawType() != String.class
                    || (definition.getField() == null && !definition.hasGetter()))
                throw new RuntimeException("@" + JsonSerializeToVersion.class.getSimpleName()
                        + " must be on a field or a getter method that returns a String");
            serializeToVersionProperty = definition;
        }/*from  ww w  .jav a  2  s  . c  om*/
    }

    return serializeToVersionProperty;
}

From source file:io.druid.guice.JsonConfigurator.java

private <T> void verifyClazzIsConfigurable(Class<T> clazz) {
    final List<BeanPropertyDefinition> beanDefs = jsonMapper.getSerializationConfig()
            .introspect(jsonMapper.constructType(clazz)).findProperties();
    for (BeanPropertyDefinition beanDef : beanDefs) {
        final AnnotatedField field = beanDef.getField();
        if (field == null || !field.hasAnnotation(JsonProperty.class)) {
            throw new ProvisionException(String.format(
                    "JsonConfigurator requires Jackson-annotated Config objects to have field annotations. %s doesn't",
                    clazz));/*from w  w  w . ja v  a  2 s. c  o m*/
        }
    }
}

From source file:org.gvnix.web.json.ConversionServiceBeanSerializerModifier.java

@Override
public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc,
        List<BeanPropertyWriter> beanProperties) {

    // We need the BeanPropertyDefinition to get the related Field
    List<BeanPropertyDefinition> properties = beanDesc.findProperties();
    Map<String, BeanPropertyDefinition> propertyDefMap = new HashMap<String, BeanPropertyDefinition>();
    for (BeanPropertyDefinition property : properties) {
        propertyDefMap.put(property.getName(), property);
    }// w  w  w  . ja v  a  2 s  .c om

    // iterate over bean's properties to configure serializers
    for (int i = 0; i < beanProperties.size(); i++) {
        BeanPropertyWriter beanPropertyWriter = beanProperties.get(i);
        Class<?> propertyType = beanPropertyWriter.getPropertyType();

        if (beanPropertyWriter.hasSerializer()) {
            continue;
        }

        // For conversion between collection, array, and map types,
        // ConversionService.canConvert() method will return 'true'
        // but better to delegate in default Jackson property writer for
        // right start and ends markers serialization and iteration
        if (propertyType.isArray() || Collection.class.isAssignableFrom(propertyType)
                || Map.class.isAssignableFrom(propertyType)) {

            // Don't set ConversionService serializer, let Jackson
            // use default Collection serializer
            continue;
        } else if (BindingResult.class.isAssignableFrom(propertyType)) {
            // Use BindingResultSerializer
            beanPropertyWriter.assignSerializer(bindingResultSerializer);
        } else {

            // ConversionService uses value Class plus related Field
            // annotations to be able to select the right converter,
            // so we must get/ the Field annotations for success
            // formatting
            BeanPropertyDefinition propertyDef = propertyDefMap.get(beanPropertyWriter.getName());
            AnnotatedField annotatedField = propertyDef.getField();
            if (annotatedField == null) {
                continue;
            }
            AnnotatedElement annotatedEl = annotatedField.getAnnotated();

            // Field contains info about Annotations, info that
            // ConversionService uses for success formatting, use it if
            // available. Otherwise use the class of given value.
            TypeDescriptor sourceType = annotatedEl != null ? new TypeDescriptor((Field) annotatedEl)
                    : TypeDescriptor.valueOf(propertyType);

            TypeDescriptor targetType = TypeDescriptor.valueOf(String.class);
            if (beanPropertyWriter.getSerializationType() != null) {
                targetType = TypeDescriptor.valueOf(beanPropertyWriter.getSerializationType().getRawClass());
            }
            if (ObjectUtils.equals(sourceType, targetType)) {
                // No conversion needed
                continue;
            } else if (sourceType.getObjectType() == Object.class && targetType.getObjectType() == String.class
                    && beanPropertyWriter.getSerializationType() == null) {
                // Can't determine source type and no target type has been
                // configure. Delegate on jackson.
                continue;
            }

            // All other converters must be set in ConversionService
            if (this.conversionService.canConvert(sourceType, targetType)) {

                // We must create BeanPropertyWriter own Serializer that
                // has knowledge about the Field related to that
                // BeanPropertyWriter in order to have access to
                // Field Annotations for success serialization
                JsonSerializer<Object> jsonSerializer = new ConversionServicePropertySerializer(
                        this.conversionService, sourceType, targetType);

                beanPropertyWriter.assignSerializer(jsonSerializer);
            }
            // If no converter set, use default Jackson property writer
            else {
                continue;
            }
        }
    }
    return beanProperties;
}

From source file:com.google.api.server.spi.config.jsonwriter.JacksonResourceSchemaProvider.java

@Override
public ResourceSchema getResourceSchema(TypeToken<?> type, ApiConfig config) {
    ResourceSchema schema = super.getResourceSchema(type, config);
    if (schema != null) {
        return schema;
    }/*from w  w  w.  j  a  va  2  s . co m*/
    ObjectMapper objectMapper = ObjectMapperUtil.createStandardObjectMapper(config.getSerializationConfig());
    JavaType javaType = objectMapper.getTypeFactory().constructType(type.getRawType());
    BeanDescription beanDescription = objectMapper.getSerializationConfig().introspect(javaType);
    ResourceSchema.Builder schemaBuilder = ResourceSchema.builderForType(type.getRawType());
    Set<String> genericDataFieldNames = getGenericDataFieldNames(type);
    for (BeanPropertyDefinition definition : beanDescription.findProperties()) {
        TypeToken<?> propertyType = getPropertyType(type, toMethod(definition.getGetter()),
                toMethod(definition.getSetter()), definition.getField(), config);
        String name = definition.getName();
        if (genericDataFieldNames == null || genericDataFieldNames.contains(name)) {
            if (hasUnresolvedType(propertyType)) {
                logger.warning("skipping field '" + name + "' of type '" + propertyType
                        + "' because it is unresolved.");
                continue;
            }
            if (propertyType != null) {
                schemaBuilder.addProperty(name, ResourcePropertySchema.of(propertyType));
            } else {
                logger.warning("No type found for property '" + name + "' on class '" + type + "'.");
            }
        } else {
            logger.fine("skipping field '" + name + "' because it's not a Java client model field.");
        }
    }
    return schemaBuilder.build();
}

From source file:com.github.jonpeterson.spring.mvc.versioning.VersionedModelResponseBodyAdvice.java

@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
        Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
    VersionedResponseBody versionedResponseBody = returnType.getMethodAnnotation(VersionedResponseBody.class);
    String targetVersion = null;/*from  w w w.  ja v a 2 s.  co  m*/

    String queryParamName = versionedResponseBody.queryParamName();
    if (!queryParamName.isEmpty()) {
        List<String> queryParamValues = UriComponentsBuilder.fromUri(request.getURI()).build().getQueryParams()
                .get(queryParamName);
        if (queryParamValues != null && !queryParamValues.isEmpty())
            targetVersion = queryParamValues.get(0);
    }

    if (targetVersion == null) {
        String headerName = versionedResponseBody.headerName();
        if (!headerName.isEmpty()) {
            List<String> headerValues = request.getHeaders().get(headerName);
            if (headerValues != null && !headerValues.isEmpty())
                targetVersion = headerValues.get(0);
        }
    }

    if (targetVersion == null)
        targetVersion = versionedResponseBody.defaultVersion();

    try {
        boolean serializeToSet = false;

        for (BeanPropertyDefinition beanPropertyDefinition : mapper.getSerializationConfig()
                .introspect(mapper.getTypeFactory().constructType(body.getClass())).findProperties()) {
            AnnotatedMember field = beanPropertyDefinition.getField();
            AnnotatedMember setter = beanPropertyDefinition.getSetter();
            if ((field != null && field.hasAnnotation(JsonSerializeToVersion.class))
                    || (setter != null && setter.hasAnnotation(JsonSerializeToVersion.class))) {
                if (setter != null)
                    setter.setValue(body, targetVersion);
                else
                    field.setValue(body, targetVersion);
                serializeToSet = true;
            }
        }

        if (!serializeToSet)
            throw new RuntimeException("no @" + JsonSerializeToVersion.class.getSimpleName()
                    + " annotation found on String field or setter method in " + body.getClass()
                    + "; this is a requirement when using @" + VersionedResponseBody.class.getSimpleName());

    } catch (Exception e) {
        throw new RuntimeException("unable to set the version of the response body model", e);
    }

    return body;
}

From source file:org.jongo.marshall.jackson.JacksonObjectIdUpdater.java

public void setObjectId(Object target, ObjectId id) {
    for (BeanPropertyDefinition def : beanDescription(target.getClass()).findProperties()) {
        if (isIdProperty(def)) {
            AnnotatedMember accessor = def.getAccessor();
            accessor.fixAccess();/*w w w.  j  a  v a  2s. c  o m*/
            if (accessor.getValue(target) != null) {
                throw new IllegalArgumentException("Unable to set objectid on class: " + target.getClass());
            }
            AnnotatedMember field = def.getField();
            field.fixAccess();
            Class<?> type = field.getRawType();
            if (ObjectId.class.isAssignableFrom(type)) {
                field.setValue(target, id);
            } else if (type.equals(String.class) && isObjectId(def)) {
                field.setValue(target, id.toString());
            }
            return;
        }
    }
}

From source file:fr.norad.jaxrs.doc.parser.ModelJacksonParser.java

@Override
public List<PropertyAccessor> findProperties(Class<?> modelClass) {
    List<PropertyAccessor> properties = new ArrayList<>();

    BasicBeanDescription beanDesc = fakeSerializer.getDescription(modelClass);
    List<BeanPropertyDefinition> findProperties = beanDesc.findProperties();
    for (BeanPropertyDefinition beanPropertyDefinition : findProperties) {
        if (modelClass.isEnum() && "declaringClass".equals(beanPropertyDefinition.getName())) {
            continue;
        }/*from w  w  w .  j av  a 2  s. c  om*/
        AnnotatedMethod getterJackson = beanPropertyDefinition.getGetter();
        AnnotatedMethod setterJackson = beanPropertyDefinition.getSetter();
        AnnotatedField fieldJackson = null;
        try {
            fieldJackson = beanPropertyDefinition.getField();
        } catch (Exception e) {
            log.warning("Name conflict on fields in bean : " + beanPropertyDefinition + " during doc generation"
                    + e.getMessage());
        }

        Method getter = getterJackson == null ? null : getterJackson.getAnnotated();
        Method setter = setterJackson == null ? null : setterJackson.getAnnotated();
        Field field = fieldJackson == null ? null : fieldJackson.getAnnotated();
        if (getter == null && setter == null && field == null) {
            log.warning(
                    "Cannot find valid property element for : " + beanPropertyDefinition + " on " + modelClass);
            continue;
        }

        PropertyAccessor property = new PropertyAccessor();
        property.setField(field);
        property.setGetter(getter);
        property.setSetter(setter);
        property.setName(beanPropertyDefinition.getName());

        properties.add(property);
    }
    return properties;
}

From source file:de.fraunhofer.iosb.ilt.sta.deserialize.custom.CustomEntityDeserializer.java

@Override
public T deserialize(JsonParser parser, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    Entity result;/* w ww  .j a va2 s . co  m*/
    try {
        result = clazz.newInstance();
    } catch (InstantiationException | IllegalAccessException ex) {
        throw new IOException("Error deserializing JSON!");
    }
    // need to make subclass of this class for every Entity subclass with custom field to get expected class!!!
    BeanDescription beanDescription = ctxt.getConfig().introspect(ctxt.constructType(clazz));
    ObjectMapper mapper = (ObjectMapper) parser.getCodec();
    JsonNode obj = (JsonNode) mapper.readTree(parser);
    List<BeanPropertyDefinition> properties = beanDescription.findProperties();
    Iterator<Map.Entry<String, JsonNode>> i = obj.fields();

    // First check if we know all properties that are present.
    if (ctxt.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)) {
        for (; i.hasNext();) {
            Map.Entry<String, JsonNode> next = i.next();
            String fieldName = next.getKey();
            JsonNode field = next.getValue();
            Optional<BeanPropertyDefinition> findFirst = properties.stream()
                    .filter(p -> p.getName().equals(fieldName)).findFirst();
            if (!findFirst.isPresent()) {
                throw new UnrecognizedPropertyException(parser, "Unknown field: " + fieldName,
                        parser.getCurrentLocation(), clazz, fieldName, null);
            }
        }
    }

    for (BeanPropertyDefinition classProperty : properties) {
        if (obj.has(classProperty.getName())) {
            // property is present in class and json
            Annotation annotation = classProperty.getAccessor().getAnnotation(CustomSerialization.class);
            if (annotation != null) {
                // property has custom annotation
                // check if encoding property is also present in json (and also in class itself for sanity reasons)
                CustomSerialization customAnnotation = (CustomSerialization) annotation;
                Optional<BeanPropertyDefinition> encodingClassProperty = properties.stream()
                        .filter(p -> p.getName().equals(customAnnotation.encoding())).findFirst();
                if (!encodingClassProperty.isPresent()) {
                    throw new IOException("Error deserializing JSON as class '" + clazz.toString() + "' \n"
                            + "Reason: field '" + customAnnotation.encoding()
                            + "' specified by annotation as encoding field is not defined in class!");
                }
                String customEncoding = null;
                if (obj.has(customAnnotation.encoding())) {
                    customEncoding = obj.get(customAnnotation.encoding()).asText();
                }
                Object customDeserializedValue = CustomDeserializationManager.getInstance()
                        .getDeserializer(customEncoding)
                        .deserialize(mapper.writeValueAsString(obj.get(classProperty.getName())));
                classProperty.getMutator().setValue(result, customDeserializedValue);
            } else {
                // TODO type identificatin is not safe beacuase may ne be backed by field. Rather do multiple checks
                Object value = mapper.readValue(mapper.writeValueAsString(obj.get(classProperty.getName())),
                        classProperty.getField().getType());
                classProperty.getMutator().setValue(result, value);
            }
        }
    }
    return (T) result;
}