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

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

Introduction

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

Prototype

public abstract AnnotatedMember getAccessor();

Source Link

Usage

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  w  w w  . j a  v a2  s  .  com*/
    }

    return serializeToVersionProperty;
}

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

private static boolean isObjectId(BeanPropertyDefinition property) {
    return property.getPrimaryMember().getAnnotation(org.jongo.marshall.jackson.oid.ObjectId.class) != null
            || property.getPrimaryMember().getAnnotation(MongoObjectId.class) != null
            || ObjectId.class.isAssignableFrom(property.getAccessor().getRawType());
}

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

public Object getId(Object pojo) {
    BasicBeanDescription beanDescription = beanDescription(pojo.getClass());
    for (BeanPropertyDefinition def : beanDescription.findProperties()) {
        if (isIdProperty(def)) {
            AnnotatedMember accessor = def.getAccessor();
            accessor.fixAccess();/*from   w  w  w .  ja v  a  2  s .c o  m*/
            Object id = accessor.getValue(pojo);
            if (id instanceof String && isObjectId(def)) {
                return new ObjectId(id.toString());
            } else {
                return id;
            }
        }
    }
    return null;
}

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

public boolean mustGenerateObjectId(Object pojo) {
    for (BeanPropertyDefinition def : beanDescription(pojo.getClass()).findProperties()) {
        if (isIdProperty(def)) {
            AnnotatedMember accessor = def.getAccessor();
            accessor.fixAccess();//from w  ww  . ja v a 2s.  c o m
            return isObjectId(def) && accessor.getValue(pojo) == null;
        }
    }
    return false;
}

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 av a  2 s. co  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:nl.talsmasoftware.enumerables.support.json.jackson2.EnumerableSerializer.java

private void serializeObject(Enumerable value, JsonGenerator jgen, SerializationConfig config)
        throws IOException {
    jgen.writeStartObject();// w w  w. ja  v  a 2  s .c  o  m
    for (BeanPropertyDefinition property : serializationPropertiesFor(value.getClass(), config)) {
        if (property.couldSerialize()) {
            final Object propertyValue = property.getAccessor().getValue(value);
            if (propertyValue != null || property.isExplicitlyIncluded() || mustIncludeNull(config)) {
                jgen.writeObjectField(property.getName(), propertyValue);
            }
        }
    }
    jgen.writeEndObject();
}

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;/*from   w  ww  .j  av a 2  s.  c om*/
    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;
}

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

public VersionedModelDeserializer(StdDeserializer<T> delegate, JsonVersionedModel jsonVersionedModel,
        BeanPropertyDefinition serializeToVersionProperty) {
    super(delegate.getValueType());

    this.delegate = delegate;
    this.jsonVersionedModel = jsonVersionedModel;
    this.serializeToVersionProperty = serializeToVersionProperty;
    this.serializeToVersionAnnotation = serializeToVersionProperty != null
            ? serializeToVersionProperty.getAccessor().getAnnotation(JsonSerializeToVersion.class)
            : null;//from   w w w .j a  va2s .c  o m

    Class<? extends VersionedModelConverter> converterClass = jsonVersionedModel.toCurrentConverterClass();
    if (converterClass != VersionedModelConverter.class)
        try {
            this.converter = converterClass.newInstance();
        } catch (Exception e) {
            throw new RuntimeException(
                    "unable to create instance of converter '" + converterClass.getName() + "'", e);
        }
    else
        converter = null;
}

From source file:org.usrz.libs.riak.JsonTest.java

@Test
public void jsonTest() throws Exception {
    RiakIntrospector introspector = new RiakIntrospector();

    System.err.println(introspector.getConverter(Set.class, Set.class));

    final Bean bean = new Bean();

    System.err.println("========================= SER");

    final BeanDescription serializationDescription = introspector.getEntityReader(bean);
    final List<BeanPropertyDefinition> serializationProperties = serializationDescription.findProperties();
    for (BeanPropertyDefinition property : serializationProperties) {
        System.err.println(property);
        property.couldDeserialize();//from w  w w .j  a  va 2  s.  c  o  m
        System.err.println(" ----> " + property.getAccessor().getClass());
        System.err.println(" ----> " + property.getAccessor().getRawType());
    }

    System.err.println("========================= DESER");

    final BeanDescription deserializationDescription = introspector.getEntityWriter(bean);
    final List<BeanPropertyDefinition> deserializationProperties = deserializationDescription.findProperties();
    for (BeanPropertyDefinition property : deserializationProperties) {
        System.err.println(property);
        System.err.println(" ----> " + property.getMutator().getClass());
        System.err.println(" ----> " + property.getMutator().getRawType());
    }

    //
    //        final ObjectMapper mapper = new ObjectMapper();
    //        mapper.enable(SerializationFeature.INDENT_OUTPUT);
    //
    //        final String json = mapper.writeValueAsString(new Bean());
    //        System.err.println(json);
    //        mapper.readValue(json, Bean.class);

}

From source file:de.fraunhofer.iosb.ilt.sta.serialize.EntitySerializer.java

protected void serializeFieldTyped(Entity entity, JsonGenerator gen, SerializerProvider serializers,
        BeanDescription beanDescription, BeanPropertyDefinition beanPropertyDefinition,
        TypeSerializer typeSerializer) throws Exception {
    try {//from  ww  w . j a  va 2s .  c  o  m
        if (typeSerializer == null) {
            typeSerializer = serializers.findTypeSerializer(
                    serializers.constructType(beanPropertyDefinition.getAccessor().getRawType()));
        }
        if (typeSerializer == null) {
            // if not static type if available use dynamic type if available
            Object propertyValue = beanPropertyDefinition.getAccessor().getValue(entity);
            if (propertyValue != null) {
                typeSerializer = serializers
                        .findTypeSerializer(serializers.constructType(propertyValue.getClass()));
            }
        }

        BeanPropertyWriter bpw = new BeanPropertyWriter(beanPropertyDefinition,
                beanPropertyDefinition.getAccessor(), beanDescription.getClassAnnotations(),
                beanPropertyDefinition.getAccessor().getType(), null, // will be searched automatically
                typeSerializer, // will not be searched automatically
                beanPropertyDefinition.getAccessor().getType(),
                suppressNulls(serializers.getConfig().getDefaultPropertyInclusion()),
                suppressableValue(serializers.getConfig().getDefaultPropertyInclusion()));
        bpw.serializeAsField(entity, gen, serializers);
    } catch (JsonMappingException ex) {
        Logger.getLogger(EntitySerializer.class.getName()).log(Level.SEVERE, null, ex);
    }
}