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.baidubce.services.moladb.model.transform.WriteRequestUnmarshaller.java

@Override
public WriteRequest unmarshall(JsonNode jsonObj) throws Exception {
    WriteRequest req = null;/*from   ww  w. ja va2 s  . c o  m*/
    JsonNode putNode = jsonObj.get(MolaDbConstants.JSON_PUT_REQUEST);
    JsonNode delNode = jsonObj.get(MolaDbConstants.JSON_DELETE_REQUEST);
    if ((null == putNode && null == delNode) || (null != putNode && null != delNode)) {
        throw new BceClientException("Invalid responseContent json:" + jsonObj.toString());
    }

    if (null != putNode) {
        PutRequestUnmarshaller unmarshaller = new PutRequestUnmarshaller();
        PutRequest putRequest = unmarshaller.unmarshall(putNode);
        req = putRequest;
    } else {
        DeleteRequestUnmarshaller unmarshaller = new DeleteRequestUnmarshaller();
        DeleteRequest delRequest = unmarshaller.unmarshall(delNode);
        req = delRequest;
    }
    return req;
}

From source file:com.mockey.ui.JsonSchemaValidateServlet.java

@Override
public void doPost(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    final Set<String> params = Sets.newHashSet();
    final Enumeration<String> enumeration = req.getParameterNames();

    // FIXME: no duplicates, it seems, but I cannot find the spec which
    // guarantees that
    while (enumeration.hasMoreElements())
        params.add(enumeration.nextElement());

    // We have required parameters
    if (!params.containsAll(ValidateRequest.REQUIRED_PARAMS)) {
        logger.warn("Missing parameters! Someone using me as a web service?");
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing parameters");
        return;/*from   w ww  .  ja  v a 2 s.co m*/
    }

    // We don't want extraneous parameters
    params.removeAll(ValidateRequest.VALID_PARAMS);

    if (!params.isEmpty()) {
        logger.warn("Invalid parameters! Someone using me as a web service?");
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid parameters");
        return;
    }

    final String rawSchema = req.getParameter(ValidateRequest.SCHEMA);
    final String data = req.getParameter(ValidateRequest.DATA);

    // Set correct content type
    resp.setContentType(MediaType.JSON_UTF_8.toString());

    final boolean useV3 = Boolean.parseBoolean(req.getParameter(ValidateRequest.USE_V3));
    final boolean useId = Boolean.parseBoolean(req.getParameter(ValidateRequest.USE_ID));

    final JsonNode ret = JsonSchemaUtil.buildResult(rawSchema, data, useV3, useId);

    final OutputStream out = resp.getOutputStream();

    try {
        out.write(ret.toString().getBytes(Charset.forName("UTF-8")));
        out.flush();
    } finally {
        Closeables.closeQuietly(out);
    }
}

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

public JsonNode eventTemplateParser(String jsonData, String eventName) {
    JsonNode updatedJson = null;// w  w w  .j  av  a2  s  .co  m
    JsonFactory factory = new JsonFactory();
    ObjectMapper mapper = new ObjectMapper(factory);
    JsonNode rootNode = null;
    try {
        String eventTemplate = accessFileInSemanticJar(EVENT_TEMPLATE_PATH + eventName.toLowerCase() + ".json");

        rootNode = mapper.readTree(jsonData);
        updatedJson = mapper.readValue(eventTemplate, JsonNode.class);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }

    // For each key/value pair for parsing to template
    Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
    while (fieldsIterator.hasNext()) {
        Map.Entry<String, JsonNode> field = fieldsIterator.next();
        // Parse values to template
        // Check if POJO required for update in event template
        Pattern p = Pattern.compile(REGEXP_END_DIGITS); // if ends with [d+]
        Matcher m = p.matcher(field.getKey());

        String myKey = "$." + templateParamHandler(field.getKey());

        if (field.getValue().toString().equals("\"<%DELETE%>\"")) {
            updatedJson = jsonPathHandlerDelete(updatedJson, myKey);
        } else if (m.find()) {
            String myValue = field.getValue().toString();
            try {
                // Fetch Class name in Event Schema
                String eventSchema = accessFileInSemanticJar(EVENT_SCHEMA_PATH + eventName + ".json");
                // Filter javatype from Event Schema = class name
                JsonNode jsonFromSchema = JsonPath.using(configuration).parse(eventSchema.toString())
                        .read(schemaClassPathHandler(field.getKey().replaceAll(REGEXP_END_DIGITS, "")));
                String myClassName = jsonFromSchema.toString().replace("[", "").replace("]", "").replace("\"",
                        ""); // Ex ["com.ericsson.eiffel.semantics.events.PersistentLog"] to com.ericsson.eiffel.semantics.events.PersistentLog
                // Initiate Class via reflection and map values - POJO
                Class myClass = Class.forName(myClassName);
                Object mapped2Pojo = mapper.readValue(myValue, myClass);
                updatedJson = jsonPathHandlerSet(updatedJson, myKey, mapped2Pojo);
            } catch (ClassNotFoundException e) {
                // No POJO required for adding new item in Array (ie no key/value pairs)
                updatedJson = jsonPathHandlerSet(updatedJson, myKey, myValue.toString().replace("\"", ""));
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }

        } else { // No POJO needed for update
            Object myValue = field.getValue();
            updatedJson = jsonPathHandlerSet(updatedJson, myKey, myValue);
        }
    } // while
    return updatedJson;
}

