List of usage examples for org.springframework.web.client RestTemplate getForObject
@Override @Nullable public <T> T getForObject(URI url, Class<T> responseType) throws RestClientException
From source file:com.unito.controller.ControllerAjaxRequests.java
@RequestMapping(value = "/verifyLogin", method = RequestMethod.POST, consumes = "application/json") public String verifyLogin(@RequestBody String data, HttpServletRequest request) { LOG.info(data != null ? "Data from google respone: " + data : "Data from google respone:NULL"); Gson gson = new Gson(); UserDetails userLogin = null;/*ww w . ja va2s.c o m*/ UserDetails dbResultUser = null; boolean ok = false; TokenValidateResponse tokenValidateResponse; RestTemplate restTemplate = new RestTemplate(); try { userLogin = gson.fromJson(data, UserDetails.class); } catch (JsonSyntaxException e) { } LOG.info("userLogin: " + userLogin.toString()); //validate the user if (userLogin != null) { tokenValidateResponse = restTemplate.getForObject(VALIDATE_HTTPS + userLogin.getIdtoken(), TokenValidateResponse.class); } else { return gson.toJson(ok); } if (tokenValidateResponse != null && tokenValidateResponse.getUser_id().equals(userLogin.getId())) { // recover the user form db dbResultUser = userDetailsRepository.find(userLogin.getId()); if (dbResultUser != null) { LOG.info("result update: " + userDetailsRepository.update(userLogin)); } else { LOG.info("Insert: " + userDetailsRepository.save(userLogin)); } LOG.info("TO SESSION: " + userLogin); request.getSession().setAttribute("userDetails", userLogin); userSession.setUserdetails(userLogin); ok = true; } else { //error login ok = false; } return gson.toJson(ok);//json; }
From source file:org.spring.data.gemfire.rest.GemFireRestInterfaceTest.java
@Test public void testRegionObjectWithDatePropertyAccessedWithRestApi() throws Exception { String key = "1"; Person jonDoe = createPerson("Jon", "Doe", createDate(1977, Calendar.OCTOBER, 31)); assertTrue(getPeopleRegion().isEmpty()); getPeopleRegion().put(key, jonDoe);// w w w .j a v a 2 s . c o m assertFalse(getPeopleRegion().isEmpty()); assertEquals(1, getPeopleRegion().size()); assertTrue(getPeopleRegion().containsKey(key)); Object jonDoeRef = getPeopleRegion().get(key); assertTrue(jonDoeRef instanceof PdxInstance); assertEquals(jonDoe.getClass().getName(), ((PdxInstance) jonDoeRef).getClassName()); assertEquals(jonDoe.getFirstName(), ((PdxInstance) jonDoeRef).getField("firstName")); assertEquals(jonDoe.getLastName(), ((PdxInstance) jonDoeRef).getField("lastName")); assertEquals(jonDoe.getBirthDate(), ((PdxInstance) jonDoeRef).getField("birthDate")); RestTemplate restTemplate = createRestTemplate(); Person jonDoeResource = restTemplate.getForObject(getRegionGetRestApiEndpoint(getPeopleRegion(), key), Person.class); assertNotNull(jonDoeResource); assertNotSame(jonDoe, jonDoeResource); assertEquals(jonDoe, jonDoeResource); /* Object result = runQueryUsingApi(getPeopleRegion().getRegionService(), String.format("SELECT * FROM %1$s", getPeopleRegion().getFullPath())); System.out.printf("(OQL Query using API) Person is (%1$s)%n", result); */ String url = getAdhocQueryRestApiEndpoint( String.format("SELECT * FROM %1$s", getPeopleRegion().getFullPath())); System.out.printf("URL (%1$s)%n", url); List<?> queryResults = restTemplate.getForObject(url, List.class); assertNotNull(queryResults); assertFalse(queryResults.isEmpty()); assertEquals(1, queryResults.size()); jonDoeResource = objectMapper.convertValue(queryResults.get(0), Person.class); assertNotNull(jonDoeResource); assertNotSame(jonDoe, jonDoeResource); assertEquals(jonDoe, jonDoeResource); }
From source file:com.skipjaq.awspricing.pricing.AwsPricing.java
private AwsOffer getAwsOffer(String awsOffersUrl) { RestTemplate restTemplate = new RestTemplate(); MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); converter.setSupportedMediaTypes(/*from www . ja v a2s . c o m*/ Arrays.asList(new MediaType[] { MediaType.APPLICATION_JSON, MediaType.APPLICATION_OCTET_STREAM })); restTemplate.setMessageConverters(Arrays.asList(converter, new FormHttpMessageConverter())); try { return restTemplate.getForObject(awsOffersUrl, AwsOffer.class); } catch (RestClientException e) { e.printStackTrace(); return null; } }
From source file:org.projecthdata.ehr.viewer.service.WeightSyncService.java
@Override protected void onHandleIntent(Intent intent) { this.editor = prefs.edit(); editor.putString(Constants.PREF_WEIGHT_SYNC_STATE, SyncState.WORKING.toString()).commit(); try {/*from w w w . jav a2s . c o m*/ Dao<RootEntry, Integer> rootDao = hDataOrmManager.getDatabaseHelper().getRootEntryDao(); Dao<SectionDocMetadata, Integer> sectionDao = hDataOrmManager.getDatabaseHelper() .getSectionDocMetadataDao(); // find the first entry that has the right schema and contains xml // documents RootEntry entry = rootDao.queryForFirst( rootDao.queryBuilder().where().eq(RootEntry.COLUMN_NAME_EXTENSION, Constants.EXTENSION_RESULT) .and().like(RootEntry.COLUMN_PATH, "%bodyweight%").and() .eq(RootEntry.COLUMN_NAME_CONTENT_TYPE, MediaType.APPLICATION_XML).prepare()); List<SectionDocMetadata> metadatas = sectionDao .query(sectionDao.queryBuilder().where().eq("rootEntry_id", entry.get_id()).and() .eq("contentType", MediaType.APPLICATION_XML).prepare()); // grab that document and parse out the patient info Connection<HData> connection = connectionRepository.getPrimaryConnection(HData.class); RestTemplate restTemplate = connection.getApi().getRootOperations().getRestTemplate(); Dao<WeightReading, Integer> weightDao = ehrDatabaseHelper.getWeightReadingDao(); //delete all entries in the table weightDao.delete(weightDao.deleteBuilder().prepare()); //add new entries to the table for (SectionDocMetadata metadata : metadatas) { Result result = restTemplate.getForObject(metadata.getLink(), Result.class); // copy result into a WeightReading an persist it WeightReading weight = new WeightReading(); weight.copy(result); weightDao.create(weight); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } editor.putString(Constants.PREF_WEIGHT_SYNC_STATE, SyncState.READY.toString()).commit(); }
From source file:com.nbempire.dentalnavarra.dao.impl.RememberDaoImplSpring.java
@Override public RemembersDTO findRemembers(String patientId) { RestTemplate restTemplate = new RestTemplate(); // Add a JSON converter (use GSON instead of Jackson because is a smaller library) restTemplate.getMessageConverters().add(new GsonHttpMessageConverter()); String urlString = MainKeys.API_HOST + "/patients/" + patientId + "/notifications"; Log.d(TAG, "Getting resource: " + urlString); RemembersDTO response = null;/*from w w w . j a va2s.c o m*/ URI url = null; try { url = new URI(urlString); response = restTemplate.getForObject(url, RemembersDTO.class); } catch (URISyntaxException e) { Log.e(TAG, "There was an error creating the URI: " + urlString); } catch (RestClientException restClientException) { Log.e(TAG, "There was an error getting remembers from URL: " + url); Log.e(TAG, restClientException.getMessage()); } return response != null ? response : new RemembersDTO(); }
From source file:com.bytebybyte.mapquest.geocoding.service.standard.MapQuestTest.java
@Test public void testGetBasicSearch() { RestTemplate restTemplate = new RestTemplate(); String ADDRESS = "http://open.mapquestapi.com/nominatim/v1/search.php?format=json&"; String callback = "q=windsor+[castle]&addressdetails=1&limit=3&"; String viewbox = "viewbox=-1.99%2C52.02%2C0.78%2C50.94&exclude_place_ids=41697"; String url = ADDRESS + callback + viewbox; String result = restTemplate.getForObject(url, String.class); System.out.println("Result : " + result); JsonElement jelement = new JsonParser().parse(result); JsonArray jsonArray = jelement.getAsJsonArray(); JsonObject jo = jsonArray.get(0).getAsJsonObject(); System.out.println("Place Id : " + jo.get("place_id")); System.out.println("License : " + jo.get("licence")); System.out.println("OSM Type : " + jo.get("osm_type")); System.out.println("OSM ID : " + jo.get("osm_id")); System.out.println("BoundingBox : " + jo.get("boundingbox")); System.out.println("Lat : " + jo.get("lat")); System.out.println("lon : " + jo.get("lon")); System.out.println("type : " + jo.get("type")); System.out.println("Importance : " + jo.get("importance")); System.out.println("Icon : " + jo.get("icon")); System.out.println("Address : " + jo.get("address")); jo = jo.getAsJsonObject("address"); System.out.println("--------------------------------"); System.out.println("Castle : " + jo.get("castle")); System.out.println("Path : " + jo.get("path")); System.out.println("Neighbourhood : " + jo.get("neighbourhood")); System.out.println("Suburb : " + jo.get("suburb")); System.out.println("Town : " + jo.get("town")); System.out.println("State_District : " + jo.get("state_district")); System.out.println("State : " + jo.get("state")); System.out.println("Postcode : " + jo.get("postcode")); System.out.println("Country : " + jo.get("country")); System.out.println("Country_code : " + jo.get("country_code")); }
From source file:org.apache.servicecomb.demo.jaxrs.client.JaxrsClient.java
private static void testJaxRSDefaultValues(RestTemplate template) { String microserviceName = "jaxrs"; for (String transport : DemoConst.transports) { CseContext.getInstance().getConsumerProviderManager().setTransport(microserviceName, transport); TestMgr.setMsg(microserviceName, transport); String cseUrlPrefix = "cse://" + microserviceName + "/JaxRSDefaultValues/"; //default values HttpHeaders headers = new HttpHeaders(); headers.setContentType(org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, String> map = new LinkedMultiValueMap<>(); HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers); String result = template.postForObject(cseUrlPrefix + "/form", request, String.class); TestMgr.check("Hello 20bobo", result); headers = new HttpHeaders(); HttpEntity<String> entity = new HttpEntity<>(null, headers); result = template.postForObject(cseUrlPrefix + "/header", entity, String.class); TestMgr.check("Hello 20bobo30", result); result = template.getForObject(cseUrlPrefix + "/query?d=10", String.class); TestMgr.check("Hello 20bobo4010", result); boolean failed = false; try {/*from www . j ava 2 s . co m*/ result = template.getForObject(cseUrlPrefix + "/query2", String.class); } catch (InvocationException e) { failed = true; TestMgr.check(e.getStatusCode(), HttpStatus.SC_BAD_REQUEST); } failed = false; try { result = template.getForObject(cseUrlPrefix + "/query2?d=2&e=2", String.class); } catch (InvocationException e) { failed = true; TestMgr.check(e.getStatusCode(), HttpStatus.SC_BAD_REQUEST); } TestMgr.check(failed, true); failed = false; try { result = template.getForObject(cseUrlPrefix + "/query2?a=&d=2&e=2", String.class); } catch (InvocationException e) { failed = true; TestMgr.check(e.getStatusCode(), HttpStatus.SC_BAD_REQUEST); } TestMgr.check(failed, true); result = template.getForObject(cseUrlPrefix + "/query2?d=30&e=2", String.class); TestMgr.check("Hello 20bobo40302", result); failed = false; try { result = template.getForObject(cseUrlPrefix + "/query3?a=2&b=2", String.class); } catch (InvocationException e) { failed = true; TestMgr.check(e.getStatusCode(), HttpStatus.SC_BAD_REQUEST); } TestMgr.check(failed, true); result = template.getForObject(cseUrlPrefix + "/query3?a=30&b=2", String.class); TestMgr.check("Hello 302", result); result = template.getForObject(cseUrlPrefix + "/query3?a=30", String.class); TestMgr.check("Hello 30null", result); //input values headers = new HttpHeaders(); headers.setContentType(org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED); Map<String, String> params = new HashMap<>(); params.put("a", "30"); params.put("b", "sam"); HttpEntity<Map<String, String>> requestPara = new HttpEntity<>(params, headers); result = template.postForObject(cseUrlPrefix + "/form", requestPara, String.class); TestMgr.check("Hello 30sam", result); headers = new HttpHeaders(); headers.add("a", "30"); headers.add("b", "sam"); headers.add("c", "40"); entity = new HttpEntity<>(null, headers); result = template.postForObject(cseUrlPrefix + "/header", entity, String.class); TestMgr.check("Hello 30sam40", result); result = template.getForObject(cseUrlPrefix + "/query?a=3&b=sam&c=5&d=30", String.class); TestMgr.check("Hello 3sam530", result); result = template.getForObject(cseUrlPrefix + "/query2?a=3&b=4&c=5&d=30&e=2", String.class); TestMgr.check("Hello 345302", result); } }
From source file:org.springframework.xd.dirt.integration.bus.rabbit.RabbitBusCleaner.java
@SuppressWarnings("unchecked") private List<String> findExchanges(String adminUri, String vhost, String busPrefix, String entity, RestTemplate restTemplate, ExchangeCandidateCallback callback) { List<String> removedExchanges = new ArrayList<>(); URI uri = UriComponentsBuilder.fromUriString(adminUri + "/api").pathSegment("exchanges", "{vhost}") .buildAndExpand(vhost).encode().toUri(); List<Map<String, Object>> exchanges = restTemplate.getForObject(uri, List.class); for (Map<String, Object> exchange : exchanges) { String exchangeName = (String) exchange.get("name"); if (callback.isCandidate(exchangeName)) { uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}", "{name}", "bindings", "source") .buildAndExpand(vhost, exchangeName).encode().toUri(); List<Map<String, Object>> bindings = restTemplate.getForObject(uri, List.class); if (bindings.size() == 0) { uri = UriComponentsBuilder.fromUriString(adminUri + "/api") .pathSegment("exchanges", "{vhost}", "{name}", "bindings", "destination") .buildAndExpand(vhost, exchangeName).encode().toUri(); bindings = restTemplate.getForObject(uri, List.class); if (bindings.size() == 0) { removedExchanges.add((String) exchange.get("name")); } else { throw new RabbitAdminException( "Cannot delete exchange " + exchangeName + "; it is a destination: " + bindings); }/*w w w . j a v a 2 s. c o m*/ } else { throw new RabbitAdminException( "Cannot delete exchange " + exchangeName + "; it has bindings: " + bindings); } } } return removedExchanges; }
From source file:com.citibanamex.api.locator.atm.service.impl.AtmServiceImpl.java
/** * This method first takes the address and gets lat lng cordinates of it and * then passes to the google places url along with radius to get list of * banamex atms and branches nearby. We must need API KEY to access google * places APIs.By default Google places limits search to 20 objects, but we * can fetch more than 20 by passing next page token to same url which we * get from first call.// ww w.j a va2 s.c om * * @param radius * @param addressLine1 * @param addressLine2 * @param nextStartIndex * @return list of CitiBanamex ATMs/Branches * @throws InterruptedException */ public List<ATM> getNearByAtmsOrBranches(String radius, String addressLine1, String addressLine2, String nextStartIndex) throws InterruptedException { String address = addressLine1 + " " + addressLine2; RestTemplate restTemplate = new RestTemplate(); Location location = new Location(); List<ATM> atmsList = new ArrayList<ATM>(); GooglePlaces response = null; Results[] resultList = null; StringBuffer imgURL = new StringBuffer(PHOTO_REF_URL); StringBuffer GEO_CODE_URI = new StringBuffer(GEO_CODE_URL); GEO_CODE_URI.append(address); GEO_CODE_URI.append(API_KEY_VALUE); log.info("****************GEO_CODE_URI****************" + GEO_CODE_URI); GeoCodeResponse cordinates = restTemplate.getForObject(GEO_CODE_URI.toString(), GeoCodeResponse.class); com.citibanamex.api.locator.atm.model.geocode.Results[] results = cordinates.getResults(); for (com.citibanamex.api.locator.atm.model.geocode.Results result : results) { location = result.getGeometry().getLocation(); location.setLat(location.getLat()); location.setLng(location.getLng()); } log.info("****Geocode coordinates for a given address : " + address + ", location: " + location.getLat() + "," + location.getLng()); StringBuffer googlePlacesURI = new StringBuffer(GOOGLE_PLACES_URL); googlePlacesURI.append(KEY_WORD); googlePlacesURI.append(API_KEY_VALUE); googlePlacesURI.append(LOCATION); googlePlacesURI.append(location.getLat()); googlePlacesURI.append(COMMA); googlePlacesURI.append(location.getLng()); googlePlacesURI.append(RADIUS); googlePlacesURI.append(radius); if (nextStartIndex != null) { googlePlacesURI.append(NEXT_START_INDEX); googlePlacesURI.append(nextStartIndex); } response = restTemplate.getForObject(googlePlacesURI.toString(), GooglePlaces.class); resultList = response.getResults(); String next_page_token = response.getNext_page_token(); log.info("****************googlePlacesURI****************" + googlePlacesURI); atmsList = getATMsList(atmsList, resultList, imgURL, next_page_token); log.info("*****List of nearby Banamex atms/branches list returning : " + atmsList.size()); return atmsList; }
From source file:com.nouveauxterritoires.eterritoires.identityserver.openid.connect.client.TaxeUserInfoFetcher.java
public UserInfo loadUserInfo(final OIDCAuthenticationToken token) { ServerConfiguration serverConfiguration = token.getServerConfiguration(); if (serverConfiguration == null) { logger.warn("No server configuration found."); return null; }/* ww w .ja v a 2s . co m*/ if (Strings.isNullOrEmpty(serverConfiguration.getUserInfoUri())) { logger.warn("No userinfo endpoint, not fetching."); return null; } try { // if we got this far, try to actually get the userinfo HttpClient httpClient = new SystemDefaultHttpClient(); HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(httpClient); String userInfoString = null; if (serverConfiguration.getUserInfoTokenMethod() == null || serverConfiguration.getUserInfoTokenMethod().equals(UserInfoTokenMethod.HEADER)) { RestTemplate restTemplate = new RestTemplate(factory) { @Override protected ClientHttpRequest createRequest(URI url, HttpMethod method) throws IOException { ClientHttpRequest httpRequest = super.createRequest(url, method); httpRequest.getHeaders().add("Authorization", String.format("Bearer %s", token.getAccessTokenValue())); return httpRequest; } }; userInfoString = restTemplate.getForObject(serverConfiguration.getUserInfoUri(), String.class); } else if (serverConfiguration.getUserInfoTokenMethod().equals(UserInfoTokenMethod.FORM)) { MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>(); form.add("access_token", token.getAccessTokenValue()); RestTemplate restTemplate = new RestTemplate(factory); userInfoString = restTemplate.postForObject(serverConfiguration.getUserInfoUri(), form, String.class); } else if (serverConfiguration.getUserInfoTokenMethod().equals(UserInfoTokenMethod.QUERY)) { URIBuilder builder = new URIBuilder(serverConfiguration.getUserInfoUri()); builder.setParameter("access_token", token.getAccessTokenValue()); RestTemplate restTemplate = new RestTemplate(factory); userInfoString = restTemplate.getForObject(builder.toString(), String.class); } if (!Strings.isNullOrEmpty(userInfoString)) { JsonObject userInfoJson = new JsonParser().parse(userInfoString).getAsJsonObject(); UserInfo userInfo = TaxeUserInfo.fromJson(userInfoJson); return userInfo; } else { // didn't get anything, return null return null; } } catch (Exception e) { logger.warn("Error fetching taxeuserinfo", e); return null; } }