com.fasterxml.jackson.databind.AnnotationIntrospector Java Examples

The following examples show how to use com.fasterxml.jackson.databind.AnnotationIntrospector. 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: ObjectMapperUtil.java    From endpoints-java with Apache License 2.0 7 votes vote down vote up
/**
 * Creates an Endpoints standard object mapper that allows unquoted field names and unknown
 * properties.
 *
 * Note on unknown properties: When Apiary FE supports a strict mode where properties
 * are checked against the schema, BE can just ignore unknown properties.  This way, FE does
 * not need to filter out everything that the BE doesn't understand.  Before that's done,
 * a property name with a typo in it, for example, will just be ignored by the BE.
 */
public static ObjectMapper createStandardObjectMapper(ApiSerializationConfig config) {
  ObjectMapper objectMapper = new ObjectMapper()
      .configure(JsonParser.Feature.ALLOW_COMMENTS, true)
      .configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true)
      .configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true)
      .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
      .setBase64Variant(Base64Variants.MODIFIED_FOR_URL)
      .setSerializerFactory(
          BeanSerializerFactory.instance.withSerializerModifier(new DeepEmptyCheckingModifier()));
  AnnotationIntrospector pair = EndpointsFlag.JSON_USE_JACKSON_ANNOTATIONS.isEnabled()
      ? AnnotationIntrospector.pair(
          new ApiAnnotationIntrospector(config),
          new JacksonAnnotationIntrospector())
      : new ApiAnnotationIntrospector(config);
  objectMapper.setAnnotationIntrospector(pair);
  return objectMapper;
}
 
Example #2
Source File: StdSubtypeResolver.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public Collection<NamedType> collectAndResolveSubtypesByClass(MapperConfig<?> config,
        AnnotatedClass type)
{
    final AnnotationIntrospector ai = config.getAnnotationIntrospector();
    HashMap<NamedType, NamedType> subtypes = new HashMap<NamedType, NamedType>();
    // then consider registered subtypes (which have precedence over annotations)
    if (_registeredSubtypes != null) {
        Class<?> rawBase = type.getRawType();
        for (NamedType subtype : _registeredSubtypes) {
            // is it a subtype of root type?
            if (rawBase.isAssignableFrom(subtype.getType())) { // yes
                AnnotatedClass curr = AnnotatedClassResolver.resolveWithoutSuperTypes(config,
                        subtype.getType());
                _collectAndResolve(curr, subtype, config, ai, subtypes);
            }
        }
    }
    // and then check subtypes via annotations from base type (recursively)
    NamedType rootType = new NamedType(type.getRawType(), null);
    _collectAndResolve(type, rootType, config, ai, subtypes);
    return new ArrayList<NamedType>(subtypes.values());
}
 
Example #3
Source File: ConcreteBeanPropertyBase.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public List<PropertyName> findAliases(MapperConfig<?> config)
{
    List<PropertyName> aliases = _aliases;
    if (aliases == null) {
        AnnotationIntrospector intr = config.getAnnotationIntrospector();
        if (intr != null) {
            aliases = intr.findPropertyAliases(getMember());
        }
        if (aliases == null) {
            aliases = Collections.emptyList();
        }
        _aliases = aliases;
    }
    return aliases;
}
 
Example #4
Source File: ConcreteBeanPropertyBase.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public JsonInclude.Value findPropertyInclusion(MapperConfig<?> config, Class<?> baseType)
{
    AnnotationIntrospector intr = config.getAnnotationIntrospector();
    AnnotatedMember member = getMember();
    if (member == null) {
        JsonInclude.Value def = config.getDefaultPropertyInclusion(baseType);
        return def;
    }
    JsonInclude.Value v0 = config.getDefaultInclusion(baseType, member.getRawType());
    if (intr == null) {
        return v0;
    }
    JsonInclude.Value v = intr.findPropertyInclusion(member);
    if (v0 == null) {
        return v;
    }
    return v0.withOverrides(v);
}
 
