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.content.rest.service.api.content.ContentItemCollectionResourceTest.java

public void testCreateContentItem() throws Exception {
    ContentItem urlContentItem = null;/*from w  w  w  .ja  v  a  2 s  .  c  o  m*/
    try {
        ObjectNode requestNode = objectMapper.createObjectNode();
        requestNode.put("name", "Simple content item");
        requestNode.put("mimeType", "application/pdf");
        requestNode.put("taskId", "12345");
        requestNode.put("processInstanceId", "123456");
        requestNode.put("contentStoreId", "id");
        requestNode.put("contentStoreName", "testStore");
        requestNode.put("createdBy", "testa");
        requestNode.put("lastModifiedBy", "testb");

        HttpPost httpPost = new HttpPost(SERVER_URL_PREFIX
                + ContentRestUrls.createRelativeResourceUrl(ContentRestUrls.URL_CONTENT_ITEM_COLLECTION));
        httpPost.setEntity(new StringEntity(requestNode.toString()));
        CloseableHttpResponse response = executeRequest(httpPost, HttpStatus.SC_CREATED);

        // Check if content item is created
        List<ContentItem> contentItems = contentService.createContentItemQuery().list();
        assertEquals(1, contentItems.size());

        urlContentItem = contentItems.get(0);

        JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
        closeResponse(response);
        assertEquals(urlContentItem.getId(), responseNode.get("id").asText());
        assertEquals("Simple content item", responseNode.get("name").asText());
        assertEquals("application/pdf", responseNode.get("mimeType").asText());
        assertEquals("12345", responseNode.get("taskId").asText());
        assertEquals("123456", responseNode.get("processInstanceId").asText());
        assertEquals("id", responseNode.get("contentStoreId").asText());
        assertEquals("testStore", responseNode.get("contentStoreName").asText());
        assertFalse(responseNode.get("contentAvailable").asBoolean());
        assertEquals("testa", responseNode.get("createdBy").asText());
        assertEquals("testb", responseNode.get("lastModifiedBy").asText());
        assertEquals(urlContentItem.getCreated(), getDateFromISOString(responseNode.get("created").asText()));
        assertEquals(urlContentItem.getLastModified(),
                getDateFromISOString(responseNode.get("lastModified").asText()));
        assertTrue(responseNode.get("url").textValue().endsWith(ContentRestUrls
                .createRelativeResourceUrl(ContentRestUrls.URL_CONTENT_ITEM, urlContentItem.getId())));

    } finally {
        if (urlContentItem != null) {
            contentService.deleteContentItem(urlContentItem.getId());
        }
    }
}

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

public static void addElementRangeIndexTemporalCollection(String dbName, String collectionName,
        String systemAxisName, String validAxisName) throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode rootNode = mapper.createObjectNode();

    rootNode.put("collection-name", collectionName);
    rootNode.put("system-axis", systemAxisName);
    rootNode.put("valid-axis", validAxisName);

    System.out.println(rootNode.toString());

    DefaultHttpClient client = new DefaultHttpClient();
    client.getCredentialsProvider().setCredentials(new AuthScope("localhost", 8002),
            new UsernamePasswordCredentials("admin", "admin"));

    HttpPost post = new HttpPost(
            "http://localhost:8002/manage/v2/databases/" + dbName + "/temporal/collections?format=json");

    post.addHeader("Content-type", "application/json");
    post.addHeader("accept", "application/json");
    post.setEntity(new StringEntity(rootNode.toString()));

    HttpResponse response = client.execute(post);
    HttpEntity respEntity = response.getEntity();
    if (response.getStatusLine().getStatusCode() == 400) {
        HttpEntity entity = response.getEntity();
        String responseString = EntityUtils.toString(entity, "UTF-8");
        System.out.println(responseString);
    } else if (respEntity != null) {
        // EntityUtils to get the response content
        String content = EntityUtils.toString(respEntity);
        System.out.println(content);

        System.out.println("Temporal collection: " + collectionName + " created");
        System.out.println("==============================================================");
    } else {/*from  w ww .j  av a  2 s .c  o  m*/
        System.out.println("No Proper Response");
    }

}

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

