List of usage examples for com.fasterxml.jackson.databind ObjectMapper readTree
public JsonNode readTree(URL source) throws IOException, JsonProcessingException
From source file:org.opendaylight.sfc.sbrest.json.SfstExporterTest.java
private boolean testExportSfstJson(String expectedResultFile, boolean nameOnly) throws IOException { ServiceFunctionSchedulerType serviceFunctionSchedulerType; String exportedSfstString;//from w w w . j a va 2 s .co m SfstExporterFactory sfstExporterFactory = new SfstExporterFactory(); if (nameOnly) { serviceFunctionSchedulerType = this.buildServiceFunctionSchedulerTypeNameOnly(); exportedSfstString = sfstExporterFactory.getExporter().exportJsonNameOnly(serviceFunctionSchedulerType); } else { serviceFunctionSchedulerType = this.buildServiceFunctionSchedulerType(); exportedSfstString = sfstExporterFactory.getExporter().exportJson(serviceFunctionSchedulerType); } ObjectMapper objectMapper = new ObjectMapper(); JsonNode expectedSfstJson = objectMapper .readTree(this.gatherServiceFunctionSchedulerTypeJsonStringFromFile(expectedResultFile)); JsonNode exportedSfstJson = objectMapper.readTree(exportedSfstString); return expectedSfstJson.equals(exportedSfstJson); }
From source file:com.comcast.cdn.traffic_control.traffic_router.core.external.CoverageZoneTest.java
@Test public void itGetsCacheLocation() throws Exception { HttpGet httpGet = new HttpGet( "http://localhost:3333/crs/coveragezone/cachelocation?ip=100.3.3.123&deliveryServiceId=steering-target-1"); CloseableHttpResponse response = null; try {/* www. ja va2 s .co m*/ response = closeableHttpClient.execute(httpGet); String jsonString = EntityUtils.toString(response.getEntity()); ObjectMapper objectMapper = new ObjectMapper(new JsonFactory()); JsonNode jsonNode = objectMapper.readTree(jsonString); assertThat(jsonNode.get("id").asText(), equalTo("location-3")); assertThat(jsonNode.get("geolocation"), not(nullValue())); assertThat(jsonNode.get("caches").get(0).get("id").asText(), startsWith("edge-cache-03")); assertThat(jsonNode.get("caches").get(0).get("fqdn").asText(), startsWith("edge-cache-03")); assertThat(jsonNode.get("caches").get(0).get("fqdn").asText(), endsWith("thecdn.example.com")); assertThat(jsonNode.get("caches").get(0).get("port").asInt(), greaterThan(1024)); assertThat(jsonNode.get("caches").get(0).get("hashValues").get(0).asDouble(), greaterThan(1.0)); assertThat(isValidIpV4String(jsonNode.get("caches").get(0).get("ip4").asText()), equalTo(true)); assertThat(jsonNode.get("caches").get(0).get("ip6").asText(), not(equalTo(""))); assertThat(jsonNode.get("caches").get(0).has("available"), equalTo(true)); assertThat(jsonNode.has("properties"), equalTo(true)); } finally { if (response != null) response.close(); } }
From source file:com.stratio.ingestion.source.rest.url.DynamicUrlHandler.java
private JsonNode loadConfiguration(String jsonFile) { JsonNode jsonNode = null;//from w w w. ja v a 2 s. c o m if (StringUtils.isNotBlank(jsonFile)) { try { File filterFile = new File(jsonFile); if (filterFile.exists()) { ObjectMapper mapper = new ObjectMapper(); jsonNode = mapper.readTree(filterFile); } else { throw new RestSourceException("The configuration file doesn't exist"); } } catch (Exception e) { throw new RestSourceException("An error ocurred while json parsing. Verify configuration file", e); } } return jsonNode; }
From source file:de.upb.wdqa.wdvd.datamodel.oldjson.jackson.deserializers.OldJacksonSnakDeserializer.java
@Override public OldJacksonSnak deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException { OldJacksonSnak result = null;//from w w w . j a va2 s. c o m if (!p.getCurrentToken().equals(JsonToken.START_ARRAY)) { logger.warn("Token " + JsonToken.START_ARRAY + " expected"); } p.nextToken(); String type = p.getText(); p.nextToken(); // determine type if (type.equals("value")) { OldJacksonValueSnak valuesnak = new OldJacksonValueSnak(); valuesnak.setProperty("P" + p.getIntValue()); p.nextToken(); valuesnak.setDatatype(p.getText()); p.nextToken(); ObjectMapper mapper = (ObjectMapper) p.getCodec(); JsonNode root = mapper.readTree(p); Class<? extends OldJacksonValue> valueClass = getValueClass(valuesnak.getDatatype()); if (valueClass != null) { valuesnak.setDatavalue(mapper.treeToValue(root, valueClass)); } p.nextToken(); result = valuesnak; } else if (type.equals("novalue")) { result = new OldJacksonNoValueSnak(); result.setProperty("P" + p.getIntValue()); p.nextToken(); } else if (type.equals("somevalue")) { result = new OldJacksonSomeValueSnak(); result.setProperty("P" + p.getIntValue()); p.nextToken(); } else { logger.warn("Unknown value type: " + type); } if (!p.getCurrentToken().equals(JsonToken.END_ARRAY)) { logger.warn("Token " + JsonToken.END_ARRAY + " expected"); } return result; }
From source file:com.comcast.cdn.traffic_control.traffic_router.core.external.CoverageZoneTest.java
@Test public void itGetsCaches() throws Exception { HttpGet httpGet = new HttpGet( "http://localhost:3333/crs/coveragezone/caches?deliveryServiceId=steering-target-4&cacheLocationId=location-3"); CloseableHttpResponse response = null; try {//from w w w . j a va2s .c o m response = closeableHttpClient.execute(httpGet); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); ObjectMapper objectMapper = new ObjectMapper(new JsonFactory()); JsonNode jsonNode = objectMapper.readTree(EntityUtils.toString(response.getEntity())); assertThat(jsonNode.isArray(), equalTo(true)); JsonNode cacheNode = jsonNode.get(0); assertThat(cacheNode.get("id").asText(), not(nullValue())); assertThat(cacheNode.get("fqdn").asText(), not(nullValue())); assertThat(cacheNode.get("ip4").asText(), not(nullValue())); assertThat(cacheNode.get("ip6").asText(), not(nullValue())); // If the value is null or otherwise not an int we'll get back -123456, so any other value returned means success assertThat(cacheNode.get("port").asInt(-123456), not(equalTo(-123456))); assertThat(cacheNode.get("deliveryServices").isArray(), equalTo(true)); assertThat(cacheNode.get("hashValues").get(0).asDouble(-1024.1024), not(equalTo(-1024.1024))); assertThat(cacheNode.get("available").asText(), anyOf(equalTo("true"), equalTo("false"))); } finally { if (response != null) response.close(); } }
From source file:de.fraunhofer.iosb.ilt.sta.deserialize.custom.CustomEntityDeserializer.java
@Override public T deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException, JsonProcessingException { Entity result;/*from ww w. j a v a 2 s .co m*/ try { result = clazz.newInstance(); } catch (InstantiationException | IllegalAccessException ex) { throw new IOException("Error deserializing JSON!"); } // need to make subclass of this class for every Entity subclass with custom field to get expected class!!! BeanDescription beanDescription = ctxt.getConfig().introspect(ctxt.constructType(clazz)); ObjectMapper mapper = (ObjectMapper) parser.getCodec(); JsonNode obj = (JsonNode) mapper.readTree(parser); List<BeanPropertyDefinition> properties = beanDescription.findProperties(); Iterator<Map.Entry<String, JsonNode>> i = obj.fields(); // First check if we know all properties that are present. if (ctxt.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)) { for (; i.hasNext();) { Map.Entry<String, JsonNode> next = i.next(); String fieldName = next.getKey(); JsonNode field = next.getValue(); Optional<BeanPropertyDefinition> findFirst = properties.stream() .filter(p -> p.getName().equals(fieldName)).findFirst(); if (!findFirst.isPresent()) { throw new UnrecognizedPropertyException(parser, "Unknown field: " + fieldName, parser.getCurrentLocation(), clazz, fieldName, null); } } } for (BeanPropertyDefinition classProperty : properties) { if (obj.has(classProperty.getName())) { // property is present in class and json Annotation annotation = classProperty.getAccessor().getAnnotation(CustomSerialization.class); if (annotation != null) { // property has custom annotation // check if encoding property is also present in json (and also in class itself for sanity reasons) CustomSerialization customAnnotation = (CustomSerialization) annotation; Optional<BeanPropertyDefinition> encodingClassProperty = properties.stream() .filter(p -> p.getName().equals(customAnnotation.encoding())).findFirst(); if (!encodingClassProperty.isPresent()) { throw new IOException("Error deserializing JSON as class '" + clazz.toString() + "' \n" + "Reason: field '" + customAnnotation.encoding() + "' specified by annotation as encoding field is not defined in class!"); } String customEncoding = null; if (obj.has(customAnnotation.encoding())) { customEncoding = obj.get(customAnnotation.encoding()).asText(); } Object customDeserializedValue = CustomDeserializationManager.getInstance() .getDeserializer(customEncoding) .deserialize(mapper.writeValueAsString(obj.get(classProperty.getName()))); classProperty.getMutator().setValue(result, customDeserializedValue); } else { // TODO type identificatin is not safe beacuase may ne be backed by field. Rather do multiple checks Object value = mapper.readValue(mapper.writeValueAsString(obj.get(classProperty.getName())), classProperty.getField().getType()); classProperty.getMutator().setValue(result, value); } } } return (T) result; }
From source file:architecture.ee.web.community.social.facebook.FacebookServiceProvider.java
public java.util.List<Post> getHomeFeed(int offset, int limit) { Token accessToken = getAccessToken(getAccessToken(), ""); OAuthRequest request = new OAuthRequest(Verb.GET, GRAPH_API_URL + "me/home"); request.addBodyParameter("offset", String.valueOf(offset)); request.addBodyParameter("limit", String.valueOf(limit)); getOAuthService().signRequest(accessToken, request); Response response = request.send(); List<Post> posts;/* ww w . j av a 2 s . co m*/ try { ObjectMapper mapper = getObjectMapper(); JsonNode dataNode = mapper.readTree(response.getBody()); JsonNode dataNode2 = dataNode.get("data"); posts = new ArrayList<Post>(); for (Iterator<JsonNode> iterator = dataNode2.iterator(); iterator.hasNext();) { JsonNode node = iterator.next(); posts.add(deserializePost(mapper, null, Post.class, (ObjectNode) node)); } } catch (Exception e) { return Collections.EMPTY_LIST; } return posts; }
From source file:com.twosigma.beakerx.kernel.MagicKernelManager.java
private Message parseMessage(String stringJson) throws IOException { ObjectMapper mapper = new ObjectMapper(); JsonNode json = mapper.readTree(stringJson); Message msg = new Message(mapper.convertValue(json.get("header"), Header.class)); msg.setContent(mapper.convertValue(json.get("content"), Map.class)); msg.setMetadata(mapper.convertValue(json.get("metadata"), Map.class)); msg.setBuffers(mapper.convertValue(json.get("buffers"), List.class)); List<byte[]> identities = mapper.convertValue(json.get("comm_id"), List.class); msg.setIdentities(identities == null ? new ArrayList<>() : identities); return msg;// ww w.ja v a 2s. c om }
From source file:io.orchestrate.client.KvListOperation.java
/** {@inheritDoc} */ @Override/*from ww w .j a va 2s. c om*/ @SuppressWarnings("unchecked") KvList<T> fromResponse(final int status, final HttpHeader httpHeader, final String json, final JacksonMapper mapper) throws IOException { assert (status == 200); final ObjectMapper objectMapper = mapper.getMapper(); final JsonNode jsonNode = objectMapper.readTree(json); final String next = (jsonNode.has("next")) ? jsonNode.get("next").asText() : null; final int count = jsonNode.get("count").asInt(); final List<KvObject<T>> results = new ArrayList<KvObject<T>>(count); final Iterator<JsonNode> iter = jsonNode.get("results").elements(); while (iter.hasNext()) { results.add(jsonToKvObject(objectMapper, iter.next(), clazz)); } return new KvList<T>(results, count, next); }
From source file:com.github.iexel.fontus.web.test.SpringMvcIntegrationTest.java
/** * Test the external web service./*w w w .j av a 2 s . c o m*/ */ @Test public void testRestService() throws Exception { MockHttpServletRequestBuilder m; ResultActions r; // Create a new record m = post("/rest/products"); m.contentType(MediaType.APPLICATION_JSON); m.accept(MediaType.APPLICATION_JSON); m.content("{\"name\":\"A record created by automated test\", \"price\":10.00, \"version\":0}"); r = this.mockMvc.perform(m); r.andDo(print()); r.andExpect(status().isOk()); // Get the new record's id and version with Jackson MvcResult result = r.andReturn(); String resultStr = result.getResponse().getContentAsString(); ObjectMapper mapper = new ObjectMapper(); JsonNode rootNode = mapper.readTree(resultStr); JsonNode nameNode = rootNode.path("id"); int id = nameNode.asInt(); JsonNode versionNode = rootNode.path("version"); String version = versionNode.asText(); // Update the new record m = put("/rest/products/" + id); m.contentType(MediaType.APPLICATION_JSON); m.accept(MediaType.APPLICATION_JSON); m.content("{\"name\":\"Updated by automated test\", \"price\":20.00, \"version\":" + version + "}"); r = this.mockMvc.perform(m); r.andDo(print()); r.andExpect(status().isOk()); // Get all records, and check that the new record is present and contains correct data m = get("/rest/products?rows=100&page=1&sidx=id&sord=asc"); m.accept(MediaType.APPLICATION_JSON); r = this.mockMvc.perform(m); r.andDo(print()); r.andExpect(status().isOk()); r.andExpect(jsonPath("$.page", equalTo(1))); // ?(@.id==8) - select all rows with id=8, and [0] - get the first of these rows r.andExpect(jsonPath("$.rows[?(@.id==" + id + ")][0].name", equalTo("Updated by automated test"))); // Delete the test record m = delete("/rest/products/" + id); m.contentType(MediaType.APPLICATION_JSON); m.accept(MediaType.APPLICATION_JSON); m.content("{\"version\":1}"); // the version after the update should be 1 r = this.mockMvc.perform(m); r.andDo(print()); r.andExpect(status().isOk()); }