Example #5
Source File: ConcreteBeanPropertyBase.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
public JsonFormat.Value findPropertyFormat(MapperConfig<?> config, Class<?> baseType)
{
    // 15-Apr-2016, tatu: Let's calculate lazily, retain; assumption being however that
    //    baseType is always the same
    JsonFormat.Value v = _propertyFormat;
    if (v == null) {
        JsonFormat.Value v1 = config.getDefaultPropertyFormat(baseType);
        JsonFormat.Value v2 = null;
        AnnotationIntrospector intr = config.getAnnotationIntrospector();
        if (intr != null) {
            AnnotatedMember member = getMember();
            if (member != null) {
                v2 = intr.findFormat(member);
            }
        }
        if (v1 == null) {
            v = (v2 == null) ? EMPTY_FORMAT : v2;
        } else {
            v = (v2 == null) ? v1 : v1.withOverrides(v2);
        }
        _propertyFormat = v;
    }
    return v;
}
 
Example #6
Source File: EnumResolver.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Factory method for constructing resolver that maps from Enum.name() into
 * Enum value
 */
public static EnumResolver constructFor(Class<Enum<?>> enumCls, AnnotationIntrospector ai)
{
    Enum<?>[] enumValues = enumCls.getEnumConstants();
    if (enumValues == null) {
        throw new IllegalArgumentException("No enum constants for class "+enumCls.getName());
    }
    String[] names = ai.findEnumValues(enumCls, enumValues, new String[enumValues.length]);
    HashMap<String, Enum<?>> map = new HashMap<String, Enum<?>>();
    for (int i = 0, len = enumValues.length; i < len; ++i) {
        String name = names[i];
        if (name == null) {
            name = enumValues[i].name();
        }
        map.put(name, enumValues[i]);
    }

    Enum<?> defaultEnum = ai.findDefaultEnumValue(enumCls);

    return new EnumResolver(enumCls, enumValues, map, defaultEnum);
}
 
Example #7
Source File: EnumResolver.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @since 2.9
 */
public static EnumResolver constructUsingMethod(Class<Enum<?>> enumCls,
        AnnotatedMember accessor,
        AnnotationIntrospector ai)
{
    Enum<?>[] enumValues = enumCls.getEnumConstants();
    HashMap<String, Enum<?>> map = new HashMap<String, Enum<?>>();
    // from last to first, so that in case of duplicate values, first wins
    for (int i = enumValues.length; --i >= 0; ) {
        Enum<?> en = enumValues[i];
        try {
            Object o = accessor.getValue(en);
            if (o != null) {
                map.put(o.toString(), en);
            }
        } catch (Exception e) {
            throw new IllegalArgumentException("Failed to access @JsonValue of Enum value "+en+": "+e.getMessage());
        }
    }
    Enum<?> defaultEnum = (ai != null) ? ai.findDefaultEnumValue(enumCls) : null;
    return new EnumResolver(enumCls, enumValues, map, defaultEnum);
}
 
Example #8
Source File: ObjectMapperModule.java    From jackson-modules-base with Apache License 2.0 6 votes vote down vote up
@Override
public ObjectMapper get()
{
    ObjectMapper mapper = objectMapper;
    if (mapper == null) {
        final GuiceAnnotationIntrospector guiceIntrospector = new GuiceAnnotationIntrospector();
        AnnotationIntrospector defaultAI = new JacksonAnnotationIntrospector();
        MapperBuilder<?,?> builder = JsonMapper.builder()
                .injectableValues(new GuiceInjectableValues(injector))
                .annotationIntrospector(new AnnotationIntrospectorPair(guiceIntrospector, defaultAI))
                .addModules(modulesToAdd);
        for (Provider<? extends Module> provider : providedModules) {
            builder = builder.addModule(provider.get());
        }
        mapper = builder.build();

      /*
  } else {
        // 05-Feb-2017, tatu: _Should_ be fine, considering instances are now (3.0) truly immutable.
      //    But if this turns out to be problematic, may need to consider addition of `copy()`
      //    back in databind
      mapper = mapper.copy();
      */
  }
  return mapper;
}
 
Example #9
Source File: EnumResolver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Method used when actual String serialization is indicated using @JsonValue
 * on a method.
 *
 * @since 2.9
 */
