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

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

Introduction

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

Prototype

public abstract String asText();

Source Link

Usage

From source file:com.squarespace.template.UnitTestBase.java

public String format(Formatter impl, Arguments args, String json) throws CodeException {
    Context ctx = new Context(JsonUtils.decode(json));
    impl.validateArgs(args);/* w  w w.j  ava 2  s .com*/
    JsonNode node = impl.apply(ctx, args, ctx.node());
    return node.asText();
}

From source file:com.digitalpebble.storm.crawler.filtering.basic.BasicURLNormalizer.java

@Override
public void configure(Map stormConf, JsonNode paramNode) {
    JsonNode node = paramNode.get("removeAnchorPart");
    if (node != null) {
        removeAnchorPart = node.booleanValue();
    }/*from  w  w w .  j ava 2  s .  co m*/

    node = paramNode.get("unmangleQueryString");
    if (node != null) {
        unmangleQueryString = node.booleanValue();
    }

    node = paramNode.get("queryElementsToRemove");
    if (node != null) {
        if (!node.isArray()) {
            LOG.warn("Failed to configure queryElementsToRemove.  Not an array: {}", node.toString());
        } else {
            ArrayNode array = (ArrayNode) node;
            for (JsonNode element : array) {
                queryElementsToRemove.add(element.asText());
            }
        }
    }
}

From source file:com.amazonaws.services.logs.subscriptions.CloudWatchLogsSubscriptionTransformer.java

@Override
public Collection<CloudWatchLogsEvent> toClass(Record record) throws IOException {
    List<CloudWatchLogsEvent> result = new ArrayList<>();

    // uncompress the payload
    byte[] uncompressedPayload;
    try {//from   ww w  .ja v a2s.  c o m
        uncompressedPayload = uncompress(record.getData().array());
    } catch (IOException e) {
        LOG.error("Unable to uncompress the record. Skipping it.", e);
        return result;
    }

    // get the JSON root node
    String jsonPayload = new String(uncompressedPayload, Charset.forName("UTF-8"));
    JsonNode rootNode;
    try {
        rootNode = JSON_OBJECT_MAPPER.readTree(new StringReader(jsonPayload));
    } catch (JsonProcessingException e) {
        LOG.error("Unable to parse the record as JSON. Skipping it.", e);
        return result;
    }

    // only process records whose type is DATA_MESSAGE
    JsonNode messageTypeNode = rootNode.get("messageType");
    if (messageTypeNode == null || !messageTypeNode.asText().equals("DATA_MESSAGE")) {
        LOG.warn("This record is not a data message. Skipping it.");
        return result;
    }

    // extract the common attributes for all the log events in the batch
    String owner = rootNode.get("owner").asText();
    String logGroup = rootNode.get("logGroup").asText();
    String logStream = rootNode.get("logStream").asText();

    // construct the log events
    for (JsonNode logEventNode : rootNode.get("logEvents")) {
        String id = logEventNode.get("id").asText();
        long timestamp = logEventNode.get("timestamp").asLong();
        String message = logEventNode.get("message").asText();

        Map<String, String> extractedFields = null;

        if (logEventNode.get("extractedFields") != null) {
            extractedFields = JSON_OBJECT_MAPPER.readValue(logEventNode.get("extractedFields").toString(),
                    MAP_TYPE);
        }

        result.add(
                new CloudWatchLogsEvent(id, timestamp, message, extractedFields, owner, logGroup, logStream));
    }

    return result;
}

From source file:snow.console.Stdin.java

@Override
public void execute(JsonNode params, StreamResults stream) {
    //        System.out.println(params.toString());
    if (params instanceof ObjectNode) {
        ObjectNode node = (ObjectNode) params;
        JsonNode id = node.get("id");
        if (id != null) {
            JsonNode data = node.get("data");
            if (data != null) {
                Terminal terminal = Terminal.get(id.asText());
                if (terminal != null)
                    terminal.in(data.asText());
            }/*from   w  w  w .j  a  v a 2s.c o m*/
        }
    }
}

From source file:com.monarchapis.driver.configuration.JsonConfiguration.java

@Override
public Optional<String> getString(String path, Object... args) {
    JsonNode node = getPathNode(path);

    if (node.isTextual()) {
        String value = node.asText();

        if (args.length > 0) {
            return Optional.of(MessageFormat.format(value, args));
        } else {//from w w w .j  a va  2  s  .co m
            return Optional.of(value);
        }
    } else {
        return Optional.absent();
    }
}

From source file:FileServer.ElasticSearch.ElasticSearchRetrievingInterface.java