/**
 * Test starting a process instance passing in variables to set.
 *///from   ww  w . ja v  a2 s. co  m
@Deployment(resources = {
        "org/activiti/rest/service/api/runtime/ProcessInstanceResourceTest.process-one.bpmn20.xml" })
public void testStartProcessWithVariablesAndReturnVariables() throws Exception {
    ArrayNode variablesNode = objectMapper.createArrayNode();

    // String variable
    ObjectNode stringVarNode = variablesNode.addObject();
    stringVarNode.put("name", "stringVariable");
    stringVarNode.put("value", "simple string value");
    stringVarNode.put("type", "string");

    ObjectNode integerVarNode = variablesNode.addObject();
    integerVarNode.put("name", "integerVariable");
    integerVarNode.put("value", 1234);
    integerVarNode.put("type", "integer");

    ObjectNode requestNode = objectMapper.createObjectNode();

    // Start using process definition key, passing in variables
    requestNode.put("processDefinitionKey", "processOne");
    requestNode.put("returnVariables", true);
    requestNode.put("variables", variablesNode);

    HttpPost httpPost = new HttpPost(
            SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_PROCESS_INSTANCE_COLLECTION));
    httpPost.setEntity(new StringEntity(requestNode.toString()));
    CloseableHttpResponse response = executeRequest(httpPost, HttpStatus.SC_CREATED);
    JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);
    assertEquals(false, responseNode.get("ended").asBoolean());
    JsonNode variablesArrayNode = responseNode.get("variables");
    assertEquals(2, variablesArrayNode.size());
    for (JsonNode variableNode : variablesArrayNode) {
        if ("stringVariable".equals(variableNode.get("name").asText())) {
            assertEquals("simple string value", variableNode.get("value").asText());
            assertEquals("string", variableNode.get("type").asText());

        } else if ("integerVariable".equals(variableNode.get("name").asText())) {
            assertEquals(1234, variableNode.get("value").asInt());
            assertEquals("integer", variableNode.get("type").asText());

        } else {
            fail("Unexpected variable " + variableNode.get("name").asText());
        }
    }

    ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().singleResult();
    assertNotNull(processInstance);

    // Check if engine has correct variables set
    Map<String, Object> processVariables = runtimeService.getVariables(processInstance.getId());
    assertEquals(2, processVariables.size());

    assertEquals("simple string value", processVariables.get("stringVariable"));
    assertEquals(1234, processVariables.get("integerVariable"));
}

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

/**
 * Test starting a process instance passing in variables to set.
 *//*w w  w.  ja v  a 2s .  c  o  m*/
@Deployment(resources = {
        "org/flowable/rest/service/api/runtime/ProcessInstanceResourceTest.process-one.bpmn20.xml" })
