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:io.swagger.jaxrs.MethodProcessor.java

private static boolean isValidResponse(Type type) {
    if (type == null) {
        return false;
    }/*w  ww .ja va 2 s.  c  o m*/
    final JavaType javaType = TypeFactory.defaultInstance().constructType(type);
    if (isVoid(javaType)) {
        return false;
    }
    final Class<?> cls = javaType.getRawClass();
    return !javax.ws.rs.core.Response.class.isAssignableFrom(cls) && !isResourceClass(cls);
}

From source file:eu.europa.ec.fisheries.uvms.reporting.service.util.ReportDeserializer.java

private MapConfigurationDTO createMapConfigurationDTO(boolean withMap, JsonNode mapConfigJsonNode) {
    if (withMap) {
        if (mapConfigJsonNode == null) {
            return MapConfigurationDTO.MapConfigurationDTOBuilder().build();
        } else {/*from  ww  w  .  jav a 2 s  .com*/
            Long spatialConnectId = (mapConfigJsonNode.get("spatialConnectId") != null)
                    ? mapConfigJsonNode.get("spatialConnectId").longValue()
                    : null;
            Long mapProjectionId = (mapConfigJsonNode.get("mapProjectionId") != null)
                    ? mapConfigJsonNode.get("mapProjectionId").longValue()
                    : null;
            Long displayProjectionId = (mapConfigJsonNode.get("displayProjectionId") != null)
                    ? mapConfigJsonNode.get("displayProjectionId").longValue()
                    : null;
            String coordinatesFormat = (mapConfigJsonNode.get("coordinatesFormat") != null)
                    ? mapConfigJsonNode.get("coordinatesFormat").textValue()
                    : null;
            String scaleBarUnits = (mapConfigJsonNode.get("scaleBarUnits") != null)
                    ? mapConfigJsonNode.get("scaleBarUnits").textValue()
                    : null;

            ObjectMapper objectMapper = new ObjectMapper();
            VisibilitySettingsDto visibilitySettingsDto;
            StyleSettingsDto styleSettingsDto;
            LayerSettingsDto layerSettingsDto;
            Map<String, ReferenceDataPropertiesDto> referenceData;

            if (mapConfigJsonNode.get("visibilitySettings") != null) {
                try {
                    visibilitySettingsDto = objectMapper.treeToValue(
                            mapConfigJsonNode.get("visibilitySettings"), VisibilitySettingsDto.class);
                } catch (JsonProcessingException e) {
                    log.warn("Unable to deserialize visibilitySettings JSON property", e);
                    visibilitySettingsDto = null;
                }
            } else {
                visibilitySettingsDto = null;
            }

            if (mapConfigJsonNode.get("stylesSettings") != null) {
                try {
                    styleSettingsDto = objectMapper.treeToValue(mapConfigJsonNode.get("stylesSettings"),
                            StyleSettingsDto.class);
                } catch (JsonProcessingException e) {
                    log.warn("Unable to deserialize stylesSettings JSON property", e);
                    styleSettingsDto = null;
                }
            } else {
                styleSettingsDto = null;
            }

            if (mapConfigJsonNode.get("layerSettings") != null) {
                try {
                    layerSettingsDto = objectMapper.treeToValue(mapConfigJsonNode.get("layerSettings"),
                            LayerSettingsDto.class);
                } catch (JsonProcessingException e) {
                    log.warn("Unable to deserialize layerSettings JSON property", e);
                    layerSettingsDto = null;
                }
            } else {
                layerSettingsDto = null;
            }

            if (mapConfigJsonNode.get("referenceDataSettings") != null) {
                try {
                    Object obj = objectMapper.treeToValue(mapConfigJsonNode.get("referenceDataSettings"),
                            Map.class);
                    String jsonString = objectMapper.writeValueAsString(obj);
                    referenceData = objectMapper.readValue(jsonString, TypeFactory.defaultInstance()
                            .constructMapType(Map.class, String.class, ReferenceDataPropertiesDto.class));
                } catch (IOException e) {
                    log.warn("Unable to deserialize referenceDataSettings JSON property", e);
                    referenceData = null;
                }
            } else {
                referenceData = null;
            }

            return MapConfigurationDTO.MapConfigurationDTOBuilder().spatialConnectId(spatialConnectId)
                    .mapProjectionId(mapProjectionId).displayProjectionId(displayProjectionId)
                    .coordinatesFormat(coordinatesFormat).scaleBarUnits(scaleBarUnits)
                    .styleSettings(styleSettingsDto).visibilitySettings(visibilitySettingsDto)
                    .layerSettings(layerSettingsDto).referenceData(referenceData).build();
        }
    } else {
        return null;
    }
}

From source file:ijfx.service.uicontext.UiContextService.java

