List of usage examples for com.fasterxml.jackson.databind ObjectMapper readTree
public JsonNode readTree(URL source) throws IOException, JsonProcessingException
From source file:org.jasig.cas.support.oauth.web.OAuth20MetadataPrincipalControllerTests.java
@Test public void verifyEmptyPrincipalListOK() throws Exception { final AccessToken accessToken = mock(AccessToken.class); when(accessToken.getId()).thenReturn(AT_ID); final List<PrincipalMetadata> principalMetas = Arrays.asList(); final CentralOAuthService centralOAuthService = mock(CentralOAuthService.class); when(centralOAuthService.getToken(AT_ID, AccessToken.class)).thenReturn(accessToken); when(centralOAuthService.getPrincipalMetadata(accessToken)).thenReturn(principalMetas); final MockHttpServletRequest mockRequest = new MockHttpServletRequest("POST", CONTEXT + OAuthConstants.METADATA_URL); mockRequest.setParameter(OAuthConstants.ACCESS_TOKEN, AT_ID); final MockHttpServletResponse mockResponse = new MockHttpServletResponse(); final OAuth20WrapperController oauth20WrapperController = new OAuth20WrapperController(); oauth20WrapperController.setCentralOAuthService(centralOAuthService); oauth20WrapperController.afterPropertiesSet(); final ModelAndView modelAndView = oauth20WrapperController.handleRequest(mockRequest, mockResponse); assertNull(modelAndView);/* w w w . j a v a 2s .com*/ assertEquals(HttpStatus.SC_OK, mockResponse.getStatus()); assertEquals(CONTENT_TYPE, mockResponse.getContentType()); final ObjectMapper mapper = new ObjectMapper(); final String expected = "{\"data\":[]}"; final JsonNode expectedObj = mapper.readTree(expected); final JsonNode receivedObj = mapper.readTree(mockResponse.getContentAsString()); final JsonNode expectedData = expectedObj.get("data"); final JsonNode receivedData = receivedObj.get("data"); assertEquals(expectedData.size(), receivedData.size()); assertEquals(0, receivedData.size()); }
From source file:org.openmhealth.shim.fatsecret.FatsecretShim.java
@Override public ShimDataResponse getData(ShimDataRequest shimDataRequest) throws ShimException { long numToSkip = 0; long numToReturn = 3; Calendar cal = Calendar.getInstance(); cal.set(2014, Calendar.AUGUST, 1); Date endDate = new Date(cal.getTimeInMillis()); cal.add(Calendar.DATE, -1);/*ww w .j av a 2s. c o m*/ Date startDate = new Date(cal.getTimeInMillis()); DateTime startTime = new DateTime(startDate.getTime()); DateTime endTime = new DateTime(endDate.getTime()); MutableDateTime epoch = new MutableDateTime(); epoch.setDate(0); int days = 16283; //Days.daysBetween(epoch, new DateTime()).getDays() - 1; String endPoint = "food_entries.get"; String accessToken = shimDataRequest.getAccessParameters().getAccessToken(); String tokenSecret = shimDataRequest.getAccessParameters().getTokenSecret(); URL url = signUrl(DATA_URL + "?date=" + days + "&format=json&method=" + endPoint, accessToken, tokenSecret, null); System.out.println("Signed URL is: \n\n" + url); // Fetch and decode the JSON data. ObjectMapper objectMapper = new ObjectMapper(); JsonNode jsonData; HttpGet get = new HttpGet(url.toString()); HttpResponse response; try { response = httpClient.execute(get); HttpEntity responseEntity = response.getEntity(); jsonData = objectMapper.readTree(responseEntity.getContent()); return ShimDataResponse.result(FatsecretShim.SHIM_KEY, jsonData); } catch (IOException e) { throw new ShimException("Could not fetch data", e); } finally { get.releaseConnection(); } }
From source file:com.msopentech.odatajclient.testservice.utils.JSONUtilities.java
public InputStream addJsonInlinecount(final InputStream src, final int count, final Accept accept) throws Exception { final ObjectMapper mapper = new ObjectMapper(); final JsonNode srcNode = mapper.readTree(src); ((ObjectNode) srcNode).put(ODATA_COUNT_NAME, count); final ByteArrayOutputStream bos = new ByteArrayOutputStream(); mapper.writeValue(bos, srcNode);//from w w w . j a v a 2s . co m final InputStream res = new ByteArrayInputStream(bos.toByteArray()); IOUtils.closeQuietly(bos); return res; }
From source file:com.bna.ezrxlookup.service.OpenFdaService.java
/** * Retrieve set of <code>DrugLabel</code> from JSON response * @param response/*from w ww . j a va2s .co m*/ * @return TreeSet with DrugLabel objects */ public Set<DrugLabel> getDrugLabelResults(String jsonResponse) throws Exception { Set<DrugLabel> labelList = new TreeSet<DrugLabel>(); if (StringUtils.isEmpty(jsonResponse)) return labelList; try { ObjectMapper objectMapper = new ObjectMapper(); JsonNode rootNode = objectMapper.readTree(jsonResponse); JsonNode resultsNodes = rootNode.path(RESULTS_TAG); LOG.debug("Results size : " + resultsNodes.size()); Iterator<JsonNode> elements = resultsNodes.elements(); while (elements.hasNext()) { JsonNode aResultsNode = elements.next(); // results node JsonNode openFdaNode = aResultsNode.get(OPENFDA_TAG); DrugLabel label = new DrugLabel(); label.setId(aResultsNode.path(ID_TAG).asText()); label.setVersion(aResultsNode.path(VERSION_TAG).asText()); label.setBrandName(openFdaNode.get(BRAND_NAME_TAG).elements().next().asText()); label.setManufactureName(openFdaNode.get(MFR_NAME_TAG).elements().next().asText()); labelList.add(label); } } catch (IOException e) { LOG.error(e); throw e; } LOG.debug(labelList); return labelList; }
From source file:com.msopentech.odatajclient.testservice.utils.JSONUtilities.java
@Override protected Map<String, InputStream> getChanges(final InputStream src) throws Exception { final Map<String, InputStream> res = new HashMap<String, InputStream>(); final ObjectMapper mapper = new ObjectMapper(); final JsonNode srcObject = mapper.readTree(src); final Iterator<Map.Entry<String, JsonNode>> fields = srcObject.fields(); while (fields.hasNext()) { final Map.Entry<String, JsonNode> field = fields.next(); res.put(field.getKey(), IOUtils.toInputStream(field.getValue().toString())); }/*from www .jav a 2s .c o m*/ return res; }
From source file:net.floodlightcontroller.configuration.ConfigurationManager.java
/** * Reads a configuration file and calls the corresponding configuration * listeners./*from ww w. j a v a 2 s. c o m*/ * * @param file An optional configuration file name. */ private void readJsonFromFile(String fileName) { String configFile = (fileName != null) ? fileName : this.fileName; ObjectMapper mapper = new ObjectMapper(); JsonFactory f = new JsonFactory(); JsonParser jp = null; try { jp = f.createJsonParser(new File(configFile)); JsonNode root = mapper.readTree(jp); // Check if the file is empty. if (root == null) return; Iterator<Entry<String, JsonNode>> iter = root.fields(); // For every configuration sub-node. while (iter.hasNext()) { Entry<String, JsonNode> entry = iter.next(); String fieldName = entry.getKey(); JsonNode child = entry.getValue(); if (configurationListener.containsKey(fieldName)) { configurationListener.get(fieldName).putJsonConfig(child); } else { if (logger.isWarnEnabled()) { logger.warn("No configuration listener found for " + fieldName); } } } } catch (FileNotFoundException e) { if (logger.isWarnEnabled()) { logger.warn("Configuration file {} not found.", configFile); } } catch (IOException e) { e.printStackTrace(); } }
From source file:com.baasbox.controllers.actions.filters.WrapResponse.java
private ObjectNode prepareOK(int statusCode, RequestHeader request, String stringBody) throws IOException { ObjectMapper mapper = new ObjectMapper(); ObjectNode result = Json.newObject(); setCallIdOnResult(request, result);/*from ww w . ja v a2s . com*/ result.put("result", "ok"); try { result.put("data", mapper.readTree(stringBody)); } catch (JsonProcessingException e) { result.put("data", stringBody); } catch (IOException e) { if (stringBody.isEmpty()) result.put("data", ""); else throw new IOException("Error parsing stringBody: " + stringBody, e); } return result; }
From source file:com.vaushell.superpipes.tools.scribe.linkedin.LinkedInClient.java
/** * Read a LinkedIn status./*from w ww. j a va2 s.c o m*/ * * @param ID Status's ID * @return the Status * @throws IOException * @throws LinkedInException */ public LNK_Status readStatus(final String ID) throws IOException, LinkedInException { if (ID == null || ID.isEmpty()) { throw new IllegalArgumentException(); } if (LOGGER.isTraceEnabled()) { LOGGER.trace("[" + getClass().getSimpleName() + "] readStatus() : ID=" + ID); } final OAuthRequest request = new OAuthRequest(Verb.GET, "http://api.linkedin.com/v1/people/~/network/updates/key=UNIU-" + ID + "-SHARE?type=SHAR&format=json"); final Response response = sendSignedRequest(request); final ObjectMapper mapper = new ObjectMapper(); final JsonNode node = (JsonNode) mapper.readTree(response.getStream()); checkErrors(response, node); return convertJsonToStatus(node); }
From source file:com.msopentech.odatajclient.testservice.utils.JSONUtilities.java
public InputStream wrapJsonEntities(final InputStream entities) throws Exception { final ObjectMapper mapper = new ObjectMapper(); final JsonNode node = mapper.readTree(entities); final ObjectNode res; final JsonNode value = node.get(JSON_VALUE_NAME); if (value.isArray()) { res = mapper.createObjectNode(); res.set("value", value); final JsonNode next = node.get(JSON_NEXTLINK_NAME); if (next != null) { res.set(JSON_NEXTLINK_NAME, next); }/* w w w .j a v a2 s.com*/ } else { res = (ObjectNode) value; } final ByteArrayOutputStream bos = new ByteArrayOutputStream(); mapper.writeValue(bos, res); final InputStream is = new ByteArrayInputStream(bos.toByteArray()); IOUtils.closeQuietly(bos); return is; }