Example usage for com.fasterxml.jackson.databind JavaType getContentType

List of usage examples for com.fasterxml.jackson.databind JavaType getContentType

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind JavaType getContentType.

Prototype

public JavaType getContentType() 

Source Link

Usage

From source file:org.springframework.amqp.support.converter.DefaultJackson2JavaTypeMapper.java

public void fromJavaType(JavaType javaType, MessageProperties properties) {
    addHeader(properties, getClassIdFieldName(), javaType.getRawClass());

    if (javaType.isContainerType() && !javaType.isArrayType()) {
        addHeader(properties, getContentClassIdFieldName(), javaType.getContentType().getRawClass());
    }// w  w w .  j  a va2s  . c om

    if (javaType.getKeyType() != null) {
        addHeader(properties, getKeyClassIdFieldName(), javaType.getKeyType().getRawClass());
    }
}

From source file:org.redisson.codec.JsonJacksonCodec.java

public JsonJacksonCodec() {
    createObjectMapper(objectMapper);/* w ww  .j a v  a  2 s.c om*/
    TypeResolverBuilder<?> typer = new DefaultTypeResolverBuilder(DefaultTyping.NON_FINAL);
    typer.init(JsonTypeInfo.Id.CLASS, null);
    typer.inclusion(JsonTypeInfo.As.PROPERTY);
    objectMapper.setDefaultTyping(typer);

    createObjectMapper(mapObjectMapper);
    // type info inclusion
    TypeResolverBuilder<?> mapTyper = new DefaultTypeResolverBuilder(DefaultTyping.NON_FINAL) {
        public boolean useForType(JavaType t) {
            switch (_appliesFor) {
            case NON_CONCRETE_AND_ARRAYS:
                while (t.isArrayType()) {
                    t = t.getContentType();
                }
                // fall through
            case OBJECT_AND_NON_CONCRETE:
                return (t.getRawClass() == Object.class) || !t.isConcrete();
            case NON_FINAL:
                while (t.isArrayType()) {
                    t = t.getContentType();
                }
                // to fix problem with wrong long to int conversion
                if (t.getRawClass() == Long.class) {
                    return true;
                }
                return !t.isFinal(); // includes Object.class
            default:
                //case JAVA_LANG_OBJECT:
                return (t.getRawClass() == Object.class);
            }
        }
    };
    mapTyper.init(JsonTypeInfo.Id.CLASS, null);
    mapTyper.inclusion(JsonTypeInfo.As.PROPERTY);
    mapObjectMapper.setDefaultTyping(mapTyper);
}

From source file:org.gvnix.web.json.DataBinderMappingJackson2HttpMessageConverter.java

/**
 * Before call to {@link ObjectMapper#readValue(java.io.InputStream, Class)}
 * creates a {@link ServletRequestDataBinder} and put it to current Thread
 * in order to be used by the {@link DataBinderDeserializer}.
 * <p/>//from  w  w w. j  a v  a2  s  . c  o  m
 * Ref: <a href=
 * "http://java.dzone.com/articles/java-thread-local-%E2%80%93-how-use">When
 * to use Thread Local?</a>
 * 
 * @param javaType
 * @param inputMessage
 * @return
 */
private Object readJavaType(JavaType javaType, HttpInputMessage inputMessage) {
    try {
        Object target = null;
        String objectName = null;

        // CRear el DataBinder con un target object en funcion del javaType,
        // ponerlo en el thread local
        Class<?> clazz = javaType.getRawClass();
        if (Collection.class.isAssignableFrom(clazz)) {
            Class<?> contentClazz = javaType.getContentType().getRawClass();
            target = new DataBinderList<Object>(contentClazz);
            objectName = "list";
        } else if (Map.class.isAssignableFrom(clazz)) {
            // TODO Class<?> contentClazz =
            // javaType.getContentType().getRawClass();
            target = CollectionFactory.createMap(clazz, 0);
            objectName = "map";
        } else {
            target = BeanUtils.instantiateClass(clazz);
            objectName = "bean";
        }

        WebDataBinder binder = new ServletRequestDataBinder(target, objectName);
        binder.setConversionService(this.conversionService);
        binder.setAutoGrowNestedPaths(true);
        binder.setValidator(validator);

        ThreadLocalUtil.setThreadVariable(BindingResult.MODEL_KEY_PREFIX.concat("JSON_DataBinder"), binder);

        Object value = getObjectMapper().readValue(inputMessage.getBody(), javaType);

        return value;
    } catch (IOException ex) {
        throw new HttpMessageNotReadableException("Could not read JSON: ".concat(ex.getMessage()), ex);
    }
}

From source file:org.candlepin.swagger.CandlepinSwaggerModelConverter.java

