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:com.blackberry.bdp.common.versioned.ZkVersioned.java

private void writeJsonToZooKeeper(String jsonString) throws Exception {
    // remove the version as that never gets written to ZK
    ObjectNode node = (ObjectNode) mapper.readTree(jsonString);
    node.remove("version");
    jsonString = node.toString();
    LOG.info("Attempt at saving {} to {} as {}", this, this.zkPath, jsonString);
    Stat stat = this.curator.checkExists().forPath(zkPath);

    for (int i = 0; i < retries; i++) {
        try {/*from   w  w w  . j  a  v a2s  . c om*/
            if (stat == null) {
                if (version != null) {
                    throw new VersionMismatchException("New objects must have null version");
                }
                LOG.info("Saving initial object in non-existent zkPath: {}", zkPath);
                curator.create().creatingParentsIfNeeded().withMode(mode).forPath(zkPath,
                        jsonString.getBytes());
                stat = this.curator.checkExists().forPath(zkPath);
                this.setVersion(stat.getVersion());
            } else {
                if (version == null) {
                    throw new VersionMismatchException("Cannot update existing objects with null version");
                }
                if (this.version != stat.getVersion()) {
                    throw new VersionMismatchException(
                            String.format("Object with version %s cannot be saved to existing version %s",
                                    this.version, stat.getVersion()));
                } else {
                    Stat newStat = curator.setData().forPath(zkPath, jsonString.getBytes());
                    this.setVersion(newStat.getVersion());
                    LOG.info("Saved new {} version {}", this.getClass(), newStat.getVersion());
                }
            }
            break;
        } catch (VersionMismatchException vme) {
            throw vme;
        } catch (Exception e) {
            if (i <= retries) {
                LOG.warn("Failed attempt {}/{} to write to {}.  Retrying in {} seconds", i, retries, zkPath,
                        (backoff / 1000), e);
                Thread.sleep(backoff);
                backoff *= backoffExponent;
            } else {
                throw new Exception(
                        String.format("Failed to write to %s and no retries left--giving up", zkPath), e);
            }
        }
    }
}

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

/**
 * Test updating a single group.//  ww w.j av a2  s.c o  m
 */
