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:org.apache.streams.sprinklr.util.SprinklrDataToActivityConverter.java

/**
 * Helper to build Media Objects for the ActivityObject
 * @param mediaItem JsonNode/*w  ww  .j a  va2 s  .  c om*/
 * @param attachments List<ActivityObject>
 * @param mediaType a String either 'video' or 'image'
 */
private void addMediaObject(JsonNode mediaItem, List<ActivityObject> attachments, String mediaType) {
    try {
        ActivityObject mediaObj = new ActivityObject();
        Image image = new Image();
        image.setUrl(mediaItem.has("source") ? mediaItem.get("source").asText() : "");
        image.withAdditionalProperty("name", mediaItem.has("name") ? mediaItem.get("name").asText() : "");
        image.withAdditionalProperty("id", mediaItem.has("id") ? mediaItem.get("id").asText() : "");
        image.withAdditionalProperty("caption",
                mediaItem.has("caption") ? mediaItem.get("caption").asText() : "");
        image.withAdditionalProperty("description",
                mediaItem.has("description") ? mediaItem.get("description").asText() : "");
        image.withAdditionalProperty("picture",
                mediaItem.has("picture") ? mediaItem.get("picture").asText() : "");

        mediaObj.setImage(image);
        mediaObj.setObjectType(mediaType);

        attachments.add(mediaObj);
    } catch (Exception e) {
        LOGGER.error("Failed to add {} object={} errorMessage={}", mediaType, mediaItem.toString(),
                e.getMessage());
    }
}

From source file:com.marklogic.jena.functionaltests.ConnectedRESTQA.java

public static String getBootStrapHostFromML() {
    InputStream jstream = null;/*from  www.  j a v a 2s.com*/
    try {
        DefaultHttpClient client = new DefaultHttpClient();
        client.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8002),
                new UsernamePasswordCredentials("admin", "admin"));
        HttpGet getrequest = new HttpGet("http://localhost:8002/manage/v2/properties?format=json");
        HttpResponse resp = client.execute(getrequest);
        jstream = resp.getEntity().getContent();
        JsonNode jnode = new ObjectMapper().readTree(jstream);
        String propName = "bootstrap-host";
        if (!jnode.isNull()) {

            if (jnode.has(propName)) {
                System.out.println("Bootstrap Host: "
                        + jnode.withArray(propName).get(0).get("bootstrap-host-name").asText());
                return jnode.withArray(propName).get(0).get("bootstrap-host-name").asText();
            } else {
                System.out.println("Missing " + propName
                        + " field from properties end point so sending java conanical host name\n"
                        + jnode.toString());
                return InetAddress.getLocalHost().getCanonicalHostName().toLowerCase();
            }
        } else {
            System.out.println("Rest endpoint returns empty stream");
            return InetAddress.getLocalHost().getCanonicalHostName().toLowerCase();
        }

    } catch (Exception e) {
        // writing error to Log
        e.printStackTrace();

        return "localhost";
    } finally {
        jstream = null;
    }
}

From source file:de.fhg.fokus.odp.registry.ckan.ODRClientImpl.java

@Override
public String status() {
    log.trace("REST > calling action api 'status' with nothing");
    long start = System.currentTimeMillis();
    JsonNode node = action.status(OM.createObjectNode());
    log.debug("/api/3/action/status_show: {}ms", System.currentTimeMillis() - start);
    log.trace("REST < returns: {}", node);
    return node.toString();
}

From source file:org.opendaylight.groupbasedpolicy.jsonrpc.JsonRpcEndpoint.java

/**
 *
 * Handle incoming {@link RpcMessage} requests. The supported messages
 * are defined by the endpoint's message map.
 *
 * @param requestJson A Jackson JsonNode that has had full Tree-Mode parsing
 *//*from w w  w. ja v  a  2 s . co m*/
public void processRequest(JsonNode requestJson) {
    RpcMessage message;
    RpcMessage callback = messageMap.get(requestJson.get("method").asText());
    if (callback != null) {
        try {
            logger.trace("Request : {} {}", requestJson.get("method"), requestJson.get("params"));

            message = objectMapper.treeToValue(requestJson, callback.getClass());
            message.setId(requestJson.get("id").asText());

            broker.publish(this, message);
        } catch (JsonProcessingException e) {
            logger.error("Unable to invoke callback " + callback.getName(), e);
        }
        return;
    }

    // Echo dont need any special processing. hence handling it internally.

    if (requestJson.get("method").asText().equals("echo")) {
        JsonRpc10Response response = new JsonRpc10Response(requestJson.get("id").asText());
        response.setError(null);
        String s = null;
        try {
            s = objectMapper.writeValueAsString(response);
            nettyChannel.writeAndFlush(s);
        } catch (JsonProcessingException e) {
            logger.error("Exception while processing JSON string " + s, e);
        }
        return;
    }

    logger.error("No handler for Request : {}", requestJson.toString());
}