public void testStartProcessWithVariablesAndReturnVariables() throws Exception {
    ArrayNode variablesNode = objectMapper.createArrayNode();

    // String variable
    ObjectNode stringVarNode = variablesNode.addObject();
    stringVarNode.put("name", "stringVariable");
    stringVarNode.put("value", "simple string value");
    stringVarNode.put("type", "string");

    ObjectNode integerVarNode = variablesNode.addObject();
    integerVarNode.put("name", "integerVariable");
    integerVarNode.put("value", 1234);
    integerVarNode.put("type", "integer");

    ObjectNode requestNode = objectMapper.createObjectNode();

    // Start using process definition key, passing in variables
    requestNode.put("processDefinitionKey", "processOne");
    requestNode.put("returnVariables", true);
    requestNode.set("variables", variablesNode);

    HttpPost httpPost = new HttpPost(
            SERVER_URL_PREFIX + RestUrls.createRelativeResourceUrl(RestUrls.URL_PROCESS_INSTANCE_COLLECTION));
    httpPost.setEntity(new StringEntity(requestNode.toString()));
    CloseableHttpResponse response = executeRequest(httpPost, HttpStatus.SC_CREATED);
    JsonNode responseNode = objectMapper.readTree(response.getEntity().getContent());
    closeResponse(response);
    assertFalse(responseNode.get("ended").asBoolean());
    JsonNode variablesArrayNode = responseNode.get("variables");
    assertEquals(2, variablesArrayNode.size());
    for (JsonNode variableNode : variablesArrayNode) {
        if ("stringVariable".equals(variableNode.get("name").asText())) {
            assertEquals("simple string value", variableNode.get("value").asText());
            assertEquals("string", variableNode.get("type").asText());

        } else if ("integerVariable".equals(variableNode.get("name").asText())) {
            assertEquals(1234, variableNode.get("value").asInt());
            assertEquals("integer", variableNode.get("type").asText());

        } else {
            fail("Unexpected variable " + variableNode.get("name").asText());
        }
    }

    ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().singleResult();
    assertNotNull(processInstance);

    // Check if engine has correct variables set
    Map<String, Object> processVariables = runtimeService.getVariables(processInstance.getId());
    assertEquals(2, processVariables.size());

    assertEquals("simple string value", processVariables.get("stringVariable"));
    assertEquals(1234, processVariables.get("integerVariable"));
}

From source file:io.gs2.identifier.Gs2IdentifierClient.java

/**
 * ?????<br>/*from  w ww .ja va 2s . c  om*/
 * <br>
 *
 * @param request 
        
 */

public void attachSecurityPolicy(AttachSecurityPolicyRequest request) {

    ObjectNode body = JsonNodeFactory.instance.objectNode().put("securityPolicyId",
            request.getSecurityPolicyId());
    HttpPut put = createHttpPut(
            Gs2Constant.ENDPOINT_HOST + "/user/"
                    + (request.getUserName() == null || request.getUserName().equals("") ? "null"
                            : request.getUserName())
                    + "/securityPolicy",
            credential, ENDPOINT, AttachSecurityPolicyRequest.Constant.MODULE,
            AttachSecurityPolicyRequest.Constant.FUNCTION, body.toString());
    if (request.getRequestId() != null) {
        put.setHeader("X-GS2-REQUEST-ID", request.getRequestId());
    }

    doRequest(put, null);

}

From source file:com.ikanow.aleph2.management_db.mongodb.services.TestIkanowV1SyncService_LibraryJars.java

