List of usage examples for com.fasterxml.jackson.databind.node ObjectNode toString
public String toString()
From source file:org.flowable.app.rest.service.BaseSpringRestTestCase.java
protected void assertResultsPresentInPostDataResponseWithStatusCheck(String url, ObjectNode body, int expectedStatusCode, String... expectedResourceIds) throws JsonProcessingException, IOException { int numberOfResultsExpected = 0; if (expectedResourceIds != null) { numberOfResultsExpected = expectedResourceIds.length; }//from www. j a v a 2s . c o m // Do the actual call HttpPost post = new HttpPost(SERVER_URL_PREFIX + url); post.setEntity(new StringEntity(body.toString())); CloseableHttpResponse response = executeRequest(post, expectedStatusCode); if (expectedStatusCode == HttpStatus.SC_OK) { // Check status and size JsonNode rootNode = objectMapper.readTree(response.getEntity().getContent()); JsonNode dataNode = rootNode.get("data"); assertEquals(numberOfResultsExpected, dataNode.size()); // Check presence of ID's if (expectedResourceIds != null) { List<String> toBeFound = new ArrayList<>(Arrays.asList(expectedResourceIds)); Iterator<JsonNode> it = dataNode.iterator(); while (it.hasNext()) { String id = it.next().get("id").textValue(); toBeFound.remove(id); } assertTrue( "Not all entries have been found in result, missing: " + StringUtils.join(toBeFound, ", "), toBeFound.isEmpty()); } } closeResponse(response); }
From source file:org.springframework.social.facebook.api.impl.FeedTemplate.java
private <T> T deserializePost(String postType, Class<T> type, ObjectNode node) { try {// w w w.jav a2s . c o m if (postType == null) { postType = determinePostType(node); } // Must have separate postType field for polymorphic deserialization. If we key off of the "type" field, then it will // be null when trying to deserialize the type property. node.put("postType", postType); // used for polymorphic deserialization node.put("type", postType); // used to set Post's type property return objectMapper.reader(type).readValue(node.toString()); // TODO: EXTREMELY HACKY--TEMPORARY UNTIL I FIGURE OUT HOW JACKSON 2 DOES THIS } catch (IOException shouldntHappen) { throw new UncategorizedApiException("facebook", "Error deserializing " + postType + " post", shouldntHappen); } }
From source file:io.gs2.notification.Gs2NotificationClient.java
/** * ????<br>/* w w w. j av a2s . c om*/ * <br> * * @param request * @return ? */ public CreateSubscribeResult createSubscribe(CreateSubscribeRequest request) { ObjectNode body = JsonNodeFactory.instance.objectNode().put("type", request.getType()).put("endpoint", request.getEndpoint()); HttpPost post = createHttpPost(Gs2Constant.ENDPOINT_HOST + "/notification/" + (request.getNotificationName() == null || request.getNotificationName().equals("") ? "null" : request.getNotificationName()) + "/subscribe", credential, ENDPOINT, CreateSubscribeRequest.Constant.MODULE, CreateSubscribeRequest.Constant.FUNCTION, body.toString()); if (request.getRequestId() != null) { post.setHeader("X-GS2-REQUEST-ID", request.getRequestId()); } return doRequest(post, CreateSubscribeResult.class); }
From source file:com.stratio.ingestion.sink.mongodb.MongoSinkTest.java
@Test public void basicTest() throws Exception { Transaction tx = channel.getTransaction(); tx.begin();// w ww .j av a 2 s . c om 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"); // Overwrites the value defined in JSON body headers.put("myInt64", "64"); headers.put("myBoolean", "true"); headers.put("myDouble", "1.0"); headers.put("myNull", null); Date myDate = new Date(); headers.put("myDate", Long.toString(myDate.getTime())); headers.put("myString2", "baz"); Event event = EventBuilder.withBody(jsonBody.toString().getBytes(Charsets.UTF_8), headers); channel.put(event); tx.commit(); tx.close(); mongoSink.process(); DBObject result = fongo.getDB("test").getCollection("test").findOne(); // System.out.println(result.toString()); assertThat(result).isNotNull(); assertThat(result.get("myString")).isEqualTo("bar"); assertThat(result.get("myInt32")).isEqualTo(32); assertThat(result.get("myInt32")).isInstanceOf(Integer.class); assertThat(result.get("myInt64")).isEqualTo(64L); assertThat(result.get("myInt64")).isInstanceOf(Long.class); assertThat(result.get("myBoolean")).isEqualTo(true); assertThat(result.get("myDouble")).isEqualTo(1.0); assertThat(result.get("myNull")).isNull(); assertThat(result.get("myDate")).isEqualTo(myDate); assertThat(result.get("myString2")).isNull(); assertThat(result.get("myStringMapped")).isEqualTo("baz"); }
From source file:com.glaf.dts.web.rest.MxQueryResource.java
@GET @POST// ww w . j ava2s. com @Path("/list") @ResponseBody @Produces({ MediaType.APPLICATION_OCTET_STREAM }) public byte[] list(@Context HttpServletRequest request) { Map<String, Object> params = RequestUtils.getParameterMap(request); QueryDefinitionQuery query = new QueryDefinitionQuery(); Tools.populate(query, params); List<QueryDefinition> queries = queryDefinitionService.list(query); ObjectNode responseJSON = new ObjectMapper().createObjectNode(); ArrayNode arrayJSON = new ObjectMapper().createArrayNode(); for (QueryDefinition q : queries) { ObjectNode json = q.toObjectNode(); arrayJSON.add(json); } responseJSON.set("data", arrayJSON); responseJSON.set("rows", arrayJSON); responseJSON.put("total", queries.size()); responseJSON.put("totalCount", queries.size()); responseJSON.put("totalRecords", queries.size()); try { return responseJSON.toString().getBytes("UTF-8"); } catch (IOException e) { return responseJSON.toString().getBytes(); } }
From source file:com.ikanow.aleph2.harvest.logstash.utils.TestLogstashConfigUtils.java
@Test public void test_logstashConfigUtils() throws IOException { LogstashHarvesterConfigBean globals = BeanTemplateUtils.build(LogstashHarvesterConfigBean.class).done() .get(); //(all defaults) // 1) Errored sources - things that break the formatting StringBuffer errors = new StringBuffer(); String testName;//from w w w . jav a 2 s. c o m // 1.1) {} mismatch 1 //a errors.setLength(0); testName = "error_1_1a"; if (null != LogstashConfigUtils.parseLogstashConfig(getTestFile(testName), errors)) { fail("**** FAIL " + testName); } else if (!errors.toString().startsWith("{} Mismatch (})")) { fail("**** FAIL " + testName + ": " + errors.toString()); } //b errors.setLength(0); testName = "error_1_1b"; if (null != LogstashConfigUtils.parseLogstashConfig(getTestFile(testName), errors)) { fail("**** FAIL " + testName); } else if (!errors.toString().startsWith("{} Mismatch (})")) { fail("**** FAIL " + testName + ": " + errors.toString()); } //c errors.setLength(0); testName = "error_1_1c"; if (null != LogstashConfigUtils.parseLogstashConfig(getTestFile(testName), errors)) { fail("**** FAIL " + testName); } else if (!errors.toString().startsWith("{} Mismatch (})")) { fail("**** FAIL " + testName + ": " + errors.toString()); } // 1.2) {} mismatch 2 //a errors.setLength(0); testName = "error_1_2a"; if (null != LogstashConfigUtils.parseLogstashConfig(getTestFile(testName), errors)) { fail("**** FAIL " + testName); } else if (!errors.toString().startsWith("{} Mismatch ({)")) { fail("**** FAIL " + testName + ": " + errors.toString()); } // 1.3) multiple input/filter blocks // 1.3a) input errors.setLength(0); testName = "error_1_3a"; if (null != LogstashConfigUtils.parseLogstashConfig(getTestFile(testName), errors)) { fail("**** FAIL " + testName); } else if (!errors.toString().equals("Multiple input or filter blocks: input")) { fail("**** FAIL " + testName + ": " + errors.toString()); } // 1.3b) filter errors.setLength(0); testName = "error_1_3b"; if (null != LogstashConfigUtils.parseLogstashConfig(getTestFile(testName), errors)) { fail("**** FAIL " + testName); } else if (!errors.toString().equals("Multiple input or filter blocks: filter")) { fail("**** FAIL " + testName + ": " + errors.toString()); } // 1.4) unrecognized blocks // a output - special case errors.setLength(0); testName = "error_1_4a"; if (null != LogstashConfigUtils.parseLogstashConfig(getTestFile(testName), errors)) { fail("**** FAIL " + testName); } else if (!errors.toString() .equals("Not allowed output blocks - these are appended automatically by the logstash harvester")) { fail("**** FAIL " + testName + ": " + errors.toString()); } // b errors.setLength(0); testName = "error_1_4b"; if (null != LogstashConfigUtils.parseLogstashConfig(getTestFile(testName), errors)) { fail("**** FAIL " + testName); } else if (!errors.toString().equals("Unrecognized processing block: something_random")) { fail("**** FAIL " + testName + ": " + errors.toString()); } // 1.5) fields/sub-elements that are not permitted // a ... sincedb_path errors.setLength(0); testName = "error_1_5a"; if (null != LogstashConfigUtils.parseLogstashConfig(getTestFile(testName), errors)) { fail("**** FAIL " + testName); } else if (!errors.toString().equals("Not allowed sincedb_path in input.* block")) { fail("**** FAIL " + testName + ": " + errors.toString()); } // b ... filter as sub-path of input errors.setLength(0); testName = "error_1_5b"; if (null != LogstashConfigUtils.parseLogstashConfig(getTestFile(testName), errors)) { fail("**** FAIL " + testName); } else if (!errors.toString().equals("Not allowed sub-elements of input called 'filter' (1)")) { fail("**** FAIL " + testName + ": " + errors.toString()); } // c ... filter as sub-path of sub-element of input errors.setLength(0); testName = "error_1_5c"; if (null != LogstashConfigUtils.parseLogstashConfig(getTestFile(testName), errors)) { fail("**** FAIL " + testName); } else if (!errors.toString().equals("Not allowed sub-elements of input called 'filter' (2)")) { fail("**** FAIL " + testName + ": " + errors.toString()); } // 2) Valid formatted source ObjectNode retVal; String output; String inputName; // (for re-using config files across text) //2.1) errors.setLength(0); testName = "success_2_1"; if (null == (retVal = LogstashConfigUtils.parseLogstashConfig(getTestFile(testName), errors))) { fail("**** FAIL " + testName + ": " + errors.toString()); } else if (!retVal.toString().equals( "{ \"input\" : { \"file\" : [ { \"path\" : { } , \"start_position\" : { } , \"type\" : { } , \"codec.multiline\" : { }}]} , \"filter\" : { \"csv\" : [ { \"columns\" : { }}] , \"drop\" : [ { }] , \"mutate\" : [ { \"convert\" : { }} , { \"add_fields\" : { }} , { \"rename\" : { }}] , \"date\" : [ { \"timezone\" : { } , \"match\" : { }}] , \"geoip\" : [ { \"source\" : { } , \"fields\" : { }}]}}" .replace(" ", ""))) { fail("**** FAIL " + testName + ": " + retVal.toString()); } //System.out.println("(val="+retVal+")"); // 2.2 errors.setLength(0); testName = "success_2_2"; if (null == (retVal = LogstashConfigUtils.parseLogstashConfig(getTestFile(testName), errors))) { fail("**** FAIL " + testName + ": " + errors.toString()); } if (null == JsonUtils.getProperty("filter.geoip.fields", retVal)) { fail("**** FAIL " + testName + ": " + retVal); } //System.out.println(retVal); //2.3) - check that the sincedb is added correctly, plus the sourceKey manipulation // (USE success_2_1 for this) errors.setLength(0); testName = "inputs_2_3"; inputName = "success_2_3"; if (null == (output = LogstashConfigUtils.validateLogstashInput(globals, testName, getTestFile(inputName), errors, true))) { fail("**** FAIL " + testName + ": errored: " + errors); } else { String outputToTest = output.replaceAll("[\r\n]", "").replaceAll("\\s+", " "); String testAgainst = "input { file { sincedb_path => \"_XXX_DOTSINCEDB_XXX_\" path => \"/root/odin-poc-data/proxy_logs/may_known_cnc.csv\" start_position => beginning type => \"proxy_logs\" codec => multiline { pattern => \"^%{YEAR}-%{MONTHNUM}-%{MONTHDAY}%{DATA:summary}\" negate => true what => \"previous\" } add_field => [ \"[@metadata][sourceKey]\", \"inputs_2_3\"] }}filter { if [@metadata][sourceKey] == \"inputs_2_3\" { if [type] == \"proxy_logs\" { csv { columns => [\"Device_Name\",\"SimpleDate\",\"Event_#Date\",\"Source_IP\",\"Source_Port\",\"Destination_IP\",\"Destination_Port\",\"Protocol\",\"Vendor_Alert\",\"MSS_Action\",\"Logging_Device_IP\",\"Application\",\"Bytes_Received\",\"Bytes_Sent\",\"Dest._Country\",\"Message\",\"Message_Type\",\"MSS_Log_Source_IP\",\"MSS_Log_Source_Type\",\"MSS_Log_Source_UUID\",\"network_protocol_id\",\"OS_Type\",\"PIX_Main-Code\",\"PIX_Sub-Code\",\"Port\",\"Product_ID\",\"Product\",\"Rule\",\"Rule_Identifier\",\"Sensor_Name\",\"Class\",\"Translate_Destination_IP\",\"Translate_Destination_Port\",\"Translate_Source_IP\"] } if [Device_Name] == \"Device Name\" { drop {} } mutate { convert => [ \"Bytes_Received\", \"integer\" ] convert => [ \"Bytes_Sent\", \"integer\" ] } date { timezone => \"Europe/London\" match => [ \"Event_Date\" , \"yyyy-MM-dd'T'HH:mm:ss\" ] } geoip { source => \"Destination_IP\" fields => [\"timezone\",\"location\",\"latitude\",\"longitude\"] } } mutate { update => [ \"[@metadata][sourceKey]\", \"inputs_2_3\"] } }}"; testAgainst = testAgainst.replaceAll("[\n\r]", "\\\\n").replaceAll("\\s+", " "); assertEquals(testAgainst, outputToTest); } // 3) Valid formatted source, access to restricted types // 3.1) input // a) restricted - admin // (USE success_2_1 for this) errors.setLength(0); testName = "inputs_3_1a"; inputName = "success_2_1"; if (null != (output = LogstashConfigUtils.validateLogstashInput(globals, testName, getTestFile(inputName), errors, false))) { fail("**** FAIL " + testName + ": Should have errored: " + output); } else if (!errors.toString() .startsWith("Security error, non-admin not allowed input type file, allowed options: ")) { fail("**** FAIL " + testName + ": " + errors.toString()); } // b) restricted - non admin // (USE success_2_1 for this) errors.setLength(0); testName = "inputs_3_1b"; inputName = "success_2_1"; if (null == (output = LogstashConfigUtils.validateLogstashInput(globals, testName, getTestFile(inputName), errors, true))) { fail("**** FAIL " + testName + ": " + errors.toString()); } // c) unrestricted - non admin errors.setLength(0); testName = "inputs_3_1c"; inputName = "inputs_3_1c"; if (null == (output = LogstashConfigUtils.validateLogstashInput(globals, testName, getTestFile(inputName), errors, true))) { fail("**** FAIL " + testName + ": " + errors.toString()); } //System.out.println("(val="+output+")"); // d) no input at all errors.setLength(0); testName = "inputs_3_1d"; inputName = "inputs_3_1d"; if (null != (output = LogstashConfigUtils.validateLogstashInput(globals, testName, getTestFile(inputName), errors, false))) { fail("**** FAIL " + testName + ": Should have errored: " + output); } else if (!errors.toString().startsWith( "Invalid input format, should be 'input { INPUT_TYPE { ... } }' (only one INPUT_TYPE) and also contain a filter, no \"s around them.")) { fail("**** FAIL " + testName + ": " + errors.toString()); } // 3.2) filter // a) restricted - admin errors.setLength(0); testName = "filters_3_2a"; inputName = "filters_3_2a"; if (null != (output = LogstashConfigUtils.validateLogstashInput(globals, testName, getTestFile(inputName), errors, false))) { fail("**** FAIL " + testName + ": Should have errored: " + output); } else if (!errors.toString() .startsWith("Security error, non-admin not allowed filter type elasticsearch, allowed options: ")) { fail("**** FAIL " + testName + ": " + errors.toString()); } //System.out.println("(err="+errors.toString()+")"); // b) restricted - non admin // (USE filters_3_2a for this) errors.setLength(0); testName = "filters_3_2a"; inputName = "filters_3_2a"; if (null == (output = LogstashConfigUtils.validateLogstashInput(globals, testName, getTestFile(inputName), errors, true))) { fail("**** FAIL " + testName + ": " + errors.toString()); } //System.out.println("(val="+output+")"); // c) unrestricted - non admin // (implicitly tested via 3.1bc) // d) no filter at all errors.setLength(0); testName = "filters_3_2d"; inputName = "filters_3_2d"; if (null != (output = LogstashConfigUtils.validateLogstashInput(globals, testName, getTestFile(inputName), errors, false))) { fail("**** FAIL " + testName + ": Should have errored: " + output); } else if (!errors.toString().startsWith( "Invalid input format, should be 'input { INPUT_TYPE { ... } }' (only one INPUT_TYPE) and also contain a filter, no \"s around them.")) { fail("**** FAIL " + testName + ": " + errors.toString()); } // e) filter w/ regex that has { } in it // (USE filters_3_2e for this) errors.setLength(0); testName = "filters_3_2e"; inputName = "filters_3_2e"; if (null == (output = LogstashConfigUtils.validateLogstashInput(globals, testName, getTestFile(inputName), errors, true))) { fail("**** FAIL " + testName + ": " + errors.toString()); } }
From source file:io.gs2.notification.Gs2NotificationClient.java
/** * ???<br>/* w w w . ja v a2s. co m*/ * <br> * * @param request * @return ? */ public UpdateNotificationResult updateNotification(UpdateNotificationRequest request) { ObjectNode body = JsonNodeFactory.instance.objectNode(); if (request.getDescription() != null) body.put("description", request.getDescription()); HttpPut put = createHttpPut(Gs2Constant.ENDPOINT_HOST + "/notification/" + (request.getNotificationName() == null || request.getNotificationName().equals("") ? "null" : request.getNotificationName()) + "", credential, ENDPOINT, UpdateNotificationRequest.Constant.MODULE, UpdateNotificationRequest.Constant.FUNCTION, body.toString()); if (request.getRequestId() != null) { put.setHeader("X-GS2-REQUEST-ID", request.getRequestId()); } return doRequest(put, UpdateNotificationResult.class); }
From source file:org.agorava.facebook.impl.FeedServiceImpl.java
private <T> T deserializePost(String postType, Class<T> type, ObjectNode node) { try {/* w ww . j av a2 s . c o m*/ if (postType == null) { postType = determinePostType(node); } // Must have separate postType field for polymorphic deserialization. If we key off of the "type" field, // then it will // be null when trying to deserialize the type property. node.put("postType", postType); // used for polymorphic deserialization node.put("type", postType); // used to set Post's type property return objectMapper.reader(type).readValue(node.toString()); // TODO: EXTREMELY HACKY--TEMPORARY UNTIL I FIGURE // OUT HOW JACKSON 2 DOES THIS } catch (IOException shouldntHappen) { throw new AgoravaException("Error deserializing " + postType + " post", shouldntHappen); } }
From source file:controllers.CommentController.java
public Result deleteComment(Long serviceId, Long versionId, Long commentId) { System.out.println("DELETE COMMENT"); ObjectNode response = Json.newObject(); try {//w ww . j av a 2 s . co m deleteCommentById(serviceId, versionId, commentId); response.put("success", true); response.put("total_comment", commentRepository.countComments(serviceId, versionId)); } catch (PersistenceException pe) { pe.printStackTrace(); System.out.println("Comment not deleted"); return badRequest(failJson("Comment not deleted")); } return ok(response.toString()); }
From source file:org.activiti.app.service.editor.ModelServiceImpl.java
public ModelRepresentation importNewVersion(String modelId, String fileName, InputStream modelStream) { Model processModel = getModel(modelId); User currentUser = SecurityUtils.getCurrentUserObject(); if (fileName != null && (fileName.endsWith(".bpmn") || fileName.endsWith(".bpmn20.xml"))) { try {/*from www .ja va 2 s . c o m*/ XMLInputFactory xif = XmlUtil.createSafeXmlInputFactory(); InputStreamReader xmlIn = new InputStreamReader(modelStream, "UTF-8"); XMLStreamReader xtr = xif.createXMLStreamReader(xmlIn); BpmnModel bpmnModel = bpmnXMLConverter.convertToBpmnModel(xtr); if (CollectionUtils.isEmpty(bpmnModel.getProcesses())) { throw new BadRequestException("No process found in definition " + fileName); } if (bpmnModel.getLocationMap().size() == 0) { throw new BadRequestException( "No required BPMN DI information found in definition " + fileName); } ObjectNode modelNode = bpmnJsonConverter.convertToJson(bpmnModel); AbstractModel savedModel = saveModel(modelId, processModel.getName(), processModel.getKey(), processModel.getDescription(), modelNode.toString(), true, "Version import via REST service", currentUser); return new ModelRepresentation(savedModel); } catch (BadRequestException e) { throw e; } catch (Exception e) { throw new BadRequestException( "Import failed for " + fileName + ", error message " + e.getMessage()); } } else { throw new BadRequestException( "Invalid file name, only .bpmn and .bpmn20.xml files are supported not " + fileName); } }