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

The following examples show how to use com.fasterxml.jackson.databind.introspect.AnnotatedField. 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: 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 #2
Source File: SettableAnyProperty.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public void set(Object instance, Object propName, Object value) throws IOException
{
    try {
        // if annotation in the field (only map is supported now)
        if (_setterIsField) {
            AnnotatedField field = (AnnotatedField) _setter;
            Map<Object,Object> val = (Map<Object,Object>) field.getValue(instance);
            /* 01-Jun-2016, tatu: At this point it is not quite clear what to do if
             *    field is `null` -- we cannot necessarily count on zero-args
             *    constructor except for a small set of types, so for now just
             *    ignore if null. May need to figure out something better in future.
             */
            if (val != null) {
                // add the property key and value
                val.put(propName, value);
            }
        } else {
            // note: cannot use 'setValue()' due to taking 2 args
            ((AnnotatedMethod) _setter).callOnWith(instance, propName, value);
        }
    } catch (Exception e) {
        _throwAsIOE(e, propName, value);
    }
}
 
Example #3
Source File: TestJaxbAnnotationIntrospector.java    From jackson-modules-base with Apache License 2.0 6 votes vote down vote up
/**
 * Additional simple tests to ensure we will retain basic namespace information
 * now that it can be included
 */
public void testNamespaces() throws Exception
{
    final TypeFactory tf = MAPPER.getTypeFactory();
    JaxbAnnotationIntrospector ai = new JaxbAnnotationIntrospector();
    AnnotatedClass ac = AnnotatedClassResolver.resolve(MAPPER.serializationConfig(),
            tf.constructType(NamespaceBean.class), null);
    AnnotatedField af = _findField(ac, "string");
    assertNotNull(af);
    PropertyName pn = ai.findNameForDeserialization(MAPPER.serializationConfig(), af);
    assertNotNull(pn);

    // JAXB seems to assert field name instead of giving "use default"...
    assertEquals("", pn.getSimpleName());
    assertEquals("urn:method", pn.getNamespace());
}
 
Example #4
Source File: JacksonResourceSchemaProvider.java    From endpoints-java with Apache License 2.0 6 votes vote down vote up
@Nullable
private TypeToken<?> getPropertyType(TypeToken<?> beanType, Method readMethod, Method writeMethod,
    AnnotatedField field, ApiConfig config) {
  if (readMethod != null) {
    // read method's return type is the property type
    return ApiAnnotationIntrospector.getSchemaType(
        beanType.resolveType(readMethod.getGenericReturnType()), config);
  } else if (writeMethod != null) {
    Type[] paramTypes = writeMethod.getGenericParameterTypes();
    if (paramTypes.length == 1) {
      // write method's first parameter type is the property type
      return ApiAnnotationIntrospector.getSchemaType(
          beanType.resolveType(paramTypes[0]), config);
    }
  } else if (field != null) {
    return ApiAnnotationIntrospector.getSchemaType(
        beanType.resolveType(field.getGenericType()), config);
  }
  return null;
}
 
Example #5
Source File: AnnotatedFieldBuilder.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
private static AnnotatedField buildAnnotatedField(AnnotatedClass annotatedClass, Field field,
												  AnnotationMap annotationMap, Constructor<?> constructor)
		throws IllegalAccessException, InstantiationException, InvocationTargetException {
	Class<?> firstParameterType = constructor.getParameterTypes()[0];

	PreconditionUtil.verify(firstParameterType == AnnotatedClass.class ||
			TypeResolutionContext.class.equals(firstParameterType), CANNOT_FIND_PROPER_CONSTRUCTOR);
	return (AnnotatedField) constructor.newInstance(annotatedClass, field, annotationMap);
}
 
Example #6
Source File: HbaseJsonEventSerializer.java    From searchanalytics-bigdata with MIT License 5 votes vote down vote up
@SuppressWarnings("rawtypes")
@Override
public String nameForField(MapperConfig config, AnnotatedField field,
		String defaultName) {
	return convert(defaultName);

}
 
Example #7
Source File: TestJaxbAnnotationIntrospector.java    From jackson-modules-base with Apache License 2.0 5 votes vote down vote up
private AnnotatedField _findField(AnnotatedClass ac, String name)
{
    for (AnnotatedField af : ac.fields()) {
        if (name.equals(af.getName())) {
            return af;
        }
    }
    return null;
}
 
