Example usage for com.fasterxml.jackson.databind BeanDescription findProperties

List of usage examples for com.fasterxml.jackson.databind BeanDescription findProperties

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind BeanDescription findProperties.

Prototype

public abstract List<BeanPropertyDefinition> findProperties();

Source Link

Usage

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 .j a v a  2 s  . co  m

    // 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:de.fraunhofer.iosb.ilt.sta.deserialize.custom.CustomEntityDeserializer.java

@Override
public T deserialize(JsonParser parser, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    Entity result;//  ww w  . j av  a2  s  .  c  o  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;
}

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();/*  w ww .j av a 2s  . com*/
        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: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 v a  2s. com*/
    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:springfox.documentation.schema.property.OptimizedModelPropertiesProvider.java

@Override
public List<ModelProperty> propertiesFor(ResolvedType type, ModelContext givenContext) {
    List<ModelProperty> properties = newArrayList();
    BeanDescription beanDescription = beanDescription(type, givenContext);
    Map<String, BeanPropertyDefinition> propertyLookup = uniqueIndex(beanDescription.findProperties(),
            BeanPropertyDefinitions.beanPropertyByInternalName());
    for (Map.Entry<String, BeanPropertyDefinition> each : propertyLookup.entrySet()) {
        LOG.debug("Reading property {}", each.getKey());
        BeanPropertyDefinition jacksonProperty = each.getValue();
        Optional<AnnotatedMember> annotatedMember = Optional
                .fromNullable(safeGetPrimaryMember(jacksonProperty));
        if (annotatedMember.isPresent()) {
            properties.addAll(candidateProperties(type, annotatedMember.get(), jacksonProperty, givenContext));
        }/* w  w  w .ja va 2 s .c om*/
    }
    return FluentIterable.from(properties).toSortedSet(byPropertyName()).asList();
}

From source file:org.candlepin.swagger.CandlepinSwaggerModelConverter.java

public Model resolve(Type rawType, ModelConverterContext context, Iterator<ModelConverter> next) {
    if (this.shouldIgnoreClass(rawType)) {
        return null;
    }/*from  ww w .  ja  v a  2  s  .c  om*/

    /**
     * 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<String>();
    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<Property>();
    for (BeanPropertyDefinition propDef : beanDesc.findProperties()) {
        parseProperty(context, isNested, beanDesc, propertiesToIgnore, props, propDef);
    }

    Collections.sort(props, getPropertyComparator());

    Map<String, Property> modelProps = new LinkedHashMap<String, Property>();
    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;
}

From source file:uk.gov.gchq.gaffer.rest.service.GraphConfigurationService.java

@SuppressFBWarnings(value = "REC_CATCH_EXCEPTION", justification = "Need to wrap all runtime exceptions before they are given to the user")
@Override/*from  w w w  .  j a  v a  2s .  c  o  m*/
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;
}