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.redhat.lightblue.eval.FieldProjectorTest.java

@Test
public void one_$parent_project_field_without_recursion() throws Exception {
    Projection p = EvalTestContext// w w w .ja  v  a2  s .c  om
            .projectionFromJson("[{'field':'field7.$parent.field2'},{'field':'field7.$parent.field6.*'}]");
    Projector projector = Projector.getInstance(p, md);
    JsonNode expectedNode = JsonUtils.json(
            "{'field2':'value2','field6':{'nf1':'nvalue1','nf2':'nvalue2','nf3':4,'nf4':false,'nf5':[],'nf6':[],'nf7':{},'nf8':[],'nf9':[],'nf10':[],'nf11':null}}"
                    .replace('\'', '\"'));

    JsonDoc pdoc = projector.project(jsonDoc, JSON_NODE_FACTORY);

    Assert.assertEquals(expectedNode.toString(), pdoc.toString());
}

From source file:com.redhat.lightblue.eval.FieldProjectorTest.java

@Test
public void two_$parent_project_field_without_recursion() throws Exception {
    Projection p = EvalTestContext.projectionFromJson(
            "[{'field':'field6.nf7.$parent.$parent.field2'},{'field':'field6.nf7.$parent.$parent.field6.*'}]");
    Projector projector = Projector.getInstance(p, md);
    JsonNode expectedNode = JsonUtils.json(
            "{'field2':'value2','field6':{'nf1':'nvalue1','nf2':'nvalue2','nf3':4,'nf4':false,'nf5':[],'nf6':[],'nf7':{},'nf8':[],'nf9':[],'nf10':[],'nf11':null}}"
                    .replace('\'', '\"'));

    JsonDoc pdoc = projector.project(jsonDoc, JSON_NODE_FACTORY);

    Assert.assertEquals(expectedNode.toString(), pdoc.toString());
}

From source file:org.pentaho.metaverse.impl.model.kettle.json.TransMetaJsonDeserializer.java

protected void writeJsonAttributes(JsonNode attributes, ObjectMapper mapper, ObjectId stepId)
        throws IOException {
    Map<String, Object> attrs = new HashMap<String, Object>();
    attrs = mapper.readValue(attributes.toString(), attrs.getClass());

    for (String s : attrs.keySet()) {
        Object val = attrs.get(s);
        try {/*from w ww.  j  a va2 s  . c  o  m*/
            if (val instanceof Integer) {
                repository.saveStepAttribute(null, stepId, s, (Integer) val);
            } else if (val instanceof Long) {
                repository.saveStepAttribute(null, stepId, s, (Long) val);
            } else if (val instanceof Double) {
                repository.saveStepAttribute(null, stepId, s, (Double) val);
            } else if (val instanceof Boolean) {
                repository.saveStepAttribute(null, stepId, s, (Boolean) val);
            } else {
                repository.saveStepAttribute(null, stepId, s, val == null ? null : (String) val);
            }
        } catch (KettleException e) {
            LOGGER.info(Messages.getString("INFO.Deserialization.Trans.SavingAttributes", s), e);
        }
    }
}

From source file:com.evrythng.java.wrapper.mapping.TaskOnBatchDeserializer.java

@Override
public TaskOnBatch deserialize(final JsonParser jp, final DeserializationContext ctx) throws IOException {

    ObjectMapper mapper = JSONUtils.OBJECT_MAPPER;
    JsonNode node = mapper.readTree(jp);
    JsonNode typeNode = node.get(TaskOnBatch.FIELD_TYPE);
    if (typeNode == null) {
        throw new JsonMappingException("Cannot deserialize task on batch without type field");
    }//  w ww  . j a va  2 s  .c o m
    String typeRaw = getFieldValue(typeNode);
    Class<? extends TaskOnBatch> subtypeClass = classForType(TaskOnBatch.Type.valueOf(typeRaw.toUpperCase()));
    return mapper.readValue(node.toString(), subtypeClass);
}

From source file:org.dspace.app.rest.repository.CollectionRestRepository.java