public ResultsWrapper<DocumentResultEntity> queryDocument(QueryWrapper queryWrapper) {

    ObjectMapper mapper = new ObjectMapper();

    String url = fileQueryURL;//from   w  w  w .ja  v a2 s .  c om
    String query = QueryStringBuilder.buildDocumentQuery(queryWrapper);

    System.out.println(query);

    ResultsWrapper<DocumentResultEntity> resultList = new ResultsWrapper<>();
    List<DocumentResultEntity> retrievedResults = new ArrayList<>();

    try {

        HttpResponse<String> res = Unirest.post(url).body(query).asString();

        JsonNode root = mapper.readTree(res.getBody());

        System.out.println("*****************************************************************");
        System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(root));
        Logger.getGlobal().log(Level.INFO, mapper.writerWithDefaultPrettyPrinter().writeValueAsString(root));

        resultList.setQuery(queryWrapper.extractedContentFeild);
        resultList.setSearchTime(root.get("took").toString());
        resultList.setResultNum(root.get("hits").get("total").toString());

        JsonNode jsonResultList = root.get("hits").get("hits");

        if (jsonResultList.isArray()) {
            for (JsonNode result : jsonResultList) {

                JsonNode content = result.get("_source");

                DocumentResultEntity resultEntity = new DocumentResultEntity();
                resultEntity.fileId = content.get("fileId").asText();
                resultEntity.filename = content.get("filename").asText();
                resultEntity.from = content.get("from").asText();
                resultEntity.to = content.get("to").asText();
                resultEntity.url = fileServerURL + content.get("filename").asText();

                JsonNode highlights = result.get("highlight");

                System.out.println(resultEntity.url);

                if (highlights != null) {
                    StringBuilder builder = new StringBuilder();
                    for (JsonNode snippet : highlights.get("extractedContent")) {
                        builder.append(snippet.asText() + ".....");
                        //fs.extractedContent += snippet.toString() + "...";
                    }

                    resultEntity.extractedContent = builder.toString();
                }

                retrievedResults.add(resultEntity);
            }
        }

        resultList.setResultList(retrievedResults);

    } catch (UnirestException ex) {
        Logger.getLogger(ElasticSearchRetrievingInterface.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ElasticSearchRetrievingInterface.class.getName()).log(Level.SEVERE, null, ex);
    }

    return resultList;

}

From source file:org.jsonschema2pojo.rules.TypeRule.java

private String getTypeName(JsonNode node) {
    if (node.has("type") && node.get("type").isArray() && node.get("type").size() > 0) {
        for (JsonNode jsonNode : node.get("type")) {
            String typeName = jsonNode.asText();
            if (!typeName.equals("null")) {
                return typeName;
            }// w  ww .  j  a  v  a2  s.  co  m
        }
    }

    if (node.has("type") && node.get("type").isTextual()) {
        return node.get("type").asText();
    }

    return DEFAULT_TYPE_NAME;
}

From source file:org.kiji.rest.serializers.JsonToKijiRestEntityId.java

/**
 * {@inheritDoc}// w  w  w .  j  a  v  a  2 s.  c  o m
 */
@Override
public KijiRestEntityId deserialize(JsonParser parser, DeserializationContext context) throws IOException {

    ObjectMapper mapper = new ObjectMapper();
    JsonNode node = mapper.readTree(parser);
    if (node.isArray()) {
        return KijiRestEntityId.create(node);
    } else if (node.isTextual()) {
        return KijiRestEntityId.create(node.asText());
    } else {
        throw new IllegalArgumentException(
                "Entity id node to deserialize must be an array or textual, it was: " + node);
    }
}

From source file:com.digitalpebble.storm.crawler.filtering.regex.RegexURLFilterBase.java

/** Populates a List of Rules off of JsonNode. */
private List<RegexRule> readRules(ArrayNode rulesList) {
    List<RegexRule> rules = new ArrayList<RegexRule>();
    for (JsonNode urlFilterNode : rulesList) {
        try {/*from   ww  w  .j a v a 2 s  .  c  o m*/
            RegexRule rule = createRule(urlFilterNode.asText());
            if (rule != null) {
                rules.add(rule);
            }
        } catch (IOException e) {
            LOG.error("There was an error reading regex filter {}", urlFilterNode.asText(), e);
        }
    }
    return rules;
}

From source file:com.github.iexel.fontus.web.test.SpringMvcIntegrationTest.java

/**
 * Test the external web service.//from   w w w  .j  av a2s.c  o m
 */
@Test
public void testRestService() throws Exception {

    MockHttpServletRequestBuilder m;
    ResultActions r;

    // Create a new record
    m = post("/rest/products");
    m.contentType(MediaType.APPLICATION_JSON);
    m.accept(MediaType.APPLICATION_JSON);
    m.content("{\"name\":\"A record created by automated test\", \"price\":10.00, \"version\":0}");
    r = this.mockMvc.perform(m);
    r.andDo(print());
    r.andExpect(status().isOk());

    // Get the new record's id and version with Jackson
    MvcResult result = r.andReturn();
    String resultStr = result.getResponse().getContentAsString();
    ObjectMapper mapper = new ObjectMapper();
    JsonNode rootNode = mapper.readTree(resultStr);
    JsonNode nameNode = rootNode.path("id");
    int id = nameNode.asInt();
    JsonNode versionNode = rootNode.path("version");
    String version = versionNode.asText();

    // Update the new record
    m = put("/rest/products/" + id);
    m.contentType(MediaType.APPLICATION_JSON);
    m.accept(MediaType.APPLICATION_JSON);
    m.content("{\"name\":\"Updated by automated test\", \"price\":20.00, \"version\":" + version + "}");
    r = this.mockMvc.perform(m);
    r.andDo(print());
    r.andExpect(status().isOk());

    // Get all records, and check that the new record is present and contains correct data
    m = get("/rest/products?rows=100&page=1&sidx=id&sord=asc");
    m.accept(MediaType.APPLICATION_JSON);
    r = this.mockMvc.perform(m);
    r.andDo(print());
    r.andExpect(status().isOk());
    r.andExpect(jsonPath("$.page", equalTo(1)));
    // ?(@.id==8) - select all rows with id=8, and [0] - get the first of these rows
    r.andExpect(jsonPath("$.rows[?(@.id==" + id + ")][0].name", equalTo("Updated by automated test")));

    // Delete the test record
    m = delete("/rest/products/" + id);
    m.contentType(MediaType.APPLICATION_JSON);
    m.accept(MediaType.APPLICATION_JSON);
    m.content("{\"version\":1}"); // the version after the update should be 1
    r = this.mockMvc.perform(m);
    r.andDo(print());
    r.andExpect(status().isOk());
}