From source file:com.olacabs.fabric.processors.kafkawriter.KafkaWriter.java

/**
 * convert the event into Kafka keyed messages.
 *
 * @param event to convert/*from   w  ww.j a  v a 2  s.  c o  m*/
 * @return KeyedMessage
 */
protected KeyedMessage<String, String> convertEvent(Event event) throws ProcessingException {
    JsonNode eventData = event.getJsonNode();
    if (null == eventData) {
        if (event.getData() instanceof byte[]) {
            try {
                eventData = mapper.readTree((byte[]) event.getData());
            } catch (IOException e) {
                LOGGER.error("Error converting byte stream to event: ", e);
                if (!ignoreError) {
                    LOGGER.error("Error converting byte stream to event");
                    throw new ProcessingException("Error converting byte stream to event", e);
                }
                return null;
            }
        } else {
            if (!ignoreError) {
                LOGGER.error("Error converting byte stream to event: Event is not byte stream");
                throw new ProcessingException(
                        "Error converting byte stream to event: Event is not byte stream");
            }
            return null;
        }
    }

    final String kafkaKey = kafkaKeyJsonPath != null ? eventData.at(kafkaKeyJsonPath).asText().replace("\"", "")
            : eventData.at(DEFAULT_KAFKA_KEY_JSON_PATH).asText().replace("\"", "");

    final String topic = isTopicOnJsonPath()
            ? eventData.at(getKafkaTopicJsonPath()).toString().replace("\"", "")
            : getKafkaTopic().replace("\"", "");

    return new KeyedMessage<>(topic, kafkaKey, eventData.toString());
}

From source file:com.ikanow.aleph2.analytics.storm.services.MockAnalyticsContext.java

@Override
public Validation<BasicMessageBean, JsonNode> emitObject(final Optional<DataBucketBean> bucket,
        final AnalyticThreadJobBean job, final Either<JsonNode, Map<String, Object>> object,
        final Optional<AnnotationBean> annotations) {
    final DataBucketBean this_bucket = bucket.orElseGet(() -> _mutable_state.bucket.get());

    if (annotations.isPresent()) {
        throw new RuntimeException(ErrorUtils.NOT_YET_IMPLEMENTED);
    }//  www.  j  a  v a 2 s  .c om
    final JsonNode obj_json = object.either(__ -> __,
            map -> (JsonNode) _mapper.convertValue(map, JsonNode.class));

    if (_batch_index_service.isPresent()) {
        _batch_index_service.get().storeObject(obj_json);
    } else if (_crud_index_service.isPresent()) { // (super slow)
        _crud_index_service.get().storeObject(obj_json);
    }
    if (_batch_storage_service.isPresent()) {
        _batch_storage_service.get().storeObject(obj_json);
    } else if (_crud_storage_service.isPresent()) { // (super slow)
        _crud_storage_service.get().storeObject(obj_json);
    }

    final String topic = _distributed_services.generateTopicName(this_bucket.full_name(),
            ICoreDistributedServices.QUEUE_END_NAME);
    if (_distributed_services.doesTopicExist(topic)) {
        // (ie someone is listening in on our output data, so duplicate it for their benefit)
        _distributed_services.produce(topic, obj_json.toString());
    }
    //(else nothing to do)

    return Validation.success(obj_json);
}

From source file:com.ikanow.aleph2.search_service.elasticsearch.services.TestElasticsearchIndexService.java

