List of usage examples for org.springframework.web.client RestTemplate exchange
@Override public <T> ResponseEntity<T> exchange(URI url, HttpMethod method, @Nullable HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType) throws RestClientException
From source file:org.starfishrespect.myconsumption.android.tasks.SensorValuesUpdater.java
public void refreshDB() { AsyncTask<Void, List, Void> task = new AsyncTask<Void, List, Void>() { @Override/*w w w . j a va 2 s . c o m*/ protected Void doInBackground(Void... params) { DatabaseHelper db = SingleInstance.getDatabaseHelper(); RestTemplate template = new RestTemplate(); HttpHeaders httpHeaders = CryptoUtils.createHeadersCurrentUser(); ResponseEntity<List> responseEnt; template.getMessageConverters().add(new MappingJacksonHttpMessageConverter()); try { SensorValuesDao valuesDao = new SensorValuesDao(db); for (SensorData sensor : db.getSensorDao().queryForAll()) { int startTime = (int) (sensor.getLastLocalValue().getTime() / 1000); String url = String.format(SingleInstance.getServerUrl() + "sensors/%s/data?start=%d", sensor.getSensorId(), startTime); Log.d(TAG, url); responseEnt = template.exchange(url, HttpMethod.GET, new HttpEntity<>(httpHeaders), List.class); List<List<Integer>> sensorData = responseEnt.getBody(); List<SensorValue> values = new ArrayList<>(); long last = 0; long first = Long.MAX_VALUE; for (List<Integer> value : sensorData) { values.add(new SensorValue(value.get(0), value.get(1))); if (value.get(0) > last) { last = value.get(0); } if (value.get(0) < first) { first = value.get(0); } } valuesDao.insertSensorValues(sensor.getSensorId(), values); sensor.setLastLocalValue(new Date(last * 1000)); long formerFirst = sensor.getFirstLocalValue().getTime() / 1000; if (formerFirst > first || formerFirst == 0) { sensor.setFirstLocalValue(new Date(first * 1000)); } db.getSensorDao().update(sensor); Log.d(TAG, "Inserted values to " + last); } } catch (SQLException e) { Log.e(TAG, "Error:" + e.toString()); } return null; } @Override protected void onPostExecute(Void aVoid) { if (updateFinishedCallback != null) { updateFinishedCallback.onUpdateFinished(); } } }; task.execute(); }
From source file:edu.harvard.i2b2.fhir.FetchInterceptor.java
void alterResponse(HttpServletResponse response, String path) throws IOException { ourLog.info("altering response"); RestTemplate restTemplate = new MyGlobal().getRestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.set("Accept", "application/json"); HttpEntity entity = new HttpEntity(headers); Map<String, String> params = new HashMap<String, String>(); String url = "http://localhost:8080/fhirRest/" + path; UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url); HttpEntity<String> responseEntity = restTemplate.exchange(builder.build().encode().toUri(), HttpMethod.GET, entity, String.class); String responseTxt = responseEntity.getBody(); response.getWriter().println(responseTxt); }
From source file:com.catalog.core.Api.java
@Override public int login(String username, String password) { setStartTime();//from w w w . j a v a 2 s . c om String url = "http://" + IP + EXTENSION + "/resources/j_spring_security_check"; // Set the username and password for creating a Basic Auth request HttpAuthentication authHeader = new HttpBasicAuthentication(username, password); HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setAuthorization(authHeader); HttpEntity<?> requestEntity = new HttpEntity<Object>(requestHeaders); // Create a new RestTemplate instance RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter()); // Make the HTTP GET request, marshaling the response from JSON to // an array of Events try { restTemplate.exchange(url, HttpMethod.GET, requestEntity, Object.class); } catch (Exception e) { // Unauthorized, probably. // maybe check for network status? e.printStackTrace(); if (e.getMessage().contains("Unauthorized")) return UNAUTHORIZED; return BAD_CONNECTION; } // everything went fine setLoginCredentials(username, password); getElapsedTime("login - "); return SUCCESS; }
From source file:com.jvoid.core.controller.HomeController.java
@RequestMapping(value = "/login", method = RequestMethod.POST) public @ResponseBody String loginToJvoid( @RequestParam(required = false, value = "params") JSONObject jsonParams) { System.out.println("Login:jsonParams=>" + jsonParams.toString()); RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON_VALUE); UriComponentsBuilder builder = UriComponentsBuilder .fromHttpUrl(ServerUris.CUSTOMER_SERVER_URI + URIConstants.GET_CUSTOMER_BY_EMAIL) .queryParam("params", jsonParams); HttpEntity<?> entity = new HttpEntity<>(headers); HttpEntity<String> returnString = restTemplate.exchange(builder.build().toUri(), HttpMethod.GET, entity, String.class); return returnString.getBody(); }
From source file:com.jvoid.core.controller.HomeController.java
@RequestMapping(value = "/password-reset", method = RequestMethod.POST) public @ResponseBody String jvoidResetPAssword( @RequestParam(required = false, value = "params") JSONObject jsonParams) { System.out.println("Login:jsonParams=>" + jsonParams.toString()); RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON_VALUE); UriComponentsBuilder builder = UriComponentsBuilder .fromHttpUrl(ServerUris.CUSTOMER_SERVER_URI + URIConstants.RESET_CUSTOMER_PASSWORD) .queryParam("params", jsonParams); HttpEntity<?> entity = new HttpEntity<>(headers); HttpEntity<String> returnString = restTemplate.exchange(builder.build().toUri(), HttpMethod.GET, entity, String.class); return returnString.getBody(); }
From source file:com.fredhopper.core.connector.index.upload.impl.RestPublishingStrategy.java
@Override public String uploadDataSet(final InstanceConfig config, final File file) throws ResponseStatusException { Preconditions.checkArgument(config != null); Preconditions.checkArgument(file != null); final RestTemplate restTemplate = restTemplateProvider.createTemplate(config.getHost(), config.getPort(), config.getUsername(), config.getPassword()); final String checkSum = createCheckSum(file); final List<NameValuePair> params = Arrays .asList(new NameValuePair[] { new BasicNameValuePair("checksum", checkSum) }); final URI url = createUri(config.getScheme(), config.getHost(), config.getPort(), config.getServername(), UPLOAD_PATH, params);/* www. j a va 2s.c o m*/ final HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.valueOf("application/zip")); final HttpEntity<Resource> httpEntity = new HttpEntity<>(new FileSystemResource(file), headers); final ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.PUT, httpEntity, String.class); final HttpStatus status = response.getStatusCode(); if (status.equals(HttpStatus.CREATED)) { return response.getBody().trim(); } else { throw new ResponseStatusException( "HttpStatus " + status.toString() + " response received. File upload failed."); } }
From source file:io.seldon.client.services.ApiServiceImpl.java
private ResourceBean getResource(final String url, Class<?> c) { logger.info("* GET Endpoint: " + url); ResourceBean bean;/*from w w w .j a v a2 s . c om*/ if (token == null) { ResourceBean r = getToken(); if (r instanceof ErrorBean) return r; } String urlWithToken = url + "&oauth_token=" + token; logger.debug("** Token: " + token); logger.debug("** Class: " + c.getName()); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> entity = new HttpEntity<String>(headers); RestTemplate restTemplate = createRestTemplate(); try { //logger.info("Calling end point: " + urlWithToken + " for class: " + c.getName()); @SuppressWarnings("unchecked") HttpEntity<ResourceBean> res = (HttpEntity<ResourceBean>) restTemplate.exchange(urlWithToken, HttpMethod.GET, entity, c); logger.debug("Result: " + res.toString() + " : " + res.getBody()); bean = res.getBody(); logger.debug("*** OK (" + urlWithToken + ")"); } catch (Exception e) { if (e.getCause() instanceof SocketTimeoutException) { return createTimeoutBean(); } logger.error("Exception class: " + e.getClass()); //logger.error("Failed Api Call for url: " + urlWithToken + " : " + e.toString()); logger.error("*** NOK (" + urlWithToken + "): " + e.getMessage()); HttpEntity<ErrorBean> res = null; try { res = restTemplate.exchange(urlWithToken, HttpMethod.GET, entity, ErrorBean.class); } catch (RestClientException e1) { if (e1.getCause() instanceof SocketTimeoutException) { return createTimeoutBean(); } } bean = res.getBody(); } if (bean instanceof ErrorBean) { if (((ErrorBean) bean).getError_id() != Constants.TOKEN_EXPIRED) { return bean; } else { logger.info("Token expired; fetching a new one."); ResourceBean r = getToken(); if (r instanceof ErrorBean) { return r; } else { return getResource(url, c); } } } else { return bean; } }
From source file:org.apache.servicecomb.demo.springmvc.client.SpringmvcClient.java
private static void testController(RestTemplate template, String microserviceName) { String prefix = "cse://" + microserviceName; TestMgr.check(7, template.getForObject(prefix + "/controller/add?a=3&b=4", Integer.class)); try {// ww w. j a v a 2 s. co m template.getForObject(prefix + "/controller/add", Integer.class); TestMgr.check("failed", "success"); } catch (InvocationException e) { TestMgr.check(e.getStatusCode(), 400); } TestMgr.check("hi world [world]", template.getForObject(prefix + "/controller/sayhi?name=world", String.class)); TestMgr.check("hi world1 [world1]", template.getForObject(prefix + "/controller/sayhi?name={name}", String.class, "world1")); TestMgr.check("hi hi [hi ]", template.getForObject(prefix + "/controller/sayhi?name={name}", String.class, "hi ")); Map<String, String> params = new HashMap<>(); params.put("name", "world2"); TestMgr.check("hi world2 [world2]", template.getForObject(prefix + "/controller/sayhi?name={name}", String.class, params)); TestMgr.check("hello world", template.postForObject(prefix + "/controller/sayhello/{name}", null, String.class, "world")); TestMgr.check("hello hello ", template.postForObject(prefix + "/controller/sayhello/{name}", null, String.class, "hello ")); HttpHeaders headers = new HttpHeaders(); headers.add("name", "world"); @SuppressWarnings("rawtypes") HttpEntity entity = new HttpEntity<>(null, headers); ResponseEntity<String> response = template.exchange(prefix + "/controller/sayhei", HttpMethod.GET, entity, String.class); TestMgr.check("hei world", response.getBody()); Person user = new Person(); user.setName("world"); TestMgr.check("ha world", template.postForObject(prefix + "/controller/saysomething?prefix={prefix}", user, String.class, "ha")); }
From source file:com.catalog.core.Api.java
@Override public TeacherVM getTeacher() { setStartTime();/* w w w .j ava 2 s . co m*/ HttpEntity<?> requestEntity = getAuthHttpEntity(); RestTemplate restTemplate = new RestTemplate(); String url = "http://" + IP + EXTENSION + "/teacher/getCurrentT"; restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter()); ResponseEntity<TeacherVM> responseEntity = null; TeacherVM teacher = null; try { responseEntity = restTemplate.exchange(url, HttpMethod.GET, requestEntity, TeacherVM.class); teacher = responseEntity.getBody(); } catch (RestClientException e) { return null; } Log.d("TAAAG", teacher.toString()); getElapsedTime("getTeacher - "); return teacher; }
From source file:com.jvoid.core.controller.HomeController.java
@RequestMapping(value = "/jvoid-checkout-cart", method = RequestMethod.POST) public @ResponseBody String jvoidChrckoutCart(@RequestParam("params") String jsonParams) { RestTemplate restTemplate = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.set("Accept", MediaType.APPLICATION_JSON_VALUE); System.out.println("jsonParams=>" + jsonParams); UriComponentsBuilder builder = UriComponentsBuilder .fromHttpUrl(ServerUris.QUOTE_SERVER_URI + URIConstants.CHECKOUT_CART) .queryParam("params", jsonParams); HttpEntity<?> entity = new HttpEntity<>(headers); HttpEntity<String> returnString = restTemplate.exchange(builder.build().toUri(), HttpMethod.GET, entity, String.class); JSONObject returnJsonObj = null;// w w w.j a va 2 s . c o m try { returnJsonObj = new JSONObject(returnString.getBody()); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("returnJsonObj=>" + returnJsonObj); String result = ""; try { result = returnJsonObj.getString("result"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } String response = ""; if (result.equals("Success")) { UriComponentsBuilder builder1 = UriComponentsBuilder .fromHttpUrl(ServerUris.ORDER_SERVER_URI + URIConstants.ADD_ORDER) .queryParam("params", jsonParams); HttpEntity<?> entity1 = new HttpEntity<>(headers); HttpEntity<String> returnString1 = restTemplate.exchange(builder1.build().toUri(), HttpMethod.GET, entity1, String.class); response = returnString1.getBody(); } return response; }