Example #8
Source File: AnnotatedFieldBuilder.java    From katharsis-framework with Apache License 2.0 5 votes vote down vote up
private static AnnotatedField buildAnnotatedField(AnnotatedClass annotatedClass, Field field,
                                                  AnnotationMap annotationMap, Constructor<?> constructor)
        throws IllegalAccessException, InstantiationException, InvocationTargetException {
    Class<?> firstParameterType = constructor.getParameterTypes()[0];
    if (firstParameterType == AnnotatedClass.class ||
            "TypeResolutionContext".equals(firstParameterType.getSimpleName())) {
        return (AnnotatedField) constructor.newInstance(annotatedClass, field, annotationMap);
    } else {
        throw new InternalException(CANNOT_FIND_PROPER_CONSTRUCTOR);
    }
}
 
Example #9
Source File: AnnotatedFieldBuilder.java    From katharsis-framework with Apache License 2.0 5 votes vote down vote up
public static AnnotatedField build(AnnotatedClass annotatedClass, Field field, AnnotationMap annotationMap) {
    for(Constructor<?> constructor : AnnotatedField.class.getConstructors()) {
        try {
            return buildAnnotatedField(annotatedClass, field, annotationMap, constructor);
        } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {
            throw new InternalException("Exception while building " + AnnotatedField.class.getCanonicalName(), e);
        }
    }
    throw new InternalException(CANNOT_FIND_PROPER_CONSTRUCTOR);
}
 
Example #10
Source File: ResourceFieldNameTransformer.java    From katharsis-framework with Apache License 2.0 5 votes vote down vote up
public String getName(Field field) {

        String name = field.getName();
        if (field.isAnnotationPresent(JsonProperty.class) &&
            !"".equals(field.getAnnotation(JsonProperty.class).value())) {
            name = field.getAnnotation(JsonProperty.class).value();
        } else if (serializationConfig != null && serializationConfig.getPropertyNamingStrategy() != null) {
            AnnotationMap annotationMap = buildAnnotationMap(field.getDeclaredAnnotations());

            AnnotatedClass annotatedClass = AnnotatedClassBuilder.build(field.getDeclaringClass(), serializationConfig);
            AnnotatedField annotatedField = AnnotatedFieldBuilder.build(annotatedClass, field, annotationMap);
            name = serializationConfig.getPropertyNamingStrategy().nameForField(serializationConfig, annotatedField, name);
        }
        return name;
    }
 
Example #11
Source File: EsPropertyNamingStrategy.java    From soundwave with Apache License 2.0 5 votes vote down vote up
@Override
public String nameForField(MapperConfig<?> config, AnnotatedField field, String defaultName) {
  if (field.getDeclaringClass() == this.effectiveType) {
    return fieldToJsonMapping
        .getOrDefault(defaultName, super.nameForField(config, field, defaultName));
  } else {
    return super.nameForField(config, field, defaultName);
  }
}
 
Example #12
Source File: FieldProperty.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public FieldProperty(BeanPropertyDefinition propDef, JavaType type,
        TypeDeserializer typeDeser, Annotations contextAnnotations, AnnotatedField field)
{
    super(propDef, type, typeDeser, contextAnnotations);
    _annotated = field;
    _field = field.getAnnotated();
    _skipNulls = NullsConstantProvider.isSkipper(_nullProvider);
}
 
Example #13
Source File: SettableAnyProperty.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public SettableAnyProperty(BeanProperty property, AnnotatedMember setter, JavaType type,
        KeyDeserializer keyDeser,
        JsonDeserializer<Object> valueDeser, TypeDeserializer typeDeser)
{
    _property = property;
    _setter = setter;
    _type = type;
    _valueDeserializer = valueDeser;
    _valueTypeDeserializer = typeDeser;
    _keyDeserializer = keyDeser;
    _setterIsField = setter instanceof AnnotatedField;
}
 
