Example usage for com.fasterxml.jackson.databind.node ObjectNode toString

List of usage examples for com.fasterxml.jackson.databind.node ObjectNode toString

Introduction

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

Prototype

public String toString() 

Source Link

Usage

From source file:org.flowable.rest.service.api.identity.GroupResourceTest.java

/**
 * Test updating a single user passing in null-values.
 *//* w  w w .ja  v a 2 s.c  o m*/
public void testUpdateGroupNullFields() throws Exception {
    try {
        Group testGroup = identityService.newGroup("testgroup");
        testGroup.setName("Test group");
        testGroup.setType("Test type");
        identityService.saveGroup(testGroup);

        ObjectNode requestNode = objectMapper.createObjectNode();
        requestNode.set("name", null);
        requestNode.set("type", null);

        HttpPut httpPut = new HttpPut(
                SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_GROUP, "testgroup"));
        httpPut.setEntity(new StringEntity(requestNode.toString()));
        CloseableHttpResponse response = executeRequest(httpPut, HttpStatus.SC_OK);
        JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
        closeResponse(response);
        assertNotNull(responseNode);
        assertEquals("testgroup", responseNode.get("id").textValue());
        assertNull(responseNode.get("name").textValue());
        assertNull(responseNode.get("type").textValue());
        assertTrue(responseNode.get("url").textValue()
                .endsWith(RestUrls.createRelativeResourceUrl(RestUrls.URL_GROUP, testGroup.getId())));

        Group createdGroup = identityService.createGroupQuery().groupId("testgroup").singleResult();
        assertNotNull(createdGroup);
        assertNull(createdGroup.getName());
        assertNull(createdGroup.getType());

    } finally {
        try {
            identityService.deleteGroup("testgroup");
        } catch (Throwable ignore) {
            // Ignore, since the group may not have been created in the test
            // or already deleted
        }
    }
}

From source file:org.jboss.aerogear.sync.client.ClientSyncEngine.java

/**
 * Converts the {@link ClientDocument} into a JSON {@code String} representation.
 *
 * @param document the {@link ClientDocument} to convert
 * @return {@code String} the JSON String representation of the document.
 *///ww w. j  a  va 2 s  . co m
public String documentToJson(final ClientDocument<T> document) {
    final ObjectNode objectNode = OM.createObjectNode();
    objectNode.put("msgType", "add");
    objectNode.put("id", document.id());
    objectNode.put("clientId", document.clientId());
    clientSynchronizer.addContent(document.content(), objectNode, "content");
    return objectNode.toString();
}

From source file:com.almende.demo.tuneswarm.ConductorAgent.java

