Example usage for com.fasterxml.jackson.databind ObjectMapper treeToValue

List of usage examples for com.fasterxml.jackson.databind ObjectMapper treeToValue

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper treeToValue.

Prototype

@SuppressWarnings("unchecked")
@Override
public <T> T treeToValue(TreeNode n, Class<T> valueType) throws JsonProcessingException 

Source Link

Document

Convenience conversion method that will bind data given JSON tree contains into specific value (usually bean) type.

Usage

From source file:services.plugins.atlassian.jira.jira1.client.JiraService.java

/**
 * Create a Jira project./* w w w  .  ja  v a  2s  . c o m*/
 * 
 * Return the id of the created project.
 * 
 * Return null if the project is already existing in Jira.
 * 
 * @param project
 *            the project to create
 */
public String createProject(Project project) throws JiraServiceException {

    JsonNode content = null;

    try {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_NULL);
        content = mapper.valueToTree(project);
        Logger.debug("project: " + mapper.writeValueAsString(project));
    } catch (JsonProcessingException e) {
        throw new JiraServiceException(
                "JiraService/createProject: error when processing the project to a Json node", e);
    }

    JsonNode response = this.callPost(CREATE_PROJECT_ACTION, content);

    CreateProjectResponse createProjectResponse = null;
    try {
        ObjectMapper objectMapper = new ObjectMapper();
        createProjectResponse = objectMapper.treeToValue(response, CreateProjectResponse.class);
    } catch (JsonProcessingException e) {
        throw new JiraServiceException(
                "JiraService/createProject: error when processing the response to CreateProjectResponse.class",
                e);
    }

    if (createProjectResponse.success) {
        return createProjectResponse.projectRefId;
    } else {
        if (createProjectResponse.alreadyExists) {
            return null;
        } else {
            throw new JiraServiceException(
                    "JiraService/createProject: the response is a 200 with an unknown error.");
        }
    }

}

From source file:services.plugins.atlassian.jira.jira1.client.JiraService.java

/**
 * Get all Jira projects.//w  w  w. ja  v  a2 s  .  co m
 */
public List<Project> getProjects() throws JiraServiceException {

    JsonNode response = this.callGet(GET_PROJECTS_ACTION);

    List<Project> projects = new ArrayList<>();
    try {
        ObjectMapper objectMapper = new ObjectMapper();

        for (final JsonNode projectNode : response) {
            projects.add(objectMapper.treeToValue(projectNode, Project.class));
        }

        return projects;

    } catch (JsonProcessingException e) {
        throw new JiraServiceException(
                "JiraService/getProjects: error when processing the response to Project.class", e);
    }

}

From source file:services.plugins.atlassian.jira.jira1.client.JiraService.java

/**
 * Perform a call.// w w w  .j av a2 s  .  c o m
 * 
 * @param httpMethod
 *            the HTTP method (GET, POST...)
 * @param action
 *            the action name
 * @param queryParams
 *            the query parameters
 * @param content
 *            the request content (for POST)
 */