From source file:controllers.AlertController.java

private models.view.Alert buildViewAlert(final Http.RequestBody body) throws IOException {
    final JsonNode jsonBody = body.asJson();
    if (jsonBody == null) {
        throw new IOException();
    }/*from w ww  .  j a v a2s .  co m*/
    return OBJECT_MAPPER.readValue(jsonBody.toString(), models.view.Alert.class);
}

From source file:com.ikanow.aleph2.distributed_services.services.TestCoreDistributedServices.java

/**
 * Tests kafka by creating a new topic, throwing 50 items on the queue
 * and making sure we get those 50 items off the queue.
 * // ww w.j a  va 2s. com
 * @throws Exception
 */
@Test
public void testKafka() throws Exception {
    if (!auto_configure) { // Only test this once per true/false cycle
        return;
    }

    //create a random topic so its new (has to call create function)
    final String TOPIC_NAME = "TEST_CDS_" + System.currentTimeMillis();
    final int num_to_test = 10;

    //grab the consumer
    Iterator<String> consumer = _core_distributed_services.consumeAs(TOPIC_NAME, Optional.empty(),
            Optional.empty());

    //throw items on the queue            
    JsonNode jsonNode = new ObjectMapper().readTree("{\"keyA\":\"val1\",\"keyB\":\"val2\",\"keyC\":\"val3\"}");
    String original_message = jsonNode.toString();
    for (int i = 0; i < num_to_test; i++) {
        _core_distributed_services.produce(TOPIC_NAME, original_message);
    }
    Thread.sleep(5000); //wait a few seconds for producers to dump batch

    String consumed_message = null;
    int message_count = 0;
    //read the item off the queue
    while (consumer.hasNext()) {
        consumed_message = consumer.next();
        message_count++;
        System.out.println(consumed_message);
    }

    assertTrue("Topic should exist", _core_distributed_services.doesTopicExist(TOPIC_NAME));

    _core_distributed_services.deleteTopic(TOPIC_NAME);

    assertEquals(num_to_test, message_count);
    assertTrue(original_message.equals(consumed_message));

    // Check some random other topic does _not_ exist

    assertTrue("Topic should _not_ exist", !_core_distributed_services.doesTopicExist(TOPIC_NAME + "xxx"));
}

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

@Test
public void testConvert() throws IOException, JSONException {
    LdapDataStore store = new LdapDataStore();
    store.setDatabase(DATABASE);/*from w w w  .j a  v a2  s.co m*/
    store.setBaseDN(BASE_DN);
    store.setUniqueAttribute(UNIQUE_ATTRIBUTE);

    JsonNode node = json("{}");

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

    JSONAssert.assertEquals("{\"database\":\"" + DATABASE + "\",\"basedn\":\"" + BASE_DN
            + "\",\"uniqueattr\":\"" + UNIQUE_ATTRIBUTE + "\"}", node.toString(), true);
}

From source file:au.org.ands.vocabs.toolkit.tasks.TaskRunner.java

/** Run the task.
 *//*from w  w  w .  j  ava2s  .c  o  m*/