/**
 * Send tune to agents.//from  w w  w  .ja va  2 s.c om
 *
 * @param tune
 *            the tune
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public void sendTuneToAgents(@Name("tune") TuneDescription tune) throws IOException {
    final Map<Tone, TuneDescription> tunes = tune.splitToTones();
    final Map<Tone, TuneDescription> plan = new HashMap<Tone, TuneDescription>();
    for (Tone tone : agents.keySet()) {
        final TuneDescription description = tunes.remove(tone);
        if (description != null) {
            LOG.warning("Adding tone:" + tone + " to plan");
            plan.put(tone, description);
        }
    }
    Iterator<TuneDescription> iter = tunes.values().iterator();
    TuneDescription td = null;
    while (iter.hasNext()) {
        boolean progress = false;
        for (Entry<Tone, TuneDescription> item : plan.entrySet()) {
            if (iter.hasNext()) {
                td = iter.next();
            } else {
                break;
            }
            LOG.warning("Merging tones:" + JOM.getInstance().valueToTree(td.getTones()) + " to plan:"
                    + JOM.getInstance().valueToTree(item));

            if (item.getValue().tryMerge(td)) {
                td = null;
                progress = true;
            }
        }
        if (!progress) {
            break;
        }
    }
    for (Entry<Tone, TuneDescription> item : plan.entrySet()) {
        for (final ToneAgent agent : agents.get(item.getKey())) {
            if (agent.offline) {
                continue;
            }
            final ObjectNode params = JOM.createObjectNode();
            params.set("description", JOM.getInstance().valueToTree(item.getValue()));
            LOG.warning("Sending:" + agent.address + " storeTune:" + params.toString());
            caller.call(agent.address, "storeTune", params);
        }
    }
}

From source file:org.activiti.editor.ui.ConvertProcessDefinitionPopupWindow.java

protected void addButtons() {
    // Cancel//from  w ww  . j  a  v  a2  s .c o m
    Button cancelButton = new Button(i18nManager.getMessage(Messages.BUTTON_CANCEL));
    cancelButton.addStyleName(Reindeer.BUTTON_SMALL);
    cancelButton.addListener(new ClickListener() {

        private static final long serialVersionUID = 1L;

        public void buttonClick(ClickEvent event) {
            close();
        }
    });

    // Convert
    Button convertButton = new Button(i18nManager.getMessage(Messages.PROCESS_CONVERT_POPUP_CONVERT_BUTTON));
    convertButton.addStyleName(Reindeer.BUTTON_SMALL);
    convertButton.addListener(new ClickListener() {

        private static final long serialVersionUID = 1L;

        public void buttonClick(ClickEvent event) {

            try {
                InputStream bpmnStream = repositoryService.getResourceAsStream(
                        processDefinition.getDeploymentId(), processDefinition.getResourceName());
                XMLInputFactory xif = XMLInputFactory.newInstance();
                InputStreamReader in = new InputStreamReader(bpmnStream, "UTF-8");
                XMLStreamReader xtr = xif.createXMLStreamReader(in);
                BpmnModel bpmnModel = new BpmnXMLConverter().convertToBpmnModel(xtr);

                if (bpmnModel.getMainProcess() == null || bpmnModel.getMainProcess().getId() == null) {
                    notificationManager.showErrorNotification(Messages.MODEL_IMPORT_FAILED,
                            i18nManager.getMessage(Messages.MODEL_IMPORT_INVALID_BPMN_EXPLANATION));
                } else {

                    if (bpmnModel.getLocationMap().size() == 0) {
                        notificationManager.showErrorNotification(Messages.MODEL_IMPORT_INVALID_BPMNDI,
                                i18nManager.getMessage(Messages.MODEL_IMPORT_INVALID_BPMNDI_EXPLANATION));
                    } else {

                        BpmnJsonConverter converter = new BpmnJsonConverter();
                        ObjectNode modelNode = converter.convertToJson(bpmnModel);
                        Model modelData = repositoryService.newModel();

                        ObjectNode modelObjectNode = new ObjectMapper().createObjectNode();
                        modelObjectNode.put(MODEL_NAME, processDefinition.getName());
                        modelObjectNode.put(MODEL_REVISION, 1);
                        modelObjectNode.put(MODEL_DESCRIPTION, processDefinition.getDescription());
                        modelData.setMetaInfo(modelObjectNode.toString());
                        modelData.setName(processDefinition.getName());

                        repositoryService.saveModel(modelData);

                        repositoryService.addModelEditorSource(modelData.getId(),
                                modelNode.toString().getBytes("utf-8"));

                        close();
                        ExplorerApp.get().getViewManager().showEditorProcessDefinitionPage(modelData.getId());

                        URL explorerURL = ExplorerApp.get().getURL();
                        URL url = new URL(explorerURL.getProtocol(), explorerURL.getHost(),
                                explorerURL.getPort(), explorerURL.getPath().replace("/ui", "")
                                        + "service/editor?id=" + modelData.getId());
                        ExplorerApp.get().getMainWindow().open(new ExternalResource(url));
                    }
                }

            } catch (Exception e) {
                notificationManager.showErrorNotification("error", e);
            }
        }
    });

    // Alignment
    HorizontalLayout buttonLayout = new HorizontalLayout();
    buttonLayout.setSpacing(true);
    buttonLayout.addComponent(cancelButton);
    buttonLayout.addComponent(convertButton);
    addComponent(buttonLayout);
    windowLayout.setComponentAlignment(buttonLayout, Alignment.BOTTOM_RIGHT);
}

From source file:org.activiti.rest.service.api.runtime.ProcessInstanceIdentityLinkResourceTest.java

/**
 * Test creating an identity link.//from   w  w  w  .j av a 2  s .  c  om
 */
@Deployment(resources = {
        "org/activiti/rest/service/api/runtime/ProcessInstanceIdentityLinkResourceTest.process.bpmn20.xml" })
