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.kiji.rest.TestRowsResource.java

@Test
public void testMultipleCellPost() throws Exception {
    // Set up./*  ww  w.  j  av  a  2 s.c  om*/
    String stringRowKey = getEntityIdString("sample_table", 54323L);
    String encodedRowKey = URLEncoder.encode(stringRowKey, "UTF-8");

    KijiCell<String> postCell1 = fromInputs("group_family", "string_qualifier", 314592L, "helloworld",
            Schema.create(Type.STRING));
    KijiCell<Long> postCell2 = fromInputs("group_family", "long_qualifier", 314592L, 123L,
            Schema.create(Type.LONG));

    Team postTeam = new Team();
    postTeam.setBarracksStatus(94103L);
    postTeam.setId(88L);
    postTeam.setName("Windrunners");

    KijiCell<JsonNode> postCell3 = fromInputs("group_family", "team_qualifier", 314592L,
            AvroToJsonStringSerializer.getJsonNode(postTeam), postTeam.getSchema());

    KijiRestRow postRow = new KijiRestRow(
            KijiRestEntityId.create(stringToJsonNode(URLDecoder.decode(stringRowKey, "UTF-8"))));

    addCellToRow(postRow, postCell1);
    addCellToRow(postRow, postCell2);
    addCellToRow(postRow, postCell3);

    // Post.
    @SuppressWarnings("unchecked")
    Map<String, List<String>> target = client().resource(DEFAULT_ROWS_RESOURCE).type(MediaType.APPLICATION_JSON)
            .accept(MediaType.APPLICATION_JSON).post(Map.class, postRow);

    // Retrieve.
    URI resourceURI = UriBuilder.fromResource(RowsResource.class).queryParam("eid", encodedRowKey)
            .build("default", "sample_table");
    KijiRestRow returnRow = client().resource(resourceURI).get(KijiRestRow.class);

    // Check.
    assertEquals(target.get("targets").get(0),
            "/v1/instances/default/tables/sample_table/rows?eid=" + URLEncoder.encode(stringRowKey, UTF_8));
    assertEquals(123, returnRow.getCells().get("group_family").get("long_qualifier").get(0).getValue());
    assertEquals("helloworld",
            returnRow.getCells().get("group_family").get("string_qualifier").get(0).getValue());
    ObjectMapper mapper = new ObjectMapper();
    JsonNode node = mapper
            .valueToTree(returnRow.getCells().get("group_family").get("team_qualifier").get(0).getValue());
    assertEquals(94103L, node.get("barracks_status").get("long").asLong());
    assertEquals(88L, node.get("id").get("long").asLong());
    assertEquals("Windrunners", node.get("name").get("string").asText());
}

From source file:org.kiji.rest.TestRowsResource.java

@Test
public void testMapColumnPost() throws Exception {
    // Set up./*ww  w.ja  va  2 s.  c  om*/
    String stringRowKey = getEntityIdString("sample_table", 54325L);
    String encodedRowKey = URLEncoder.encode(stringRowKey, "UTF-8");

    KijiCell<String> postCell1 = fromInputs("strings", EXTENSIVE_COLUMN_TEST, 3141592L, "helloworld",
            Schema.create(Type.STRING));
    String longsColumnDec = " ";

    KijiCell<Long> postCell2 = fromInputs("longs", longsColumnDec, 3141592L, 987654567890L,
            Schema.create(Type.LONG));
    String bansColumnDec = "harkonnen:.:.?&;& ";

    PickBan postBan = new PickBan();
    postBan.setHeroId(1029384756L);
    postBan.setIsPick(true);
    postBan.setOrder(6L);
    postBan.setTeam(7654L);

    KijiCell<JsonNode> postCell3 = fromInputs("pick_bans", bansColumnDec, 3141592L,
            AvroToJsonStringSerializer.getJsonNode(postBan), postBan.getSchema());

    KijiRestRow postRow = new KijiRestRow(
            KijiRestEntityId.create(stringToJsonNode(URLDecoder.decode(stringRowKey, "UTF-8"))));

    addCellToRow(postRow, postCell1);
    addCellToRow(postRow, postCell2);
    addCellToRow(postRow, postCell3);

    // Post.
    URI resourceURI = UriBuilder.fromResource(RowsResource.class).build("default", "sample_table");
    Object target = client().resource(resourceURI).type(MediaType.APPLICATION_JSON)
            .accept(MediaType.APPLICATION_JSON).post(Object.class, postRow);

    // Retrieve.
    resourceURI = UriBuilder.fromResource(RowsResource.class).queryParam("eid", encodedRowKey).build("default",
            "sample_table");
    KijiRestRow returnRow = client().resource(resourceURI).get(KijiRestRow.class);

    // Check.
    assertTrue(target.toString().contains(
            "/v1/instances/default/tables/sample_table/rows?eid=" + URLEncoder.encode(stringRowKey, UTF_8)));
    assertTrue(returnRow.getCells().get("longs").containsKey(longsColumnDec));
    assertEquals(987654567890L, returnRow.getCells().get("longs").get(longsColumnDec).get(0).getValue());
    assertTrue(returnRow.getCells().get("strings").containsKey(EXTENSIVE_COLUMN_TEST));
    assertEquals("helloworld",
            returnRow.getCells().get("strings").get(EXTENSIVE_COLUMN_TEST).get(0).getValue());
    assertTrue(returnRow.getCells().get("pick_bans").containsKey(bansColumnDec));

    ObjectMapper mapper = new ObjectMapper();
    JsonNode node = mapper
            .valueToTree(returnRow.getCells().get("pick_bans").get(bansColumnDec).get(0).getValue());
    assertEquals(7654L, node.get("team").get("long").asLong());
    assertEquals(1029384756L, node.get("hero_id").get("long").asLong());
    assertEquals(6L, node.get("order").get("long").asLong());
    assertEquals(true, node.get("is_pick").get("boolean").asBoolean());
}