private JsonNode call(HttpMethod httpMethod, String action, List<NameValuePair> queryParams, JsonNode content)
        throws JiraServiceException {

    Date timestamp = new Date();

    Logger.debug("URL: " + this.getActionUrl(action));
    Logger.debug("URI: " + this.getActionUri(action, queryParams));
    Logger.debug(TIMESTAMP_HEADER + ": " + String.valueOf(timestamp.getTime()));
    Logger.debug(AUTHENTICATION_DIGEST_HEADER + ": "
            + getAuthenticationDigest(timestamp.getTime(), this.getActionUri(action, queryParams)));

    WSRequest request = getWsClient().url(this.getActionUrl(action));
    request.setHeader(TIMESTAMP_HEADER, String.valueOf(timestamp.getTime()));
    request.setHeader(AUTHENTICATION_DIGEST_HEADER,
            getAuthenticationDigest(timestamp.getTime(), this.getActionUri(action, queryParams)));

    for (NameValuePair param : queryParams) {
        request = request.setQueryParameter(param.getName(), param.getValue());
    }

    Promise<WSResponse> reponse = null;

    switch (httpMethod) {
    case GET:
        reponse = request.get();
        break;
    case POST:
        reponse = request.post(content);
        break;
    }

    Promise<Pair<Integer, JsonNode>> jsonPromise = reponse
            .map(new Function<WSResponse, Pair<Integer, JsonNode>>() {
                public Pair<Integer, JsonNode> apply(WSResponse response) {
                    if (log.isDebugEnabled()) {
                        log.debug(response.getBody());
                    }
                    return Pair.of(response.getStatus(), response.asJson());
                }
            });

    Pair<Integer, JsonNode> response = jsonPromise.get(WS_TIMEOUT);

    Logger.debug("STATUS CODE: " + response.getLeft());

    if (response.getLeft().equals(200)) {
        return response.getRight();
    } else if (response.getLeft().equals(400)) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            ErrorResponse errorResponse = objectMapper.treeToValue(response.getRight(), ErrorResponse.class);
            Logger.error("API Message: " + errorResponse.message + " / API code: " + errorResponse.code);
            Logger.debug(errorResponse.trace);
            throw new JiraServiceException("JiraService: the call for the action '" + action
                    + "' returns a 400, please refer above for more details.");
        } catch (JsonProcessingException e) {
            throw new JiraServiceException("JiraService: the call for the action '" + action
                    + "' returns a 400 but an error occurred when processing the response to ErrorResponse.class",
                    e);
        }

    } else {
        throw new JiraServiceException(
                "JiraService: the call for the action '" + action + "' returns a " + response.getLeft());
    }

}

From source file:services.plugins.atlassian.jira.jira1.client.JiraService.java

/**
 * Get the issues of a project./*from   w  w  w  .j  a v a2 s  .  c om*/
 * 
 * @param isDefect
 *            set to true to get the defects, else the needs.
 * @param projectRefId
 *            the Jira project id
 * @param portfolioEntry
 *            the portfolio entry
 */
private List<Issue> getIssues(boolean isDefect, String projectRefId, PortfolioEntry portfolioEntry)
        throws JiraServiceException {

    JsonNode content = null;

    GetIssuesRequest getIssuesRequest = new GetIssuesRequest(projectRefId, portfolioEntry);
    try {
        ObjectMapper mapper = new ObjectMapper();
        content = mapper.valueToTree(getIssuesRequest);
        Logger.debug("issueRequest: " + mapper.writeValueAsString(getIssuesRequest));
    } catch (JsonProcessingException e) {
        throw new JiraServiceException(
                "JiraService/getIssues: error when processing the getIssuesRequest to a Json node", e);
    }

    String action = null;
    if (isDefect) {
        action = GET_DEFECTS_ACTION;
    } else {
        action = GET_NEEDS_ACTION;
    }

    JsonNode response = this.callPost(action, content);

    List<Issue> issues = new ArrayList<>();
    try {
        ObjectMapper objectMapper = new ObjectMapper();

        for (final JsonNode issueNode : response) {
            issues.add(objectMapper.treeToValue(issueNode, Issue.class));
        }

        return issues;

    } catch (JsonProcessingException e) {
        throw new JiraServiceException(
                "JiraService/getIssues: error when processing the response to Issue.class", e);
    }
}

From source file:cc.arduino.packages.discoverers.PluggableDiscovery.java

