Example usage for com.fasterxml.jackson.databind JsonNode toString

List of usage examples for com.fasterxml.jackson.databind JsonNode toString

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind JsonNode toString.

Prototype

public abstract String toString();

Source Link

Usage

From source file:com.servioticy.api.commons.data.SO.java

/** Return the actions
*
* @return The actions in the SO//from   www  .j a  v  a 2s . co m
*/
public String responseActuations() {

    JsonNode actions = soRoot.path("actions");
    if (actions == null)
        return null;

    return actions.toString();
}

From source file:com.spoiledmilk.ibikecph.map.SMHttpRequest.java

public void findNearestPoint(final IGeoPoint loc, final SMHttpRequestListener listener) {
    new Thread(new Runnable() {
        @Override/* ww w . j  av  a  2  s  .c  o m*/
        public void run() {
            String url = String.format(Locale.US, "%s/nearest?loc=%.6f,%.6f", Config.OSRM_SERVER,
                    loc.getLatitudeE6() / (float) 1E6, loc.getLongitudeE6() / (float) 1E6);
            JsonNode response = HttpUtils.get(url);
            Location loc = null;
            if (response != null && response.path("mapped_coordinate").get(0) != null
                    && response.path("mapped_coordinate").get(1) != null) {
                LOG.d("response: " + response.toString());
                loc = Util.locationFromCoordinates(response.path("mapped_coordinate").get(0).asDouble(),
                        response.path("mapped_coordinate").get(1).asDouble());
            }
            sendMsg(REQUEST_FIND_NEAREST_LOC, (Object) loc, listener);
        }
    }).start();
}

From source file:com.servioticy.api.commons.data.Subscription.java

/** Generate response to a Subscription creation
 *
 * @return//w w  w . ja  v  a 2s . co m
 */
public String responseCreateSubs() {
    JsonNode root = mapper.createObjectNode();

    try {
        ((ObjectNode) root).put("id", subsId);
        ((ObjectNode) root).put("createdAt", subsRoot.get("createdAt").asLong());
    } catch (Exception e) {
        LOG.error(e);
        throw new ServIoTWebApplicationException(Response.Status.INTERNAL_SERVER_ERROR, e.getMessage());
    }
    return root.toString();
}

From source file:com.ericsson.eiffel.remrem.publish.service.EventTemplateHandlerTest.java

private void testParser(String EventName) {
    try {/*from  ww  w.j av a2 s.c o  m*/
        EventTemplateHandler eventTemplateHandler = new EventTemplateHandler();
        String dataToBeParsed = FileUtils.readFileToString(
                new File(INPUT_FILE_PATH_DATA + "test_data_for_parsing_" + EventName + ".json"), "UTF-8");
        String expectedDocument = FileUtils.readFileToString(
                new File(INPUT_FILE_PATH_EXPECTED_DATA + "expected_parsed_" + EventName + ".json"), "UTF-8");

        ObjectMapper mapper = new ObjectMapper();
        JsonNode expectedJson = mapper.readTree(expectedDocument);

        JsonNode actualParsedEventJson = eventTemplateHandler.eventTemplateParser(dataToBeParsed, EventName);

        LOG.info("expectedJsonString: " + expectedJson.toString());
        LOG.info("actualParsedEventJson: " + actualParsedEventJson.toString());

        JSONAssert.assertEquals(expectedJson.toString(), actualParsedEventJson.toString(), true);

    } catch (Exception e) {
        LOG.error(e.getMessage(), e);
    }

}

From source file:com.redhat.lightblue.crud.ldap.ITCaseLdapCRUDControllerTest.java

@Test
public void series1_phase1_Person_Insert() throws Exception {
    Response response = getLightblueFactory().getMediator().insert(
            createRequest_FromResource(InsertionRequest.class, "./crud/insert/person-insert-many.json"));

    assertNotNull(response);// www.j ava  2 s .c  om
    assertNoErrors(response);
    assertNoDataErrors(response);
    assertEquals(4, response.getModifiedCount());

    JsonNode entityData = response.getEntityData();
    assertNotNull(entityData);
    JSONAssert.assertEquals("[{\"dn\":\"uid=junior.doe," + BASEDB_USERS + "\"},{\"dn\":\"uid=john.doe,"
            + BASEDB_USERS + "\"},{\"dn\":\"uid=jane.doe," + BASEDB_USERS + "\"},{\"dn\":\"uid=jack.buck,"
            + BASEDB_USERS + "\"}]", entityData.toString(), false);
}

