com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition Java Examples

The following examples show how to use com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BeanDeserializerModifierForIgnorables.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
@Override
public List<BeanPropertyDefinition> updateProperties(
	DeserializationConfig config, BeanDescription beanDesc,
	List<BeanPropertyDefinition> propDefs) {
	if (!type.equals(beanDesc.getBeanClass())) {
		return propDefs;
	}

	List<BeanPropertyDefinition> newPropDefs = new ArrayList<>();
	for (BeanPropertyDefinition propDef : propDefs) {
		if (!ignorables.contains(propDef.getName())) {
			newPropDefs.add(propDef);
		}
	}
	return newPropDefs;
}
 
Example #2
Source File: JsonConfigurator.java    From druid-api with Apache License 2.0 6 votes vote down vote up
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
          )
      );
    }
  }
}
 
Example #3
Source File: ConfigObjectFactory.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
private void doCreate() {
  JavaType javaType = TypeFactory.defaultInstance().constructType(cls);
  BeanDescription beanDescription = JsonUtils.OBJ_MAPPER.getSerializationConfig().introspect(javaType);
  for (BeanPropertyDefinition propertyDefinition : beanDescription.findProperties()) {
    if (propertyDefinition.getField() == null) {
      continue;
    }

    if (propertyDefinition.getSetter() == null && !propertyDefinition.getField().isPublic()) {
      continue;
    }

    SetterWrapper setter = propertyDefinition.getSetter() == null ?
        new SetterWrapper(LambdaMetafactoryUtils.createSetter(propertyDefinition.getField().getAnnotated())) :
        new SetterWrapper(LambdaMetafactoryUtils.createSetter(propertyDefinition.getSetter().getAnnotated()));

    PriorityProperty<?> priorityProperty = createPriorityProperty(propertyDefinition.getField().getAnnotated());
    priorityProperty.setCallback((value, target) -> setter.set(target, value), instance);
    priorityProperties.add(priorityProperty);
  }
}
 
Example #4
Source File: SerializerProvider.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Helper method called to indicate problem in POJO (serialization) definitions or settings
 * regarding specific property (of a type), unrelated to actual JSON content to map.
 * Default behavior is to construct and throw a {@link JsonMappingException}.
 *
 * @since 2.9
 */
public <T> T reportBadPropertyDefinition(BeanDescription bean, BeanPropertyDefinition prop,
        String message, Object... msgArgs) throws JsonMappingException {
    message = _format(message, msgArgs);
    String propName = "N/A";
    if (prop != null) {
        propName = _quotedString(prop.getName());
    }
    String beanDesc = "N/A";
    if (bean != null) {
        beanDesc = ClassUtil.nameOf(bean.getBeanClass());
    }
    message = String.format("Invalid definition for property %s (of type %s): %s",
            propName, beanDesc, message);
    throw InvalidDefinitionException.from(getGenerator(), message, bean, prop);
}
 
Example #5
Source File: JsonSchemaBuilder.java    From moserp with Apache License 2.0 6 votes vote down vote up
private void populateProperties(Class<?> domainType, BusinessEntity entity) {
    Map<String, EntityProperty> properties = new HashMap<>();
    final PersistentEntity<?, ?> persistentEntity = persistentEntities.getPersistentEntity(domainType);
    JacksonMetadata jacksonMetadata = new JacksonMetadata(objectMapper, domainType);
    for (BeanPropertyDefinition definition : jacksonMetadata) {
        PersistentProperty<?> persistentProperty = persistentEntity.getPersistentProperty(definition.getInternalName());
        PropertyFactoryContext context = new PropertyFactoryContext(definition, jacksonMetadata, persistentProperty);
        PropertyFactory factory = getFactoryFor(context);
        if (factory != null) {
            EntityProperty property = factory.create(context);
            properties.put(definition.getInternalName(), property);
            if(property.isRequired()) {
                entity.getRequired().add(definition.getInternalName());
            }
        }
    }
    entity.setProperties(properties);
}
 
Example #6
Source File: AbstractOperationGenerator.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
protected void extractAggregatedParameterGenerators(Map<String, List<Annotation>> methodAnnotationMap,
    java.lang.reflect.Parameter methodParameter) {
  JavaType javaType = TypeFactory.defaultInstance().constructType(methodParameter.getParameterizedType());
  BeanDescription beanDescription = Json.mapper().getSerializationConfig().introspect(javaType);
  for (BeanPropertyDefinition propertyDefinition : beanDescription.findProperties()) {
    if (!propertyDefinition.couldSerialize()) {
      continue;
    }

    Annotation[] annotations = collectAnnotations(propertyDefinition);
    ParameterGenerator propertyParameterGenerator = new ParameterGenerator(method,
        methodAnnotationMap,
        propertyDefinition.getName(),
        annotations,
        propertyDefinition.getPrimaryType().getRawClass());
    parameterGenerators.add(propertyParameterGenerator);
  }
}
 