private void processJsonNode(ObjectMapper mapper, JsonNode node) {
    JsonNode eventTypeNode = node.get("eventType");
    if (eventTypeNode == null) {
        System.err.println(format("{0}: Invalid message, missing eventType", discoveryName));
        return;// ww w .  j av  a  2 s  . c  o m
    }

    switch (eventTypeNode.asText()) {
    case "error":
        try {
            PluggableDiscoveryMessage msg = mapper.treeToValue(node, PluggableDiscoveryMessage.class);
            debug("error: " + msg.getMessage());
            if (msg.getMessage().contains("START_SYNC")) {
                startPolling();
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return;

    case "list":
        JsonNode portsNode = node.get("ports");
        if (portsNode == null) {
            System.err.println(format("{0}: Invalid message, missing ports list", discoveryName));
            return;
        }
        if (!portsNode.isArray()) {
            System.err.println(format("{0}: Invalid message, ports list should be an array", discoveryName));
            return;
        }

        synchronized (portList) {
            portList.clear();
        }
        portsNode.forEach(portNode -> {
            BoardPort port = mapJsonNodeToBoardPort(mapper, node);
            if (port != null) {
                addOrUpdate(port);
            }
        });
        return;

    // Messages for SYNC updates

    case "add":
        BoardPort addedPort = mapJsonNodeToBoardPort(mapper, node);
        if (addedPort != null) {
            addOrUpdate(addedPort);
        }
        return;

    case "remove":
        BoardPort removedPort = mapJsonNodeToBoardPort(mapper, node);
        if (removedPort != null) {
            remove(removedPort);
        }
        return;

    default:
        debug("Invalid event: " + eventTypeNode.asText());
        return;
    }
}

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  www .j  a v  a  2  s .co m
            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:com.hortonworks.registries.schemaregistry.client.SchemaRegistryClient.java

private <T> List<T> getEntities(WebTarget target, Class<T> clazz) {
    List<T> entities = new ArrayList<>();
    String response = target.request(MediaType.APPLICATION_JSON_TYPE).get(String.class);
    try {/*from   www. ja v a  2s.co m*/
        ObjectMapper mapper = new ObjectMapper();
        JsonNode node = mapper.readTree(response);
        Iterator<JsonNode> it = node.get("entities").elements();
        while (it.hasNext()) {
            entities.add(mapper.treeToValue(it.next(), clazz));
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
    return entities;
}

From source file:com.hortonworks.streamline.webservice.RestIntegrationTest.java

/**
 * Get entity from the response string.//ww  w.  ja  va2 s . co  m
 *
 * @param response
 * @param clazz
 * @param <T>
 * @return
 */
private <T> T getEntity(String response, Class<T> clazz, List<String> fieldsToIgnore) {
    try {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode node = mapper.readTree(response);
        return filterFields(mapper.treeToValue(node, clazz), fieldsToIgnore);
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:com.hortonworks.streamline.webservice.RestIntegrationTest.java

/**
 * Get the entities from response string
 *
 * @param response//w  ww .j a v  a  2s .  c o m
 * @param clazz
 * @param <T>
 * @return
 */
private <T extends Object> List<T> getEntities(String response, Class<T> clazz, List<String> fieldsToIgnore) {
    List<T> entities = new ArrayList<>();
    try {
        ObjectMapper mapper = new ObjectMapper();
        JsonNode node = mapper.readTree(response);
        Iterator<JsonNode> it = node.get("entities").elements();
        while (it.hasNext()) {
            entities.add(filterFields(mapper.treeToValue(it.next(), clazz), fieldsToIgnore));
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
    return entities;
}

From source file:org.mitre.mpf.mvc.controller.JobController.java

private <T> T jsonPathToJsonNode(String jsonFilePath, String type, Class<T> returnTypeClass) {
    T jsonOutputObject = null;//from w w w . j  ava 2s . c  om
    JsonNode jsonNode = null;
    //this just means that the file was read, not that it is valid
    boolean successfulRead = false;
    ObjectMapper mapper = new ObjectMapper();

    if (jsonFilePath != null) {
        try {
            FileInputStream inputStream = new FileInputStream(jsonFilePath);
            if (inputStream != null) {
                String allText = IOUtils.toString(inputStream);
                if (allText != null && !allText.isEmpty()) {
                    jsonNode = mapper.readTree(allText);
                    successfulRead = true;
                }
                inputStream.close();

                //now try to map it to the object
                if (jsonNode != null) {
                    try {
                        jsonOutputObject = mapper.treeToValue(jsonNode, returnTypeClass);
                    } catch (JsonProcessingException e) {
                        log.error("Failed to map json output object file at '{}' to a JsonOutputObject.",
                                jsonFilePath, e);
                    }
                }
            }
        } catch (Exception ex) {
            log.error(
                    "Failed to read the json file at path '{}' in order to produce a json node, raised exception: ",
                    jsonFilePath, ex);
        }
    } else {
        //types can be - output
        log.error("Cannot create a json node without a '{}' output object file path.", type);
    }

    //making sure to log for null inputStream, null or empty read text, and a null jsonNode (though this should throw an
    //   exception from readTree and any issues mapping from a non null jsonNode should throw an exception when mapping to the output object
    //This will like produce multiple log statements when there is an error, but that is better than none and the extra
    //   statement will be helpful!
    if (!successfulRead || jsonNode == null) {
        log.error("Failed to properly read json from the object file at '{}'.", jsonFilePath);
    }

    return jsonOutputObject;
}