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:controllers.core.OrgUnitController.java

/**
 * Get all actors portfolio entry allocation ids according to the current
 * filter configuration./*  w  ww . ja  v  a 2s. c o m*/
 * 
 * @param id
 *            the org unit id
 */
@Restrict({ @Group(IMafConstants.ORG_UNIT_EDIT_ALL_PERMISSION) })
public Result getAllActorsPortfolioEntryAllocationIds(Long id) {

    try {

        // get the uid of the current user
        String uid = getUserSessionManagerPlugin().getUserSessionId(ctx());

        // fill the filter config
        FilterConfig<PortfolioEntryResourcePlanAllocatedActorListView> filterConfig = this.getTableProvider()
                .get().portfolioEntryResourcePlanAllocatedActor.filterConfig.persistCurrentInDefault(uid,
                        request());

        ExpressionList<PortfolioEntryResourcePlanAllocatedActor> expressionList = filterConfig
                .updateWithSearchExpression(PortfolioEntryResourcePlanDAO
                        .getPEPlanAllocatedActorAsExprByOrgUnitAndActive(id, true));

        List<String> ids = new ArrayList<>();
        for (PortfolioEntryResourcePlanAllocatedActor allocatedActor : expressionList.findList()) {
            ids.add(String.valueOf(allocatedActor.id));
        }

        ObjectMapper mapper = new ObjectMapper();
        JsonNode node = mapper.valueToTree(ids);

        return ok(node);

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

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

@Test
public void testForwardCompatibilitySimple() throws Exception {
    ObjectMapper mapper = objectMapper();
    AnnotatedText.Builder builder = new AnnotatedText.Builder();
    builder.data(THIS_IS_THE_TERRIER_SHOT_TO_BOSTON);
    AnnotatedText simpleText = builder.build();

    JsonNode tree = mapper.valueToTree(simpleText);
    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);/*from w  w w .j a v  a 2s  .c  o  m*/
    assertEquals(4, novelty.getExtendedProperties().get("startOffset"));
    assertEquals(8, novelty.getExtendedProperties().get("endOffset"));
    assertEquals("pari", novelty.getExtendedProperties().get("color"));
}

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

@Test
@SuppressWarnings("unchecked")
public void testForwardCompatibilityList() throws Exception {
    ObjectMapper mapper = objectMapper();
    AnnotatedText.Builder builder = new AnnotatedText.Builder();
    builder.data(THIS_IS_THE_TERRIER_SHOT_TO_BOSTON);
    AnnotatedText simpleText = builder.build();

    JsonNode tree = mapper.valueToTree(simpleText);
    ObjectNode attributes = (ObjectNode) tree.get("attributes");
    ObjectNode extendedObject = attributes.putObject("novelty");
    extendedObject.put("type", "list");
    extendedObject.put("itemType", "noveltyItem");
    ArrayNode items = extendedObject.putArray("items");
    ObjectNode item0 = items.addObject();
    item0.put("startOffset", 4);
    item0.put("endOffset", 8);
    item0.put("color", "pari");
    ObjectNode item1 = items.addObject();
    item1.put("startOffset", 10);
    item1.put("endOffset", 12);
    item1.put("color", "off");

    AnnotatedText read = mapper.treeToValue(tree, AnnotatedText.class);
    ListAttribute<BaseAttribute> novelty = (ListAttribute<BaseAttribute>) read.getAttributes().get("novelty");
    assertNotNull(novelty);//  w  ww .j  a  v  a2 s.  c  o  m
    assertEquals(2, novelty.size());
    BaseAttribute item = novelty.get(0);
    assertEquals(4, item.getExtendedProperties().get("startOffset"));
    assertEquals(8, item.getExtendedProperties().get("endOffset"));
    assertEquals("pari", item.getExtendedProperties().get("color"));

    item = novelty.get(1);
    assertEquals(10, item.getExtendedProperties().get("startOffset"));
    assertEquals(12, item.getExtendedProperties().get("endOffset"));
    assertEquals("off", item.getExtendedProperties().get("color"));

}

From source file:controllers.core.ActorController.java

/**
 * Get the activities of a type.//ww  w. jav  a 2 s.  c  o m
 */
@SubjectPresent
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:com.ikanow.aleph2.data_model.utils.TestBeanTemplateUtils.java

@Test
public void testNumberDeserializer() {
    TestDeserializeBean bean1 = BeanTemplateUtils
            .from("{\"testMap\":{\"test\":1.0}}", TestDeserializeBean.class).get();
    JsonNode jn1 = BeanTemplateUtils.toJson(bean1);

    assertEquals("{\"testMap\":{\"test\":1}}", jn1.toString());

    TestDeserializeBean bean2 = BeanTemplateUtils.from(
            "{\"testMap\":{\"test\":10000000000000,\"test1\":10000000000000.1,\"test2\":\"some string\"}}",
            TestDeserializeBean.class).get();
    JsonNode jn2 = BeanTemplateUtils.toJson(bean2);

    assertEquals(//from   w  ww.  j  a  v a2  s .c  o m
            "{\"testMap\":{\"test\":10000000000000,\"test1\":1.00000000000001E13,\"test2\":\"some string\"}}",
            jn2.toString());

    TestDeserializeBean bean3 = BeanTemplateUtils
            .from("{\"testMap\":{\"test\":1e7, \"test2\":1.0000000000000E7,\"test3\":1E19}}",
                    TestDeserializeBean.class)
            .get();
    JsonNode jn3 = BeanTemplateUtils.toJson(bean3);

    assertEquals("{\"testMap\":{\"test\":10000000,\"test2\":1.0E7,\"test3\":1.0E19}}", jn3.toString());

    //Mapper without the Number deserializer to make sure the double values are staying the same
    ObjectMapper plainMapper = new ObjectMapper();
    plainMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    plainMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
    plainMapper.setSerializationInclusion(Include.NON_NULL);

    //Checking that the deserializer doesn't break existing double values
    TestDeserializeBean bean4 = BeanTemplateUtils.from(
            "{\"testMap\":{\"test\":1e7, \"test2\":1.0000000000000E7,\"test3\":1.1,\"test4\":10000000000000.1,\"test4\":6e9,\"test5\":6e300,\"test5\":1E7 }}",
            TestDeserializeBean.class).get();
    JsonNode number_deserialized = BeanTemplateUtils.toJson(bean4);
    JsonNode plain = plainMapper.valueToTree(bean4);

    assertEquals(plain.toString(), number_deserialized.toString());

    // Just check it doesn't mess up actual double deserialization:

    TestDeserializeBean2 bean2_1 = BeanTemplateUtils
            .from("{\"testMap\":{\"test\":1.0}}", TestDeserializeBean2.class).get();
    JsonNode jn2_1 = BeanTemplateUtils.toJson(bean2_1);

    assertEquals("{\"testMap\":{\"test\":1.0}}", jn2_1.toString());

}

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

@Test
public void testShouldFetchASingleGenericAvroCellFromGroupFamily() throws Exception {

    String eid = getUrlEncodedEntityIdString("sample_table", 12345L);

    // Test group qualifier, generic avro type
    URI resourceURI = UriBuilder.fromResource(RowsResource.class).queryParam("eid", eid)
            .queryParam("cols", "group_family:inline_record").build("default", "sample_table");

    KijiRestRow returnRow = client().resource(resourceURI).get(KijiRestRow.class);
    assertEquals(1, returnRow.getCells().size());

    ObjectMapper mapper = new ObjectMapper();
    JsonNode node = mapper//from  w  w  w. j a  va2s .  c o  m
            .valueToTree(returnRow.getCells().get("group_family").get("inline_record").get(0).getValue());
    assertEquals("some_user", node.get("username").asText());
}

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

@Test
public void testShouldFetchASingleSpecificAvroCellFromMapFamily() throws Exception {

    String eid = getUrlEncodedEntityIdString("sample_table", 12345L);

    // Test map qualifier, specific Avro
    URI resourceURI = UriBuilder.fromResource(RowsResource.class).queryParam("eid", eid)
            .queryParam("cols", "pick_bans:ban_pick_1").build("default", "sample_table");

    KijiRestRow returnRow = client().resource(resourceURI).get(KijiRestRow.class);
    assertEquals(1, returnRow.getCells().size());

    ObjectMapper mapper = new ObjectMapper();
    JsonNode node = mapper//from   w w  w . j  a  v  a2 s.c o  m
            .valueToTree(returnRow.getCells().get("pick_bans").get("ban_pick_1").get(0).getValue());
    assertEquals(1, node.get("hero_id").get("long").asLong());
}

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

@Test
public void testShouldFetchASingleSpecificAvroCellFromGroupFamily() throws Exception {

    String eid = getUrlEncodedEntityIdString("sample_table", 12345L);

    // Test group qualifier, specific avro type

    URI resourceURI = UriBuilder.fromResource(RowsResource.class).queryParam("eid", eid)
            .queryParam("cols", "group_family:team_qualifier").build("default", "sample_table");

    KijiRestRow returnRow = client().resource(resourceURI).get(KijiRestRow.class);
    assertEquals(1, returnRow.getCells().size());

    ObjectMapper mapper = new ObjectMapper();
    JsonNode node = mapper/*from   w  w  w  .j  a v  a  2s  . c  om*/
            .valueToTree(returnRow.getCells().get("group_family").get("team_qualifier").get(0).getValue());
    assertEquals(1234, node.get("barracks_status").get("long").asLong());
}

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

@Test
public void testGenericAvroPost() throws Exception {
    // Set up.//from w ww  .j  a va2 s .  c  o  m
    String stringRowKey = getEntityIdString("sample_table", 54324L);
    String encodedRowKey = URLEncoder.encode(stringRowKey, "UTF-8");

    KijiTableLayout layout = KijiTableLayouts.getTableLayout("org/kiji/rest/layouts/sample_table.json");
    CellSpec spec = layout.getCellSpec(KijiColumnName.create("group_family", "inline_record"));
    GenericData.Record genericRecord = new GenericData.Record(spec.getAvroSchema());
    genericRecord.put("username", "gumshoe");
    genericRecord.put("num_purchases", 5647382910L);
    KijiCell<JsonNode> postCell = fromInputs("group_family", "inline_record", 3141592L,
            AvroToJsonStringSerializer.getJsonNode(genericRecord), spec.getAvroSchema());
    KijiRestRow postRow = new KijiRestRow(
            KijiRestEntityId.create(stringToJsonNode(URLDecoder.decode(stringRowKey, "UTF-8"))));
    addCellToRow(postRow, postCell);

    // 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)));
    ObjectMapper mapper = new ObjectMapper();
    JsonNode node = mapper
            .valueToTree(returnRow.getCells().get("group_family").get("inline_record").get(0).getValue());
    assertEquals("gumshoe", node.get("username").asText());
    assertEquals(5647382910L, node.get("num_purchases").asLong());
}