public final void runTask() {
    status = TaskStatus.SUCCESS;
    task = taskInfo.getTask();
    results.put("task_id", task.getId().toString());
    ArrayNode subtasks = TaskUtils.getSubtasks(task.getParams());
    if (subtasks == null || subtasks.size() == 0) {
        status = TaskStatus.ERROR;
        results.put("runTask", "No subtasks specified, or invalid" + " format.");
        addTimestamp(results);
        TaskUtils.updateMessageAndTaskStatus(logger, task, results, status,
                "No subtasks specified. Nothing to do.");
        return;
    }
    boolean success = false;
    for (JsonNode subtask : subtasks) {
        logger.debug("Got subtask: " + subtask.toString());
        if (!(subtask instanceof ObjectNode)) {
            logger.error("runTask() didn't get an object:" + subtask.toString());
            status = TaskStatus.ERROR;
            addTimestamp(results);
            TaskUtils.updateMessageAndTaskStatus(logger, task, results, status, "Bad subtask specification.");
            return;
        }
        logger.debug("subtask type: " + subtask.get("type"));
        String thisTask = subtask.get("type").textValue();
        switch (thisTask) {
        case "HARVEST":
        case "UNHARVEST":
            success = runHarvest(subtask, thisTask);
            break;
        case "TRANSFORM":
        case "UNTRANSFORM":
            success = runTransform(subtask, thisTask);
            break;
        case "IMPORT":
        case "UNIMPORT":
            success = runImport(subtask, thisTask);
            break;
        case "PUBLISH":
        case "UNPUBLISH":
            success = runPublish(subtask, thisTask);
            break;
        //                case "DELETE":
        //                    success = runDelete(subtask);
        //                    break;
        default:
            status = TaskStatus.ERROR;
            results.put("invalid_sub_task", thisTask);
            TaskUtils.updateMessageAndTaskStatus(logger, task, results, status,
                    "Invalid subtask specification.");
            break;
        }
        if (!success) {
            logger.error("ERROR while running task: " + thisTask);
            results.put("error_subtask", thisTask);
            status = TaskStatus.ERROR;
            addTimestamp(results);
            TaskUtils.updateMessageAndTaskStatus(logger, task, results, status, "Error in subtask.");
            return;
        }
    }
    status = TaskStatus.SUCCESS;
    results.put("output_path", ToolkitFileUtils.getTaskOutputPath(taskInfo, null));
    addTimestamp(results);
    TaskUtils.updateMessageAndTaskStatus(logger, task, results, status, "All tasks completed.");
}

From source file:de.tudarmstadt.ukp.clarin.webanno.crowdflower.CrowdClient.java

/**
 * Upload the data vector as JSON to the specified Crowdflower job
 * @param job/*from w w  w.  j  a v a2 s . co  m*/
 * @param data - Generic vector of data, containing ordinary java classes.
 * They should be annotated so that Jackson understands how to map them to JSON.
 *
 */

void uploadData(CrowdJob job, List<?> data) {
    Log LOG = LogFactory.getLog(getClass());

    //Crowdflower wants a Multi-line JSON, with each line having a new JSON object
    //Thus we have to map each (raw) object in data individually to a JSON string

    ObjectMapper mapper = new ObjectMapper();
    String jsonObjectCollection = "";

    StringBuilder jsonStringBuilder = new StringBuilder();
    int count = 0;
    for (Object obj : data) {
        count++;
        JsonNode jsonData = mapper.convertValue(obj, JsonNode.class);
        jsonStringBuilder.append(jsonData.toString());
        jsonStringBuilder.append("\n");
    }

    jsonObjectCollection = jsonStringBuilder.toString();

    RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter());

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<String> request = new HttpEntity<String>(jsonObjectCollection, headers);

    String result = "";

    if (job == null) {
        LOG.info("Upload new data and create new job: " + String.valueOf(count) + " data items");
        result = restTemplate.postForObject(uploadDataURL, request, String.class, apiKey);
    } else {
        LOG.info("Uploading new data to job: " + job.getId() + ": " + String.valueOf(count) + " data items");
        result = restTemplate.postForObject(uploadDataWithJobURL, request, String.class, job.getId(), apiKey);
    }
    LOG.info("Upload response:" + result);

    //set gold? this is what i would like to do...
    //updateVariable(job, "https://api.crowdflower.com/v1/jobs/{jobid}/gold?key={apiKey}", "set_standard_gold", "TRUE");
}

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

@Test
public void projection_list() throws Exception {
    String pr = "[{'field':'field6.*','include':1},{'field':'field5'}]";
    Projector projector = projector(pr, md);
    JsonNode expectedNode = JsonUtils.json(
            "{'field5':true,'field6':{'nf1':'nvalue1','nf2':'nvalue2','nf3':4,'nf4':false,'nf5':[],'nf6':[],'nf7':{},'nf8':[],'nf9':[],'nf10':[],'nf11':null}}"
                    .replace('\'', '\"'));

    JsonDoc newDoc = projector.project(doc, factory);

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

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

@Test
public void one_$parent_projection_list() throws Exception {
    String pr = "[{'field':'field7.$parent.field6.*','include':1},{'field':'field5'}]";
    Projector projector = projector(pr, md);
    JsonNode expectedNode = JsonUtils.json(
            "{'field5':true,'field6':{'nf1':'nvalue1','nf2':'nvalue2','nf3':4,'nf4':false,'nf5':[],'nf6':[],'nf7':{},'nf8':[],'nf9':[],'nf10':[],'nf11':null}}"
                    .replace('\'', '\"'));

    JsonDoc newDoc = projector.project(doc, factory);

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