public Property resolveProperty(Type type, ModelConverterContext context, Annotation[] annotations,
        Iterator<ModelConverter> next) {
    JavaType propType = null;

    /**//ww  w  .jav  a  2  s .  c om
     * See java doc of NestedComplexType. This unwrapping makes sure that a
     * real type of field is passed to _mapper
     */
    if (type instanceof NestedComplexType) {
        propType = pMapper.constructType(((NestedComplexType) type).getOriginalType());
    } else {
        propType = pMapper.constructType(type);
    }

    log.debug("resolveProperty {}", propType);

    Property property = null;
    if (propType.isContainerType()) {
        JavaType keyType = propType.getKeyType();
        JavaType valueType = propType.getContentType();
        if (keyType != null && valueType != null) {
            property = new MapProperty()
                    .additionalProperties(context.resolveProperty(valueType, new Annotation[] {}));
        } else if (valueType != null) {
            ArrayProperty arrayProperty = new ArrayProperty()
                    .items(context.resolveProperty(valueType, new Annotation[] {}));
            if (pIsSetType(propType.getRawClass())) {
                arrayProperty.setUniqueItems(true);
            }
            property = arrayProperty;
        }
    } else {
        property = PrimitiveType.createProperty(propType);
    }

    if (property == null) {
        if (propType.isEnumType()) {
            property = new StringProperty();
            pAddEnumProps(propType.getRawClass(), property);
        } else if (pIsOptionalType(propType)) {
            property = context.resolveProperty(propType.containedType(0), null);
        } else {
            // complex type
            Model innerModel = context.resolve(type);
            if (innerModel instanceof ModelImpl) {
                ModelImpl mi = (ModelImpl) innerModel;
                property = new RefProperty(
                        StringUtils.isNotEmpty(mi.getReference()) ? mi.getReference() : mi.getName());
            }
        }
    }

    return property;
}

From source file:org.candlepin.swagger.CandlepinSwaggerModelConverter.java

public Model resolve(Type rawType, ModelConverterContext context, Iterator<ModelConverter> next) {
    if (this.shouldIgnoreClass(rawType)) {
        return null;
    }//from  w ww .j a v a2  s .  co  m

    /**
     * See java doc of NestedComplexType. This unwrapping makes sure that a
     * real type of field used throughout the method. At the same time flag
     * 'isNested' helps to indicate later in the method that this type may
     * be introspected as Hateoas enabled field
     */
    boolean isNested = false;
    if (rawType instanceof NestedComplexType) {
        isNested = true;
        NestedComplexType nested = (NestedComplexType) rawType;
        rawType = nested.getOriginalType();
    }
    JavaType type = pMapper.constructType(rawType);

    if (type.isEnumType() || PrimitiveType.fromType(type) != null) {
        // We don't build models for primitive types
        return null;
    }

    final BeanDescription beanDesc = pMapper.getSerializationConfig().introspect(type);
    // Couple of possibilities for defining
    String name = isNested ? "Nested" : "";
    name += pTypeName(type, beanDesc);

    if ("Object".equals(name)) {
        return new ModelImpl();
    }

    final ModelImpl model = new ModelImpl().type(ModelImpl.OBJECT).name(name)
            .description(pDescription(beanDesc.getClassInfo()));

    if (!type.isContainerType()) {
        // define the model here to support self/cyclic referencing of
        // models
        context.defineModel(name, model, type, null);
    }

    if (type.isContainerType()) {
        // We treat collections as primitive types, just need to add models
        // for values (if any)
        context.resolve(type.getContentType());
        return null;
    }
    // if XmlRootElement annotation, construct an Xml object and attach it
    // to the model
    XmlRootElement rootAnnotation = beanDesc.getClassAnnotations().get(XmlRootElement.class);
    if (rootAnnotation != null && !"".equals(rootAnnotation.name())
            && !"##default".equals(rootAnnotation.name())) {
        log.debug(rootAnnotation.toString());
        Xml xml = new Xml().name(rootAnnotation.name());
        if (rootAnnotation.namespace() != null && !"".equals(rootAnnotation.namespace())
                && !"##default".equals(rootAnnotation.namespace())) {
            xml.namespace(rootAnnotation.namespace());
        }
        model.xml(xml);
    }

    // see if @JsonIgnoreProperties exist
    Set<String> propertiesToIgnore = new HashSet<String>();
    JsonIgnoreProperties ignoreProperties = beanDesc.getClassAnnotations().get(JsonIgnoreProperties.class);
    if (ignoreProperties != null) {
        propertiesToIgnore.addAll(Arrays.asList(ignoreProperties.value()));
    }

    final ApiModel apiModel = beanDesc.getClassAnnotations().get(ApiModel.class);
    String disc = (apiModel == null) ? "" : apiModel.discriminator();

    if (apiModel != null && StringUtils.isNotEmpty(apiModel.reference())) {
        model.setReference(apiModel.reference());
    }

    if (disc.isEmpty()) {
        // longer method would involve
        // AnnotationIntrospector.findTypeResolver(...) but:
        JsonTypeInfo typeInfo = beanDesc.getClassAnnotations().get(JsonTypeInfo.class);
        if (typeInfo != null) {
            disc = typeInfo.property();
        }
    }
    if (!disc.isEmpty()) {
        model.setDiscriminator(disc);
    }

    List<Property> props = new ArrayList<Property>();
    for (BeanPropertyDefinition propDef : beanDesc.findProperties()) {
        parseProperty(context, isNested, beanDesc, propertiesToIgnore, props, propDef);
    }

    Collections.sort(props, getPropertyComparator());

    Map<String, Property> modelProps = new LinkedHashMap<String, Property>();
    for (Property prop : props) {
        modelProps.put(prop.getName(), prop);
    }
    model.setProperties(modelProps);

    /**
     * This must be done after model.setProperties so that the model's set
     * of properties is available to filter from any subtypes
     **/
    if (!resolveSubtypes(model, beanDesc, context)) {
        model.setDiscriminator(null);
    }

    return model;
}