@Override
@PreAuthorize("hasPermission(#id, 'COLLECTION', 'WRITE')")
protected CollectionRest put(Context context, HttpServletRequest request, String apiCategory, String model,
        UUID id, JsonNode jsonNode)
        throws RepositoryMethodNotImplementedException, SQLException, AuthorizeException {
    CollectionRest collectionRest;//from   ww  w  . j  av a2  s  .  c om
    try {
        collectionRest = new ObjectMapper().readValue(jsonNode.toString(), CollectionRest.class);
    } catch (IOException e) {
        throw new UnprocessableEntityException("Error parsing collection json: " + e.getMessage());
    }
    Collection collection = cs.find(context, id);
    if (collection == null) {
        throw new ResourceNotFoundException(apiCategory + "." + model + " with id: " + id + " not found");
    }
    CollectionRest originalCollectionRest = converter.fromModel(collection);
    if (collectionRestEqualityUtils.isCollectionRestEqualWithoutMetadata(originalCollectionRest,
            collectionRest)) {
        metadataConverter.setMetadata(context, collection, collectionRest.getMetadata());
    } else {
        throw new IllegalArgumentException("The UUID in the Json and the UUID in the url do not match: " + id
                + ", " + collectionRest.getId());
    }
    return converter.fromModel(collection);
}

From source file:org.pentaho.metaverse.impl.model.kettle.json.TransMetaJsonDeserializer.java

protected void writeJsonFields(JsonNode fields, ObjectMapper mapper, ObjectId stepId) throws IOException {
    List<Map<String, Object>> fieldLists = new ArrayList<Map<String, Object>>();
    fieldLists = mapper.readValue(fields.toString(), fieldLists.getClass());
    int idx = 0;/*ww  w . ja va  2 s  . co m*/
    for (Map<String, Object> fieldAttrs : fieldLists) {
        for (String s : fieldAttrs.keySet()) {
            Object val = fieldAttrs.get(s);
            try {
                if (val instanceof Integer) {
                    repository.saveStepAttribute(null, stepId, idx, s, (Integer) val);
                } else if (val instanceof Long) {
                    repository.saveStepAttribute(null, stepId, idx, s, (Long) val);
                } else if (val instanceof Double) {
                    repository.saveStepAttribute(null, stepId, idx, s, (Double) val);
                } else if (val instanceof Boolean) {
                    repository.saveStepAttribute(null, stepId, idx, s, (Boolean) val);
                } else {
                    repository.saveStepAttribute(null, stepId, idx, s, val == null ? null : (String) val);
                }
            } catch (KettleException e) {
                LOGGER.info(Messages.getString("INFO.Deserialization.Trans.SavingAttributes", s,
                        String.valueOf(idx)), e);
            }
        }
        idx++;
    }
}

From source file:volker.streaming.music.lastfm.LastFmApi.java

