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

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

Introduction

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

Prototype

public abstract String getName();

Source Link

Usage

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   ww  w  .  j a  v  a  2 s .c  o 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:springfox.documentation.schema.property.PojoPropertyBuilderFactory.java

/**
 * Applies to constructor/* www.j  a  va 2  s. c  o  m*/
   new POJOPropertyBuilder(new PropertyName(beanProperty.getName()),  annotationIntrospector,  true);
 */
private Optional<POJOPropertyBuilder> jackson26Instance(BeanPropertyDefinition beanProperty,
        AnnotationIntrospector annotationIntrospector, boolean forSerialization) {
    try {
        Constructor<POJOPropertyBuilder> constructor = constructorWithParams(PropertyName.class,
                AnnotationIntrospector.class, Boolean.TYPE);

        return Optional.of(constructor.newInstance(new PropertyName(beanProperty.getName()),
                annotationIntrospector, forSerialization));
    } catch (Exception e) {
        LOG.debug("Unable to instantiate jackson 26 object", e);
    }
    return Optional.absent();
}

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

@Override
public void serialize(Entity entity, JsonGenerator gen, SerializerProvider serializers)
        throws IOException, JsonProcessingException {
    gen.writeStartObject();// w  w  w .j av a  2  s.  c  om
    try {
        BasicBeanDescription beanDescription = serializers.getConfig()
                .introspect(serializers.constructType(entity.getClass()));
        List<BeanPropertyDefinition> properties = beanDescription.findProperties();
        for (BeanPropertyDefinition property : properties) {
            // 0. check if it should be serialized
            if (selectedProperties != null) {
                if (!selectedProperties.contains(property.getName())) {
                    continue;
                }
            }
            // 1. is it a NavigableElement?
            if (NavigableElement.class.isAssignableFrom(property.getAccessor().getRawType())) {
                Object rawValue = property.getAccessor().getValue(entity);
                if (rawValue != null) {
                    NavigableElement value = (NavigableElement) rawValue;
                    // If navigation link set, output navigation link.
                    if (value.getNavigationLink() != null && !value.getNavigationLink().isEmpty()) {
                        gen.writeFieldName(property.getName() + "@iot.navigationLink");
                        gen.writeString(value.getNavigationLink());
                    }
                    // If object should not be exported, skip any further processing.
                    if (!value.isExportObject()) {
                        continue;
                    }
                }
            }
            // 2. check if property has CustomSerialization annotation -> use custom serializer
            Annotation annotation = property.getAccessor().getAnnotation(CustomSerialization.class);
            if (annotation != null) {
                serializeFieldCustomized(entity, gen, property, properties, (CustomSerialization) annotation);
            } else {
                serializeField(entity, gen, serializers, beanDescription, property);
            }
            // 3. check if property is EntitySet than eventually write count
            if (EntitySet.class.isAssignableFrom(property.getAccessor().getRawType())) {
                Object rawValue = property.getAccessor().getValue(entity);
                if (rawValue != null) {
                    EntitySet set = (EntitySet) rawValue;
                    long count = set.getCount();
                    if (count >= 0) {
                        gen.writeNumberField(property.getName() + "@iot.count", count);
                    }
                    String nextLink = set.getNextLink();
                    if (nextLink != null) {
                        gen.writeStringField(property.getName() + "@iot.nextLink", nextLink);
                    }
                }
            }
        }
    } catch (Exception e) {
        LOGGER.error("could not serialize Entity", e);
        throw new IOException("could not serialize Entity", e);
    } finally {
        gen.writeEndObject();
    }
}

From source file:nl.talsmasoftware.enumerables.support.json.jackson2.EnumerableSerializer.java

