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

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

Introduction

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

Prototype

@SuppressWarnings({ "unchecked", "resource" })
public <T extends JsonNode> T valueToTree(Object fromValue) throws IllegalArgumentException 

Source Link

Document

Reverse of #treeToValue ; given a value (usually bean), will construct equivalent JSON Tree representation.

Usage

From source file:org.thingsboard.rule.engine.action.TbAlarmNodeTest.java

private void initWithClearAlarmScript() {
    try {//from w  w w .jav a 2 s.c o  m
        TbClearAlarmNodeConfiguration config = new TbClearAlarmNodeConfiguration();
        config.setAlarmType("SomeType");
        config.setAlarmDetailsBuildJs("DETAILS");
        ObjectMapper mapper = new ObjectMapper();
        TbNodeConfiguration nodeConfiguration = new TbNodeConfiguration(mapper.valueToTree(config));

        when(ctx.createJsScriptEngine("DETAILS")).thenReturn(detailsJs);

        when(ctx.getTenantId()).thenReturn(tenantId);
        when(ctx.getJsExecutor()).thenReturn(executor);
        when(ctx.getAlarmService()).thenReturn(alarmService);
        when(ctx.getDbCallbackExecutor()).thenReturn(dbExecutor);

        mockJsExecutor();

        node = new TbClearAlarmNode();
        node.init(ctx, nodeConfiguration);
    } catch (TbNodeException ex) {
        throw new IllegalStateException(ex);
    }
}

From source file:org.thingsboard.rule.engine.action.TbAlarmNodeTest.java

private void initWithCreateAlarmScript() {
    try {/* w w w  .  ja  v  a 2  s .c  om*/
        TbCreateAlarmNodeConfiguration config = new TbCreateAlarmNodeConfiguration();
        config.setPropagate(true);
        config.setSeverity(CRITICAL);
        config.setAlarmType("SomeType");
        config.setAlarmDetailsBuildJs("DETAILS");
        ObjectMapper mapper = new ObjectMapper();
        TbNodeConfiguration nodeConfiguration = new TbNodeConfiguration(mapper.valueToTree(config));

        when(ctx.createJsScriptEngine("DETAILS")).thenReturn(detailsJs);

        when(ctx.getTenantId()).thenReturn(tenantId);
        when(ctx.getJsExecutor()).thenReturn(executor);
        when(ctx.getAlarmService()).thenReturn(alarmService);
        when(ctx.getDbCallbackExecutor()).thenReturn(dbExecutor);

        mockJsExecutor();

        node = new TbCreateAlarmNode();
        node.init(ctx, nodeConfiguration);
    } catch (TbNodeException ex) {
        throw new IllegalStateException(ex);
    }
}

From source file:com.googlecode.jsonschema2pojo.integration.FormatIT.java

@Test
public void valueCanBeSerializedAndDeserialized() throws NoSuchMethodException, IOException,
        IntrospectionException, IllegalAccessException, InvocationTargetException {

    ObjectMapper objectMapper = new ObjectMapper();

    ObjectNode node = objectMapper.createObjectNode();
    node.put(propertyName, jsonValue.toString());

    Object pojo = objectMapper.treeToValue(node, classWithFormattedProperties);

    Method getter = new PropertyDescriptor(propertyName, classWithFormattedProperties).getReadMethod();

    assertThat(getter.invoke(pojo).toString(), is(equalTo(javaValue.toString())));

    JsonNode jsonVersion = objectMapper.valueToTree(pojo);

    assertThat(jsonVersion.get(propertyName).asText(), is(equalTo(jsonValue.toString())));

}

From source file:ru.histone.spring.mvc.HistoneView.java