From source file:controllers.core.PortfolioEntryDeliveryController.java

/**
 * Follow a deliverable: get the deliverables of the other portfolio entry
 * (represented by the "id" query param).
 *//* www  .  j a  v  a 2 s .  c om*/
@With(CheckPortfolioEntryExists.class)
@Dynamic(IMafConstants.PORTFOLIO_ENTRY_VIEW_DYNAMIC_PERMISSION)
public Result getDeliverables() {

    Long id = Long.valueOf(request().getQueryString("id"));

    List<Deliverable> deliverables = DeliverableDAO.getDeliverableAsExprByPE(id).findList();
    List<OptionData> options = new ArrayList<OptionData>();

    for (Deliverable deliverable : deliverables) {
        options.add(new OptionData(deliverable.id, deliverable.getName()));
    }

    ObjectMapper mapper = new ObjectMapper();

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

}

From source file:io.cloudslang.content.json.actions.AddJsonPropertyToObject.java

/**
 * Inserts a new name/value property into a JSON object, where the value is a valid JSON string.
 * If the <b>newPropertyValue</b> input is not a valid string representation of a JSON object, the operation fails.
 * This operation can be used to add a property with a simple string value.
 *
 * @param jsonObject       The string representation of a JSON object.
 *                         Objects in JSON are a collection of name value pairs, separated by a colon and surrounded with curly brackets {}.
 *                         The name must be a string value, and the value can be a single string or any valid JSON object or array.
 *                         Examples: {"one":1, "two":2}, {"one":{"a":"a","B":"B"}, "two":"two", "three":[1,2,3.4]}
 * @param newPropertyName  The name of the new property that will be added to the JSON object.
 *                         Examples: property1, some_property, another property
 * @param newPropertyValue The value for the new property. This must be a valid JSON object.
 *                         Examples: 1, {"A":"A"}, [1,2,3,4]
 * @return a map containing the output of the operation. Keys present in the map are:
 * <p/>//from  www  .  j a  v a  2  s.c o m
 * <br><br><b>returnResult</b> - This will contain the JSON with the new property/value added.
 * <br><b>exception</b> - In case of success response, this result is empty. In case of failure response,
 * this result contains the java stack trace of the runtime exception.
 * <br><br><b>returnCode</b> - The returnCode of the operation: 0 for success, -1 for failure.
 */
@Action(name = "Add JSON Property to Object", outputs = { @Output(OutputNames.RETURN_RESULT),
        @Output(OutputNames.RETURN_CODE), @Output(OutputNames.EXCEPTION) }, responses = {
                @Response(text = ResponseNames.SUCCESS, field = OutputNames.RETURN_CODE, value = ReturnCodes.SUCCESS, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED),
                @Response(text = ResponseNames.FAILURE, field = OutputNames.RETURN_CODE, value = ReturnCodes.FAILURE, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR, isOnFail = true) })