Example #7
Source File: BeanDeserializerModifierForIgnorables.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
public List<BeanPropertyDefinition> updateProperties(
	DeserializationConfig config, BeanDescription beanDesc,
	List<BeanPropertyDefinition> propDefs) {
	if (!type.equals(beanDesc.getBeanClass())) {
		return propDefs;
	}

	List<BeanPropertyDefinition> newPropDefs = new ArrayList<>();
	for (BeanPropertyDefinition propDef : propDefs) {
		if (!ignorables.contains(propDef.getName())) {
			newPropDefs.add(propDef);
		}
	}
	return newPropDefs;
}
 
Example #8
Source File: JacksonValueMapper.java    From graphql-spqr with Apache License 2.0 6 votes vote down vote up
private boolean isIncluded(AnnotatedType declaringType, BeanPropertyDefinition prop, boolean deserializableInSubType, InclusionStrategy inclusionStrategy) {
    List<AnnotatedElement> elements = Utils.flatten(
            Optional.ofNullable(prop.getConstructorParameter()).map(ElementFactory::getParameter),
            Optional.ofNullable(prop.getSetter()).map(Annotated::getAnnotated),
            Optional.ofNullable(prop.getGetter()).map(Annotated::getAnnotated),
            Optional.ofNullable(prop.getField()).map(Annotated::getAnnotated))
            .collect(Collectors.toList());

    InputFieldInclusionParams params = InputFieldInclusionParams.builder()
            .withType(declaringType)
            .withElementDeclaringClass(prop.getPrimaryMember().getDeclaringClass())
            .withElements(elements)
            .withDeserializationInfo(prop.couldDeserialize(), deserializableInSubType)
            .build();

    return inclusionStrategy.includeInputField(params);
}
 
Example #9
Source File: BeanDeserializerModifierForIgnorables.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
public List<BeanPropertyDefinition> updateProperties(
	DeserializationConfig config, BeanDescription beanDesc,
	List<BeanPropertyDefinition> propDefs) {
	if (!type.equals(beanDesc.getBeanClass())) {
		return propDefs;
	}

	List<BeanPropertyDefinition> newPropDefs = new ArrayList<>();
	for (BeanPropertyDefinition propDef : propDefs) {
		if (!ignorables.contains(propDef.getName())) {
			newPropDefs.add(propDef);
		}
	}
	return newPropDefs;
}
 
Example #10
Source File: EntitySerializer.java    From FROST-Server with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void writeCountNextlinkForSet(BeanPropertyDefinition property, Entity entity, JsonGenerator gen) throws IOException {
    Object rawValue = property.getAccessor().getValue(entity);
    if (rawValue == null) {
        return;
    }
    EntitySet set = (EntitySet) rawValue;
    long count = set.getCount();
    if (count >= 0) {
        gen.writeNumberField(property.getName() + AT_IOT_COUNT, count);
    }
    String nextLink = set.getNextLink();
    if (nextLink != null) {
        gen.writeStringField(property.getName() + AT_IOT_NEXT_LINK, nextLink);
    }
}
 
Example #11
Source File: VirtualPropertiesWriter.java    From log4j2-elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public VirtualPropertiesWriter withConfig(MapperConfig<?> config, AnnotatedClass declaringClass, BeanPropertyDefinition propDef, JavaType type) {
    return new VirtualPropertiesWriter(
            propDef,
            new AnnotationCollector.OneAnnotation(
                    declaringClass.getRawType(),
                    declaringClass.getAnnotations().get(JsonAppend.class)
            ),
            type,
            virtualProperties,
            valueResolver,
            filters
    );
}
 
Example #12
Source File: EntitySerializer.java    From FROST-Server with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected void serializeFieldCustomized(
        Entity entity,
        JsonGenerator gen,
        BeanPropertyDefinition property,
        List<BeanPropertyDefinition> properties,
        CustomSerialization annotation) throws IOException {
    // check if encoding field is present in current bean
    // get value
    // call CustomSerializationManager
    Optional<BeanPropertyDefinition> encodingProperty = properties.stream().filter(p -> p.getName().equals(annotation.encoding())).findFirst();
    if (!encodingProperty.isPresent()) {
        throw new JsonGenerationException("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!",
                gen);
    }
    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);
    }
}
 