From source file:com.codeveo.lago.bot.stomp.client.LagoJsonMessageConverter.java

@Override
public Object fromMessage(Message<?> message, Class<?> targetClass) {
    try {//from ww  w.j  a v a 2  s.  co m
        /* NOTE: Message that came from STOMP broker */
        /* class discovery */
        RObjectType rObjectType = mapper.readValue((byte[]) message.getPayload(), RObjectType.class);

        if (rObjectType == null) {
            LOG.warn("Could not get R-object type from message '{}'", message);
            throw new Exception("Could not get R-Object type");
        }

        Class<?> clazz = ClientCommunicationHelperService.getClassFromClassId(rObjectType.getClassId());

        if (clazz == null) {
            LOG.warn("Could not identify class of R-object with class ID '{}' in message '{}'",
                    rObjectType.getClassId(), message);
            throw new Exception("Could not identify class of R-object");
        }

        Object obj = mapper.readValue((byte[]) message.getPayload(), clazz);

        if (clazz.equals(RClientMessage.class)) {
            JsonNode rootNode = mapper.readValue((byte[]) message.getPayload(), JsonNode.class);
            JsonNode dataJsonObject = rootNode.get("data");

            RObjectType data = null;
            RClientMessage clientMessage = (RClientMessage) obj;

            if (clientMessage.getData() != null) {
                Class<?> dataClass = ClientCommunicationHelperService
                        .getClassFromClassId(clientMessage.getData().getClassId());

                data = (RObjectType) mapper.readValue(dataJsonObject.toString(), dataClass);
            }

            clientMessage.setData(data);
        }

        return obj;
    } catch (Exception e) {
        LOG.error("Error occured during message deserialization", e);
    }

    return null;
}

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  w  w. j ava2  s.co  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.dspace.app.rest.repository.ItemRestRepository.java

@Override
@PreAuthorize("hasPermission(#id, 'ITEM', 'WRITE')")
protected ItemRest put(Context context, HttpServletRequest request, String apiCategory, String model, UUID uuid,
        JsonNode jsonNode) throws RepositoryMethodNotImplementedException, SQLException, AuthorizeException {
    HttpServletRequest req = getRequestService().getCurrentRequest().getHttpServletRequest();
    ObjectMapper mapper = new ObjectMapper();
    ItemRest itemRest = null;/*from www .  j a  v  a  2 s  .c o m*/
    try {
        itemRest = mapper.readValue(jsonNode.toString(), ItemRest.class);
    } catch (IOException e1) {
        throw new UnprocessableEntityException("Error parsing request body", e1);
    }

    Item item = itemService.find(context, uuid);
    if (item == null) {
        throw new ResourceNotFoundException(apiCategory + "." + model + " with id: " + uuid + " not found");
    }

    if (StringUtils.equals(uuid.toString(), itemRest.getId())) {
        metadataConverter.setMetadata(context, item, itemRest.getMetadata());
    } else {
        throw new IllegalArgumentException(
                "The UUID in the Json and the UUID in the url do not match: " + uuid + ", " + itemRest.getId());
    }
    return dsoConverter.fromModel(item);
}

From source file:com.amazonaws.services.cloudtrail.processinglibrary.serializer.AbstractEventSerializer.java

/**
 * Parse the event with key as default value.
 *
 * If the value is JSON null, then we will return null.
 * If the value is JSON object (of starting with START_ARRAY or START_OBject) , then we will convert the object to String.
 * If the value is JSON scalar value (non-structured object), then we will return simply return it as String.
 *
 * @param key//from   w  w w. j  a va 2s . c o m
 * @throws IOException
 */
private String parseDefaultValue(String key) throws IOException {
    this.jsonParser.nextToken();
    String value = null;
    JsonToken currentToken = this.jsonParser.getCurrentToken();
    if (currentToken != JsonToken.VALUE_NULL) {
        if (currentToken == JsonToken.START_ARRAY || currentToken == JsonToken.START_OBJECT) {
            JsonNode node = this.jsonParser.readValueAsTree();
            value = node.toString();
        } else {
            value = this.jsonParser.getValueAsString();
        }
    }
    return value;
}

From source file:com.servioticy.api.commons.data.SO.java

/** Generate response to getting a SO
 *
 * @return String//from  w  w  w.j a va  2s.co  m
 */
public String responseGetSO() {
    JsonNode root = soRoot;

    ((ObjectNode) root).remove("userId");
    ((ObjectNode) root).remove("data");

    return root.toString();
}