@SuppressWarnings({ "unchecked" })
public static EnumResolver constructUnsafeUsingMethod(Class<?> rawEnumCls,
        AnnotatedMember accessor,
        AnnotationIntrospector ai)
{            
    // wrong as ever but:
    Class<Enum<?>> enumCls = (Class<Enum<?>>) rawEnumCls;
    return constructUsingMethod(enumCls, accessor, ai);
}
 
Example #10
Source File: EnumResolver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Method that needs to be used instead of {@link #constructUsingToString}
 * if static type of enum is not known.
 *
 * @since 2.8
 */
@SuppressWarnings({ "unchecked" })
public static EnumResolver constructUnsafeUsingToString(Class<?> rawEnumCls,
        AnnotationIntrospector ai)
{
    // oh so wrong... not much that can be done tho
    Class<Enum<?>> enumCls = (Class<Enum<?>>) rawEnumCls;
    return constructUsingToString(enumCls, ai);
}
 
Example #11
Source File: EnumResolver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * This method is needed because of the dynamic nature of constructing Enum
 * resolvers.
 */
@SuppressWarnings({ "unchecked" })
public static EnumResolver constructUnsafe(Class<?> rawEnumCls, AnnotationIntrospector ai)
{            
    /* This is oh so wrong... but at least ugliness is mostly hidden in just
     * this one place.
     */
    Class<Enum<?>> enumCls = (Class<Enum<?>>) rawEnumCls;
    return constructFor(enumCls, ai);
}
 
Example #12
Source File: Utility.java    From SNOMED-in-5-minutes with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the graph for json.
 *
 * @param <T> the generic type
 * @param json the json
 * @param graphClass the graph class
 * @return the graph for json
 * @throws Exception the exception
 */
public static <T> T getGraphForJson(String json, Class<T> graphClass)
  throws Exception {
  InputStream in =
      new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8));
  ObjectMapper mapper = new ObjectMapper();
  AnnotationIntrospector introspector =
      new JaxbAnnotationIntrospector(mapper.getTypeFactory());
  mapper.setAnnotationIntrospector(introspector);
  return mapper.readValue(in, graphClass);

}
 
Example #13
Source File: BasicClassIntrospector.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected POJOPropertiesCollector collectPropertiesWithBuilder(MapperConfig<?> config,
        JavaType type, MixInResolver r, boolean forSerialization)
{
    AnnotatedClass ac = _resolveAnnotatedClass(config, type, r);
    AnnotationIntrospector ai = config.isAnnotationProcessingEnabled() ? config.getAnnotationIntrospector() : null;
    JsonPOJOBuilder.Value builderConfig = (ai == null) ? null : ai.findPOJOBuilderConfig(ac);
    String mutatorPrefix = (builderConfig == null) ? JsonPOJOBuilder.DEFAULT_WITH_PREFIX : builderConfig.withPrefix;
    return constructPropertyCollector(config, ac, type, forSerialization, mutatorPrefix);
}
 
Example #14
Source File: EnumResolver.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Factory method for constructing resolver that maps from Enum.toString() into
 * Enum value
 *
 * @since 2.8
 */
public static EnumResolver constructUsingToString(Class<Enum<?>> enumCls,
        AnnotationIntrospector ai)
{
    Enum<?>[] enumValues = enumCls.getEnumConstants();
    HashMap<String, Enum<?>> map = new HashMap<String, Enum<?>>();
    // from last to first, so that in case of duplicate values, first wins
    for (int i = enumValues.length; --i >= 0; ) {
        Enum<?> e = enumValues[i];
        map.put(e.toString(), e);
    }
    Enum<?> defaultEnum = (ai == null) ? null : ai.findDefaultEnumValue(enumCls);
    return new EnumResolver(enumCls, enumValues, map, defaultEnum);
}
 
Example #15
Source File: ApiObjectMapper.java    From components with Apache License 2.0 5 votes vote down vote up
public ApiObjectMapper() {
    // Print the JSON with indentation (ie. pretty print)
    configure(SerializationFeature.INDENT_OUTPUT, true);

    // Allow JAX-B annotations.
    setAnnotationIntrospector(AnnotationIntrospector.pair(getSerializationConfig().getAnnotationIntrospector(),
            new JaxbAnnotationIntrospector()));

    // Make Jackson respect @XmlElementWrapper.
    enable(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME);

    // Print all dates in ISO8601 format
    setDateFormat(makeISODateFormat());
}
 