@Test
public void test_updateV1SourceStatus()
        throws JsonProcessingException, IOException, InterruptedException, ExecutionException, ParseException {
    @SuppressWarnings("unchecked")
    ICrudService<JsonNode> v1_share_db = this._service_context.getCoreManagementDbService()
            .getUnderlyingPlatformDriver(ICrudService.class, Optional.of("social.share")).get();

    final DBCollection dbc = v1_share_db.getUnderlyingPlatformDriver(DBCollection.class, Optional.empty())
            .get();/*from   w w w .  j  a  v  a 2s.com*/

    v1_share_db.deleteDatastore().get();

    IManagementCrudService<SharedLibraryBean> library_db = this._service_context.getCoreManagementDbService()
            .getSharedLibraryStore();

    library_db.deleteDatastore().get();

    final ObjectMapper mapper = BeanTemplateUtils.configureMapper(Optional.empty());

    final ObjectNode v1_share_1 = (ObjectNode) mapper
            .readTree(this.getClass().getResourceAsStream("test_v1_sync_sample_share.json"));
    final DBObject v1_share_1_dbo = (DBObject) JSON.parse(v1_share_1.toString());
    v1_share_1_dbo.put("_id", new ObjectId(v1_share_1.get("_id").asText()));

    assertEquals(0L, (long) v1_share_db.countObjects().get());
    dbc.save(v1_share_1_dbo);
    //v1_share_db.storeObjects(Arrays.asList(v1_share_1)).get();
    assertEquals(1L, (long) v1_share_db.countObjects().get());

    final SharedLibraryBean share1 = IkanowV1SyncService_LibraryJars.getLibraryBeanFromV1Share(v1_share_1);

    assertEquals(0L, (long) library_db.countObjects().get());
    library_db.storeObjects(Arrays.asList(share1)).get();
    assertEquals(1L, (long) library_db.countObjects().get());

    // No error - create
    {
        final ManagementFuture<?> test_1 = FutureUtils.createManagementFuture(
                CompletableFuture.completedFuture(Unit.unit()),
                CompletableFuture.completedFuture(Arrays.asList(ErrorUtils.buildSuccessMessage("", "", "", ""))) // (single non error)                                       
        );

        final CompletableFuture<Boolean> res = IkanowV1SyncService_LibraryJars.updateV1ShareErrorStatus_top(
                "555d44e3347d336b3e8c4cbe", test_1, library_db, v1_share_db, true);

        assertEquals(false, res.get());

        ObjectNode unchanged = (ObjectNode) v1_share_db.getRawService()
                .getObjectById(new ObjectId("555d44e3347d336b3e8c4cbe")).get().get();

        assertEquals(v1_share_1.without("_id").toString(), unchanged.without("_id").toString());
    }

    // DB call throws exception
    {
        final CompletableFuture<?> error_out = new CompletableFuture<>();
        error_out.completeExceptionally(new RuntimeException("test"));

        final ManagementFuture<?> test_1 = FutureUtils.createManagementFuture(error_out);

        final CompletableFuture<Boolean> res = IkanowV1SyncService_LibraryJars.updateV1ShareErrorStatus_top(
                "555d44e3347d336b3e8c4cbe", test_1, library_db, v1_share_db, true);

        assertEquals(true, res.get());

        JsonNode changed = v1_share_db.getRawService().getObjectById(new ObjectId("555d44e3347d336b3e8c4cbe"))
                .get().get();

        assertTrue(changed.get("description").asText()
                .contains("] (unknown) ((unknown)): ERROR: [java.lang.RuntimeException: test"));
        // This shouldn't yet pe present
        assertFalse("Description error time travels: " + changed.get("description").asText(),
                changed.get("description").asText().contains("] (test) (unknown): ERROR: test"));
    }

    // db call throws exception, object doesn't exist (code coverage!)
    {
        final CompletableFuture<?> error_out = new CompletableFuture<>();
        error_out.completeExceptionally(new RuntimeException("test"));

        final ManagementFuture<?> test_1 = FutureUtils.createManagementFuture(error_out);

        final CompletableFuture<Boolean> res = IkanowV1SyncService_LibraryJars.updateV1ShareErrorStatus_top(
                "555d44e3347d336b3e8c4cbf", test_1, library_db, v1_share_db, true);

        assertEquals(false, res.get());
    }

    // User errors (+update not create)
    {
        final ManagementFuture<?> test_1 = FutureUtils.createManagementFuture(
                CompletableFuture.completedFuture(Unit.unit()), CompletableFuture.completedFuture(
                        Arrays.asList(ErrorUtils.buildErrorMessage("test", "test", "test", "test"))) // (single non error)                                       
        );

        final CompletableFuture<Boolean> res = IkanowV1SyncService_LibraryJars.updateV1ShareErrorStatus_top(
                "555d44e3347d336b3e8c4cbe", test_1, library_db, v1_share_db, false);

        assertEquals(true, res.get());

        JsonNode changed = v1_share_db.getRawService().getObjectById(new ObjectId("555d44e3347d336b3e8c4cbe"))
                .get().get();

        SharedLibraryBean v2_version = library_db.getObjectById("v1_555d44e3347d336b3e8c4cbe").get().get();
        assertTrue("v2 lib bean needed updating: " + v2_version.modified(),
                new Date().getTime() - v2_version.modified().getTime() < 5000L);

        // Still has the old error
        assertTrue("Description missing errors: " + changed.get("description").asText(),
                changed.get("description").asText()
                        .contains("] (unknown) ((unknown)): ERROR: [java.lang.RuntimeException: test"));
        // Now has the new error
        assertTrue("Description missing errors: " + changed.get("description").asText(),
                changed.get("description").asText().contains("] test (test): ERROR: test"));
    }

}

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

