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

The following examples show how to use com.fasterxml.jackson.databind.introspect.AnnotatedMethod. 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: BQTimeModule.java    From bootique with Apache License 2.0 6 votes vote down vote up
protected AnnotatedMethod _findFactory(AnnotatedClass cls, String name, Class<?>... argTypes) {
    final int argCount = argTypes.length;
    for (AnnotatedMethod method : cls.getFactoryMethods()) {
        if (!name.equals(method.getName())
                || (method.getParameterCount() != argCount)) {
            continue;
        }
        for (int i = 0; i < argCount; ++i) {
            Class<?> argType = method.getParameter(i).getRawType();
            if (!argType.isAssignableFrom(argTypes[i])) {
                continue;
            }
        }
        return method;
    }
    return null;
}
 
Example #2
Source File: ResourceFieldNameTransformer.java    From katharsis-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Extract name to be used by Katharsis from getter's name. It uses
 * {@link ResourceFieldNameTransformer#getMethodName(Method)}, {@link JsonProperty} annotation and
 * {@link PropertyNamingStrategy}.
 *
 * @param method method to extract name
 * @return method name
 */
public String getName(Method method) {
    String name = getMethodName(method);

    if (method.isAnnotationPresent(JsonProperty.class) &&
        !"".equals(method.getAnnotation(JsonProperty.class).value())) {
        name = method.getAnnotation(JsonProperty.class).value();
    } else if (serializationConfig != null && serializationConfig.getPropertyNamingStrategy() != null) {
        Annotation[] declaredAnnotations = method.getDeclaredAnnotations();
        AnnotationMap annotationMap = buildAnnotationMap(declaredAnnotations);

        int paramsLength = method.getParameterAnnotations().length;
        AnnotationMap[] paramAnnotations = new AnnotationMap[paramsLength];
        for (int i = 0; i < paramsLength; i++) {
            AnnotationMap parameterAnnotationMap = buildAnnotationMap(method.getParameterAnnotations()[i]);
            paramAnnotations[i] = parameterAnnotationMap;
        }

        AnnotatedClass annotatedClass = AnnotatedClassBuilder.build(method.getDeclaringClass(), serializationConfig);
        AnnotatedMethod annotatedField = AnnotatedMethodBuilder.build(annotatedClass, method, annotationMap, paramAnnotations);
        name = serializationConfig.getPropertyNamingStrategy().nameForGetterMethod(serializationConfig, annotatedField, name);
    }
    return name;
}
 
Example #3
Source File: JtModule.java    From haven-platform with Apache License 2.0 6 votes vote down vote up
@Override
public Object findDeserializationConverter(Annotated a) {
    JtToMap ann = a.getAnnotation(JtToMap.class);
    if (ann == null) {
        return null;
    }
    JavaType javaType = a.getType();
    if(a instanceof AnnotatedMethod) {
        AnnotatedMethod am = (AnnotatedMethod) a;
        if(am.getParameterCount() == 1) {
            javaType = am.getParameterType(0);
        } else {
            throw new RuntimeException("Invalid property setter: " + am.getAnnotated());
        }
    }
    return new DeserializationConverterImpl(ann, new Ctx(a, javaType));
}
 
Example #4
Source File: KvSupportModule.java    From haven-platform with Apache License 2.0 6 votes vote down vote up
@Override
public Object findDeserializationConverter(Annotated a) {
    Class<? extends PropertyInterceptor>[] interceptors = getInterceptors(a);
    if (interceptors == null) {
        return null;
    }
    JavaType javaType = a.getType();
    if(a instanceof AnnotatedMethod) {
        AnnotatedMethod am = (AnnotatedMethod) a;
        if(am.getParameterCount() == 1) {
            javaType = am.getParameterType(0);
        } else {
            throw new RuntimeException("Invalid property setter: " + am.getAnnotated());
        }
    }
    return new KvInterceptorsDeserializationConverter(interceptors, new KvPropertyContextImpl(a, javaType));
}
 
Example #5
Source File: JavaTimeModule.java    From jackson-modules-java8 with Apache License 2.0 6 votes vote down vote up
protected AnnotatedMethod _findFactory(AnnotatedClass cls, String name, Class<?>... argTypes)
{
    final int argCount = argTypes.length;
    for (AnnotatedMethod method : cls.getFactoryMethods()) {
        if (!name.equals(method.getName())
                || (method.getParameterCount() != argCount)) {
            continue;
        }
        for (int i = 0; i < argCount; ++i) {
            Class<?> argType = method.getParameter(i).getRawType();
            if (!argType.isAssignableFrom(argTypes[i])) {
                continue;
            }
        }
        return method;
    }
    return null;
}
 
Example #6
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 #7
Source File: TestAccessorGeneration.java    From jackson-modules-base with Apache License 2.0 6 votes vote down vote up
public void testSingleIntAccessorGeneration() throws Exception
{
    Method method = Bean1.class.getDeclaredMethod("getX");
    AnnotatedMethod annMethod = new AnnotatedMethod(null, method, null, null);
    PropertyAccessorCollector coll = new PropertyAccessorCollector(Bean1.class);
    BeanPropertyWriter bpw = new BeanPropertyWriter(SimpleBeanPropertyDefinition
            .construct(MAPPER_CONFIG, annMethod, new PropertyName("x")),
            annMethod, null,
            null,
            null, null, null,
            false, null, null);
    coll.addIntGetter(bpw);
    BeanPropertyAccessor acc = coll.findAccessor(null);
    Bean1 bean = new Bean1();
    int value = acc.intGetter(bean, 0);
    assertEquals(bean.getX(), value);
}
 
Example #8
Source File: IssueTrackerConfiguration.java    From spring-data-dev-tools with Apache License 2.0 6 votes vote down vote up
@Override
public void setupModule(SetupContext context) {

	context.insertAnnotationIntrospector(new NopAnnotationIntrospector() {

		private static final long serialVersionUID = 479313244908256455L;

		@Override
		public boolean hasIgnoreMarker(AnnotatedMember m) {

			if (!(m instanceof AnnotatedMethod)) {
				return super.hasIgnoreMarker(m);
			}

			AnnotatedMethod method = (AnnotatedMethod) m;

			return method.getName().startsWith("lambda$") ? true : super.hasIgnoreMarker(m);
		}
	});
}
 
Example #9
Source File: BeanUtil.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * This method was added to address the need to weed out
 * CGLib-injected "getCallbacks" method. 
 * At this point caller has detected a potential getter method
 * with name "getCallbacks" and we need to determine if it is
 * indeed injectect by Cglib. We do this by verifying that the
 * result type is "net.sf.cglib.proxy.Callback[]"
 */
protected static boolean isCglibGetCallbacks(AnnotatedMethod am)
{
    Class<?> rt = am.getRawType();
    // Ok, first: must return an array type
    if (rt.isArray()) {
        /* And that type needs to be "net.sf.cglib.proxy.Callback".
         * Theoretically could just be a type that implements it, but
         * for now let's keep things simple, fix if need be.
         */
        Class<?> compType = rt.getComponentType();
        // Actually, let's just verify it's a "net.sf.cglib.*" class/interface
        String pkgName = ClassUtil.getPackageName(compType);
        if (pkgName != null) {
            if (pkgName.contains(".cglib")) {
                return pkgName.startsWith("net.sf.cglib")
                    // also, as per [JACKSON-177]
                    || pkgName.startsWith("org.hibernate.repackage.cglib")
                    // and [core#674]
                    || pkgName.startsWith("org.springframework.cglib");
            }
        }
    }
    return false;
}
 
Example #10
Source File: JacksonResourceFieldInformationProvider.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
protected Optional<String> getName(Method method) {
	ObjectMapper objectMapper = context.getObjectMapper();
	SerializationConfig serializationConfig = objectMapper.getSerializationConfig();
	if (serializationConfig != null && serializationConfig.getPropertyNamingStrategy() != null) {
		String name = ClassUtils.getGetterFieldName(method);
		Annotation[] declaredAnnotations = method.getDeclaredAnnotations();
		AnnotationMap annotationMap = buildAnnotationMap(declaredAnnotations);

		int paramsLength = method.getParameterAnnotations().length;
		AnnotationMap[] paramAnnotations = new AnnotationMap[paramsLength];
		for (int i = 0; i < paramsLength; i++) {
			AnnotationMap parameterAnnotationMap = buildAnnotationMap(method.getParameterAnnotations()[i]);
			paramAnnotations[i] = parameterAnnotationMap;
		}

		AnnotatedClass annotatedClass = AnnotatedClassBuilder.build(method.getDeclaringClass(), serializationConfig);
		AnnotatedMethod annotatedField = AnnotatedMethodBuilder.build(annotatedClass, method, annotationMap, paramAnnotations);
		return Optional.of(serializationConfig.getPropertyNamingStrategy().nameForGetterMethod(serializationConfig, annotatedField, name));
	}
	return Optional.empty();
}
 
Example #11
Source File: BeanUtil.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Similar to {@link #isCglibGetCallbacks}, need to suppress
 * a cyclic reference.
 */
protected static boolean isGroovyMetaClassSetter(AnnotatedMethod am)
{
    Class<?> argType = am.getRawParameterType(0);
    String pkgName = ClassUtil.getPackageName(argType);
    return (pkgName != null) && pkgName.startsWith("groovy.lang");
}
 
Example #12
Source File: BeanUtil.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * @since 2.5
 */
public static String okNameForGetter(AnnotatedMethod am, boolean stdNaming) {
    String name = am.getName();
    String str = okNameForIsGetter(am, name, stdNaming);
    if (str == null) {
        str = okNameForRegularGetter(am, name, stdNaming);
    }
    return str;
}
 
Example #13
Source File: EsPropertyNamingStrategy.java    From soundwave with Apache License 2.0 5 votes vote down vote up
@Override
public String nameForGetterMethod(MapperConfig<?> config, AnnotatedMethod method,
                                  String defaultName) {
  if (method.getDeclaringClass() == this.effectiveType) {
    return fieldToJsonMapping
        .getOrDefault(defaultName, super.nameForGetterMethod(config, method, defaultName));
  } else {
    return super.nameForGetterMethod(config, method, defaultName);
  }
}
 
Example #14
Source File: EsPropertyNamingStrategy.java    From soundwave with Apache License 2.0 5 votes vote down vote up
@Override
public String nameForSetterMethod(MapperConfig<?> config, AnnotatedMethod method,
                                  String defaultName) {
  if (method.getDeclaringClass() == this.effectiveType) {
    return fieldToJsonMapping
        .getOrDefault(defaultName, super.nameForSetterMethod(config, method, defaultName));
  } else {
    return super.nameForSetterMethod(config, method, defaultName);
  }
}
 
Example #15
Source File: EnumDeserializer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Factory method used when Enum instances are to be deserialized
 * using a creator (static factory method)
 * 
 * @return Deserializer based on given factory method
 *
 * @since 2.8
 */
public static JsonDeserializer<?> deserializerForCreator(DeserializationConfig config,
        Class<?> enumClass, AnnotatedMethod factory,
        ValueInstantiator valueInstantiator, SettableBeanProperty[] creatorProps)
{
    if (config.canOverrideAccessModifiers()) {
        ClassUtil.checkAndFixAccess(factory.getMember(),
                config.isEnabled(MapperFeature.OVERRIDE_PUBLIC_ACCESS_MODIFIERS));
    }
    return new FactoryBasedEnumDeserializer(enumClass, factory,
            factory.getParameterType(0),
            valueInstantiator, creatorProps);
}
 
Example #16
Source File: BeanAsArrayBuilderDeserializer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Main constructor used both for creating new instances (by
 * {@link BeanDeserializer#asArrayDeserializer}) and for
 * creating copies with different delegate.
 *
 * @since 2.9
 */
public BeanAsArrayBuilderDeserializer(BeanDeserializerBase delegate,
        JavaType targetType,
        SettableBeanProperty[] ordered,
        AnnotatedMethod buildMethod)
{
    super(delegate);
    _delegate = delegate;
    _targetType = targetType;
    _orderedProperties = ordered;
    _buildMethod = buildMethod;
}
 
Example #17
Source File: SetterlessProperty.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public SetterlessProperty(BeanPropertyDefinition propDef, JavaType type,
        TypeDeserializer typeDeser, Annotations contextAnnotations, AnnotatedMethod method)
{
    super(propDef, type, typeDeser, contextAnnotations);
    _annotated = method;
    _getter = method.getAnnotated();
}
 
Example #18
Source File: FriendlyIdAnnotationIntrospector.java    From friendly-id with Apache License 2.0 5 votes vote down vote up
private Class<?> rawDeserializationType(Annotated a) {
	if (a instanceof AnnotatedMethod) {
		AnnotatedMethod am = (AnnotatedMethod) a;
		if (am.getParameterCount() == 1) {
			return am.getRawParameterType(0);
		}
	}
	return a.getRawType();
}
 
Example #19
Source File: RosettaAnnotationIntrospector.java    From Rosetta with Apache License 2.0 5 votes vote down vote up
private Annotated getAnnotatedTypeFromAnnotatedMethod(AnnotatedMethod a) {
  if (a.getParameterCount() > 0) {
    return a.getParameter(0);
  } else if (a.hasReturnType()) {
    return a;
  } else {
    throw new IllegalArgumentException("Cannot have @StoredAsJson on a method with no parameters AND no arguments");
  }
}
 
Example #20
Source File: AnnotatedMethodBuilder.java    From katharsis-framework with Apache License 2.0 5 votes vote down vote up
public static AnnotatedMethod build(AnnotatedClass annotatedClass, Method method, AnnotationMap annotationMap,
                                    AnnotationMap[] paramAnnotations) {
    for(Constructor<?> constructor : AnnotatedMethod.class.getConstructors()) {
        try {
            return buildAnnotatedField(annotatedClass, method, annotationMap, paramAnnotations, constructor);
        } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {
            throw new InternalException("Exception while building " + AnnotatedMethod.class.getCanonicalName(), e);
        }
    }
    throw new InternalException(CANNOT_FIND_PROPER_CONSTRUCTOR);
}
 
Example #21
Source File: AnnotatedMethodBuilder.java    From katharsis-framework with Apache License 2.0 5 votes vote down vote up
private static AnnotatedMethod buildAnnotatedField(AnnotatedClass annotatedClass, Method method,
                                                   AnnotationMap annotationMap, AnnotationMap[] paramAnnotations,
                                                   Constructor<?> constructor)
        throws IllegalAccessException, InstantiationException, InvocationTargetException {
    Class<?> firstParameterType = constructor.getParameterTypes()[0];
    if (firstParameterType == AnnotatedClass.class ||
            "TypeResolutionContext".equals(firstParameterType.getSimpleName())) {
        return (AnnotatedMethod) constructor.newInstance(annotatedClass, method, annotationMap, paramAnnotations);
    } else {
        throw new InternalException(CANNOT_FIND_PROPER_CONSTRUCTOR);
    }
}
 
Example #22
Source File: ConvertingDeserializer.java    From graphql-spqr with Apache License 2.0 5 votes vote down vote up
private JavaType extractType(Annotated annotated) {
    if (annotated instanceof AnnotatedMethod) {
        AnnotatedMethod method = (AnnotatedMethod) annotated;
        if (ClassUtils.isSetter(method.getAnnotated())) {
            return method.getParameterType(0);
        }
        return method.getType();
    }
    return annotated.getType();
}
 
Example #23
Source File: TestAccessorGeneration.java    From jackson-modules-base with Apache License 2.0 5 votes vote down vote up
public void testDualIntAccessorGeneration() throws Exception
{
    PropertyAccessorCollector coll = new PropertyAccessorCollector(Bean3.class);

    String[] methodNames = new String[] {
            "getX", "getY", "get3"
    };
    
    /*
public BeanPropertyWriter(BeanPropertyDefinition propDef,
        AnnotatedMember member, Annotations contextAnnotations,
        JavaType declaredType,
        JsonSerializer<Object> ser, TypeSerializer typeSer, JavaType serType,
        boolean suppressNulls, Object suppressableValue)
     */
    
    for (String methodName : methodNames) {
        Method method = Bean3.class.getDeclaredMethod(methodName);
        AnnotatedMethod annMethod = new AnnotatedMethod(null, method, null, null);
        // should we translate from method name to property name?
        coll.addIntGetter(new BeanPropertyWriter(SimpleBeanPropertyDefinition
                .construct(MAPPER_CONFIG, annMethod, new PropertyName(methodName)),
                annMethod, null,
                null,
                null, null, null,
                false, null, null));
    }

    BeanPropertyAccessor acc = coll.findAccessor(null);
    Bean3 bean = new Bean3();

    assertEquals(bean.getX(), acc.intGetter(bean, 0));
    assertEquals(bean.getY(), acc.intGetter(bean, 1));
    assertEquals(bean.get3(), acc.intGetter(bean, 2));
}
 
Example #24
Source File: TestAccessorGeneration.java    From jackson-modules-base with Apache License 2.0 5 votes vote down vote up
public void testLotsaIntAccessorGeneration() throws Exception
{
    PropertyAccessorCollector coll = new PropertyAccessorCollector(BeanN.class);
    String[] methodNames = new String[] {
            "getX", "getY", "get3", "get4", "get5", "get6", "get7"
    };
    for (String methodName : methodNames) {
        Method method = BeanN.class.getDeclaredMethod(methodName);
        AnnotatedMethod annMethod = new AnnotatedMethod(null, method, null, null);
        coll.addIntGetter(new BeanPropertyWriter(SimpleBeanPropertyDefinition.construct(
                MAPPER_CONFIG, annMethod, new PropertyName(methodName)),
                annMethod, null,
                null,
                null, null, null,
                false, null, null));
    }

    BeanPropertyAccessor acc = coll.findAccessor(null);
    BeanN bean = new BeanN();

    assertEquals(bean.getX(), acc.intGetter(bean, 0));
    assertEquals(bean.getY(), acc.intGetter(bean, 1));

    assertEquals(bean.get3(), acc.intGetter(bean, 2));
    assertEquals(bean.get4(), acc.intGetter(bean, 3));
    assertEquals(bean.get5(), acc.intGetter(bean, 4));
    assertEquals(bean.get6(), acc.intGetter(bean, 5));
    assertEquals(bean.get7(), acc.intGetter(bean, 6));
}
 
Example #25
Source File: AutoMatterAnnotationIntrospector.java    From auto-matter with Apache License 2.0 5 votes vote down vote up
@Override
public String findImplicitPropertyName(final AnnotatedMember member) {
  final AutoMatter.Field field = member.getAnnotation(AutoMatter.Field.class);
  if (field == null) {
    return null;
  }
  if (member instanceof AnnotatedParameter) {
    return field.value();
  }
  if (member instanceof AnnotatedMethod) {
    return member.getName();
  }
  return null;
}
 
Example #26
Source File: JacksonLombokAnnotationIntrospector.java    From jackson-lombok with MIT License 5 votes vote down vote up
@Override
public String findImplicitPropertyName(AnnotatedMember member) {
    JsonProperty property = member.getAnnotation(JsonProperty.class);
    if (property == null) {
        if (member instanceof AnnotatedMethod) {
            AnnotatedMethod method = (AnnotatedMethod) member;
            String fieldName = BeanUtil.okNameForGetter(method);
            return getJacksonPropertyName(member.getDeclaringClass(), fieldName);
        }
    } else if (!property.value().equals("")) {
        return property.value();
    }

    return null;
}
 
Example #27
Source File: HbaseJsonEventSerializer.java    From searchanalytics-bigdata with MIT License 5 votes vote down vote up
@SuppressWarnings("rawtypes")
@Override
public String nameForSetterMethod(MapperConfig config,
		AnnotatedMethod method, String defaultName) {
	String a = convert(defaultName);
	return a;
}
 
Example #28
Source File: JsonUtils.java    From mblog with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Object findSerializer(Annotated a) {
	if (a instanceof AnnotatedMethod) {
		AnnotatedElement m = a.getAnnotated();
		DateTimeFormat an = m.getAnnotation(DateTimeFormat.class);
		if (an != null) {
			if (!DEFAULT_DATE_FORMAT.equals(an.pattern())) {
				return new JsonDateSerializer(an.pattern());
			}
		}
	}
	return super.findSerializer(a);
}
 
Example #29
Source File: RosettaAnnotationIntrospector.java    From Rosetta with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public JsonDeserializer<?> findDeserializer(Annotated a) {
  StoredAsJson storedAsJson = a.getAnnotation(StoredAsJson.class);
  RosettaDeserialize rosettaDeserialize = a.getAnnotation(RosettaDeserialize.class);
  if (storedAsJson != null && rosettaDeserialize != null) {
    throw new IllegalArgumentException("Cannot have @StoredAsJson as well as @RosettaDeserialize annotations on the same entry");
  }
  if (storedAsJson != null) {
    if (a instanceof AnnotatedMethod) {
      a = getAnnotatedTypeFromAnnotatedMethod((AnnotatedMethod) a);
    }

    String empty = StoredAsJson.NULL.equals(storedAsJson.empty()) ? "null" : storedAsJson.empty();
    return new StoredAsJsonDeserializer(a.getRawType(), getType(a), empty, objectMapper);
  }

  if (rosettaDeserialize != null) {
    Class<? extends JsonDeserializer> klass = rosettaDeserialize.using();
    if (klass != JsonDeserializer.None.class) {
      return ClassUtil.createInstance(
          klass,
          objectMapper.getDeserializationConfig().canOverrideAccessModifiers());
    }
  }

  return null;
}
 
Example #30
Source File: KebabCaseEnforcingAnnotationInspector.java    From conjure with Apache License 2.0 5 votes vote down vote up
@Override
public PropertyName findNameForDeserialization(Annotated annotatedEntity) {
    // This logic relies on the fact that Immutables generates setters annotated with @JsonProperty.
    // It thus becomes obsolete whenever we move away from Immutables and the deserialization target no longer
    // carries those annotations.

    JsonProperty propertyAnnotation = _findAnnotation(annotatedEntity, JsonProperty.class);
    if (propertyAnnotation != null) {
        String jsonFieldName = propertyAnnotation.value();
        Preconditions.checkArgument(
                KEBAB_CASE_PATTERN.matcher(jsonFieldName).matches(),
                "Conjure grammar requires kebab-case field names: %s",
                jsonFieldName);
    }

    if (annotatedEntity instanceof AnnotatedMethod) {
        AnnotatedMethod maybeSetter = (AnnotatedMethod) annotatedEntity;
        if (maybeSetter.getName().startsWith("set")) {
            // As a pre-caution, require that all setters have a JsonProperty annotation.
            Preconditions.checkArgument(
                    _findAnnotation(annotatedEntity, JsonProperty.class) != null,
                    "All setter ({@code set*}) deserialization targets require @JsonProperty annotations: %s",
                    maybeSetter.getName());
        }
    }

    return null; // delegate to the next introspector in an AnnotationIntrospectorPair.
}