public void importContextConfiguration(String json) {
    ObjectMapper mapper = new ObjectMapper();

    List<UiContext> contextList = null;

    try {//from  w w w  .j  av  a 2 s  .co m
        contextList = mapper.readValue(json,
                TypeFactory.defaultInstance().constructCollectionType(List.class, UiContext.class));

    } catch (IOException ex) {
        logger.log(Level.SEVERE, "Error when converting the json file into context configuration.", ex);
    }

    contextList.forEach(context -> {
        logger.info(String.format("Loaded context %s which is incompatible with : %s", context.getId(),
                context.getIncompatibles().stream().collect(Collectors.joining(", "))));
        uiContextMap.put(context.getId(), context);
    });

}

From source file:com.spotify.helios.client.HeliosClient.java

public ListenableFuture<Map<String, HostStatus>> hostStatuses(final List<String> hosts,
        final Map<String, String> queryParams) {
    final ConvertResponseToPojo<Map<String, HostStatus>> converter = ConvertResponseToPojo.create(
            TypeFactory.defaultInstance().constructMapType(Map.class, String.class, HostStatus.class),
            ImmutableSet.of(HTTP_OK));/*from  w w  w. ja v  a  2  s  . c om*/

    return transform(request(uri("/hosts/statuses", queryParams), "POST", hosts), converter);
}

From source file:io.sinistral.proteus.server.tools.swagger.Reader.java