public Track getNowPlaying() {
    Track result = null;//w  w  w .  ja  v  a2  s.com

    // setup API url
    URI uri = null;
    try {
        uri = getApiUri().addParameter("method", "user.getrecenttracks").addParameter("user", config.getUser())
                .addParameter("api_key", config.getApiKey()).addParameter("format", "json")
                .addParameter("limit", "1").addParameter("extended", "0").build();
    } catch (URISyntaxException e) {
        LOG.fatal("Configuration error. Invalid API url.", e);
        return null;
    }

    // setup the request
    CloseableHttpClient client = getClient().build();
    HttpGet getRequest = new HttpGet(uri);
    setHeaders(getRequest);

    // execute the request
    CloseableHttpResponse response = null;
    try {
        response = client.execute(getRequest);
    } catch (IOException e) {
        LOG.fatal("Failed to execute request.", e);
        close(response, client);
        return null;
    }

    // read the response
    InputStream responseStream = null;
    JsonNode root = null;
    try {
        ObjectMapper mapper = new ObjectMapper();
        responseStream = response.getEntity().getContent();
        root = mapper.readTree(responseStream);
        LOG.info("Last FM API returned :" + root.toString());
    } catch (JsonProcessingException e1) {
        LOG.fatal("Returned JSON was invalid.", e1);
        close(response, client);
        return null;
    } catch (IOException e1) {
        LOG.fatal("Failed to read response stream.", e1);
        close(response, client);
        return null;
    } finally {
        close(responseStream);
    }

    if (root.hasNonNull("error")) {
        LOG.error("Error returned by API: " + (root.hasNonNull("message") ? root.get("message").asText() : ""));
    } else {
        JsonNode recentTracks = root.get("recenttracks");
        Iterator<JsonNode> tracks;
        if (recentTracks.hasNonNull("track")) {
            tracks = recentTracks.get("track").elements();
        } else {
            // no tracks ever listened to
            tracks = new ArrayList<JsonNode>().iterator();
        }
        if (tracks.hasNext()) {
            JsonNode mostRecent = tracks.next();
            if (mostRecent.hasNonNull("@attr")) {
                JsonNode attr = mostRecent.get("@attr");
                if (attr.hasNonNull("nowplaying") && attr.get("nowplaying").asBoolean()) {
                    // mostRecent is the currently playing track
                    try {
                        result = LastFmTrackFactory.fromJson(mostRecent);
                    } catch (IllegalArgumentException e) {
                        LOG.error("JSON response contained an invalid Track.", e);
                    }
                }
            }
        }
    }

    // close stuff
    close(response, client);
    return result;
}

From source file:com.redhat.lightblue.metadata.ldap.parser.LdapPropertyParserTest.java

@Test
public void testConvert() throws IOException, JSONException {
    LdapMetadata ldapMetadata = new LdapMetadata();
    ldapMetadata.addFieldToAttribute(new Path("firstName"), "givenName");
    ldapMetadata.addFieldToAttribute(new Path("lastName"), "sn");

    JsonNode node = json("{}");

    new LdapPropertyParser<JsonNode>()
            .convert(MetadataUtil.createJSONMetadataParser(LdapConstant.BACKEND, null), node, ldapMetadata);

    JSONAssert.assertEquals(/* ww w.  j  av a  2s. co m*/
            "{\"fieldsToAttributes\":[{\"field\":\"lastName\",\"attribute\":\"sn\"},{\"field\":\"firstName\",\"attribute\":\"givenName\"}]}",
            node.toString(), false);
}

From source file:com.redhat.lightblue.eval.ArrayQueryProjectorTest.java

@Test
public void array_query_projection_with_match() throws Exception {
    Projection p = EvalTestContext.projectionFromJson(
            "{'field':'field7','match':{'field':'elemf3','op':'>','rvalue':4},'project':{'field':'*'}}");
    Projector projector = Projector.getInstance(p, md);
    JsonNode expectedNode = JsonUtils.json(
            "{'field7':[{'elemf1':'elvalue2_1','elemf2':'elvalue2_2','elemf3':5},{'elemf1':'elvalue3_1','elemf2':'elvalue3_2','elemf3':6}]}"
                    .replace('\'', '\"'));

    JsonDoc pdoc = projector.project(jsonDoc, JSON_NODE_FACTORY);

    Assert.assertEquals(expectedNode.toString(), pdoc.toString());
}

From source file:com.redhat.lightblue.eval.ArrayQueryProjectorTest.java

@Test
public void one_$parent_array_query_projection_with_match() throws Exception {
    Projection p = EvalTestContext.projectionFromJson(
            "{'field':'field6.$parent.field7','match':{'field':'elemf3','op':'>','rvalue':4},'project':{'field':'*'}}");
    Projector projector = Projector.getInstance(p, md);
    JsonNode expectedNode = JsonUtils.json(
            "{'field7':[{'elemf1':'elvalue2_1','elemf2':'elvalue2_2','elemf3':5},{'elemf1':'elvalue3_1','elemf2':'elvalue3_2','elemf3':6}]}"
                    .replace('\'', '\"'));

    JsonDoc pdoc = projector.project(jsonDoc, JSON_NODE_FACTORY);

    Assert.assertEquals(expectedNode.toString(), pdoc.toString());
}