public void testCreateIdentityLink() throws Exception {

    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");

    // Add user link
    ObjectNode requestNode = objectMapper.createObjectNode();
    requestNode.put("user", "kermit");
    requestNode.put("type", "myType");

    HttpPost httpPost = new HttpPost(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(
            RestUrls.URL_PROCESS_INSTANCE_IDENTITYLINKS_COLLECTION, processInstance.getId()));
    httpPost.setEntity(new StringEntity(requestNode.toString()));
    CloseableHttpResponse response = executeRequest(httpPost, HttpStatus.SC_CREATED);

    JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);
    assertNotNull(responseNode);
    assertEquals("kermit", responseNode.get("user").textValue());
    assertEquals("myType", responseNode.get("type").textValue());
    assertTrue(responseNode.get("group").isNull());
    assertTrue(responseNode.get("url").textValue().endsWith(RestUrls.createRelativeResourceUrl(
            RestUrls.URL_PROCESS_INSTANCE_IDENTITYLINK, processInstance.getId(), "kermit", "myType")));

    // Test with unexisting process
    httpPost = new HttpPost(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(
            RestUrls.URL_PROCESS_INSTANCE_IDENTITYLINKS_COLLECTION, "unexistingprocess"));
    httpPost.setEntity(new StringEntity(requestNode.toString()));
    closeResponse(executeRequest(httpPost, HttpStatus.SC_NOT_FOUND));

    // Test with no user
    requestNode = objectMapper.createObjectNode();
    requestNode.put("type", "myType");

    httpPost = new HttpPost(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(
            RestUrls.URL_PROCESS_INSTANCE_IDENTITYLINKS_COLLECTION, processInstance.getId()));
    httpPost.setEntity(new StringEntity(requestNode.toString()));
    closeResponse(executeRequest(httpPost, HttpStatus.SC_BAD_REQUEST));

    // Test with group (which is not supported on processes)
    requestNode = objectMapper.createObjectNode();
    requestNode.put("type", "myType");
    requestNode.put("group", "sales");
    httpPost.setEntity(new StringEntity(requestNode.toString()));
    closeResponse(executeRequest(httpPost, HttpStatus.SC_BAD_REQUEST));

    // Test with no type
    requestNode = objectMapper.createObjectNode();
    requestNode.put("user", "kermit");
    httpPost.setEntity(new StringEntity(requestNode.toString()));
    closeResponse(executeRequest(httpPost, HttpStatus.SC_BAD_REQUEST));
}

From source file:org.flowable.rest.service.api.runtime.ProcessInstanceIdentityLinkResourceTest.java

/**
 * Test creating an identity link.//from ww  w. j a  va2  s  .  c o  m
 */
@Deployment(resources = {
        "org/flowable/rest/service/api/runtime/ProcessInstanceIdentityLinkResourceTest.process.bpmn20.xml" })
public void testCreateIdentityLink() throws Exception {

    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("oneTaskProcess");

    // Add user link
    ObjectNode requestNode = objectMapper.createObjectNode();
    requestNode.put("user", "kermit");
    requestNode.put("type", "myType");

    HttpPost httpPost = new HttpPost(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(
            RestUrls.URL_PROCESS_INSTANCE_IDENTITYLINKS_COLLECTION, processInstance.getId()));
    httpPost.setEntity(new StringEntity(requestNode.toString()));
    CloseableHttpResponse response = executeRequest(httpPost, HttpStatus.SC_CREATED);

    JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);
    assertNotNull(responseNode);
    assertEquals("kermit", responseNode.get("user").textValue());
    assertEquals("myType", responseNode.get("type").textValue());
    assertTrue(responseNode.get("group").isNull());
    assertTrue(responseNode.get("url").textValue().endsWith(RestUrls.createRelativeResourceUrl(
            RestUrls.URL_PROCESS_INSTANCE_IDENTITYLINK, processInstance.getId(), "kermit", "myType")));

    // Test with unexisting process
    httpPost = new HttpPost(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(
            RestUrls.URL_PROCESS_INSTANCE_IDENTITYLINKS_COLLECTION, "unexistingprocess"));
    httpPost.setEntity(new StringEntity(requestNode.toString()));
    closeResponse(executeRequest(httpPost, HttpStatus.SC_NOT_FOUND));

    // Test with no user
    requestNode = objectMapper.createObjectNode();
    requestNode.put("type", "myType");

    httpPost = new HttpPost(SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(
            RestUrls.URL_PROCESS_INSTANCE_IDENTITYLINKS_COLLECTION, processInstance.getId()));
    httpPost.setEntity(new StringEntity(requestNode.toString()));
    closeResponse(executeRequest(httpPost, HttpStatus.SC_BAD_REQUEST));

    // Test with group (which is not supported on processes)
    requestNode = objectMapper.createObjectNode();
    requestNode.put("type", "myType");
    requestNode.put("group", "sales");
    httpPost.setEntity(new StringEntity(requestNode.toString()));
    closeResponse(executeRequest(httpPost, HttpStatus.SC_BAD_REQUEST));

    // Test with no type
    requestNode = objectMapper.createObjectNode();
    requestNode.put("user", "kermit");
    httpPost.setEntity(new StringEntity(requestNode.toString()));
    closeResponse(executeRequest(httpPost, HttpStatus.SC_BAD_REQUEST));
}

