Java Code Examples for com.fasterxml.jackson.databind.SerializationConfig#introspect()

The following examples show how to use com.fasterxml.jackson.databind.SerializationConfig#introspect() . 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: Jackson2Parser.java    From typescript-generator with MIT License 5 votes vote down vote up
private static TypeProcessor createSpecificTypeProcessor() {
    return new TypeProcessor.Chain(
            new ExcludingTypeProcessor(Arrays.asList(JsonNode.class.getName())),
            new TypeProcessor() {
                @Override
                public TypeProcessor.Result processType(Type javaType, TypeProcessor.Context context) {
                    if (context.getTypeContext() instanceof Jackson2TypeContext) {
                        final Jackson2TypeContext jackson2TypeContext = (Jackson2TypeContext) context.getTypeContext();
                        if (!jackson2TypeContext.disableObjectIdentityFeature) {
                            final Type resultType = jackson2TypeContext.parser.processIdentity(javaType, jackson2TypeContext.beanPropertyWriter);
                            if (resultType != null) {
                                return context.withTypeContext(null).processType(resultType);
                            }
                        }
                        // Map.Entry
                        final Class<?> rawClass = Utils.getRawClassOrNull(javaType);
                        if (rawClass != null && Map.Entry.class.isAssignableFrom(rawClass)) {
                            final ObjectMapper objectMapper = jackson2TypeContext.parser.objectMapper;
                            final SerializationConfig serializationConfig = objectMapper.getSerializationConfig();
                            final BeanDescription beanDescription = serializationConfig
                                    .introspect(TypeFactory.defaultInstance().constructType(rawClass));
                            final JsonFormat.Value formatOverride = serializationConfig.getDefaultPropertyFormat(Map.Entry.class);
                            final JsonFormat.Value formatFromAnnotation = beanDescription.findExpectedFormat(null);
                            final JsonFormat.Value format = JsonFormat.Value.merge(formatFromAnnotation, formatOverride);
                            if (format.getShape() != JsonFormat.Shape.OBJECT) {
                                final Type mapType = Utils.replaceRawClassInType(javaType, Map.class);
                                return context.processType(mapType);
                            }
                        }
                    }
                    return null;
                }
            }
    );
}
 
Example 2
Source File: ConfigTreeBuilder.java    From dropwizard-guicey with MIT License 4 votes vote down vote up
/**
 * Use jackson serialization api to extract all configuration values with paths from configuration object.
 * Always analyze types, even if actual branch is not present at all (null value) in order to always bind
 * nulls and avoid "Schrodinger's binding" case. In short, bindings should not depend on configuration values
 * (presence).
 * <p>
 * Still, bindings may vary: for example, bound implementations may differ (best example is dropwizard server type),
 * as a consequences, parsed type may be different and so different properties paths could be recognized.
 *
 * @param config  jackson serialization config
 * @param content currently parsed paths
 * @param type    analyzed part type
 * @param object  analyzed part instance (may be null)
 * @return all configuration paths values
 */
@SuppressWarnings("checkstyle:CyclomaticComplexity")
private static List<ConfigPath> resolvePaths(final SerializationConfig config,
                                             final ConfigPath root,
                                             final List<ConfigPath> content,
                                             final Class type,
                                             final Object object,
                                             final GenericsContext genericsContext) {
    final BasicBeanDescription description = config.introspect(
            config.constructType(type)
    );

    for (BeanPropertyDefinition prop : description.findProperties()) {
        // ignore write-only or groovy special property
        if (!prop.couldSerialize() || prop.getName().equals("metaClass")) {
            continue;
        }
        final Object value;
        // if configuration doesn't expect serialization and throws error on access
        // (like netflix dynamic properties) it should not break app startup
        try {
            value = readValue(prop.getAccessor(), object);
        } catch (Exception ex) {
            LOGGER.warn("Can't bind configuration path '{}' due to {}: {}. Enable debug logs to see "
                            + "complete stack trace or use @JsonIgnore on property getter.",
                    fullPath(root, prop), ex.getClass().getSimpleName(), ex.getMessage());
            LOGGER.debug("Complete error: ", ex);
            continue;
        }

        final ConfigPath item = createItem(root, prop, value, genericsContext);
        content.add(item);
        if (root != null) {
            root.getChildren().add(item);
        }

        if (item.isCustomType() && !detectRecursion(item)) {
            // build generics context for actual value type (if not null)
            final GenericsContext subContext = prop.getGetter() != null
                    ? genericsContext.method(prop.getGetter().getAnnotated()).returnTypeAs(item.getValueType())
                    : genericsContext.fieldTypeAs(prop.getField().getAnnotated(), item.getValueType());

            resolvePaths(config, item, content, item.getValueType(),
                    item.getValue(), subContext);
        }
    }
    if (root != null) {
        // simple properties goes up and composite objects go lower (both groups sorted alphabetically)
        root.getChildren().sort(Comparator.comparing(o -> (o.isCustomType() ? 'b' : 'a') + o.getPath()));
    }
    return content;
}