Example #13
Source File: InvalidDefinitionException.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected InvalidDefinitionException(JsonParser p, String msg,
        BeanDescription bean, BeanPropertyDefinition prop) {
    super(p, msg);
    _type = (bean == null) ? null : bean.getType();
    _beanDesc = bean;
    _property = prop;
}
 
Example #14
Source File: EntitySerializer.java    From FROST-Server with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void serialize(Entity entity, JsonGenerator gen, SerializerProvider serializers) throws IOException {
    gen.writeStartObject();
    try {
        BasicBeanDescription beanDescription = serializers.getConfig().introspect(serializers.constructType(entity.getClass()));
        List<BeanPropertyDefinition> properties = beanDescription.findProperties();
        for (BeanPropertyDefinition property : properties) {
            serializeProperty(property, entity, properties, gen, serializers, beanDescription);
        }
    } catch (IOException | RuntimeException exc) {
        throw new IOException("could not serialize Entity", exc);
    } finally {
        gen.writeEndObject();
    }
}
 
Example #15
Source File: EntitySerializer.java    From FROST-Server with GNU Lesser General Public License v3.0 5 votes vote down vote up
private boolean serialiseNavigationElement(BeanPropertyDefinition property, Entity entity, boolean selected, JsonGenerator gen) throws IOException {
    Object rawValue = property.getAccessor().getValue(entity);
    if (rawValue == null) {
        return selected;
    }
    NavigableElement<?> value = (NavigableElement<?>) rawValue;
    // If navigation link set, and selected, output navigation link.
    if (selected && value.getNavigationLink() != null && !value.getNavigationLink().isEmpty()) {
        gen.writeFieldName(property.getName() + AT_IOT_NAVIGATION_LINK);
        gen.writeString(value.getNavigationLink());
    }
    // If object should not be exported, skip any further processing.
    return value.isExportObject();
}
 
Example #16
Source File: CustomEntityDeserializer.java    From FROST-Server with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void deserialiseProperty(JsonNode obj, BeanPropertyDefinition classProperty, List<BeanPropertyDefinition> properties, ObjectMapper mapper, T result) throws IOException {
    if (obj.has(classProperty.getName())) {
        // property is present in class and json
        Annotation annotation = classProperty.getAccessor().getAnnotation(CustomSerialization.class);
        if (annotation == null) {
            Object value = mapper.convertValue(
                    obj.get(classProperty.getName()),
                    classProperty.getField().getType());
            classProperty.getMutator().setValue(result, value);
        } else {
            // 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);
        }
    }
}
 
Example #17
Source File: EntitySerializer.java    From FROST-Server with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected void serializeField(
        Entity entity,
        JsonGenerator gen,
        SerializerProvider serializers,
        BeanDescription beanDescription,
        BeanPropertyDefinition beanPropertyDefinition) {
    serializeFieldTyped(entity, gen, serializers, beanDescription, beanPropertyDefinition, null);
}
 
Example #18
Source File: TestVirtualProperties.java    From jackson-modules-base with Apache License 2.0 5 votes vote down vote up
@Override
public VirtualBeanPropertyWriter withConfig(MapperConfig<?> config,
        AnnotatedClass declaringClass, BeanPropertyDefinition propDef,
        JavaType type)
{
    return new CustomVProperty(propDef, declaringClass.getAnnotations(), type);
}
 
Example #19
Source File: JacksonValueMapper.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
protected Object defaultValue(AnnotatedType declaringType, BeanPropertyDefinition prop, AnnotatedType fieldType, TypeTransformer typeTransformer, GlobalEnvironment environment) {
    ElementFactory elementFactory = new ElementFactory(declaringType, typeTransformer);
    List<TypedElement> annotatedCandidates = Utils.flatten(
            Optional.ofNullable(prop.getConstructorParameter()).map(elementFactory::fromConstructorParameter),
            Optional.ofNullable(prop.getSetter()).map(elementFactory::fromSetter),
            Optional.ofNullable(prop.getGetter()).map(elementFactory::fromGetter),
            Optional.ofNullable(prop.getField()).map(elementFactory::fromField)
    ).collect(Collectors.toList());
    return inputInfoGen.defaultValue(annotatedCandidates, fieldType, environment).orElse(null);
}
 