@SuppressWarnings("deprecation")
private Swagger read(Class<?> cls, String parentPath, String parentMethod, boolean isSubresource,
        String[] parentConsumes, String[] parentProduces, Map<String, Tag> parentTags,
        List<Parameter> parentParameters, Set<Class<?>> scannedResources) {

    Map<String, Tag> tags = new TreeMap<>();

    List<SecurityRequirement> securities = new ArrayList<>();

    String[] consumes = new String[0];
    String[] produces = new String[0];
    final Set<Scheme> globalSchemes = EnumSet.noneOf(Scheme.class);

    Api api = ReflectionUtils.getAnnotation(cls, Api.class);

    boolean hasPathAnnotation = (ReflectionUtils.getAnnotation(cls, javax.ws.rs.Path.class) != null);
    boolean hasApiAnnotation = (api != null);
    boolean isApiHidden = hasApiAnnotation && api.hidden();

    // class readable only if annotated with ((@Path and @Api) or isSubresource ) - and @Api not hidden
    boolean classReadable = ((hasPathAnnotation && hasApiAnnotation) || isSubresource) && !isApiHidden;

    // with scanAllResources true in config and @Api not hidden scan only if it has also @Path annotation or is subresource
    boolean scanAll = !isApiHidden && config.isScanAllResources() && (hasPathAnnotation || isSubresource);

    // readable if classReadable or scanAll
    boolean readable = classReadable || scanAll;

    if (!readable) {
        return swagger;
    }/*from w w w . j  av a2 s.co m*/

    // api readable only if @Api present; cannot be hidden because checked in classReadable.

    if (hasApiAnnotation) {
        // the value will be used as a tag for 2.0 UNLESS a Tags annotation is present
        Set<String> tagStrings = extractTags(api);
        for (String tagString : tagStrings) {
            Tag tag = new Tag().name(tagString);
            tags.put(tagString, tag);
        }
        for (String tagName : tags.keySet()) {
            swagger.tag(tags.get(tagName));
        }

        if (!api.produces().isEmpty()) {
            produces = ReaderUtils.splitContentValues(new String[] { api.produces() });
        }
        if (!api.consumes().isEmpty()) {
            consumes = ReaderUtils.splitContentValues(new String[] { api.consumes() });
        }
        globalSchemes.addAll(parseSchemes(api.protocols()));

        for (Authorization auth : api.authorizations()) {
            if (auth.value() != null && !auth.value().isEmpty()) {
                SecurityRequirement security = new SecurityRequirement();
                security.setName(auth.value());
                for (AuthorizationScope scope : auth.scopes()) {
                    if (scope.scope() != null && !scope.scope().isEmpty()) {
                        security.addScope(scope.scope());
                    }
                }
                securities.add(security);
            }
        }
    }

    if (readable) {
        if (isSubresource) {
            if (parentTags != null) {
                tags.putAll(parentTags);
            }
        }
        // merge consumes, produces
        if (consumes.length == 0 && cls.getAnnotation(Consumes.class) != null) {
            consumes = ReaderUtils.splitContentValues(cls.getAnnotation(Consumes.class).value());
        }
        if (produces.length == 0 && cls.getAnnotation(Produces.class) != null) {
            produces = ReaderUtils.splitContentValues(cls.getAnnotation(Produces.class).value());
        }
        // look for method-level annotated properties

        // handle sub-resources by looking at return type

        final List<Parameter> globalParameters = new ArrayList<Parameter>();

        // look for constructor-level annotated properties
        globalParameters.addAll(ReaderUtils.collectConstructorParameters(cls, swagger));

        // look for field-level annotated properties
        globalParameters.addAll(ReaderUtils.collectFieldParameters(cls, swagger));

        // build class/interface level @ApiResponse list
        ApiResponses classResponseAnnotation = ReflectionUtils.getAnnotation(cls, ApiResponses.class);
        List<ApiResponse> classApiResponses = new ArrayList<ApiResponse>();
        if (classResponseAnnotation != null) {
            classApiResponses.addAll(Arrays.asList(classResponseAnnotation.value()));
        }

        // parse the method
        final javax.ws.rs.Path apiPath = ReflectionUtils.getAnnotation(cls, javax.ws.rs.Path.class);
        JavaType classType = TypeFactory.defaultInstance().constructType(cls);
        BeanDescription bd = new ObjectMapper().getSerializationConfig().introspect(classType);
        Method methods[] = cls.getMethods();
        for (Method method : methods) {
            AnnotatedMethod annotatedMethod = bd.findMethod(method.getName(), method.getParameterTypes());
            if (ReflectionUtils.isOverriddenMethod(method, cls)) {
                continue;
            }
            javax.ws.rs.Path methodPath = ReflectionUtils.getAnnotation(method, javax.ws.rs.Path.class);

            String operationPath = getPath(apiPath, methodPath, parentPath);
            Map<String, String> regexMap = new LinkedHashMap<>();
            operationPath = PathUtils.parsePath(operationPath, regexMap);

            if (operationPath != null) {
                if (isIgnored(operationPath)) {
                    continue;
                }

                List<String> pathParamNames = new ArrayList<>();

                Matcher m = PATH_PATTERN.matcher(operationPath);
                while (m.find()) {
                    String pathParamName = m.group(1);
                    int bracketIndex = pathParamName.indexOf('[');

                    if (bracketIndex > -1) {
                        pathParamName = pathParamName.substring(0, bracketIndex);
                    }

                    pathParamNames.add(pathParamName);
                }

                final ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class);
                String httpMethod = extractOperationMethod(apiOperation, method, SwaggerExtensions.chain());

                Operation operation = null;
                if (apiOperation != null || config.isScanAllResources() || httpMethod != null
                        || methodPath != null) {
                    operation = parseMethod(cls, method, annotatedMethod, globalParameters, classApiResponses,
                            pathParamNames);
                }
                if (operation == null) {
                    continue;
                }
                if (parentParameters != null) {
                    for (Parameter param : parentParameters) {
                        operation.parameter(param);
                    }
                }

                for (Parameter param : operation.getParameters()) {
                    if (regexMap.get(param.getName()) != null) {
                        String pattern = regexMap.get(param.getName());
                        param.setPattern(pattern);
                    }
                }

                if (apiOperation != null) {
                    for (Scheme scheme : parseSchemes(apiOperation.protocols())) {
                        operation.scheme(scheme);
                    }
                }

                if (operation.getSchemes() == null || operation.getSchemes().isEmpty()) {
                    for (Scheme scheme : globalSchemes) {
                        operation.scheme(scheme);
                    }
                }

                String[] apiConsumes = consumes;
                if (parentConsumes != null) {
                    Set<String> both = new LinkedHashSet<>(Arrays.asList(apiConsumes));
                    both.addAll(new LinkedHashSet<>(Arrays.asList(parentConsumes)));
                    if (operation.getConsumes() != null) {
                        both.addAll(new LinkedHashSet<String>(operation.getConsumes()));
                    }
                    apiConsumes = both.toArray(new String[both.size()]);
                }

                String[] apiProduces = produces;
                if (parentProduces != null) {
                    Set<String> both = new LinkedHashSet<>(Arrays.asList(apiProduces));
                    both.addAll(new LinkedHashSet<>(Arrays.asList(parentProduces)));
                    if (operation.getProduces() != null) {
                        both.addAll(new LinkedHashSet<String>(operation.getProduces()));
                    }
                    apiProduces = both.toArray(new String[both.size()]);
                }
                final Class<?> subResource = getSubResourceWithJaxRsSubresourceLocatorSpecs(method);
                if (subResource != null && !scannedResources.contains(subResource)) {
                    scannedResources.add(subResource);
                    read(subResource, operationPath, httpMethod, true, apiConsumes, apiProduces, tags,
                            operation.getParameters(), scannedResources);
                    // remove the sub resource so that it can visit it later in another path
                    // but we have a room for optimization in the future to reuse the scanned result
                    // by caching the scanned resources in the reader instance to avoid actual scanning
                    // the the resources again
                    scannedResources.remove(subResource);
                }

                // can't continue without a valid http method
                httpMethod = (httpMethod == null) ? parentMethod : httpMethod;

                if (httpMethod != null) {
                    if (apiOperation != null) {
                        for (String tag : apiOperation.tags()) {
                            if (!"".equals(tag)) {
                                operation.tag(tag);
                                swagger.tag(new Tag().name(tag));
                            }
                        }

                        operation.getVendorExtensions()
                                .putAll(BaseReaderUtils.parseExtensions(apiOperation.extensions()));
                    }

                    if (operation.getConsumes() == null) {
                        for (String mediaType : apiConsumes) {
                            operation.consumes(mediaType);
                        }
                    }
                    if (operation.getProduces() == null) {
                        for (String mediaType : apiProduces) {
                            operation.produces(mediaType);
                        }
                    }

                    if (operation.getTags() == null) {
                        for (String tagString : tags.keySet()) {
                            operation.tag(tagString);
                        }
                    }
                    // Only add global @Api securities if operation doesn't already have more specific securities
                    if (operation.getSecurity() == null) {
                        for (SecurityRequirement security : securities) {
                            operation.security(security);
                        }
                    }

                    Path path = swagger.getPath(operationPath);
                    if (path == null) {
                        path = new Path();
                        swagger.path(operationPath, path);
                    }
                    path.set(httpMethod, operation);

                    readImplicitParameters(method, operation);

                    readExternalDocs(method, operation);
                }
            }
        }
    }

    List<Tag> swaggerTags = new ArrayList<Tag>(swagger.getTags());

    swaggerTags.sort((a, b) -> {
        return a.getName().compareTo(b.getName());
    });

    swagger.setTags(swaggerTags);

    return swagger;
}