public void testUpdateGroup() throws Exception {
    try {
        Group testGroup = identityService.newGroup("testgroup");
        testGroup.setName("Test group");
        testGroup.setType("Test type");
        identityService.saveGroup(testGroup);

        ObjectNode requestNode = objectMapper.createObjectNode();
        requestNode.put("name", "Updated group");
        requestNode.put("type", "Updated type");

        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());
        assertEquals("Updated group", responseNode.get("name").textValue());
        assertEquals("Updated type", 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);
        assertEquals("Updated group", createdGroup.getName());
        assertEquals("Updated type", 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.activiti.rest.service.api.identity.GroupResourceTest.java

/**
 * Test updating a single user passing in null-values.
 *///from w w  w. jav a  2s .  c  om
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.put("name", (JsonNode) null);
        requestNode.put("type", (JsonNode) 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.activiti.rest.service.api.repository.ModelResourceTest.java

@Deployment(resources = { "org/activiti/rest/service/api/repository/oneTaskProcess.bpmn20.xml" })
public void testUpdateModelNoFields() throws Exception {

    Model model = null;/*from w w  w  . j  ava  2 s  .  c o  m*/
    try {
        Calendar now = Calendar.getInstance();
        now.set(Calendar.MILLISECOND, 0);
        processEngineConfiguration.getClock().setCurrentTime(now.getTime());

        model = repositoryService.newModel();
        model.setCategory("Model category");
        model.setKey("Model key");
        model.setMetaInfo("Model metainfo");
        model.setName("Model name");
        model.setVersion(2);
        model.setDeploymentId(deploymentId);
        repositoryService.saveModel(model);

        // Use empty request-node, nothing should be changed after update
        ObjectNode requestNode = objectMapper.createObjectNode();

        HttpPut httpPut = new HttpPut(
                SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_MODEL, model.getId()));
        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("Model name", responseNode.get("name").textValue());
        assertEquals("Model key", responseNode.get("key").textValue());
        assertEquals("Model category", responseNode.get("category").textValue());
        assertEquals(2, responseNode.get("version").intValue());
        assertEquals("Model metainfo", responseNode.get("metaInfo").textValue());
        assertEquals(deploymentId, responseNode.get("deploymentId").textValue());
        assertEquals(model.getId(), responseNode.get("id").textValue());

        assertEquals(now.getTime().getTime(),
                getDateFromISOString(responseNode.get("createTime").textValue()).getTime());
        assertEquals(now.getTime().getTime(),
                getDateFromISOString(responseNode.get("lastUpdateTime").textValue()).getTime());

        assertTrue(responseNode.get("url").textValue()
                .endsWith(RestUrls.createRelativeResourceUrl(RestUrls.URL_MODEL, model.getId())));
        assertTrue(responseNode.get("deploymentUrl").textValue()
                .endsWith(RestUrls.createRelativeResourceUrl(RestUrls.URL_DEPLOYMENT, deploymentId)));

    } finally {
        try {
            repositoryService.deleteModel(model.getId());
        } catch (Throwable ignore) {
            // Ignore, model might not be created
        }
    }
}

From source file:org.flowable.rest.service.api.repository.ModelResourceTest.java

@Deployment(resources = { "org/flowable/rest/service/api/repository/oneTaskProcess.bpmn20.xml" })
public void testUpdateModelNoFields() throws Exception {

    Model model = null;//from w ww  . j  a  v a2s .co m
    try {
        Calendar now = Calendar.getInstance();
        now.set(Calendar.MILLISECOND, 0);
        processEngineConfiguration.getClock().setCurrentTime(now.getTime());

        model = repositoryService.newModel();
        model.setCategory("Model category");
        model.setKey("Model key");
        model.setMetaInfo("Model metainfo");
        model.setName("Model name");
        model.setVersion(2);
        model.setDeploymentId(deploymentId);
        repositoryService.saveModel(model);

        // Use empty request-node, nothing should be changed after update
        ObjectNode requestNode = objectMapper.createObjectNode();

        HttpPut httpPut = new HttpPut(
                SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_MODEL, model.getId()));
        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("Model name", responseNode.get("name").textValue());
        assertEquals("Model key", responseNode.get("key").textValue());
        assertEquals("Model category", responseNode.get("category").textValue());
        assertEquals(2, responseNode.get("version").intValue());
        assertEquals("Model metainfo", responseNode.get("metaInfo").textValue());
        assertEquals(deploymentId, responseNode.get("deploymentId").textValue());
        assertEquals(model.getId(), responseNode.get("id").textValue());

        assertEquals(now.getTime().getTime(),
                getDateFromISOString(responseNode.get("createTime").textValue()).getTime());
        assertEquals(now.getTime().getTime(),
                getDateFromISOString(responseNode.get("lastUpdateTime").textValue()).getTime());

        assertTrue(responseNode.get("url").textValue()
                .endsWith(RestUrls.createRelativeResourceUrl(RestUrls.URL_MODEL, model.getId())));
        assertTrue(responseNode.get("deploymentUrl").textValue()
                .endsWith(RestUrls.createRelativeResourceUrl(RestUrls.URL_DEPLOYMENT, deploymentId)));

    } finally {
        try {
            repositoryService.deleteModel(model.getId());
        } catch (Throwable ignore) {
            // Ignore, model might not be created
        }
    }
}

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

/**
 * Test creating a comment for a task. POST runtime/tasks/{taskId}/comments
 *//*ww w.j  ava2s. c  om*/
public void testCreateComment() throws Exception {
    try {
        Task task = taskService.newTask();
        taskService.saveTask(task);

        ObjectNode requestNode = objectMapper.createObjectNode();
        requestNode.put("message", "This is a comment...");

        HttpPost httpPost = new HttpPost(SERVER_URL_PREFIX
                + RestUrls.createRelativeResourceUrl(RestUrls.URL_TASK_COMMENT_COLLECTION, task.getId()));
        httpPost.setEntity(new StringEntity(requestNode.toString()));
        CloseableHttpResponse response = executeRequest(httpPost, HttpStatus.SC_CREATED);
        List<Comment> commentsOnTask = taskService.getTaskComments(task.getId());
        assertNotNull(commentsOnTask);
        assertEquals(1, commentsOnTask.size());

        JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
        closeResponse(response);
        assertNotNull(responseNode);
        assertEquals("kermit", responseNode.get("author").textValue());
        assertEquals("This is a comment...", responseNode.get("message").textValue());
        assertEquals(commentsOnTask.get(0).getId(), responseNode.get("id").textValue());
        assertTrue(responseNode.get("taskUrl").textValue().endsWith(RestUrls.createRelativeResourceUrl(
                RestUrls.URL_TASK_COMMENT, task.getId(), commentsOnTask.get(0).getId())));
        assertEquals(task.getId(), responseNode.get("taskId").asText());
        assertTrue(responseNode.get("processInstanceUrl").isNull());
        assertTrue(responseNode.get("processInstanceId").isNull());

    } finally {
        // Clean adhoc-tasks even if test fails
        List<Task> tasks = taskService.createTaskQuery().list();
        for (Task task : tasks) {
            taskService.deleteTask(task.getId(), true);
        }
    }
}

From source file:com.baasbox.Global.java

@Override
public F.Promise<SimpleResult> onBadRequest(RequestHeader request, String error) {
    ObjectNode result = prepareError(request, error);
    result.put("http_code", 400);
    SimpleResult resultToReturn = badRequest(result);
    try {//from   ww w  . j a va  2s. c  o  m
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("Global.onBadRequest:\n  + result: \n" + result.toString() + "\n  --> Body:\n"
                    + result.toString(), "UTF-8");
    } finally {
        return F.Promise.pure(resultToReturn);
    }
}

From source file:com.activiti.service.activiti.ProcessInstanceService.java

public JsonNode listProcesInstances(ObjectNode bodyNode, ServerConfig serverConfig) {
    JsonNode resultNode = null;/*  w  w w . j a v a  2  s  .  c o  m*/
    try {
        URIBuilder builder = new URIBuilder("query/historic-process-instances");

        String uri = clientUtil.getUriWithPagingAndOrderParameters(builder, bodyNode);
        HttpPost post = clientUtil.createPost(uri, serverConfig);

        post.setEntity(clientUtil.createStringEntity(bodyNode.toString()));
        resultNode = clientUtil.executeRequest(post, serverConfig);
    } catch (Exception e) {
        throw new ActivitiServiceException(e.getMessage(), e);
    }
    return resultNode;
}

From source file:org.apache.olingo.fit.utils.JSONUtilities.java

@Override
public InputStream addEditLink(final InputStream content, final String title, final String href)
        throws IOException {

    final ObjectNode srcNode = (ObjectNode) mapper.readTree(content);
    IOUtils.closeQuietly(content);//from  w  w w . j  a v  a2s  .c om

    srcNode.set(Constants.get(ConstantKey.JSON_EDITLINK_NAME), new TextNode(href));
    return IOUtils.toInputStream(srcNode.toString(), Constants.ENCODING);
}

From source file:com.baasbox.Global.java

@Override
public F.Promise<SimpleResult> onHandlerNotFound(RequestHeader request) {
    debug("API not found: " + request.method() + " " + request);
    ObjectNode result = prepareError(request, "API not found");
    result.put("http_code", 404);
    SimpleResult resultToReturn = notFound(result);
    try {//  w  w w.  ja v  a  2  s  .c o  m
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("Global.onBadRequest:\n  + result: \n" + result.toString() + "\n  --> Body:\n"
                    + new String(JavaResultExtractor.getBody(resultToReturn), "UTF-8"));
    } finally {
        return F.Promise.pure(resultToReturn);
    }
}