Example #20
Source File: KeeperBeanDeserializerModifier.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
@Override
public BeanDeserializerBuilder updateBuilder(DeserializationConfig config, BeanDescription beanDesc, BeanDeserializerBuilder builder) {
    for (BeanPropertyDefinition propDef : beanDesc.findProperties()) {
        if (!propDef.hasGetter() || propDef.hasSetter()) {
            continue;
        }
        AnnotatedMember getter = propDef.getAccessor();
        if (!Keeper.class.equals(getter.getRawType())) {
            continue;
        }

        builder.addOrReplaceProperty(new CustomGetterBeanProperty(propDef, getter), true);
    }
    return builder;
}
 
Example #21
Source File: JacksonValueMapper.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
TypedElement fromProperty(BeanPropertyDefinition prop) {
    Optional<TypedElement> constParam = Optional.ofNullable(prop.getConstructorParameter()).map(this::fromConstructorParameter);
    Optional<TypedElement> setter = Optional.ofNullable(prop.getSetter()).map(this::fromSetter);
    Optional<TypedElement> getter = Optional.ofNullable(prop.getGetter()).map(this::fromGetter);
    Optional<TypedElement> field = Optional.ofNullable(prop.getField()).map(this::fromField);

    Optional<TypedElement> mutator = Utils.flatten(constParam, setter, field).findFirst();
    Optional<TypedElement> explicit = Utils.flatten(constParam, setter, getter, field).filter(e -> e.isAnnotationPresent(GraphQLInputField.class)).findFirst();

    List<TypedElement> elements = Utils.flatten(explicit, mutator, field).collect(Collectors.toList());
    if (elements.isEmpty()) {
        elements = getter.map(Collections::singletonList).orElse(Collections.emptyList());
    }
    return new TypedElement(elements);
}
 
Example #22
Source File: CustomEntityDeserializer.java    From FROST-Server with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public T deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException {
    T result;
    try {
        result = clazz.getDeclaredConstructor().newInstance();
    } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException ex) {
        throw new IOException("Error deserializing JSON!", ex);
    }
    // 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 = 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)) {
        while (i.hasNext()) {
            Map.Entry<String, JsonNode> next = i.next();
            String fieldName = next.getKey();
            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) {
        deserialiseProperty(obj, classProperty, properties, mapper, result);
    }
    return result;
}
 