@Override
protected InputStream replaceLink(final InputStream toBeChanged, final String linkName,
        final InputStream replacement) throws IOException {

    final ObjectNode toBeChangedNode = (ObjectNode) mapper.readTree(toBeChanged);
    final ObjectNode replacementNode = (ObjectNode) mapper.readTree(replacement);

    if (toBeChangedNode.get(linkName + Constants.get(ConstantKey.JSON_NAVIGATION_SUFFIX)) == null) {
        throw new NotFoundException();
    }//from  www  .j  av  a  2 s .co m

    toBeChangedNode.set(linkName, replacementNode.get(Constants.get(ConstantKey.JSON_VALUE_NAME)));

    final JsonNode next = replacementNode.get(linkName + Constants.get(ConstantKey.JSON_NEXTLINK_NAME));
    if (next != null) {
        toBeChangedNode.set(linkName + Constants.get(ConstantKey.JSON_NEXTLINK_SUFFIX), next);
    }

    return IOUtils.toInputStream(toBeChangedNode.toString(), Constants.ENCODING);
}

From source file:org.apache.streams.jackson.TypeConverterProcessor.java

@Override
public List<StreamsDatum> process(StreamsDatum entry) {
    List<StreamsDatum> result = Lists.newLinkedList();
    Object inDoc = entry.getDocument();
    ObjectNode node = null;
    if (inClass == String.class || inDoc instanceof String) {
        try {//from w  w  w. jav a 2s  .co  m
            node = this.mapper.readValue((String) entry.getDocument(), ObjectNode.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {
        node = this.mapper.convertValue(inDoc, ObjectNode.class);
    }

    if (node != null) {
        Object outDoc;
        try {
            if (outClass == String.class)
                outDoc = this.mapper.writeValueAsString(node);
            else
                outDoc = this.mapper.convertValue(node, outClass);

            StreamsDatum outDatum = new StreamsDatum(outDoc, entry.getId(), entry.getTimestamp(),
                    entry.getSequenceid());
            outDatum.setMetadata(entry.getMetadata());
            result.add(outDatum);
        } catch (Throwable e) {
            LOGGER.warn(e.getMessage());
            LOGGER.warn(node.toString());
        }
    }

    return result;
}

From source file:io.gs2.stamina.Gs2StaminaClient.java

/**
 * ???<br>//from  www  .j  a  v  a2 s .  co m
 * <br>
 * - : 5<br>
 * <br>
 *
 * @param request 
        
 * @return ?
        
 */

public ChangeStaminaResult changeStamina(ChangeStaminaRequest request) {

    ObjectNode body = JsonNodeFactory.instance.objectNode().put("variation", request.getVariation())
            .put("maxValue", request.getMaxValue());
    if (request.getOverflow() != null)
        body.put("overflow", request.getOverflow());

    HttpPost post = createHttpPost(
            Gs2Constant.ENDPOINT_HOST + "/staminaPool/"
                    + (request.getStaminaPoolName() == null || request.getStaminaPoolName().equals("") ? "null"
                            : request.getStaminaPoolName())
                    + "/stamina",
            credential, ENDPOINT, ChangeStaminaRequest.Constant.MODULE, ChangeStaminaRequest.Constant.FUNCTION,
            body.toString());
    if (request.getRequestId() != null) {
        post.setHeader("X-GS2-REQUEST-ID", request.getRequestId());
    }

    post.setHeader("X-GS2-ACCESS-TOKEN", request.getAccessToken());

    return doRequest(post, ChangeStaminaResult.class);

}