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.alfresco.integrations.google.docs.service.GoogleDocsServiceImpl.java
private InputStream getFileInputStream(DriveFile driveFile, String mimetype) throws GoogleDocsAuthenticationException, GoogleDocsRefreshTokenException, GoogleDocsServiceException { RestTemplate restTemplate = new RestTemplate(); String url = getExportLink(driveFile, mimetype); log.debug("Google Export Format (mimetype) link: " + url); if (url == null) { throw new GoogleDocsServiceException("Google Docs Export Format not found.", HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE); }// www. j av a 2 s. co m HttpHeaders headers = new HttpHeaders(); headers.add("Authorization", "Bearer " + getConnection().getApi().getAccessToken()); MultiValueMap<String, Object> body = new LinkedMultiValueMap<String, Object>(); HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<MultiValueMap<String, Object>>(body, headers); ResponseEntity<byte[]> response = restTemplate.exchange(url, HttpMethod.GET, entity, byte[].class); return new ByteArrayInputStream(response.getBody()); }
From source file:org.venice.piazza.servicecontroller.messaging.ServiceMessageWorker.java
/** * This method is for demonstrating ingest of raster data This will be * refactored once the API changes have been communicated to other team * members//w w w . jav a 2s. c om */ public void handleRasterType(ExecuteServiceJob executeJob, Job job, Producer<String, String> producer) { RestTemplate restTemplate = new RestTemplate(); ExecuteServiceData data = executeJob.data; // Get the id from the data String serviceId = data.getServiceId(); Service sMetadata = accessor.getServiceById(serviceId); // Default request mimeType application/json String requestMimeType = "application/json"; new LinkedMultiValueMap<String, String>(); UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(sMetadata.getUrl()); Map<String, DataType> postObjects = new HashMap<String, DataType>(); Iterator<Entry<String, DataType>> it = data.getDataInputs().entrySet().iterator(); String postString = ""; while (it.hasNext()) { Entry<String, DataType> entry = it.next(); String inputName = entry.getKey(); if (entry.getValue() instanceof URLParameterDataType) { String paramValue = ((TextDataType) entry.getValue()).getContent(); if (inputName.length() == 0) { builder = UriComponentsBuilder.fromHttpUrl(sMetadata.getUrl() + "?" + paramValue); } else { builder.queryParam(inputName, paramValue); } } else if (entry.getValue() instanceof BodyDataType) { BodyDataType bdt = (BodyDataType) entry.getValue(); postString = bdt.getContent(); requestMimeType = bdt.getMimeType(); } // Default behavior for other inputs, put them in list of objects // which are transformed into JSON consistent with default // requestMimeType else { postObjects.put(inputName, entry.getValue()); } } if (postString.length() > 0 && postObjects.size() > 0) { return; } else if (postObjects.size() > 0) { ObjectMapper mapper = makeNewObjectMapper(); try { postString = mapper.writeValueAsString(postObjects); } catch (JsonProcessingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } URI url = URI.create(builder.toUriString()); HttpHeaders headers = new HttpHeaders(); // Set the mimeType of the request MediaType mediaType = createMediaType(requestMimeType); headers.setContentType(mediaType); // Set the mimeType of the request // headers.add("Content-type", // sMetadata.getOutputs().get(0).getDataType().getMimeType()); if (postString.length() > 0) { coreLogger.log("The postString is " + postString, PiazzaLogger.DEBUG); HttpHeaders theHeaders = new HttpHeaders(); // headers.add("Authorization", "Basic " + credentials); theHeaders.setContentType(MediaType.APPLICATION_JSON); // Create the Request template and execute HttpEntity<String> request = new HttpEntity<String>(postString, theHeaders); try { coreLogger.log("About to call special service " + url, PiazzaLogger.DEBUG); ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, request, String.class); coreLogger.log("The Response is " + response.getBody(), PiazzaLogger.DEBUG); String serviceControlString = response.getBody(); coreLogger.log("Service Control String " + serviceControlString, PiazzaLogger.DEBUG); ObjectMapper tempMapper = makeNewObjectMapper(); DataResource dataResource = tempMapper.readValue(serviceControlString, DataResource.class); coreLogger.log("dataResource type is " + dataResource.getDataType().getClass().getSimpleName(), PiazzaLogger.DEBUG); dataResource.dataId = uuidFactory.getUUID(); coreLogger.log("dataId " + dataResource.dataId, PiazzaLogger.DEBUG); PiazzaJobRequest pjr = new PiazzaJobRequest(); pjr.createdBy = "pz-sc-ingest-raster-test"; IngestJob ingestJob = new IngestJob(); ingestJob.data = dataResource; ingestJob.host = true; pjr.jobType = ingestJob; ProducerRecord<String, String> newProdRecord = JobMessageFactory.getRequestJobMessage(pjr, uuidFactory.getUUID(), SPACE); producer.send(newProdRecord); coreLogger.log("newProdRecord sent " + newProdRecord.toString(), PiazzaLogger.DEBUG); StatusUpdate statusUpdate = new StatusUpdate(StatusUpdate.STATUS_SUCCESS); // Create a text result and update status DataResult textResult = new DataResult(dataResource.dataId); statusUpdate.setResult(textResult); ProducerRecord<String, String> prodRecord = JobMessageFactory.getUpdateStatusMessage(job.getJobId(), statusUpdate, SPACE); producer.send(prodRecord); coreLogger.log("prodRecord sent " + prodRecord.toString(), PiazzaLogger.DEBUG); } catch (JsonProcessingException jpe) { jpe.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } } }
From source file:org.apache.fineract.restwebservice.PlatformRestClient.java
/** * Executes a HTTP request using the spring framework RestTemplate * // www . j a v a2 s.c o m * @param url the URL * @param method the HTTP method (GET, POST, etc) * @param requestEntity the entity (headers and/or body) to write to the request, may be null * @param responseType the type of the return value * @return the response as entity * @throws InterruptedException * @throws RestClientException */ public <T> ResponseEntity<T> executeHttpRequest(final URI url, final HttpMethod method, final HttpEntity<?> requestEntity, final Class<T> responseType) { final RestTemplate restTemplate = new RestTemplate(); HttpStatus statusCode = null; ResponseEntity<T> responseEntity = null; // increment the number of request attempts by 1 this.numberOfHttpRequestAttempts++; try { // execute the HTTP request responseEntity = restTemplate.exchange(url, method, requestEntity, responseType); statusCode = responseEntity.getStatusCode(); // catch all server HTTP error exceptions } catch (HttpServerErrorException exception) { statusCode = exception.getStatusCode(); // if HTTP status is 503 or 504, sleep for 5 seconds and retry if ((statusCode.equals(HttpStatus.SERVICE_UNAVAILABLE) || statusCode.equals(HttpStatus.GATEWAY_TIMEOUT)) && (this.numberOfHttpRequestAttempts < this.numberOfHttpRequestRetries)) { logger.info("Server returned an error response with status: " + statusCode + ", retrying again in 5 seconds"); logger.info("Number of attempts: " + this.numberOfHttpRequestAttempts); try { // sleep for 5 seconds and try again Thread.sleep(5000); } catch (InterruptedException interruptedException) { logger.error(interruptedException.getMessage(), interruptedException); } // execute HTTP request again this.executeHttpRequest(url, method, requestEntity, responseType); } else { // in other cases, throw back the exception throw exception; } } return responseEntity; }
From source file:org.apache.servicecomb.demo.springmvc.client.CodeFirstRestTemplateSpringmvc.java
private void testResponseEntity(String microserviceName, RestTemplate template, String cseUrlPrefix) { Map<String, Object> body = new HashMap<>(); Date date = new Date(); body.put("date", date); CseHttpEntity<Map<String, Object>> httpEntity = new CseHttpEntity<>(body); httpEntity.addContext("contextKey", "contextValue"); String srcName = RegistryUtils.getMicroservice().getServiceName(); ResponseEntity<Date> responseEntity = template.exchange(cseUrlPrefix + "responseEntity", HttpMethod.POST, httpEntity, Date.class); TestMgr.check(date, responseEntity.getBody()); TestMgr.check("h1v " + srcName, responseEntity.getHeaders().getFirst("h1")); TestMgr.check("h2v " + srcName, responseEntity.getHeaders().getFirst("h2")); checkStatusCode(microserviceName, 202, responseEntity.getStatusCode()); responseEntity = template.exchange(cseUrlPrefix + "responseEntity", HttpMethod.PATCH, httpEntity, Date.class); TestMgr.check(date, responseEntity.getBody()); TestMgr.check("h1v " + srcName, responseEntity.getHeaders().getFirst("h1")); TestMgr.check("h2v " + srcName, responseEntity.getHeaders().getFirst("h2")); checkStatusCode(microserviceName, 202, responseEntity.getStatusCode()); int retryResult = template.getForObject(cseUrlPrefix + "retrySuccess?a=2&b=3", Integer.class); TestMgr.check(retryResult, 5);//w w w . ja v a 2 s . c o m }
From source file:org.apache.zeppelin.livy.BaseLivyInterprereter.java
private String callRestAPI(String targetURL, String method, String jsonData) throws LivyException { targetURL = livyURL + targetURL;/*from w w w.ja v a 2 s. co m*/ LOGGER.debug("Call rest api in {}, method: {}, jsonData: {}", targetURL, method, jsonData); RestTemplate restTemplate = getRestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.add("Content-Type", "application/json"); headers.add("X-Requested-By", "zeppelin"); ResponseEntity<String> response = null; try { if (method.equals("POST")) { HttpEntity<String> entity = new HttpEntity<>(jsonData, headers); response = restTemplate.exchange(targetURL, HttpMethod.POST, entity, String.class); } else if (method.equals("GET")) { HttpEntity<String> entity = new HttpEntity<>(headers); response = restTemplate.exchange(targetURL, HttpMethod.GET, entity, String.class); } else if (method.equals("DELETE")) { HttpEntity<String> entity = new HttpEntity<>(headers); response = restTemplate.exchange(targetURL, HttpMethod.DELETE, entity, String.class); } } catch (HttpClientErrorException e) { response = new ResponseEntity(e.getResponseBodyAsString(), e.getStatusCode()); LOGGER.error(String.format("Error with %s StatusCode: %s", response.getStatusCode().value(), e.getResponseBodyAsString())); } if (response == null) { throw new LivyException("No http response returned"); } LOGGER.debug("Get response, StatusCode: {}, responseBody: {}", response.getStatusCode(), response.getBody()); if (response.getStatusCode().value() == 200 || response.getStatusCode().value() == 201) { return response.getBody(); } else if (response.getStatusCode().value() == 404) { if (response.getBody().matches("\"Session '\\d+' not found.\"")) { throw new SessionNotFoundException(response.getBody()); } else { throw new APINotFoundException( "No rest api found for " + targetURL + ", " + response.getStatusCode()); } } else { String responseString = response.getBody(); if (responseString.contains("CreateInteractiveRequest[\\\"master\\\"]")) { return responseString; } throw new LivyException(String.format("Error with %s StatusCode: %s", response.getStatusCode().value(), responseString)); } }
From source file:org.apache.zeppelin.livy.LivyHelper.java
protected String executeHTTP(String targetURL, String method, String jsonData, String paragraphId) throws Exception { LOGGER.debug("Call rest api in {}, method: {}, jsonData: {}", targetURL, method, jsonData); RestTemplate restTemplate = getRestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.add("Content-Type", "application/json"); headers.add("X-Requested-By", "zeppelin"); ResponseEntity<String> response = null; try {/*w w w . ja va2 s.com*/ if (method.equals("POST")) { HttpEntity<String> entity = new HttpEntity<>(jsonData, headers); response = restTemplate.exchange(targetURL, HttpMethod.POST, entity, String.class); paragraphHttpMap.put(paragraphId, response); } else if (method.equals("GET")) { HttpEntity<String> entity = new HttpEntity<>(headers); response = restTemplate.exchange(targetURL, HttpMethod.GET, entity, String.class); paragraphHttpMap.put(paragraphId, response); } else if (method.equals("DELETE")) { HttpEntity<String> entity = new HttpEntity<>(headers); response = restTemplate.exchange(targetURL, HttpMethod.DELETE, entity, String.class); } } catch (HttpClientErrorException e) { response = new ResponseEntity(e.getResponseBodyAsString(), e.getStatusCode()); LOGGER.error(String.format("Error with %s StatusCode: %s", response.getStatusCode().value(), e.getResponseBodyAsString())); } if (response == null) { return null; } if (response.getStatusCode().value() == 200 || response.getStatusCode().value() == 201 || response.getStatusCode().value() == 404) { return response.getBody(); } else { String responseString = response.getBody(); if (responseString.contains("CreateInteractiveRequest[\\\"master\\\"]")) { return responseString; } LOGGER.error(String.format("Error with %s StatusCode: %s", response.getStatusCode().value(), responseString)); throw new Exception(String.format("Error with %s StatusCode: %s", response.getStatusCode().value(), responseString)); } }
From source file:org.cloudfoundry.identity.uaa.integration.feature.SamlLoginWithLocalIdpIT.java
public static SamlIdentityProviderDefinition createLocalSamlIdpDefinition(String alias, String zoneId) { String url;//ww w. j a va2 s.c o m if (StringUtils.isNotEmpty(zoneId) && !zoneId.equals("uaa")) { url = "http://" + zoneId + ".localhost:8080/uaa/saml/idp/metadata"; } else { url = "http://localhost:8080/uaa/saml/idp/metadata"; } RestTemplate client = new RestTemplate(); MultiValueMap<String, String> headers = new LinkedMultiValueMap<>(); headers.add("Accept", "application/samlmetadata+xml"); headers.add(IdentityZoneSwitchingFilter.HEADER, zoneId); HttpEntity<String> getHeaders = new HttpEntity<String>(headers); ResponseEntity<String> metadataResponse = client.exchange(url, HttpMethod.GET, getHeaders, String.class); String idpMetaData = metadataResponse.getBody(); return SamlTestUtils.createLocalSamlIdpDefinition(alias, zoneId, idpMetaData); }
From source file:org.cloudfoundry.identity.uaa.integration.feature.SamlLoginWithLocalIdpIT.java
public static SamlServiceProviderDefinition createLocalSamlSpDefinition(String alias, String zoneId) { String url;/*ww w .j a v a 2 s . c o m*/ if (StringUtils.isNotEmpty(zoneId) && !zoneId.equals("uaa")) { url = "http://" + zoneId + ".localhost:8080/uaa/saml/metadata/alias/" + zoneId + "." + alias; } else { url = "http://localhost:8080/uaa/saml/metadata/alias/" + alias; } RestTemplate client = new RestTemplate(); MultiValueMap<String, String> headers = new LinkedMultiValueMap<>(); headers.add("Accept", "application/samlmetadata+xml"); headers.add(IdentityZoneSwitchingFilter.HEADER, zoneId); HttpEntity<String> getHeaders = new HttpEntity<String>(headers); ResponseEntity<String> metadataResponse = client.exchange(url, HttpMethod.GET, getHeaders, String.class); String spMetaData = metadataResponse.getBody(); SamlServiceProviderDefinition def = new SamlServiceProviderDefinition(); def.setMetaDataLocation(spMetaData); def.setNameID("urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress"); def.setSingleSignOnServiceIndex(0); def.setMetadataTrustCheck(false); return def; }