Example #23
Source File: VirtualPropertiesWriter.java    From log4j2-elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * This constructor should not be invoked directly and should only be used within
 * {@link #withConfig(MapperConfig, AnnotatedClass, BeanPropertyDefinition, JavaType)} call.
 *
 * @param propDef property definition created by {@code by com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector}
 * @param annotations contains only @JsonAppend at the moment
 * @param type {@link VirtualProperty}[]
 * @param virtualProperties {@link VirtualProperty}-ies to append
 * @param valueResolver {@link ValueResolver} dynamic variables resolver
 * @param filters {@link VirtualPropertyFilter} inclusion filters. Allow to include/exclude
 * {@link VirtualProperty} by name or value returned by {@link ValueResolver}
 */
VirtualPropertiesWriter(
        BeanPropertyDefinition propDef,
        Annotations annotations,
        JavaType type,
        VirtualProperty[] virtualProperties,
        ValueResolver valueResolver,
        VirtualPropertyFilter[] filters
) {
    super(propDef, annotations, type);
    this.virtualProperties = virtualProperties;
    this.valueResolver = valueResolver;
    this.filters = filters;
}
 
Example #24
Source File: ApplicationStructureBuilder.java    From moserp with Apache License 2.0 5 votes vote down vote up
private List<EntityProperty> buildProperties(Class<?> domainType) {
    List<EntityProperty> properties = new ArrayList<>();
    final PersistentEntity<?, ?> persistentEntity = persistentEntities.getPersistentEntity(domainType);
    JacksonMetadata jacksonMetadata = new JacksonMetadata(objectMapper, domainType);
    for (BeanPropertyDefinition definition : jacksonMetadata) {
        PersistentProperty<?> persistentProperty = persistentEntity.getPersistentProperty(definition.getInternalName());
        PropertyFactoryContext context = new PropertyFactoryContext(definition, jacksonMetadata, persistentProperty);
        PropertyFactory factory = getFactoryFor(context);
        if (factory != null) {
            properties.add(factory.create(context));
        }
    }
    return properties;
}
 
Example #25
Source File: ConstraintViolationExceptionMapper.java    From microservices-springboot with MIT License 5 votes vote down vote up
/**
 * Get the JSON property name.
 *
 * @param mapper
 * @param beanClass
 * @param nodeName
 * @return
 */
private Optional<String> getJsonPropertyName(ObjectMapper mapper, Class<?> beanClass, String nodeName) {

    JavaType javaType = mapper.getTypeFactory().constructType(beanClass);
    BeanDescription introspection = mapper.getSerializationConfig().introspect(javaType);
    List<BeanPropertyDefinition> properties = introspection.findProperties();

    return properties.stream()
            .filter(propertyDefinition -> nodeName.equals(propertyDefinition.getField().getName()))
            .map(BeanPropertyDefinition::getName)
            .findFirst();
}
 
Example #26
Source File: DeserializationContext.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Helper method called to indicate problem in POJO (serialization) definitions or settings
 * regarding specific property (of a type), unrelated to actual JSON content to map.
 * Default behavior is to construct and throw a {@link JsonMappingException}.
 *
 * @since 2.9
 */
public <T> T reportBadPropertyDefinition(BeanDescription bean, BeanPropertyDefinition prop,
        String msg, Object... msgArgs) throws JsonMappingException {
    msg = _format(msg, msgArgs);
    String propName = ClassUtil.nameOf(prop);
    String beanDesc = ClassUtil.nameOf(bean.getBeanClass());
    msg = String.format("Invalid definition for property %s (of type %s): %s",
            propName, beanDesc, msg);
    throw InvalidDefinitionException.from(_parser, msg, bean, prop);
}
 
Example #27
Source File: DeserializerModifier.java    From requery with Apache License 2.0 5 votes vote down vote up
@Override
public List<BeanPropertyDefinition> updateProperties(DeserializationConfig config,
                                                     BeanDescription beanDesc,
                                                     List<BeanPropertyDefinition> propDefs) {
    List<BeanPropertyDefinition> definitions = super.updateProperties(config, beanDesc, propDefs);
    List<BeanPropertyDefinition> remove = new ArrayList<>();
    List<BeanPropertyDefinition> add = new ArrayList<>();
    for (BeanPropertyDefinition definition : definitions) {
        if (definition.hasGetter() &&
                Collection.class.isAssignableFrom(definition.getGetter().getRawType())) {

            if (definition instanceof POJOPropertyBuilder) {
                POJOPropertyBuilder builder = (POJOPropertyBuilder) definition;
                builder = new POJOPropertyBuilder(builder, builder.getFullName()) {
                    @Override
                    public boolean hasField() {
                        return false; // forces the getter to be used on the collection
                    }
                };
                remove.add(definition);
                add.add(builder);
            }
        }
    }

    definitions.removeAll(remove);
    definitions.addAll(add);

    return definitions;
}
 
Example #28
Source File: JacksonDeserializer.java    From hawkular-alerts with Apache License 2.0 5 votes vote down vote up
@Override
public List<BeanPropertyDefinition> updateProperties(DeserializationConfig config,
        BeanDescription beanDesc, List<BeanPropertyDefinition> propDefs) {
    if (!thinnables.contains(beanDesc.getBeanClass())) {
        return propDefs;
    }
    List<BeanPropertyDefinition> newPropDefs = new ArrayList<>();
    for (BeanPropertyDefinition propDef : propDefs) {
        if (!ignorables.contains(propDef.getName())) {
            newPropDefs.add(propDef);
        }
    }
    return newPropDefs;
}
 
Example #29
Source File: InvalidDefinitionException.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected InvalidDefinitionException(JsonGenerator g, String msg,
        BeanDescription bean, BeanPropertyDefinition prop) {
    super(g, msg);
    _type = (bean == null) ? null : bean.getType();
    _beanDesc = bean;
    _property = prop;
}
 
Example #30
Source File: JacksonResourceSchemaProvider.java    From endpoints-java with Apache License 2.0 5 votes vote down vote up
@Override
public ResourceSchema getResourceSchema(TypeToken<?> type, ApiConfig config) {
  ResourceSchema schema = super.getResourceSchema(type, config);
  if (schema != null) {
    return schema;
  }
  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.atWarning().log("skipping field '%s' of type '%s' because it is unresolved.", name,
            propertyType);
        continue;
      }
      if (propertyType != null) {
        ResourcePropertySchema propertySchema = ResourcePropertySchema.of(propertyType);
        propertySchema.setDescription(definition.getMetadata().getDescription());
        schemaBuilder.addProperty(name, propertySchema);
      } else {
        logger.atWarning().log("No type found for property '%s' on class '%s'.", name, type);
      }
    } else {
      logger.atFine()
          .log("skipping field '%s' because it's not a Java client model field.", name);
    }
  }
  return schemaBuilder.build();
}