List of usage examples for org.springframework.http.client ClientHttpResponse getBody
InputStream getBody() throws IOException;
From source file:fr.itldev.koya.services.impl.util.AlfrescoRestErrorHandler.java
@Override public void handleError(ClientHttpResponse clienthttpresponse) throws IOException { if (!statusOK.contains(clienthttpresponse.getStatusCode())) { AlfrescoServiceException ex;/* ww w . j a v a2s . c o m*/ if (clienthttpresponse.getStatusCode().equals(HttpStatus.INTERNAL_SERVER_ERROR)) { java.util.Scanner s = new java.util.Scanner(clienthttpresponse.getBody()).useDelimiter("\\A"); String message = s.hasNext() ? s.next() : ""; /* Try to get any Koya Error code if exists */ Integer koyaErrorCode = null; Matcher matcher = ERRORCODEPATTERN.matcher(message); if (matcher.find()) { koyaErrorCode = Integer.valueOf(matcher.group(1)); } ex = new AlfrescoServiceException( "Erreur " + clienthttpresponse.getStatusCode() + " : " + clienthttpresponse.getStatusText(), koyaErrorCode); ex.setHttpErrorCode(clienthttpresponse.getStatusCode().value()); } else if (clienthttpresponse.getStatusCode().equals(HttpStatus.FORBIDDEN)) { ex = new AlfrescoServiceException("Acces Denied"); ex.setHttpErrorCode(clienthttpresponse.getStatusCode().value()); } else { ex = new AlfrescoServiceException(); ex.setHttpErrorCode(clienthttpresponse.getStatusCode().value()); throw ex; } throw ex; } }
From source file:org.springframework.social.mixcloud.api.impl.MixcloudErrorHandler.java
@Override public boolean hasError(ClientHttpResponse response) throws IOException { if (super.hasError(response)) { return true; }/*from w ww. j a v a2s . co m*/ // only bother checking the body for errors if we get past the default // error check String content = readFully(response.getBody()); return content.startsWith("{\"error\":"); }
From source file:org.zalando.riptide.OAuth2CompatibilityTest.java
@Test public void responseIsConsumedIfOtherHandlerIsUsed() throws IOException { final RestTemplate template = new RestTemplate(); final MockRestServiceServer server = MockRestServiceServer.createServer(template); server.expect(requestTo(url)).andRespond(withUnauthorizedRequest().body(new byte[] { 0x13, 0x37 })); template.setErrorHandler(new OAuth2ErrorHandler(new PassThroughResponseErrorHandler(), null)); final Rest rest = Rest.create(template); final ClientHttpResponse response = rest.execute(GET, url).dispatch(status(), on(UNAUTHORIZED).capture()) .to(ClientHttpResponse.class); // Since our mocked response is using a byte[] stream we check for the remaining bytes instead // of expecting an "already closed" IOException. assertThat(response.getBody().available(), is(0)); }
From source file:org.springframework.social.betaseries.api.impl.BetaSerieErrorHandler.java
/** * Extract error details from response./* w w w . jav a2 s . com*/ * * @param response * the response * @return the map * @throws IOException * Signals that an I/O exception has occurred. */ @SuppressWarnings("unchecked") private Map<String, Object> extractErrorDetailsFromResponse(ClientHttpResponse response) throws IOException { ObjectMapper mapper = new ObjectMapper(new JsonFactory()); String json = readFully(response.getBody()); System.out.println(json); if (logger.isDebugEnabled()) { logger.debug("Error from BetaSeries: " + json); } try { Map<String, Object> responseMap = mapper.<Map<String, Object>>readValue(json, new TypeReference<Map<String, Object>>() { }); // all beta series response contain a json errors object, even if // there are no error, // only checking if the object contain an "errors" key is not enough // to consider an error occur if (responseMap.containsKey("errors")) { Object errorMap = responseMap.get("errors"); Map<String, Object> errors = new HashMap<String, Object>(); if (errorMap instanceof List) { List<Map<String, Object>> list = (List<Map<String, Object>>) errorMap; if (list.size() > 0) { errors = list.get(0); } } else if (errorMap instanceof Map) { errors = (Map<String, Object>) errorMap; } // checking if the errors Map size is not empty its the best // way to make sure an error occur if (errors != null) { return errors; } } } catch (JsonParseException e) { return null; } return null; }
From source file:com.tyro.oss.pact.spring4.pact.consumer.ReturnExpect.java
private void getOrCreateWorkflowAndAddInteraction(Pact pact, ClientHttpRequest clientRequest, ClientHttpResponse response) throws IOException { String bodyString = StreamUtils.copyToString(response.getBody(), Charset.defaultCharset()); response.getBody().reset();//w w w .j a v a2s . c om Pact.Interaction interaction = new Pact.Interaction(null, new Pact.InteractionRequest(restRequestDescriptor.getMethod(), urlencode(restRequestDescriptor.getUrl()), clientRequest.getHeaders(), extractBodyContent(restRequestDescriptor.getRequest())), new Pact.InteractionResponse(response.getRawStatusCode(), response.getHeaders(), bodyString, schema), objectConverter); Pact.Workflow workflow = pact.getWorkflow(this.workflowId, this.providerStates); workflow.addInteraction(interaction); }
From source file:org.springframework.social.soundcloud.api.impl.SoundCloudErrorHandler.java
@Override public boolean hasError(ClientHttpResponse response) throws IOException { if (super.hasError(response)) { return true; }/*from ww w . j a v a 2s . c om*/ // only bother checking the body for errors if we get past the default error check String content = readFully(response.getBody()); return content.startsWith("{\"errors\":"); }
From source file:com.springsource.insight.plugin.springweb.http.SimpleClientHttpRequestFactoryCollectionAspectTest.java
@Test public void testConnectionFactory() throws Exception { SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); factory.setBufferRequestBody(false); factory.setConnectTimeout(15 * 1000); factory.setReadTimeout(15 * 1000);/*from w w w .j a v a 2 s.c o m*/ URI uri = new URI("http://localhost:" + TEST_PORT + "/testConnectionFactory"); HttpMethod method = HttpMethod.GET; ClientHttpRequest request = factory.createRequest(uri, method); ClientHttpResponse response = request.execute(); assertEquals("Mismatched response code", HttpStatus.OK.value(), response.getRawStatusCode()); BufferedReader rdr = new BufferedReader(new InputStreamReader(response.getBody())); try { for (String line = rdr.readLine(); line != null; line = rdr.readLine()) { logger.info(line); } } finally { rdr.close(); } Operation op = assertConnectionOperation(uri, method); assertExternalResource(op, uri); }
From source file:com.appglu.impl.StorageTemplate.java
protected boolean streamStorageFile(StorageFile file, final InputStreamCallback inputStreamCallback, RequestCallback requestCallback) throws AppGluRestClientException { URI uri = this.getStorageFileURI(file); try {//from www . j a v a 2 s . c om ResponseExtractor<Boolean> responseExtractor = new ResponseExtractor<Boolean>() { public Boolean extractData(ClientHttpResponse response) throws IOException { if (response.getStatusCode() == HttpStatus.NOT_MODIFIED) { return false; } Md5DigestCalculatingInputStream inputStream = new Md5DigestCalculatingInputStream( response.getBody()); inputStreamCallback.doWithInputStream(inputStream); String eTagHeader = response.getHeaders().getETag(); if (StringUtils.isNotEmpty(eTagHeader)) { String eTag = StringUtils.removeDoubleQuotes(eTagHeader); byte[] contentMd5 = inputStream.getMd5Digest(); if (!HashUtils.md5MatchesWithETag(contentMd5, eTag)) { throw new AppGluRestClientException("Unable to verify integrity of downloaded file. " + "Client calculated content hash didn't match hash calculated by server"); } } return true; } }; return this.downloadRestOperations.execute(uri, HttpMethod.GET, requestCallback, responseExtractor); } catch (RestClientException e) { throw new AppGluRestClientException(e.getMessage(), e); } }
From source file:com.netflix.genie.web.services.impl.HttpFileTransferImpl.java
/** * {@inheritDoc}/* w ww . ja v a 2s .c om*/ */ @Override public void getFile(@NotBlank(message = "Source file path cannot be empty.") final String srcRemotePath, @NotBlank(message = "Destination local path cannot be empty") final String dstLocalPath) throws GenieException { final long start = System.nanoTime(); log.debug("Called with src path {} and destination path {}", srcRemotePath, dstLocalPath); try { final File outputFile = new File(dstLocalPath); if (!this.isValid(srcRemotePath)) { throw new GenieServerException("Unable to download " + srcRemotePath + " not a valid URL"); } this.restTemplate.execute(srcRemotePath, HttpMethod.GET, requestEntity -> requestEntity.getHeaders().setAccept(Lists.newArrayList(MediaType.ALL)), new ResponseExtractor<Void>() { @Override public Void extractData(final ClientHttpResponse response) throws IOException { // Documentation I could find pointed to the HttpEntity reading the bytes off // the stream so this should resolve memory problems if the file returned is large FileUtils.copyInputStreamToFile(response.getBody(), outputFile); return null; } }); } finally { this.downloadTimer.record(System.nanoTime() - start, TimeUnit.NANOSECONDS); } }