Example #16
Source File: CreatorCandidate.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public static CreatorCandidate construct(AnnotationIntrospector intr,
        AnnotatedWithParams creator, BeanPropertyDefinition[] propDefs)
{
    final int pcount = creator.getParameterCount();
    Param[] params = new Param[pcount];
    for (int i = 0; i < pcount; ++i) {
        AnnotatedParameter annParam = creator.getParameter(i);
        JacksonInject.Value injectId = intr.findInjectableValue(annParam);
        params[i] = new Param(annParam, (propDefs == null) ? null : propDefs[i], injectId);
    }
    return new CreatorCandidate(intr, creator, params, pcount);
}
 
Example #17
Source File: CreatorCandidate.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
protected CreatorCandidate(AnnotationIntrospector intr,
        AnnotatedWithParams ct, Param[] params, int count) {
    _intr = intr;
    _creator = ct;
    _params = params;
    _paramCount = count;
}
 
Example #18
Source File: AnnotatedMethodCollector.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public static AnnotatedMethodMap collectMethods(AnnotationIntrospector intr,
        TypeResolutionContext tc,
        MixInResolver mixins, TypeFactory types,
        JavaType type, List<JavaType> superTypes, Class<?> primaryMixIn)
{
    // Constructor also always members of resolved class, parent == resolution context
    return new AnnotatedMethodCollector(intr, mixins)
            .collect(types, tc, type, superTypes, primaryMixIn);
}
 
Example #19
Source File: Utility.java    From SNOMED-in-5-minutes with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the json for graph.
 *
 * @param object the object
 * @return the json for graph
 * @throws Exception the exception
 */
public static String getJsonForGraph(Object object) throws Exception {
  ObjectMapper mapper = new ObjectMapper();
  AnnotationIntrospector introspector =
      new JaxbAnnotationIntrospector(mapper.getTypeFactory());
  mapper.setAnnotationIntrospector(introspector);
  return mapper.writeValueAsString(object);
}
 
Example #20
Source File: AnnotatedClassBuilder.java    From katharsis-framework with Apache License 2.0 5 votes vote down vote up
private static AnnotatedClass buildOldAnnotatedClass(Method method, Class<?> declaringClass,
                                                     SerializationConfig serializationConfig)
    throws InvocationTargetException, IllegalAccessException {
    boolean useAnnotations = serializationConfig.isAnnotationProcessingEnabled();
    AnnotationIntrospector aintr = useAnnotations ? serializationConfig.getAnnotationIntrospector() : null;
    return AnnotatedClass.class.cast(method.invoke(null, declaringClass, aintr, serializationConfig));
}
 
Example #21
Source File: ApiObjectMapper.java    From components with Apache License 2.0 5 votes vote down vote up
public ApiObjectMapper() {
    // Print the JSON with indentation (ie. pretty print)
    configure(SerializationFeature.INDENT_OUTPUT, true);

    // Allow JAX-B annotations.
    setAnnotationIntrospector(AnnotationIntrospector.pair(getSerializationConfig().getAnnotationIntrospector(),
            new JaxbAnnotationIntrospector()));

    // Make Jackson respect @XmlElementWrapper.
    enable(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME);

    // Print all dates in ISO8601 format
    setDateFormat(makeISODateFormat());
}
 
Example #22
Source File: AnnotatedCreatorCollector.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public static Creators collectCreators(AnnotationIntrospector intr,
        TypeResolutionContext tc, 
        JavaType type, Class<?> primaryMixIn)
{
    // Constructor also always members of resolved class, parent == resolution context
    return new AnnotatedCreatorCollector(intr, tc)
            .collect(type, primaryMixIn);
}
 