From source file:org.talend.components.service.rest.JdbcComponentIntegrationTest.java

@Test
public void getJdbcDefinition() throws java.io.IOException {
    // when// www. j av a2  s  .c  om
    Response response = given().accept(APPLICATION_JSON_UTF8_VALUE) //
            .expect() //
            .statusCode(200).log().ifError() //
            .get("/definitions/DATA_STORE");

    // then
    List<DefinitionDTO> definitions = mapper
            .readerFor(TypeFactory.defaultInstance().constructCollectionType(List.class, DefinitionDTO.class))
            .readValue(response.asInputStream());

    DefinitionDTO jdbcDef = null;

    for (DefinitionDTO definition : definitions) {
        if (DATA_STORE_DEFINITION_NAME.equals(definition.getName())) {
            jdbcDef = definition;
            break;
        }
    }
    assertNotNull(jdbcDef);
}

From source file:org.springframework.social.facebook.api.impl.FacebookTemplate.java

@SuppressWarnings("unchecked")
private <T> List<T> deserializeDataList(JsonNode jsonNode, final Class<T> elementType) {
    try {//from   www. jav  a 2  s. c  om
        CollectionType listType = TypeFactory.defaultInstance().constructCollectionType(List.class,
                elementType);
        return (List<T>) objectMapper.reader(listType).readValue(jsonNode.toString()); // TODO: EXTREMELY HACKY--TEMPORARY UNTIL I FIGURE OUT HOW JACKSON 2 DOES THIS
    } catch (IOException e) {
        throw new UncategorizedApiException("facebook",
                "Error deserializing data from Facebook: " + e.getMessage(), e);
    }
}

From source file:org.talend.components.service.rest.JdbcComponentTestIT.java

@Test
public void getJdbcDefinition() throws java.io.IOException {
    // when/*ww w . ja v a 2s  .co m*/
    Response response = given().accept(APPLICATION_JSON_UTF8_VALUE) //
            .expect() //
            .statusCode(200).log().ifError() //
            .get(getVersionPrefix() + "/definitions/DATA_STORE");

    // then
    List<DefinitionDTO> definitions = mapper
            .readerFor(TypeFactory.defaultInstance().constructCollectionType(List.class, DefinitionDTO.class))
            .readValue(response.asInputStream());

    DefinitionDTO jdbcDef = null;

    for (DefinitionDTO definition : definitions) {
        if (DATA_STORE_DEFINITION_NAME.equals(definition.getName())) {
            jdbcDef = definition;
            break;
        }
    }
    assertNotNull(jdbcDef);
}

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

/**
 * Reads a JSON-PRC response from the server. This blocks until a response
 * is received.//from  ww w  .ja  va  2 s.c  o  m
 * 
 * @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
 */
private <T> T readResponse(Type returnType, InputStream ips) throws Throwable {

    // read the response
    JsonNode response = mapper.readTree(new NoCloseInputStream(ips));
    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);

    // 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) {

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

        return mapper.readValue(returnJsonParser, returnJavaType);
    }

    // no return type
    return null;
}