Example usage for com.fasterxml.jackson.databind.type TypeFactory defaultInstance

List of usage examples for com.fasterxml.jackson.databind.type TypeFactory defaultInstance

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind.type TypeFactory defaultInstance.

Prototype

public static TypeFactory defaultInstance() 

Source Link

Usage

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

@Test
public void shouldUseTheKeyClassProvidedByTheLookupMapIfPresent() {
    properties.getHeaders().put(javaTypeMapper.getClassIdFieldName(), mapClass.getName());
    properties.getHeaders().put(javaTypeMapper.getContentClassIdFieldName(), "java.lang.String");
    properties.getHeaders().put("__KeyTypeId__", "trade");

    Map<String, Class<?>> map = map("trade", SimpleTrade.class);
    map.put(javaTypeMapper.getClassIdFieldName(), mapClass);
    map.put(javaTypeMapper.getContentClassIdFieldName(), String.class);
    javaTypeMapper.setIdClassMapping(map);

    JavaType javaType = javaTypeMapper.toJavaType(properties);

    assertThat((MapType) javaType,// www  .j a  v  a2s  .c  o m
            equalTo(TypeFactory.defaultInstance().constructMapType(mapClass,
                    TypeFactory.defaultInstance().constructType(SimpleTrade.class),
                    TypeFactory.defaultInstance().constructType(String.class))));
}

From source file:org.brutusin.json.impl.JacksonCodec.java

public Pair<Object, Integer> parse(String json, Type type, Map<String, InputStream> streams)
        throws ParseException {
    if (json == null || json.trim().isEmpty()) {
        return null;
    }/*from  w  ww .  j  a v  a  2  s . c om*/
    try {
        SerializationContext sc = new SerializationContext(streams);
        SerializationContext.setCurrentContext(sc);
        JavaType jt = TypeFactory.defaultInstance().constructType(type);
        return new Pair<Object, Integer>(mapper.readValue(json, jt), sc.getDeclaredStreams());
    } catch (JsonParseException ex) {
        throw new ParseException(ex);
    } catch (JsonMappingException ex) {
        throw new ParseException(ex);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    } finally {
        SerializationContext.closeCurrentContext();
    }
}

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

@Test
public void fromJavaTypeShouldPopulateWithKeyTypeAndContentJavaTypeNameByDefault() {

    javaTypeMapper.fromJavaType(TypeFactory.defaultInstance().constructMapType(mapClass,
            TypeFactory.defaultInstance().constructType(SimpleTrade.class),
            TypeFactory.defaultInstance().constructType(String.class)), properties);

    String className = (String) properties.getHeaders().get(javaTypeMapper.getClassIdFieldName());
    String contentClassName = (String) properties.getHeaders().get(javaTypeMapper.getContentClassIdFieldName());
    String keyClassName = (String) properties.getHeaders().get(javaTypeMapper.getKeyClassIdFieldName());

    assertThat(className, equalTo(HashMap.class.getName()));
    assertThat(contentClassName, equalTo(String.class.getName()));
    assertThat(keyClassName, equalTo(SimpleTrade.class.getName()));
}

From source file:com.zxy.commons.json.JsonUtils.java

/**
 * json?Map/*w w w . j a v a  2 s . co  m*/
 * 
 * @param <K> This is the key parameter
 * @param <V> This is the value parameter
 * @param include include
 * @param mapJsonString map?json
 * @param keyClass key
 * @param valueClass class
 * @return ?
 */