@Test
public void test_validationSuccess() throws IOException {
    final String bucket_str = Resources.toString(Resources.getResource(
            "com/ikanow/aleph2/search_service/elasticsearch/services/test_bucket_validate_success.json"),
            Charsets.UTF_8);// w w w . j a va2s .  c  o  m
    final DataBucketBean bucket = BeanTemplateUtils.build(bucket_str, DataBucketBean.class).done().get();

    // 1) Verbose mode off
    {
        final Collection<BasicMessageBean> res_col = _index_service
                .validateSchema(bucket.data_schema().columnar_schema(), bucket)._2();
        final Collection<BasicMessageBean> res_search = _index_service
                .validateSchema(bucket.data_schema().search_index_schema(), bucket)._2();
        final Collection<BasicMessageBean> res_time = _index_service
                .validateSchema(bucket.data_schema().temporal_schema(), bucket)._2();

        assertEquals(0, res_col.size());
        assertEquals(0, res_search.size());
        assertEquals(0, res_time.size());
    }

    // 2) Verbose mode on
    {
        final DataBucketBean bucket_verbose = BeanTemplateUtils.clone(bucket).with(DataBucketBean::data_schema,
                BeanTemplateUtils.clone(bucket.data_schema()).with(DataSchemaBean::search_index_schema,
                        BeanTemplateUtils.clone(bucket.data_schema().search_index_schema()).with(
                                DataSchemaBean.SearchIndexSchemaBean::technology_override_schema,
                                ImmutableMap.builder()
                                        .putAll(bucket.data_schema().search_index_schema()
                                                .technology_override_schema())
                                        .put("verbose", true).build())
                                .done())
                        .done())
                .done();

        final Collection<BasicMessageBean> res_col = _index_service
                .validateSchema(bucket_verbose.data_schema().columnar_schema(), bucket)._2();
        final Collection<BasicMessageBean> res_search = _index_service
                .validateSchema(bucket_verbose.data_schema().search_index_schema(), bucket)._2();
        final Collection<BasicMessageBean> res_time = _index_service
                .validateSchema(bucket_verbose.data_schema().temporal_schema(), bucket)._2();

        assertEquals(0, res_col.size());
        assertEquals(0, res_time.size());
        assertEquals(2, res_search.size());
        assertEquals(true, res_search.stream().allMatch(BasicMessageBean::success));
        Iterator<BasicMessageBean> res_search_message = res_search.iterator();

        final String mapping_str = Resources.toString(Resources.getResource(
                "com/ikanow/aleph2/search_service/elasticsearch/services/test_verbose_mapping_validate_results.json"),
                Charsets.UTF_8);
        final JsonNode mapping_json = _mapper.readTree(mapping_str.getBytes());
        assertEquals(mapping_json.toString(), _mapper.readTree(res_search_message.next().message()).toString());
        assertTrue(
                "Sets the max index override: "
                        + res_search.stream().skip(1).map(m -> m.message()).collect(Collectors.joining()),
                res_search_message.next().message().contains("1,000 MB"));

        // 2b) Same but with valid overrides

        final DataSchemaBean.ColumnarSchemaBean empty_field_spec = BeanTemplateUtils
                .build(DataSchemaBean.ColumnarSchemaBean.class).done().get();
        final Collection<BasicMessageBean> res_search_2 = _index_service.validateSchema(
                BeanTemplateUtils.clone(bucket_verbose.data_schema().search_index_schema()).with(
                        DataSchemaBean.SearchIndexSchemaBean::type_override,
                        ElasticsearchIndexService._supported_types
                                .stream().<Tuple2<String, DataSchemaBean.ColumnarSchemaBean>>map(
                                        s -> Tuples._2T(s, empty_field_spec))
                                .collect(Collectors.toMap(
                                        (Tuple2<String, DataSchemaBean.ColumnarSchemaBean> t2) -> t2._1(),
                                        t2 -> t2._2())))
                        .with(DataSchemaBean.SearchIndexSchemaBean::tokenization_override,
                                ImmutableMap.of("_default_", empty_field_spec, "_none_", empty_field_spec))
                        .done(),
                bucket)._2();

        assertEquals(2, res_search_2.size());
    }

    // 3) Temporal

    {
        final DataBucketBean bucket_temporal_no_grouping = BeanTemplateUtils.clone(bucket)
                .with(DataBucketBean::data_schema,
                        BeanTemplateUtils.clone(bucket.data_schema())
                                .with(DataSchemaBean::temporal_schema, BeanTemplateUtils
                                        .build(DataSchemaBean.TemporalSchemaBean.class).done().get())
                                .done())
                .done();

        assertEquals("", _index_service
                .validateSchema(bucket_temporal_no_grouping.data_schema().temporal_schema(), bucket)._1());

        final DataBucketBean bucket_temporal_grouping = BeanTemplateUtils.clone(bucket)
                .with(DataBucketBean::data_schema,
                        BeanTemplateUtils.clone(bucket.data_schema()).with(DataSchemaBean::temporal_schema,
                                BeanTemplateUtils.build(DataSchemaBean.TemporalSchemaBean.class)
                                        .with(DataSchemaBean.TemporalSchemaBean::grouping_time_period, "1d")
                                        .done().get())
                                .done())
                .done();

        assertEquals("_{yyyy.MM.dd}", _index_service
                .validateSchema(bucket_temporal_grouping.data_schema().temporal_schema(), bucket)._1());
    }
}