@Override
protected void renderMergedTemplateModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    ObjectMapper jackson = new ObjectMapper();
    ObjectNode context = jackson.createObjectNode();
    for (Map.Entry<String, Object> entry : model.entrySet()) {
        if (entry.getKey().startsWith("context.")) {
            String key = entry.getKey().substring(8);
            Object val = entry.getValue();

            if (val instanceof JsonNode) {
                context.put(key, (JsonNode) val);
            } else {
                JsonNode jsonVal = jackson.valueToTree(val);
                context.put(key, jsonVal);
            }/*from   w  w w  .  j  a  v  a 2s .  c om*/
        }
    }

    response.setCharacterEncoding("UTF-8");
    Reader content = new InputStreamReader(getServletContext().getResourceAsStream(getUrl()), "UTF-8");
    getHistone().setGlobalProperty(GlobalProperty.BASE_URI, "webapp:" + getUrl());
    String result = getHistone().evaluate(getUrl(), content, context);
    response.getOutputStream().write(result.getBytes("UTF-8"));
}

From source file:com.baasbox.Global.java

public ObjectNode prepareError(RequestHeader request, String error) {
    ObjectNode result = Json.newObject();
    ObjectMapper mapper = new ObjectMapper();
    result.put("result", "error");
    result.put("message", error);
    result.put("resource", request.path());
    result.put("method", request.method());
    result.put("request_header", (JsonNode) mapper.valueToTree(request.headers()));
    result.put("API_version", BBConfiguration.configuration.getString(BBConfiguration.API_VERSION));
    setCallIdOnResult(request, result);//from  www  .j  a v  a  2s. co  m
    return result;
}

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

/**
 * Get the issues of a project.//from  w w w  .  j  av  a 2  s.  c o m
 * 
 * @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:services.plugins.atlassian.jira.jira1.client.JiraService.java

/**
 * Create a Jira project.//from  w  ww  .  ja  v a 2 s.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:controllers.core.TimesheetController.java

/**
 * Get the activities of type./*from   w  w  w  .  j  a va  2 s  .c om*/
 */
@Restrict({ @Group(IMafConstants.TIMESHEET_ENTRY_PERMISSION) })
public Result getActivities() {

    JsonNode json = request().body().asJson();
    Long activityTypeId = json.findPath("activityTypeId").asLong();

    List<TimesheetActivity> activities = TimesheetDao.getTimesheetActivityAsListByActivityType(activityTypeId);
    List<OptionData> options = new ArrayList<OptionData>();

    for (TimesheetActivity activity : activities) {
        options.add(new OptionData(activity.id, activity.getName()));
    }

    ObjectMapper mapper = new ObjectMapper();

    return ok((JsonNode) mapper.valueToTree(options));
}

From source file:controllers.core.TimesheetController.java

/**
 * Get the packages of a portfolio entry.
 *//* w w w  .  j  a  v a2s  .com*/
@Restrict({ @Group(IMafConstants.TIMESHEET_ENTRY_PERMISSION) })
public Result getPackages() {

    JsonNode json = request().body().asJson();
    Long portfolioEntryId = json.findPath("portfolioEntryId").asLong();

    List<PortfolioEntryPlanningPackage> packages = PortfolioEntryPlanningPackageDao
            .getPEPlanningPackageAsListByPE(portfolioEntryId);
    List<OptionData> options = new ArrayList<OptionData>();

    for (PortfolioEntryPlanningPackage p : packages) {
        options.add(new OptionData(p.id, p.getName()));
    }

    ObjectMapper mapper = new ObjectMapper();

    return ok((JsonNode) mapper.valueToTree(options));
}

From source file:com.basistech.rosette.dm.json.plain.JsonTest.java

@Test
public void testForwardCompatibilityNoisy() throws Exception {
    ObjectMapper mapper = objectMapper();
    JsonNode tree = mapper.valueToTree(referenceTextOldEntities);
    ObjectNode attributes = (ObjectNode) tree.get("attributes");
    ObjectNode extendedObject = attributes.putObject("novelty");
    extendedObject.put("type", "novelty");
    extendedObject.put("startOffset", 4);
    extendedObject.put("endOffset", 8);
    extendedObject.put("color", "pari");

    AnnotatedText read = mapper.treeToValue(tree, AnnotatedText.class);
    BaseAttribute novelty = read.getAttributes().get("novelty");
    assertNotNull(novelty);/*  w  w w .  ja va  2s . co m*/
    assertEquals(4, novelty.getExtendedProperties().get("startOffset"));
    assertEquals(8, novelty.getExtendedProperties().get("endOffset"));
    assertEquals("pari", novelty.getExtendedProperties().get("color"));
}