Example #23
Source File: Util.java    From oxAuth with MIT License 5 votes vote down vote up
public static ObjectMapper createJsonMapper() {
    final AnnotationIntrospector jaxb = new JaxbAnnotationIntrospector();
    final AnnotationIntrospector jackson = new JacksonAnnotationIntrospector();

    final AnnotationIntrospector pair = AnnotationIntrospector.pair(jackson, jaxb);

    final ObjectMapper mapper = new ObjectMapper();
    mapper.getDeserializationConfig().with(pair);
    mapper.getSerializationConfig().with(pair);
    return mapper;
}
 
Example #24
Source File: AllureReportUtils.java    From allure1 with Apache License 2.0 5 votes vote down vote up
/**
 * Create Jackson mapper with {@link JaxbAnnotationIntrospector}
 *
 * @return {@link com.fasterxml.jackson.databind.ObjectMapper}
 */
public static ObjectMapper createMapperWithJaxbAnnotationInspector() {
    ObjectMapper mapper = new ObjectMapper();
    AnnotationIntrospector annotationInspector = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
    mapper.getSerializationConfig().with(annotationInspector);
    return mapper;
}
 
Example #25
Source File: QueryResponseMessageJsonEncoder.java    From datawave with Apache License 2.0 5 votes vote down vote up
@Override
public void init(EndpointConfig config) {
    mapper = new ObjectMapper();
    mapper.enable(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME);
    mapper.setAnnotationIntrospector(AnnotationIntrospector.pair(new JacksonAnnotationIntrospector(),
                    new JaxbAnnotationIntrospector(mapper.getTypeFactory())));
    // Don't close the output stream
    mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
    // Don't include NULL properties.
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
 
Example #26
Source File: JacksonContextResolver.java    From datawave with Apache License 2.0 5 votes vote down vote up
public JacksonContextResolver() {
    mapper = new ObjectMapper();
    mapper.enable(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME);
    mapper.setAnnotationIntrospector(AnnotationIntrospector.pair(new JacksonAnnotationIntrospector(),
                    new JaxbAnnotationIntrospector(mapper.getTypeFactory())));
    mapper.setSerializationInclusion(Include.NON_NULL);
}
 
Example #27
Source File: ShopifySdkObjectMapper.java    From shopify-sdk with Apache License 2.0 5 votes vote down vote up
public static ObjectMapper buildMapper() {
	final ObjectMapper mapper = new ObjectMapper();
	mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

	final AnnotationIntrospector pair = AnnotationIntrospector.pair(
			new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()), new JacksonAnnotationIntrospector());
	mapper.setAnnotationIntrospector(pair);

	mapper.enable(MapperFeature.USE_ANNOTATIONS);
	return mapper;
}
 
Example #28
Source File: ConjureParser.java    From conjure with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static ObjectMapper createConjureParserObjectMapper() {
    ObjectMapper mapper = new ObjectMapper(new YAMLFactory())
            .registerModule(new Jdk8Module())
            .setAnnotationIntrospector(AnnotationIntrospector.pair(
                    new KebabCaseEnforcingAnnotationInspector(), // needs to come first.
                    new JacksonAnnotationIntrospector()));
    mapper.enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION);
    return mapper;
}
 
Example #29
Source File: ObjectMapperProvider.java    From hermes with Apache License 2.0 5 votes vote down vote up
private static ObjectMapper createDefaultMapper() {
	AnnotationIntrospector jacksonIntrospector = new JacksonAnnotationIntrospector();
	ObjectMapper result = new ObjectMapper();
	result.configure(SerializationFeature.INDENT_OUTPUT, true);
	result.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
	result.getDeserializationConfig().withInsertedAnnotationIntrospector(jacksonIntrospector);
	result.getSerializationConfig().withInsertedAnnotationIntrospector(jacksonIntrospector);
	return result;
}
 
Example #30
Source File: AnnotatedClassBuilder.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
private static AnnotatedClass buildOldAnnotatedClass(Method method, Class<?> declaringClass,
													 SerializationConfig serializationConfig)
		throws InvocationTargetException, IllegalAccessException {
	boolean useAnnotations = serializationConfig.isAnnotationProcessingEnabled();
	AnnotationIntrospector aintr = useAnnotations ? serializationConfig.getAnnotationIntrospector() : null;
	return (AnnotatedClass) method.invoke(null, declaringClass, aintr, serializationConfig);
}