From source file:com.stratio.ingestion.sink.kafka.KafkaSinkTest.java

@Test
public void test() throws EventDeliveryException, UnsupportedEncodingException {
    Transaction tx = channel.getTransaction();
    tx.begin();/*from   ww  w.j  a  v  a 2 s .  co m*/

    ObjectNode jsonBody = new ObjectNode(JsonNodeFactory.instance);
    jsonBody.put("myString", "foo");
    jsonBody.put("myInt32", 32);

    Map<String, String> headers = new HashMap<String, String>();
    headers.put("myString", "bar");
    headers.put("myInt64", "64");
    headers.put("myBoolean", "true");
    headers.put("myDouble", "1.0");
    headers.put("myNull", "foobar");

    Event event = EventBuilder.withBody(jsonBody.toString().getBytes(Charsets.UTF_8), headers);
    channel.put(event);

    tx.commit();
    tx.close();

    kafkaSink.process();

    kafka.api.FetchRequest req = new FetchRequestBuilder().clientId(CLIENT_ID).addFetch("test", 0, 0L, 100)
            .build();
    FetchResponse fetchResponse = simpleConsumer.fetch(req);
    ByteBufferMessageSet messageSet = fetchResponse.messageSet("test", 0);

    Assert.assertTrue(messageSet.sizeInBytes() > 0);
    for (MessageAndOffset messageAndOffset : messageSet) {
        ByteBuffer payload = messageAndOffset.message().payload();
        byte[] bytes = new byte[payload.limit()];
        payload.get(bytes);
        String message = new String(bytes, "UTF-8");
        Assert.assertNotNull(message);
        Assert.assertEquals(message, "{\"myString\":\"foo\",\"myInt32\":32}");
    }
}

From source file:com.stratio.ingestion.sink.kafka.KafkaSinkTestIT.java

@Test
public void test() throws EventDeliveryException, UnsupportedEncodingException {
    Transaction tx = channel.getTransaction();
    tx.begin();//  www.j  a v a2 s  . co  m

    ObjectNode jsonBody = new ObjectNode(JsonNodeFactory.instance);
    jsonBody.put("myString", "foo");
    jsonBody.put("myInt32", 32);

    Map<String, String> headers = new HashMap<String, String>();
    headers.put("myString", "bar");
    headers.put("myInt64", "64");
    headers.put("myBoolean", "true");
    headers.put("myDouble", "1.0");
    headers.put("myNull", "foobar");

    Event event = EventBuilder.withBody(jsonBody.toString().getBytes(Charsets.UTF_8), headers);
    channel.put(event);

    tx.commit();
    tx.close();

    kafkaSink.process();

    kafka.api.FetchRequest req = new FetchRequestBuilder().clientId(CLIENT_ID).addFetch("test", 0, 0L, 100)
            .build();
    FetchResponse fetchResponse = simpleConsumer.fetch(req);
    ByteBufferMessageSet messageSet = fetchResponse.messageSet("test", 0);

    for (MessageAndOffset messageAndOffset : messageSet) {
        ByteBuffer payload = messageAndOffset.message().payload();
        byte[] bytes = new byte[payload.limit()];
        payload.get(bytes);
        String message = new String(bytes, "UTF-8");
        Assert.assertNotNull(message);
        Assert.assertEquals(message, "{\"myString\":\"foo\",\"myInt32\":32}");
    }
}

From source file:com.github.lynxdb.server.api.http.handlers.EpError.java

@RequestMapping(value = "", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity error(HttpServletRequest request, HttpServletResponse response) {

    HttpStatus status = HttpStatus.valueOf((int) request.getAttribute("javax.servlet.error.status_code"));

    ObjectMapper mapper = new ObjectMapper();
    ObjectNode error = mapper.createObjectNode();
    error.put("code", status.value());
    error.put("message", status.getReasonPhrase());
    error.put("details", getErrorAttributes(request, true).get("message").toString());
    if (getErrorAttributes(request, true).get("exception") != null) {
        error.put("trace", getErrorAttributes(request, true).get("exception").toString() + "\n"
                + getErrorAttributes(request, true).get("trace").toString());
    }//w w w .j a v  a2s . com

    return ResponseEntity.status(status).body(error.toString());
}