Example #14
Source File: JacksonResourceFieldInformationProvider.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
protected Optional<String> getName(Field field) {
	ObjectMapper objectMapper = context.getObjectMapper();
	SerializationConfig serializationConfig = objectMapper.getSerializationConfig();

	if (serializationConfig != null && serializationConfig.getPropertyNamingStrategy() != null) {
		AnnotationMap annotationMap = buildAnnotationMap(field.getDeclaredAnnotations());

		AnnotatedClass annotatedClass = AnnotatedClassBuilder.build(field.getDeclaringClass(), serializationConfig);
		AnnotatedField annotatedField = AnnotatedFieldBuilder.build(annotatedClass, field, annotationMap);
		return Optional.of(serializationConfig.getPropertyNamingStrategy().nameForField(serializationConfig, annotatedField, field.getName()));
	}
	return Optional.empty();
}
 
Example #15
Source File: AnnotatedFieldBuilder.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
public static AnnotatedField build(final AnnotatedClass annotatedClass, final Field field,
								   final AnnotationMap annotationMap) {
	final Constructor<?> constructor = AnnotatedField.class.getConstructors()[0];
	return ExceptionUtil.wrapCatchedExceptions(new Callable<AnnotatedField>() {
		@Override
		public AnnotatedField call() throws Exception {
			return buildAnnotatedField(annotatedClass, field, annotationMap, constructor);
		}
	}, "Exception while building AnnotatedField");
}
 
Example #16
Source File: EntitySetCamelCaseNamingStrategy.java    From FROST-Server with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Override
public String nameForField(MapperConfig<?> config, AnnotatedField field, String defaultName) {
    return translate(defaultName, field.getRawType());
}
 
Example #17
Source File: MattermostPropertyNamingStrategy.java    From mattermost4j with Apache License 2.0 4 votes vote down vote up
@Override
public String nameForField(MapperConfig<?> config, AnnotatedField field, String defaultName) {
  return judgeStrategy(field).nameForField(config, field, defaultName);
}
 
Example #18
Source File: PropertyNamingStrategy.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public String nameForField(MapperConfig<?> config, AnnotatedField field, String defaultName)
{
    return translate(defaultName);
}
 
Example #19
Source File: JacksonValueMapper.java    From graphql-spqr with Apache License 2.0 4 votes vote down vote up
TypedElement fromField(AnnotatedField fld) {
    Field field = fld.getAnnotated();
    AnnotatedType fieldType = transform(ClassUtils.getFieldType(field, type), field, type);
    return new TypedElement(fieldType, field);
}
 
Example #20
Source File: JsonldPropertyNamingStrategy.java    From jackson-jsonld with MIT License 4 votes vote down vote up
@Override
public String nameForField(MapperConfig<?> config, AnnotatedField field, String defaultName) {
    String name = config instanceof DeserializationConfig? jsonldName(field): null;
    return Optional.ofNullable(name).orElse(super.nameForField(config, field, defaultName));
}
 
Example #21
Source File: SwaggerNamingStrategy.java    From herd with Apache License 2.0 4 votes vote down vote up
@Override
public String nameForField(MapperConfig config, AnnotatedField field, String defaultName)
{
    return convertName(defaultName);
}
 
Example #22
Source File: SplitorPropertyStrategy.java    From onetwo with Apache License 2.0 4 votes vote down vote up
@Override
public String nameForField(MapperConfig<?> config, AnnotatedField field,
		String defaultName) {
	return convertName(defaultName);
}
 
Example #23
Source File: PossiblyStrictPreferringFieldsVisibilityChecker.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
@Override
public boolean isFieldVisible(AnnotatedField f) {
    return isFieldVisible(f.getAnnotated());
}
 
Example #24
Source File: LowerCasePropertyNamingStrategy.java    From Cheddar with Apache License 2.0 4 votes vote down vote up
@Override
public String nameForField(final MapperConfig<?> config, final AnnotatedField field, final String defaultName) {
    return formattedFieldName(defaultName);

}
 
Example #25
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;
}
 
Example #26
Source File: PropertyNamingStrategy.java    From lams with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Method called to find external name (name used in JSON) for given logical
 * POJO property,
 * as defined by given field.
 * 
 * @param config Configuration in used: either <code>SerializationConfig</code>
 *   or <code>DeserializationConfig</code>, depending on whether method is called
 *   during serialization or deserialization
 * @param field Field used to access property
 * @param defaultName Default name that would be used for property in absence of custom strategy
 * 
 * @return Logical name to use for property that the field represents
 */
public String nameForField(MapperConfig<?> config, AnnotatedField field,
        String defaultName)
{
    return defaultName;
}