From source file:dao.SearchDAO.java

public static JsonNode elasticSearchFlowByKeyword(String category, String keywords, int page, int size) {
    ObjectNode queryNode = Json.newObject();
    queryNode.put("from", (page - 1) * size);
    queryNode.put("size", size);
    JsonNode searchOpt = null;/* w  ww  .j a v a2  s . c om*/
    JsonNode responseNode = null;
    ObjectNode keywordNode = null;

    try {
        keywordNode = utils.Search.generateElasticSearchQueryString(category, null, keywords);
    } catch (Exception e) {
        Logger.error("Elastic search flow input query is not JSON format. Error message :" + e.getMessage());
    }

    if (keywordNode != null) {
        queryNode.set("query", keywordNode);
        Promise<WSResponse> responsePromise = WS
                .url(Play.application().configuration().getString(SearchDAO.ELASTICSEARCH_FLOW_URL_KEY))
                .post(queryNode);
        responseNode = responsePromise.get(1000).asJson();
    }

    ObjectNode resultNode = Json.newObject();
    Long count = 0L;
    List<FlowJob> pagedFlowJobs = new ArrayList<>();
    resultNode.put("page", page);
    resultNode.put("category", category);
    resultNode.put("isFlowJob", true);
    resultNode.put("itemsPerPage", size);
    resultNode.put("keywords", keywords);

    if (responseNode != null && responseNode.isContainerNode() && responseNode.has("hits")) {
        JsonNode hitsNode = responseNode.get("hits");
        if (hitsNode != null) {
            if (hitsNode.has("total")) {
                count = hitsNode.get("total").asLong();
            }
            if (hitsNode.has("hits")) {
                JsonNode dataNode = hitsNode.get("hits");
                if (dataNode != null && dataNode.isArray()) {
                    Iterator<JsonNode> arrayIterator = dataNode.elements();
                    if (arrayIterator != null) {
                        while (arrayIterator.hasNext()) {
                            JsonNode node = arrayIterator.next();
                            if (node.isContainerNode() && node.has("_id")) {
                                FlowJob flowJob = new FlowJob();
                                if (node.has("_source")) {
                                    JsonNode sourceNode = node.get("_source");
                                    if (sourceNode != null) {
                                        if (sourceNode.has("app_code")) {
                                            flowJob.appCode = sourceNode.get("app_code").asText();
                                        }
                                        if (sourceNode.has("app_id")) {
                                            flowJob.appId = sourceNode.get("app_id").asInt();
                                        }
                                        if (sourceNode.has("flow_id")) {
                                            flowJob.flowId = sourceNode.get("flow_id").asLong();
                                        }
                                        if (sourceNode.has("flow_name")) {
                                            flowJob.flowName = sourceNode.get("flow_name").asText();
                                            flowJob.displayName = flowJob.flowName;
                                        }
                                        if (sourceNode.has("flow_path")) {
                                            flowJob.flowPath = sourceNode.get("flow_path").asText();
                                        }
                                        if (sourceNode.has("flow_group")) {
                                            flowJob.flowGroup = sourceNode.get("flow_group").asText();
                                        }
                                        flowJob.link = "#/flows/name/" + flowJob.appCode + "/"
                                                + Long.toString(flowJob.flowId) + "/page/1?urn="
                                                + flowJob.flowGroup;
                                        flowJob.path = flowJob.appCode + "/" + flowJob.flowPath;

                                        flowJob.schema = sourceNode.toString();
                                    }
                                }
                                pagedFlowJobs.add(flowJob);
                            }
                        }
                    }

                }
            }

        }
    }
    resultNode.put("count", count);
    resultNode.put("totalPages", (int) Math.ceil(count / ((double) size)));
    resultNode.set("data", Json.toJson(pagedFlowJobs));
    return resultNode;
}

From source file:dao.SearchDAO.java

