Java Code Examples for com.fasterxml.jackson.databind.BeanDescription#findProperties()

The following examples show how to use com.fasterxml.jackson.databind.BeanDescription#findProperties() . 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: 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 2
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 3
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 4
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 5
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();
}
 
Example 6
Source File: MixinSerForMethodsJacksonTest.java    From gwt-jackson with Apache License 2.0 5 votes vote down vote up
@Test
public void testIntermediateMixin() {
    objectMapper.addMixIn( BaseClass.class, MixIn.class );

    JavaType type = objectMapper.getTypeFactory().constructType( LeafClass.class );
    BeanDescription desc = objectMapper.getSerializationConfig().introspect( type );
    List<BeanPropertyDefinition> props = desc.findProperties();

    MixinSerForMethodsTester.INSTANCE.testIntermediateMixin( createWriter( LeafClass.class ) );
}
 
Example 7
Source File: SerializerOfExecutionResult.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 4 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void serialize(ExecutionResult value, JsonGenerator jgen, SerializerProvider provider)
            throws IOException, JsonGenerationException
{
    
    SerializationConfig config = provider.getConfig();
    Object rootObj = value.getRoot();
    if (rootObj == null)
    {
        provider.getDefaultNullValueSerializer().serialize(null, jgen, provider);
    }
    else
    {
        Class<?> cls = rootObj.getClass();
        Map toBeSerialized = new HashMap(); //create an untyped map, add the contents of the root + the embeds.
        BeanPropertiesFilter filter = value.getFilter();
        if (filter == null) filter = BeanPropertiesFilter.ALLOW_ALL;
        
        if (Map.class.isAssignableFrom(cls))
        {
            // Its a map so 
            Map rootAsaMap = (Map) rootObj;
            toBeSerialized.putAll(rootAsaMap);
        }
        else
        {
            JavaType classType = config.constructType(cls);
            BeanDescription beanDesc = provider.getConfig().introspect(classType);
            List<BeanPropertyDefinition> props = beanDesc.findProperties();
            for (BeanPropertyDefinition beanProperty : props)
            {
                if (beanProperty.couldSerialize() && filter.isAllowed(beanProperty.getName()))
                {
                    Object propertyValue = ResourceInspectorUtil.invokeMethod(beanProperty.getGetter().getAnnotated(), rootObj);
                    if (propertyValue != null)
                    {
                        if((propertyValue instanceof String))
                        {
                        	if(((String)propertyValue).trim().length() > 0)
                        	{
                        		toBeSerialized.put(beanProperty.getName(), propertyValue);
                        	}
                        }
                        else
                        {
                        	toBeSerialized.put(beanProperty.getName(), propertyValue);
                        }
                    }
                }
            }
        }
        
        //Add embedded
        for (Entry<String, Object> embedded : value.getEmbedded().entrySet())
        {
            if (filter == null || filter.isAllowed(embedded.getKey()))
            {
              toBeSerialized.put(embedded.getKey(),embedded.getValue());
            }
        }

        //if its an embedded entity then render the properties (not as an "entry:")
        if (value.isAnEmbeddedEntity())
        {
            jgen.writeObject(toBeSerialized);
        }
        else
        {
            jgen.writeStartObject();
            jgen.writeObjectField("entry", toBeSerialized);
            if (value.getRelated() != null && !value.getRelated().isEmpty())
            {
              jgen.writeObjectField("relations", value.getRelated());
            }
            jgen.writeEndObject();
        }

    }

}
 
Example 8
Source File: ConversionServiceBeanSerializerModifier.java    From gvnix with GNU General Public License v3.0 4 votes vote down vote up
@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);
    }

    // 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;
}