public static <K, V> Map<K, V> toMap(JsonInclude.Include include, String mapJsonString, Class<K> keyClass,
        Class<V> valueClass) {
    // Map<K, V> map = mapper.readValue(mapString, new TypeReference<Map<K, V>>() {});
    try {
        ObjectMapper mapper = getObjectMapper(include);
        return mapper.readValue(mapJsonString,
                TypeFactory.defaultInstance().constructMapType(Map.class, keyClass, valueClass));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.springframework.rest.documentation.boot.SwaggerDocumentationEndpoint.java

private void addModelForType(String type, Map<String, ClassDescriptor> responseClasses,
        Documentation documentation) {/*from   w  w w.j  a v  a2s .  c  o m*/
    String name = getSwaggerDataType(type);
    if (documentation.getModels() == null || !documentation.getModels().containsKey(name)) {
        DocumentationSchema schema = new DocumentationSchema();

        ClassDescriptor classDescriptor = responseClasses.get(type);
        if (classDescriptor != null) {
            schema.setDescription(classDescriptor.getName());
        }

        try {
            Class<?> clazz = Class.forName(type);

            if (clazz.isEnum()) {
                Object[] enumConstants = clazz.getEnumConstants();
                List<String> values = new ArrayList<String>();
                for (Object enumConstant : enumConstants) {
                    values.add(enumConstant.toString());
                }
                schema.setAllowableValues(new DocumentationAllowableListValues(values));
            } else {
                BasicClassIntrospector introspector = new BasicClassIntrospector();

                Map<String, DocumentationSchema> properties = new HashMap<String, DocumentationSchema>();

                BasicBeanDescription descriptor = introspector.forSerialization(
                        this.objectMapper.getSerializationConfig(),
                        TypeFactory.defaultInstance().constructType(clazz),
                        this.objectMapper.getSerializationConfig());

                for (BeanPropertyDefinition property : descriptor.findProperties()) {
                    String propertyName = property.getName();
                    DocumentationSchema propertySchema = new DocumentationSchema();
                    MethodDescriptor methodDescriptor = classDescriptor
                            .getMethodDescriptor((Method) property.getAccessor().getAnnotated());
                    if (methodDescriptor != null) {
                        Class<?> propertyClass = Class.forName(methodDescriptor.getReturnType());

                        propertySchema.setDescription(methodDescriptor.getSummary());

                        if (propertyClass.isEnum()) {
                            Object[] enumConstants = propertyClass.getEnumConstants();
                            List<String> values = new ArrayList<String>();
                            for (Object enumConstant : enumConstants) {
                                values.add(enumConstant.toString());
                            }
                            propertySchema.setType("string");
                            propertySchema.setAllowableValues(new DocumentationAllowableListValues(values));
                        } else {
                            propertySchema.setType(getSwaggerDataType(methodDescriptor.getReturnType()));
                            addModelForType(methodDescriptor.getReturnType(), responseClasses, documentation);
                        }
                    }

                    properties.put(propertyName, propertySchema);
                }

                schema.setProperties(properties);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

        documentation.addModel(name, schema);
    }
}

From source file:com.palantir.typescript.services.language.LanguageEndpoint.java

public List<NavigationBarItem> getNavigationBarItems(String serviceKey, String fileName) {
    checkNotNull(serviceKey);//from w  w  w  . ja  v  a 2s.com
    checkNotNull(fileName);

    Request request = new Request(SERVICE, "getNavigationBarItems", serviceKey, fileName);
    CollectionType returnType = TypeFactory.defaultInstance().constructCollectionType(List.class,
            NavigationBarItem.class);
    return this.bridge.call(request, returnType);
}

From source file:com.palantir.typescript.services.language.LanguageEndpoint.java

public List<ReferenceEntry> getOccurrencesAtPosition(String serviceKey, String fileName, int position) {
    checkNotNull(serviceKey);//from w  ww .  j a v  a  2s  .  co m
    checkNotNull(fileName);
    checkArgument(position >= 0);

    Request request = new Request(SERVICE, "getOccurrencesAtPosition", serviceKey, fileName, position);
    CollectionType returnType = TypeFactory.defaultInstance().constructCollectionType(List.class,
            ReferenceEntry.class);
    return this.bridge.call(request, returnType);
}

From source file:io.swagger.jaxrs.MethodProcessor.java

private static boolean isVoid(Type type) {
    final Class<?> cls = TypeFactory.defaultInstance().constructType(type).getRawClass();
    return Void.class.isAssignableFrom(cls) || Void.TYPE.isAssignableFrom(cls);
}

From source file:com.googlecode.jsonrpc4j.JsonRpcClient.java

/**
 * Reads a JSON-PRC response from the server.  This blocks until
 * a response is received./*from   w ww. ja  v  a2  s . com*/
 *
 * @param returnType the expected return type
 * @param ips the {@link InputStream} to read from
 * @return the object returned by the JSON-RPC response
 * @throws Throwable on error
 */
public Object readResponse(Type returnType, InputStream ips) throws Throwable {

    // get node iterator
    ReadContext ctx = ReadContext.getReadContext(ips, mapper);

    // read the response
    ctx.assertReadable();
    JsonNode response = ctx.nextValue();
    if (LOGGER.isLoggable(Level.FINE)) {
        LOGGER.log(Level.FINE, "JSON-PRC Response: " + response.toString());
    }

    // bail on invalid response
    if (!response.isObject()) {
        throw new JsonRpcClientException(0, "Invalid JSON-RPC response", response);
    }
    ObjectNode jsonObject = ObjectNode.class.cast(response);

    // show to listener
    if (this.requestListener != null) {
        this.requestListener.onBeforeResponseProcessed(this, jsonObject);
    }

    // detect errors
    if (jsonObject.has("error") && jsonObject.get("error") != null && !jsonObject.get("error").isNull()) {

        // resolve and throw the exception
        if (exceptionResolver == null) {
            throw DefaultExceptionResolver.INSTANCE.resolveException(jsonObject);
        } else {
            throw exceptionResolver.resolveException(jsonObject);
        }
    }

    // convert it to a return object
    if (jsonObject.has("result") && !jsonObject.get("result").isNull() && jsonObject.get("result") != null) {
        if (returnType == null) {
            LOGGER.warning("Server returned result but returnType is null");
            return null;
        }

        JsonParser returnJsonParser = mapper.treeAsTokens(jsonObject.get("result"));
        JavaType returnJavaType = TypeFactory.defaultInstance().constructType(returnType);

        return mapper.readValue(returnJsonParser, returnJavaType);
    }

    // no return type
    return null;
}