public static JsonNode elasticSearchMetricByKeyword(String category, String keywords, int page, int size) {
    ObjectNode queryNode = Json.newObject();
    queryNode.put("from", (page - 1) * size);
    queryNode.put("size", size);
    JsonNode responseNode = null;/*from   www  .ja v a2s .c  o  m*/
    ObjectNode keywordNode = null;

    try {
        keywordNode = utils.Search.generateElasticSearchQueryString(category, null, keywords);
    } catch (Exception e) {
        Logger.error("Elastic search metric input query is not JSON format. Error message :" + e.getMessage());
    }

    if (keywordNode != null) {
        queryNode.set("query", keywordNode);
        Promise<WSResponse> responsePromise = WS
                .url(Play.application().configuration().getString(SearchDAO.ELASTICSEARCH_METRIC_URL_KEY))
                .post(queryNode);
        responseNode = responsePromise.get(1000).asJson();
    }

    ObjectNode resultNode = Json.newObject();
    Long count = 0L;
    List<Metric> pagedMetrics = new ArrayList<>();
    resultNode.put("page", page);
    resultNode.put("category", category);
    resultNode.put("isMetrics", true);
    resultNode.put("itemsPerPage", size);
    resultNode.put("keywords", keywords);

    if (responseNode != null && responseNode.isContainerNode() && responseNode.has("hits")) {
        JsonNode hitsNode = responseNode.get("hits");
        if (hitsNode != null) {
            if (hitsNode.has("total")) {
                count = hitsNode.get("total").asLong();
            }
            if (hitsNode.has("hits")) {
                JsonNode dataNode = hitsNode.get("hits");
                if (dataNode != null && dataNode.isArray()) {
                    Iterator<JsonNode> arrayIterator = dataNode.elements();
                    if (arrayIterator != null) {
                        while (arrayIterator.hasNext()) {
                            JsonNode node = arrayIterator.next();
                            if (node.isContainerNode() && node.has("_id")) {
                                Metric metric = new Metric();
                                metric.id = node.get("_id").asInt();
                                if (node.has("_source")) {
                                    JsonNode sourceNode = node.get("_source");
                                    if (sourceNode != null) {
                                        if (sourceNode.has("metric_name")) {
                                            metric.name = sourceNode.get("metric_name").asText();
                                        }
                                        if (sourceNode.has("metric_description")) {
                                            metric.description = sourceNode.get("metric_description").asText();
                                        }
                                        if (sourceNode.has("dashboard_name")) {
                                            metric.dashboardName = sourceNode.get("dashboard_name").asText();
                                        }
                                        if (sourceNode.has("metric_group")) {
                                            metric.group = sourceNode.get("metric_group").asText();
                                        }
                                        if (sourceNode.has("metric_category")) {
                                            metric.category = sourceNode.get("metric_category").asText();
                                        }
                                        if (sourceNode.has("urn")) {
                                            metric.urn = sourceNode.get("urn").asText();
                                        }
                                        if (sourceNode.has("metric_source")) {
                                            metric.source = sourceNode.get("metric_source").asText();
                                            if (StringUtils.isBlank(metric.source)) {
                                                metric.source = null;
                                            }
                                        }
                                        metric.schema = sourceNode.toString();
                                    }
                                }
                                pagedMetrics.add(metric);
                            }
                        }
                    }

                }
            }

        }
    }
    resultNode.put("count", count);
    resultNode.put("totalPages", (int) Math.ceil(count / ((double) size)));
    resultNode.set("data", Json.toJson(pagedMetrics));
    return resultNode;
}

From source file:org.apache.syncope.core.workflow.activiti.ActivitiUserWorkflowAdapter.java

@Override
public void importDefinition(final WorkflowDefinitionFormat format, final String definition) {
    Model model = getModel(getProcessDefinition());
    switch (format) {
    case JSON://  ww  w  .jav  a 2s .c o m
        JsonNode definitionNode;
        try {
            definitionNode = new ObjectMapper().readTree(definition);
            if (definitionNode.has(MODEL_DATA_JSON_MODEL)) {
                definitionNode = definitionNode.get(MODEL_DATA_JSON_MODEL);
            }
            if (!definitionNode.has(BpmnJsonConverter.EDITOR_CHILD_SHAPES)) {
                throw new IllegalArgumentException(
                        "Could not find JSON node " + BpmnJsonConverter.EDITOR_CHILD_SHAPES);
            }

            BpmnModel bpmnModel = new BpmnJsonConverter().convertToBpmnModel(definitionNode);
            ActivitiImportUtils.fromXML(engine, new BpmnXMLConverter().convertToXML(bpmnModel));
        } catch (Exception e) {
            throw new WorkflowException(
                    "While updating process " + ActivitiUserWorkflowAdapter.WF_PROCESS_RESOURCE, e);
        }

        ActivitiImportUtils.fromJSON(engine, definitionNode.toString().getBytes(), getProcessDefinition(),
                model);
        break;

    case XML:
    default:
        ActivitiImportUtils.fromXML(engine, definition.getBytes());

        ActivitiImportUtils.fromJSON(engine, getProcessDefinition(), model);
    }
}