List of usage examples for com.fasterxml.jackson.databind JsonNode toString
public abstract String toString();
From source file:com.redhat.lightblue.eval.FieldProjectorTest.java
@Test public void project_field_with_recursion() throws Exception { Projection p = EvalTestContext/*from w ww . j av a2 s . com*/ .projectionFromJson("[{'field':'field2'},{'field':'field6.*','recursive':true}]"); Projector projector = Projector.getInstance(p, md); JsonNode expectedNode = JsonUtils.json( "{'field2':'value2','field6':{'nf1':'nvalue1','nf2':'nvalue2','nf3':4,'nf4':false,'nf5':[5,10,15,20],'nf6':['one','two','three','four'],'nf7':{'nnf1':'nnvalue1','nnf2':2},'nf8':['four','three','two','one'],'nf9':[20,15,10,5],'nf10':[20.1,15.2,10.3,5.4],'nf11':null}}" .replace('\'', '\"')); JsonDoc pdoc = projector.project(jsonDoc, JSON_NODE_FACTORY); Assert.assertEquals(expectedNode.toString(), pdoc.toString()); }
From source file:com.redhat.lightblue.eval.FieldProjectorTest.java
@Test public void one_$parent_project_field_with_recursion() throws Exception { Projection p = EvalTestContext.projectionFromJson( "[{'field':'field7.$parent.field2'},{'field':'field7.$parent.field6.*','recursive':true}]"); Projector projector = Projector.getInstance(p, md); JsonNode expectedNode = JsonUtils.json( "{'field2':'value2','field6':{'nf1':'nvalue1','nf2':'nvalue2','nf3':4,'nf4':false,'nf5':[5,10,15,20],'nf6':['one','two','three','four'],'nf7':{'nnf1':'nnvalue1','nnf2':2},'nf8':['four','three','two','one'],'nf9':[20,15,10,5],'nf10':[20.1,15.2,10.3,5.4],'nf11':null}}" .replace('\'', '\"')); JsonDoc pdoc = projector.project(jsonDoc, JSON_NODE_FACTORY); Assert.assertEquals(expectedNode.toString(), pdoc.toString()); }
From source file:com.redhat.lightblue.eval.FieldProjectorTest.java
@Test public void two_$parent_project_field_with_recursion() throws Exception { Projection p = EvalTestContext.projectionFromJson( "[{'field':'field6.nf7.$parent.$parent.field2'},{'field':'field6.nf7.$parent.$parent.field6.*','recursive':true}]"); Projector projector = Projector.getInstance(p, md); JsonNode expectedNode = JsonUtils.json( "{'field2':'value2','field6':{'nf1':'nvalue1','nf2':'nvalue2','nf3':4,'nf4':false,'nf5':[5,10,15,20],'nf6':['one','two','three','four'],'nf7':{'nnf1':'nnvalue1','nnf2':2},'nf8':['four','three','two','one'],'nf9':[20,15,10,5],'nf10':[20.1,15.2,10.3,5.4],'nf11':null}}" .replace('\'', '\"')); JsonDoc pdoc = projector.project(jsonDoc, JSON_NODE_FACTORY); Assert.assertEquals(expectedNode.toString(), pdoc.toString()); }
From source file:com.redhat.lightblue.crud.ldap.ITCaseLdapCRUDControllerTest.java
@Test public void series2_phase2_Department_FindWithRoles() throws Exception { FindRequest findRequest = createRequest_FromResource(FindRequest.class, "./crud/find/department-find-single.json"); findRequest.setClientId(new FakeClientIdentification("fakeUser", "admin")); Response response = getLightblueFactory().getMediator().find(findRequest); assertNotNull(response);// w w w . ja v a2 s.com assertNoErrors(response); assertNoDataErrors(response); assertEquals(1, response.getMatchCount()); JsonNode entityData = response.getEntityData(); assertNotNull(entityData); JSONAssert.assertEquals( "[{\"member#\":2,\"member\":[\"cn=John Doe," + BASEDB_USERS + "\",\"cn=Jane Doe," + BASEDB_USERS + "\"],\"cn\":\"Marketing\",\"description\":\"Department devoted to Marketing\"}]", entityData.toString(), true); }
From source file:org.pentaho.metaverse.api.MetaverseLogicalIdGeneratorTest.java
@Test public void testGenerateLogicalId_escapedCharacters() throws Exception { when(node.getProperty("name")).thenReturn("john\ndoe"); when(node.getProperty("age")).thenReturn(30); when(node.getProperty("address")).thenReturn("1234 Pentaho Way\\Orlando, FL 12345"); Calendar cal = GregorianCalendar.getInstance(); cal.set(1976, Calendar.JANUARY, 1, 0, 0, 0); when(node.getProperty("birthday")).thenReturn(cal.getTime()); when(node.getPropertyKeys()).thenReturn(new HashSet<String>() { {//from w ww .j av a 2 s . c om add("address"); add("age"); add("birthday"); add("name"); } }); // make sure there is no logicalid on the node initially assertNull(node.getProperty(DictionaryConst.PROPERTY_LOGICAL_ID)); String logicalId = idGenerator.generateId(node); // it should come out in alphabetical order by key assertEquals( "{\"address\":\"1234 Pentaho Way\\\\Orlando, FL 12345\",\"age\":\"30\",\"birthday\":\"1976-01-01 00:00:00\",\"name\":\"john\\ndoe\"}", logicalId); // make sure the json string is parseable JsonNode jsonObject = objectMapper.readTree(logicalId); JsonNode address = jsonObject.get("address"); assertEquals("1234 Pentaho Way\\Orlando, FL 12345", address.textValue()); JsonNode name = jsonObject.get("name"); assertEquals("john\ndoe", name.textValue()); System.out.println(jsonObject.toString()); // make sure a call was made to add the logical id as a property verify(node).setProperty(DictionaryConst.PROPERTY_LOGICAL_ID, logicalId); }
From source file:org.apache.solr.kelvin.testcases.SimpleTestCase.java
private void readConditions(JsonNode config, String configName) throws Exception { if (config.has(configName)) { for (JsonNode condition : (ArrayNode) ConfigurableLoader.assureArray(config.get(configName))) { try { conditonList.add(SingletonConditionRegistry.instantiate(condition)); } catch (Exception e) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "Error in config " + config.toString()); }// w w w. j a v a 2 s . co m } if (conditonList.isEmpty()) throw new Exception("missing conditions in simple test case"); } }
From source file:graphene.dao.es.impl.CombinedDAOESImpl.java
@Override public G_SearchResults search(final G_EntityQuery pq) { // TODO: Use a helper class final G_SearchResults results = G_SearchResults.newBuilder().setTotal(0) .setResults(new ArrayList<G_SearchResult>()).build(); final List<G_SearchResult> resultsList = new ArrayList<G_SearchResult>(); JestResult jestResult = new JestResult(null); try {//from w ww .j a va 2 s . c om final io.searchbox.core.Search.Builder action = buildSearchAction(pq); JestClient jestClient = c.getClient(); synchronized (jestClient) { jestResult = jestClient.execute(action.build()); } } catch (final DataAccessException e) { e.printStackTrace(); } catch (final Exception e) { e.printStackTrace(); } // logger.debug(jestResult.getJsonString()); JsonNode rootNode; long totalNumberOfPossibleResults = 0l; try { rootNode = mapper.readValue(jestResult.getJsonString(), JsonNode.class); if ((rootNode != null) && (rootNode.get("hits") != null) && (rootNode.get("hits").get("total") != null)) { totalNumberOfPossibleResults = rootNode.get("hits").get("total").asLong(); logger.debug("Found " + totalNumberOfPossibleResults + " hits in hitparent!"); final ArrayNode actualListOfHits = getListOfHitsFromResult(jestResult); for (int i = 0; i < actualListOfHits.size(); i++) { final JsonNode currentHit = actualListOfHits.get(i); if (ValidationUtils.isValid(currentHit)) { final G_SearchResult result = db.buildSearchResultFromDocument(i, currentHit, pq); if (result == null) { logger.error("could not build search result from hit " + currentHit.toString()); } CollectionUtils.addIgnoreNull(resultsList, result); } else { logger.error("Invalid search result at index " + i + " for query " + pq.toString()); } } } } catch (final IOException e) { e.printStackTrace(); } results.setResults(resultsList); results.setTotal(totalNumberOfPossibleResults); return results; }
From source file:com.redhat.lightblue.crud.ldap.ITCaseLdapCRUDController_WithProperties_Test.java
@Test public void test2FindCustomerWithProperties() throws Exception { Response response = lightblueFactory.getMediator() .find(createRequest_FromResource(FindRequest.class, "./crud/find/customer-find-single.json")); assertNotNull(response);/*from www.j ava 2 s. c o m*/ assertNoErrors(response); assertNoDataErrors(response); assertEquals(1, response.getMatchCount()); JsonNode entityData = response.getEntityData(); assertNotNull(entityData); JSONAssert.assertEquals( "[{\"id\":\"uid=frodo.baggins," + BASEDB_CUSTOMERS + "\"," + "\"customerId\":\"frodo.baggins\"," + "\"firstName\":\"Frodo\"," + "\"lastName\":\"Baggins\"," + "\"cn\":\"Frodo Baggins\"," + "\"interfaces#\":4," + "\"interfaces\":[\"top\",\"person\",\"organizationalPerson\",\"inetOrgPerson\"]}]", entityData.toString(), true); }
From source file:com.amazonaws.services.iot.client.shadow.AwsIotDeviceCommandManager.java
private void appendCommandId(AWSIotMessage message, String commandId) throws AWSIotException { String payload = message.getStringPayload(); if (payload == null) { payload = "{}"; }//from w ww. j a v a 2 s . co m try { JsonNode jsonNode = objectMapper.readTree(payload); if (!jsonNode.isObject()) { throw new AWSIotException("Invalid Json string in payload"); } ((ObjectNode) jsonNode).put(COMMAND_ID_FIELD, commandId); message.setStringPayload(jsonNode.toString()); } catch (IOException e) { throw new AWSIotException(e); } }
From source file:io.cloudslang.content.json.actions.GetValueFromObject.java
/** * This operation accepts an object in the JavaScript Object Notation format (JSON) and returns a value for the specified key. * * @param object The string representation of a JSON object. * Objects in JSON are a collection of name value pairs, separated by a colon and surrounded with curly brackets {}. * The name must be a string value, and the value can be a single string or any valid JSON object or array. * Examples: {"one":1, "two":2}, {"one":{"a":"a","B":"B"}, "two":"two", "three":[1,2,3.4]} * @param key The key in the object to get the value of. * Examples: city, location[0].city * @return a map containing the output of the operation. Keys present in the map are: * <p/>/*w w w . jav a 2s. c o m*/ * <br><br><b>returnResult</b> - This will contain the value for the specified key in the object. * <br><b>exception</b> - In case of success response, this result is empty. In case of failure response, * this result contains the java stack trace of the runtime exception. * <br><br><b>returnCode</b> - The returnCode of the operation: 0 for success, -1 for failure. */ @Action(name = "Get Value from Object", outputs = { @Output(OutputNames.RETURN_RESULT), @Output(OutputNames.RETURN_CODE), @Output(OutputNames.EXCEPTION) }, responses = { @Response(text = ResponseNames.SUCCESS, field = OutputNames.RETURN_CODE, value = ReturnCodes.SUCCESS, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED), @Response(text = ResponseNames.FAILURE, field = OutputNames.RETURN_CODE, value = ReturnCodes.FAILURE, matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR, isOnFail = true) }) public Map<String, String> execute(@Param(value = Constants.InputNames.OBJECT, required = true) String object, @Param(value = Constants.InputNames.KEY, required = true) String key) { Map<String, String> returnResult = new HashMap<>(); if (StringUtilities.isBlank(object)) { return populateResult(returnResult, new Exception("Empty object provided!")); } if (key == null) { return populateResult(returnResult, new Exception("Null key provided!")); } final JsonNode jsonRoot; ObjectMapper objectMapper = new ObjectMapper(); try { jsonRoot = objectMapper.readTree(object); } catch (Exception exception) { final String value = "Invalid object provided! " + exception.getMessage(); return populateResult(returnResult, value, exception); } int startIndex = 0; final JsonNode valueFromObject; try { valueFromObject = getObject(jsonRoot, key.split(ESCAPED_SLASH + "."), startIndex); } catch (Exception exception) { return populateResult(returnResult, exception); } if (valueFromObject.isValueNode()) { return populateResult(returnResult, valueFromObject.asText(), null); } else { return populateResult(returnResult, valueFromObject.toString(), null); } }