public Map<String, String> execute(
        @Param(value = Constants.InputNames.JSON_OBJECT, required = true) String jsonObject,
        @Param(value = Constants.InputNames.NEW_PROPERTY_NAME, required = true) String newPropertyName,
        @Param(value = Constants.InputNames.NEW_PROPERTY_VALUE, required = true) String newPropertyValue,
        @Param(value = Constants.InputNames.VALIDATE_VALUE) String validateValue) {

    Map<String, String> returnResult = new HashMap<>();
    if (jsonObject == null || jsonObject.trim().equals(OtherValues.EMPTY_STRING)) {
        return populateResult(returnResult, new Exception("Empty jsonObject provided!"));
    }

    ObjectMapper mapper = new ObjectMapper().configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
    final boolean validateValueBoolean = JsonUtils.parseBooleanWithDefault(validateValue, true);

    if (StringUtilities.isBlank(newPropertyValue)) {
        final String exceptionValue = "The value for the property " + newPropertyName
                + " it is not a valid JSON object!";
        return populateResult(returnResult, new Exception(exceptionValue));
    }

    if (newPropertyName == null) {
        return populateResult(returnResult, new Exception("Null newPropertyName provided!"));
    }

    JsonNode jsonRoot;
    try {
        jsonRoot = mapper.readTree(jsonObject);
    } catch (Exception exception) {
        final String exceptionValue = "Invalid jsonObject provided! " + exception.getMessage();
        return populateResult(returnResult, exceptionValue, exception);
    }

    ContainerNode jsonNodes = null;
    JsonNode jsonNodeValueWrapper;
    try {
        jsonNodeValueWrapper = mapper.readTree(newPropertyValue);
    } catch (IOException exception) {
        if (!validateValueBoolean) {
            jsonNodeValueWrapper = mapper.valueToTree(newPropertyValue);
        } else {
            final String exceptionValue = "The value for the property " + newPropertyName
                    + " it is not a valid JSON object!";
            return populateResult(returnResult, exceptionValue, exception);
        }
    }
    if (jsonRoot instanceof ObjectNode) {
        jsonNodes = ((ObjectNode) jsonRoot).putPOJO(newPropertyName, jsonNodeValueWrapper);
    }
    if (jsonRoot instanceof ArrayNode) {
        jsonNodes = ((ArrayNode) jsonRoot).add(jsonNodeValueWrapper);
    }

    if (jsonNodes == null) {
        return populateResult(returnResult, new Exception("The value cannot be added!"));
    }
    return populateResult(returnResult, jsonNodes.toString(), null);
}

From source file:com.baasbox.controllers.actions.filters.WrapResponse.java

private ObjectNode prepareError(RequestHeader request, String error) {
    //List<StackTraceElement> st = this.tryToExtractTheStackTrace(error);
    List<String> st = this.tryToExtractTheStackTrace(error);

    com.fasterxml.jackson.databind.ObjectMapper mapper = com.baasbox.service.scripting.js.Json.mapper();
    ObjectNode result = Json.newObject();
    result.put("result", "error");

    //the error is an exception or a plain message?
    if (st.size() == 0) {
        result.put("message", error);
    } else {//  www. j  a va  2 s.  c o m
        Matcher headLineMatcher = headLinePattern.matcher(error);
        StringBuilder message = new StringBuilder();
        if (headLineMatcher.find()) {
            message.append(headLineMatcher.group(1));
            if (headLineMatcher.group(2) != null) {
                message.append(" ").append(headLineMatcher.group(2));
            }
        }
        result.put("message", message.toString());
        ArrayNode ston = result.putArray("stacktrace");
        st.forEach(x -> {
            ston.add(x);
        });
        result.put("full_stacktrace", 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));
    this.setCallIdOnResult(request, result);
    return result;
}

From source file:com.ikanow.aleph2.data_model.utils.TestCrudUtils.java