private void serializeObject(Enumerable value, JsonGenerator jgen, SerializationConfig config)
        throws IOException {
    jgen.writeStartObject();/*from   w  w  w. ja v  a2s .  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:springfox.documentation.schema.property.ObjectMapperBeanPropertyNamingStrategy.java

@Override
public String nameForSerialization(final BeanPropertyDefinition beanProperty) {

    SerializationConfig serializationConfig = objectMapper.getSerializationConfig();

    Optional<PropertyNamingStrategy> namingStrategy = Optional
            .fromNullable(serializationConfig.getPropertyNamingStrategy());
    String newName = namingStrategy
            .transform(BeanPropertyDefinitions.overTheWireName(beanProperty, serializationConfig))
            .or(beanProperty.getName());

    LOG.debug("Name '{}' renamed to '{}'", beanProperty.getName(), newName);

    return newName;
}

From source file:springfox.documentation.schema.property.ObjectMapperBeanPropertyNamingStrategy.java

@Override
public String nameForDeserialization(final BeanPropertyDefinition beanProperty) {

    DeserializationConfig deserializationConfig = objectMapper.getDeserializationConfig();

    Optional<PropertyNamingStrategy> namingStrategy = Optional
            .fromNullable(deserializationConfig.getPropertyNamingStrategy());
    String newName = namingStrategy
            .transform(BeanPropertyDefinitions.overTheWireName(beanProperty, deserializationConfig))
            .or(beanProperty.getName());

    LOG.debug("Name '{}' renamed to '{}'", beanProperty.getName(), newName);

    return newName;
}

From source file:springfox.documentation.schema.property.PojoPropertyBuilderFactory.java

/**
 * Applies to constructor// ww  w. j a va2s . c  o m
    new POJOPropertyBuilder(
config,
annotationIntrospector,
forSerialization,
new PropertyName(beanProperty.getName()))
 */
private POJOPropertyBuilder jackson27Instance(MapperConfig<?> config, BeanPropertyDefinition beanProperty,
        AnnotationIntrospector annotationIntrospector, boolean forSerialization) {
    try {
        Constructor<POJOPropertyBuilder> constructor = constructorWithParams(MapperConfig.class,
                AnnotationIntrospector.class, Boolean.TYPE, PropertyName.class);

        return constructor.newInstance(config, annotationIntrospector, forSerialization,
                new PropertyName(beanProperty.getName()));
    } catch (Exception e) {
        throw new InstantiationError("Unable to create an instance of POJOPropertyBuilder");
    }
}

From source file:org.springframework.data.rest.webmvc.json.PersistentEntityToJsonSchemaConverter.java

private JsonSchemaProperty getSchemaProperty(BeanPropertyDefinition definition, TypeInformation<?> type,
        ResourceDescription description) {

    String name = definition.getName();
    String title = resolveMessageWithDefault(new ResolvableProperty(definition));
    String resolvedDescription = resolveMessage(description);
    boolean required = definition.isRequired();
    Class<?> rawType = type.getType();

    if (!rawType.isEnum()) {
        return new JsonSchemaProperty(name, title, resolvedDescription, required).with(type);
    }/* w w  w  . ja v  a  2s . c  om*/

    String message = resolveMessage(new DefaultMessageSourceResolvable(description.getMessage()));

    return new EnumProperty(name, title, rawType,
            description.getDefaultMessage().equals(resolvedDescription) ? message : resolvedDescription,
            required);
}

From source file:org.springframework.data.rest.webmvc.alps.RootResourceInformationToAlpsDescriptorConverter.java

private List<Descriptor> createJacksonDescriptor(String name, Class<?> type) {

    List<Descriptor> descriptors = new ArrayList<Descriptor>();

    for (BeanPropertyDefinition definition : new JacksonMetadata(mapper, type)) {

        AnnotatedMethod getter = definition.getGetter();
        Description description = getter.getAnnotation(Description.class);
        ResourceDescription fallback = SimpleResourceDescription
                .defaultFor(String.format("%s.%s", name, definition.getName()));
        ResourceDescription resourceDescription = description == null ? null
                : new AnnotationBasedResourceDescription(description, fallback);

        descriptors.add(//
                descriptor().//
                        name(definition.getName()).//
                        type(Type.SEMANTIC).//
                        doc(getDocFor(resourceDescription)).//
                        build());/*from w w  w . ja v  a2  s .  c om*/
    }

    return descriptors;
}

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

protected void serializeFieldCustomized(Entity entity, JsonGenerator gen, BeanPropertyDefinition property,
        List<BeanPropertyDefinition> properties, CustomSerialization annotation) throws Exception {
    // check if encoding field is present in current bean
    // get calue/*from  ww w. j a  va2s .co m*/
    // call CustomSerializationManager
    Optional<BeanPropertyDefinition> encodingProperty = properties.stream()
            .filter(p -> p.getName().equals(annotation.encoding())).findFirst();
    if (!encodingProperty.isPresent()) {
        // TODO use more specific exception type
        throw new Exception("can not serialize instance of class '" + entity.getClass() + "'! \n"
                + "Reason: trying to use custom serialization for field '" + property.getName()
                + "' but field '" + annotation.encoding() + "' specifying enconding is not present!");
    }
    Object value = encodingProperty.get().getAccessor().getValue(entity);
    String encodingType = null;
    if (value != null) {
        encodingType = value.toString();
    }
    String customJson = CustomSerializationManager.getInstance().getSerializer(encodingType)
            .serialize(property.getAccessor().getValue(entity));
    if (customJson != null && !customJson.isEmpty()) {
        gen.writeFieldName(property.getName());
        gen.writeRawValue(customJson);
    }
}