List of usage examples for com.fasterxml.jackson.databind ObjectReader readValue
@SuppressWarnings("unchecked") public <T> T readValue(JsonNode src) throws IOException, JsonProcessingException
From source file:org.jasig.portlet.proxy.mvc.portlet.json.JsonPortletController.java
@RequestMapping public ModelAndView showContent(PortletRequest request) { final ModelAndView mv = new ModelAndView(); final PortletPreferences preferences = request.getPreferences(); // locate the content service to use to retrieve our JSON final String contentServiceKey = preferences.getValue(CONTENT_SERVICE_KEY, null); final IContentService contentService = applicationContext.getBean(contentServiceKey, IContentService.class); final IContentRequest proxyRequest = contentService.getRequest(request); // retrieve the JSON content final IContentResponse proxyResponse = contentService.getContent(proxyRequest, request); // parse our JSON into a map and add it to the model final ObjectMapper mapper = new ObjectMapper(); final ObjectReader reader = mapper.reader(Map.class); try {//www .ja v a 2 s .co m final Map<String, Object> map = reader.readValue(proxyResponse.getContent()); mv.addAllObjects(map); } catch (JsonProcessingException e) { log.error("Error parsing JSON content", e); } catch (IOException e) { log.error("IOException reading JSON content", e); } finally { if (proxyResponse != null) { proxyResponse.close(); } } // set the appropriate view name final String mainView = preferences.getValue(MAIN_VIEW_KEY, null); final String mobileView = preferences.getValue(MOBILE_VIEW_KEY, null); final String viewName; if (mobileView != null) { final boolean isMobile = viewSelector.isMobile(request); viewName = isMobile ? mobileView : mainView; } else { viewName = mainView; } mv.setViewName(viewName); return mv; }
From source file:org.jongo.marshall.jackson.oid.AnnotationsTest.java
@Test public void shouldHandleIdAnnotation() throws IOException { Mapping build = new Mapping.Builder().build(); ObjectReader reader = build.getReader(WithMongoId.class); BsonDocument document = Bson.createDocument(new BasicDBObject("_id", "53a499be60b2a2248d956875")); WithMongoId friend = reader.readValue(document.toByteArray()); assertThat(friend.id, equalTo("53a499be60b2a2248d956875")); }
From source file:com.codenvy.cli.preferences.file.JsonPreferences.java
protected void put(String key, Object value, boolean overwrite) { Object previousValue = innerPreferences.get(key); if (previousValue != null && !overwrite) { ObjectReader updater = mapper.readerForUpdating(previousValue); try {//from www. ja v a 2s . co m updater.readValue(this.mapper.valueToTree(value)); } catch (IllegalArgumentException | IOException e) { throw new IllegalStateException("Unable to put the value", e); } } else { if (!shouldMapUnmap(value.getClass())) { innerPreferences.put(key, value); } else { innerPreferences.put(key, this.mapper.convertValue(value, mapType)); } } }
From source file:io.seldon.external.ExternalPredictionServer.java
@Override public PredictionServiceResult predictFromJSON(String client, JsonNode jsonNode, OptionsHolder options) { try {/* www. j a v a2s . c o m*/ JsonNode actualObj = predict(client, jsonNode, options); ObjectMapper mapper = new ObjectMapper(); ObjectReader reader = mapper.reader(PredictionServiceResult.class); PredictionServiceResult res = reader.readValue(actualObj); return res; } catch (JsonProcessingException e) { logger.error("Couldn't retrieve prediction from external prediction server - ", e); throw new APIException(APIException.GENERIC_ERROR); } catch (IOException e) { logger.error("Couldn't retrieve prediction from external prediction server - ", e); throw new APIException(APIException.GENERIC_ERROR); } }
From source file:com.octo.monitoring_flux.cep.esper.EsperComponentTest.java
/** * Sample communication test./*from w w w .ja v a 2 s. c om*/ * * @throws Exception */ @Test @Ignore public void testCEP() throws Exception { // read sample as event ObjectReader jacksonReader = new ObjectMapper().reader(Map.class); MonitoringEvent frontBegin = new MonitoringEvent(jacksonReader.readValue(FRONTEND_BEGIN)); MonitoringEvent frontStartCall = new MonitoringEvent(jacksonReader.readValue(FRONTEND_STARTCALL)); MonitoringEvent frontEndCall = new MonitoringEvent(jacksonReader.readValue(FRONTEND_ENDCALL)); MockEndpoint mockSLA = getMockEndpoint("mock:unit-sla"); template.sendBody("direct:start", frontBegin); for (int i = 0; i < 20; i++) { template.sendBody("direct:start", frontStartCall); Thread.sleep(i * 100); // Correct the elasped time frontEndCall.setElapsedTime(new Double(i) / 10); // Slowing down template.sendBody("direct:start", frontEndCall); } // Asserts mockSLA.expectedMinimumMessageCount(9); assertMockEndpointsSatisfied(); }
From source file:io.seldon.external.ExternalItemRecommendationAlgorithm.java
@Override public ItemRecommendationResultSet recommend(String client, Long user, Set<Integer> dimensions, int maxRecsCount, RecommendationContext ctxt, List<Long> recentItemInteractions) { long timeNow = System.currentTimeMillis(); String recommenderName = ctxt.getOptsHolder().getStringOption(ALG_NAME_PROPERTY_NAME); String baseUrl = ctxt.getOptsHolder().getStringOption(URL_PROPERTY_NAME); if (ctxt.getInclusionKeys().isEmpty()) { logger.warn("Cannot get external recommendations are no includers were used. Returning 0 results"); return new ItemRecommendationResultSet(recommenderName); }//from www . j av a2 s .com URI uri = URI.create(baseUrl); try { URIBuilder builder = new URIBuilder().setScheme("http").setHost(uri.getHost()).setPort(uri.getPort()) .setPath(uri.getPath()).setParameter("client", client).setParameter("user_id", user.toString()) .setParameter("recent_interactions", StringUtils.join(recentItemInteractions, ",")) .setParameter("dimensions", StringUtils.join(dimensions, ",")) .setParameter("exclusion_items", StringUtils.join(ctxt.getExclusionItems(), ",")) .setParameter("data_key", StringUtils.join(ctxt.getInclusionKeys(), ",")) .setParameter("limit", String.valueOf(maxRecsCount)); if (ctxt.getCurrentItem() != null) builder.setParameter("item_id", ctxt.getCurrentItem().toString()); uri = builder.build(); } catch (URISyntaxException e) { logger.error("Couldn't create URI for external recommender with name " + recommenderName, e); return new ItemRecommendationResultSet(recommenderName); } HttpContext context = HttpClientContext.create(); HttpGet httpGet = new HttpGet(uri); try { if (logger.isDebugEnabled()) logger.debug("Requesting " + httpGet.getURI().toString()); CloseableHttpResponse resp = httpClient.execute(httpGet, context); try { if (resp.getStatusLine().getStatusCode() == 200) { ConsumerBean c = new ConsumerBean(client); ObjectReader reader = mapper.reader(AlgsResult.class); AlgsResult recs = reader.readValue(resp.getEntity().getContent()); List<ItemRecommendationResultSet.ItemRecommendationResult> results = new ArrayList<>( recs.recommended.size()); for (AlgResult rec : recs.recommended) { Map<String, Integer> attrDimsCandidate = itemService.getDimensionIdsForItem(c, rec.item); if (CollectionUtils.containsAny(dimensions, attrDimsCandidate.values()) || dimensions.contains(Constants.DEFAULT_DIMENSION)) { if (logger.isDebugEnabled()) logger.debug("Adding item " + rec.item); results.add( new ItemRecommendationResultSet.ItemRecommendationResult(rec.item, rec.score)); } else { if (logger.isDebugEnabled()) logger.debug("Rejecting item " + rec.item + " as not in dimensions " + dimensions); } } if (logger.isDebugEnabled()) logger.debug("External recommender took " + (System.currentTimeMillis() - timeNow) + "ms"); return new ItemRecommendationResultSet(results, recommenderName); } else { logger.error( "Couldn't retrieve recommendations from external recommender -- bad http return code: " + resp.getStatusLine().getStatusCode()); } } finally { if (resp != null) resp.close(); } } catch (IOException e) { logger.error("Couldn't retrieve recommendations from external recommender - ", e); } catch (Exception e) { logger.error("Couldn't retrieve recommendations from external recommender - ", e); } return new ItemRecommendationResultSet(recommenderName); }
From source file:com.stackify.metric.impl.MetricMonitorService.java
/** * Gets the monitor id for this metric//from ww w. j av a2 s . c o m * @param identity The metric identity * @return The monitor id (optional) * @throws IOException * @throws HttpException */ private int getMetricInfo(final MetricIdentity identity, final AppIdentity appIdentity) throws IOException, HttpException { Preconditions.checkNotNull(identity); Preconditions.checkNotNull(appIdentity); // build the json objects JsonGetMetricInfoRequest.Builder requestBuilder = JsonGetMetricInfoRequest.newBuilder(); requestBuilder.category(identity.getCategory()); requestBuilder.metricName(identity.getName()); requestBuilder.deviceId(appIdentity.getDeviceId()); requestBuilder.deviceAppId(appIdentity.getDeviceAppId()); requestBuilder.appNameId(appIdentity.getAppNameId()); requestBuilder.metricTypeId(identity.getType().getId()); JsonGetMetricInfoRequest request = requestBuilder.build(); // convert to json bytes byte[] jsonBytes = objectMapper.writer().writeValueAsBytes(request); // post to stackify HttpClient httpClient = new HttpClient(apiConfig); String responseString = httpClient.post("/Metrics/GetMetricInfo", jsonBytes); // deserialize the response and return the monitor id ObjectReader jsonReader = objectMapper.reader(new TypeReference<JsonGetMetricInfoResponse>() { }); JsonGetMetricInfoResponse response = jsonReader.readValue(responseString); if (response != null) { return response.getMonitorId(); } return 0; }
From source file:com.stackify.api.common.AppIdentityService.java
/** * Retrieves the application identity given the environment details * @return The application identity/*from w w w . ja va 2 s . co m*/ * @throws IOException * @throws HttpException */ private AppIdentity identifyApp(ApiConfiguration apiConfig) throws IOException, HttpException { // convert to json bytes byte[] jsonBytes = objectMapper.writer().writeValueAsBytes(apiConfig.getEnvDetail()); if (LOGGER.isDebugEnabled()) { LOGGER.debug("IdentifyApp Request: {}", new String(jsonBytes, "UTF-8")); } // post to stackify final HttpClient httpClient = new HttpClient(apiConfig); final String responseString = httpClient.post("/Metrics/IdentifyApp", jsonBytes); LOGGER.debug("IdentifyApp Response: {}", responseString); // deserialize the response and return the app identity ObjectReader jsonReader = objectMapper.reader(new TypeReference<AppIdentity>() { }); AppIdentity identity = jsonReader.readValue(responseString); // make sure it has a valid DeviceAppID before accepting it if (deviceAppIdRequired) { if (identity.getDeviceAppId() == null) { throw new NullPointerException("DeviceAppId is null"); } } // done return identity; }
From source file:org.jongo.marshall.jackson.oid.AnnotationsTest.java
@Test public void shouldHandleObjectIdAnnotation() throws IOException { Mapping build = new Mapping.Builder().build(); ObjectReader reader = build.getReader(WithMongoObjectId.class); DBObject oid = new BasicDBObject("$oid", "53a499be60b2a2248d956875"); BasicDBObject dbObject = new BasicDBObject("id", oid); BsonDocument document = Bson.createDocument(dbObject); WithMongoObjectId testObj = reader.readValue(document.toByteArray()); assertThat(testObj.id, equalTo("53a499be60b2a2248d956875")); }
From source file:cf.nats.message.Demarshalling.java
@Test public void routerRegisterCloudController() throws Exception { final ObjectReader reader = mapper.reader(RouterRegister.class); final String routerRegisterMessage = "{\"host\":\"127.0.0.1\",\"port\":9022,\"uris\":[\"api.mikeheath.cloudfoundry.me\"],\"tags\":{\"component\":\"CloudController\"}}"; final RouterRegister routerRegister = reader.readValue(routerRegisterMessage); assertNotNull(routerRegister);//from w w w . j av a 2s . com assertEquals("127.0.0.1", routerRegister.getHost()); assertEquals(Integer.valueOf(9022), routerRegister.getPort()); assertEquals("api.mikeheath.cloudfoundry.me", routerRegister.getUris().get(0)); }