@Test
public void updateBeanTest() {

    // Test 1 - getter fields

    final BeanTemplate<TestBean.NestedTestBean> nested1 = BeanTemplateUtils.build(TestBean.NestedTestBean.class)
            .with("nested_string_field", "test1").done(); //(2)
    final BeanUpdateComponent<TestBean> test1 = CrudUtils.update(TestBean.class)
            .add(TestBean::string_fields, "AA", false) //(0)
            .increment(TestBean::long_field, 4) //(1)
            .nested(TestBean::nested_list, CrudUtils.update(nested1) //(2)
                    .unset(TestBean.NestedTestBean::nested_string_field) //(3a)
                    .remove(TestBean.NestedTestBean::nested_string_list, Arrays.asList("x", "y", "z")) //(4)
                    .add(TestBean.NestedTestBean::nested_string_list, "A", true) // (5)
            ).unset(TestBean::bool_field) //(3b)
            .unset(TestBean::nested_object) //(3c)
            .remove(TestBean::nested_list,
                    CrudUtils.allOf(TestBean.NestedTestBean.class).when("nested_string_field", "1")) //6)
    ;/*from  w  w w. jav  a  2s.  c om*/

    assertEquals(TestBean.class, test1.getElementClass());

    final UpdateComponent<JsonNode> test1_json = test1.toJson();
    System.out.println(test1_json.toString());

    final DBObject result1 = createUpdateObject(test1);
    final DBObject result1_json = createUpdateObject(test1_json);

    final String expected1 = "{ \"$push\" : { \"string_fields\" : \"AA\"} , \"$inc\" : { \"long_field\" : 4} , \"$set\" : { \"nested_list.nested_string_field\" : \"test1\"} , \"$unset\" : { \"nested_list.nested_string_field\" : 1 , \"bool_field\" : 1 , \"nested_object\" : 1} , \"$pullAll\" : { \"nested_list.nested_string_list\" : [ \"x\" , \"y\" , \"z\"]} , \"$addToSet\" : { \"nested_list.nested_string_list\" : \"A\"} , \"$pull\" : { \"nested_list\" : { \"$and\" : [ { \"nested_string_field\" : \"1\"}]}}}";
    // (see above for analysis of results) 

    assertEquals(expected1, result1.toString());
    assertEquals(expected1, result1_json.toString());

    // Test 1b - string fields

    final BeanTemplate<TestBean.NestedTestBean> nested1b = BeanTemplateUtils
            .build(TestBean.NestedTestBean.class).with("nested_string_field", "test1").done(); //(2)
    final UpdateComponent<TestBean> test1b = CrudUtils.update(TestBean.class).add("string_fields", "AA", false) //(0)
            .increment("long_field", 4) //(1)
            .nested("nested_list", CrudUtils.update(nested1b) //(2)
                    .unset("nested_string_field") //(3a)
                    .remove("nested_string_list", Arrays.asList("x", "y", "z")) //(4)
                    .add("nested_string_list", "A", true) // (5)
            ).unset("bool_field") //(3b)
            .unset("nested_object") //(3c)
            .remove("nested_list",
                    CrudUtils.allOf(TestBean.NestedTestBean.class).when("nested_string_field", "1")) //6)
    ;

    final UpdateComponent<JsonNode> test1b_json1 = CrudUtils.update().add("string_fields", "AA", false) //(0)
            .increment("long_field", 4) //(1)
            .nested("nested_list", CrudUtils.update(nested1b) //(2)
                    .unset("nested_string_field") //(3a)
                    .remove("nested_string_list", Arrays.asList("x", "y", "z")) //(4)
                    .add("nested_string_list", "A", true) // (5)
            ).unset("bool_field") //(3b)
            .unset("nested_object") //(3c)
            .remove("nested_list",
                    CrudUtils.allOf(TestBean.NestedTestBean.class).when("nested_string_field", "1")) //6)
    ;
    final UpdateComponent<JsonNode> test1b_json2 = test1b.toJson();

    System.out.println(test1b.toString());
    System.out.println(test1b_json2.toString());

    final DBObject result1b = createUpdateObject(test1b);
    final DBObject result1b_json1 = createUpdateObject(test1b_json1);
    final DBObject result1b_json2 = createUpdateObject(test1b_json2);

    final String expected1b = "{ \"$push\" : { \"string_fields\" : \"AA\"} , \"$inc\" : { \"long_field\" : 4} , \"$set\" : { \"nested_list.nested_string_field\" : \"test1\"} , \"$unset\" : { \"nested_list.nested_string_field\" : 1 , \"bool_field\" : 1 , \"nested_object\" : 1} , \"$pullAll\" : { \"nested_list.nested_string_list\" : [ \"x\" , \"y\" , \"z\"]} , \"$addToSet\" : { \"nested_list.nested_string_list\" : \"A\"} , \"$pull\" : { \"nested_list\" : { \"$and\" : [ { \"nested_string_field\" : \"1\"}]}}}";
    // (see above for analysis of results) 

    assertEquals(expected1b, result1b.toString());
    assertEquals(expected1b, result1b_json1.toString());
    assertEquals(expected1b, result1b_json2.toString());

    // Test2 - more coverage

    final BeanTemplate<TestBean> testbean2 = BeanTemplateUtils.build(TestBean.class)
            .with(TestBean::map, ImmutableMap.<String, String>builder().put("a", "b").build()).done();

    final UpdateComponent<TestBean> test2 = CrudUtils.update(testbean2) //(3)
            .set(TestBean::string_fields, "A").add(TestBean::string_fields, Arrays.asList("a", "b", "c"), true) //(1)
            .set("long_field", 1L).nested("nested_list", CrudUtils.update(TestBean.NestedTestBean.class)
                    .add(TestBean.NestedTestBean::nested_string_list, "A", false) // (will be overwritten)
            ).add("nested_list.nested_string_list", Arrays.asList("x", "y"), false); //(2)

    final DBObject result2 = createUpdateObject(test2);

    final String expected2 = "{ \"$set\" : { \"string_fields\" : \"A\" , \"long_field\" : 1 , \"map\" : { \"a\" : \"b\"}} , \"$addToSet\" : { \"string_fields\" : { \"$each\" : [ \"a\" , \"b\" , \"c\"]}} , \"$push\" : { \"nested_list.nested_string_list\" : { \"$each\" : [ \"x\" , \"y\"]}}}";
    // (see above for analysis of results) 

    assertEquals(expected2, result2.toString());

    // Test3 - delete object

    final UpdateComponent<TestBean> test3 = CrudUtils.update(TestBean.class).deleteObject();

    final DBObject result3 = createUpdateObject(test3);

    assertEquals("{ \"$unset\" :  null }", result3.toString());

    // Test4 - bean templates as JsonNode (see _json for the other way round!)

    final BeanTemplate<TestBean.NestedTestBean> nested4a = BeanTemplateUtils
            .build(TestBean.NestedTestBean.class).with("nested_string_field", "test4a").done(); //(2)

    final BeanTemplate<TestBean.NestedTestBean> nested4b = BeanTemplateUtils
            .build(TestBean.NestedTestBean.class).with("nested_string_field", "test4b").done(); //(2)

    //convert to JsonNode:
    final ObjectMapper object_mapper = MongoJackModule
            .configure(BeanTemplateUtils.configureMapper(Optional.empty()));
    JsonNode nested4a_json = object_mapper.valueToTree(nested4a.get());
    JsonNode nested4b_json = object_mapper.valueToTree(nested4b.get());

    final UpdateComponent<TestBean> test4 = CrudUtils.update(TestBean.class)
            .set(TestBean::nested_object, nested4a_json)
            .add(TestBean::nested_list, Arrays.asList(nested4a_json, nested4b_json), false);

    final UpdateComponent<JsonNode> test4_json = CrudUtils.update().set("nested_object", nested4a_json)
            .add("nested_list", Arrays.asList(nested4a_json, nested4b_json), false);

    final DBObject result4 = createUpdateObject(test4);
    final DBObject result4_json = createUpdateObject(test4_json);
    String expected4 = "{ \"$set\" : { \"nested_object\" : { \"nested_string_field\" : \"test4a\"}} , \"$push\" : { \"nested_list\" : { \"$each\" : [ { \"nested_string_field\" : \"test4a\"} , { \"nested_string_field\" : \"test4b\"}]}}}";

    assertEquals(expected4, result4.toString());
    assertEquals(expected4, result4_json.toString());
}

From source file:controllers.core.RoadmapController.java

/**
 * Get all portfolio entries id according to the current filter.
 *///from  ww  w . ja  v  a 2  s  .co m
public Result getAllIds() {

    try {

        // get the filter config
        String uid = getUserSessionManagerPlugin().getUserSessionId(ctx());
        FilterConfig<PortfolioEntryListView> filterConfig = this.getTableProvider()
                .get().portfolioEntry.filterConfig.getCurrent(uid, request());

        ObjectMapper mapper = new ObjectMapper();
        List<String> ids = new ArrayList<>();

        OrderBy<PortfolioEntry> orderBy = filterConfig.getSortExpression();
        ExpressionList<PortfolioEntry> expressionList = PortfolioEntryDynamicHelper
                .getPortfolioEntriesViewAllowedAsQuery(filterConfig.getSearchExpression(), orderBy,
                        getSecurityService());

        for (PortfolioEntry portfolioEntry : expressionList.findList()) {
            ids.add(String.valueOf(portfolioEntry.id));
        }

        JsonNode node = mapper.valueToTree(ids);

        return ok(node);

    } catch (Exception e) {
        return internalServerError();
    }
}