List of usage examples for org.springframework.http.client ClientHttpResponse getBody
InputStream getBody() throws IOException;
From source file:de.blizzy.documentr.system.Downloader.java
String getTextFromUrl(String url, Charset encoding) throws IOException { ClientHttpResponse response = null; try {//from w w w . j a v a 2 s. com SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); requestFactory.setConnectTimeout((int) TIMEOUT); requestFactory.setReadTimeout((int) TIMEOUT); ClientHttpRequest request = requestFactory.createRequest(URI.create(url), HttpMethod.GET); response = request.execute(); HttpStatus status = response.getStatusCode(); if (status.series() == Series.SUCCESSFUL) { return IOUtils.toString(response.getBody(), encoding); } } finally { if (response != null) { response.close(); } } return null; }
From source file:com.codeabovelab.dm.gateway.filestorage.GetResponseExtractor.java
@Override public Object extractData(ClientHttpResponse response) throws IOException { HttpHeaders headers = new HttpHeaders(); headers.putAll(response.getHeaders()); for (Map.Entry<String, List<String>> e : headers.entrySet()) { List<String> values = e.getValue(); for (int i = 0; i < values.size(); i++) { final String key = e.getKey(); if (FORBIDDEN_HEADERS.contains(key)) { continue; }// w w w . j a v a2 s .c om servletResponse.setHeader(key, values.get(i)); } } try (InputStream is = response.getBody(); ServletOutputStream os = servletResponse.getOutputStream()) { IOUtils.copy(is, os); servletResponse.flushBuffer(); } return null; }
From source file:fi.helsinki.opintoni.integration.interceptor.OodiExceptionInterceptor.java
@Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { ClientHttpResponse response = execution.execute(request, body); /*/* ww w.ja v a2 s . c o m*/ * The following code cannot be run with test profile, because it uses MockClientHttpResponse * that does not allow getBody() to be called multiple times even when using BufferingClientHttpRequestFactory */ if (env.acceptsProfiles(Constants.SPRING_PROFILE_LOCAL_DEVELOPMENT, Constants.SPRING_PROFILE_DEMO, Constants.SPRING_PROFILE_QA, Constants.SPRING_PROFILE_PRODUCTION)) { if (HttpStatus.OK.equals(response.getStatusCode())) { JsonHttpStatus jsonHttpStatus = objectMapper.readValue(response.getBody(), JsonHttpStatus.class); if (jsonHttpStatus.is5xxError()) { throw new RestClientServiceException( String.format("%s returned a %s response", request.getURI(), jsonHttpStatus.status)); } } } return response; }
From source file:com.goldengekko.meetr.service.sugarcrm.SugarCRMClient.java
public String getToken(String user, String password) { LOG.debug("Get SugarCRM token"); if (null == user || null == password || user.isEmpty() || password.isEmpty()) { LOG.info("User and password must be provided when creating token"); throw new BadRequestException(ERR_MISSING_USER_PASSWORD, "User and password must be provided when creating token"); }/*from w ww .j a va 2s . co m*/ String data = String.format( "{\"user_auth\":{\"user_name\":\"%s\",\"password\":\"%s\",\"version\":\"%s\"},\"application_name\":\"%s\"}", this.user, md5Hash(this.password), "1.0", "Meeter"); //LOG.debug("Send login with data:{}", data); this.token = TEMPLATE.execute(this.sugarCRMUrl + PARAM_TEMPLATE, HttpMethod.GET, new RequestCallback() { @Override public void doWithRequest(ClientHttpRequest clientHttpRequest) throws IOException { LOG.debug("Sending login request with url:{}", clientHttpRequest.getURI().toURL().toExternalForm()); } }, new ResponseExtractor<String>() { @Override public String extractData(ClientHttpResponse clientHttpResponse) throws IOException { LOG.debug("Response with http code:{}", clientHttpResponse.getStatusCode().value()); if (clientHttpResponse.getStatusCode() == HttpStatus.OK) { SugarCRMLoginResponse response = MAPPER.readValue(clientHttpResponse.getBody(), SugarCRMLoginResponse.class); LOG.debug("Response:{}", response); if (!response.hasError()) { return response.getId(); } else if (response.isInvalidCredentials()) { LOG.info("SugarCRM login failed with invalid credentials", new StringHttpMessageConverter().read(String.class, clientHttpResponse)); throw new RestException(ERR_SUGAR_LOGIN_FAILED, HttpStatus.FORBIDDEN, "SugarCRM login failed with invalid credentials"); } else { LOG.info("SugarCRM login failed with unknown reason:{}", new StringHttpMessageConverter().read(String.class, clientHttpResponse)); throw new RestException(ERR_SUGAR_LOGIN_FAILED, HttpStatus.FORBIDDEN, "SugarCRM login failed with unknown reason"); } } else { // If the SugarCRM does not respond with 200 throw http 503 LOG.warn("SugarCRM is responding with http code:{}", clientHttpResponse.getStatusCode().value()); throw new RestException(ERR_SUGAR_NOT_AVAILABLE, HttpStatus.SERVICE_UNAVAILABLE, "SugarCRM request failed"); } } }, "login", "json", "json", data); LOG.debug("Got token:{}", this.token); return this.token; }
From source file:com.goldengekko.meetr.service.sugarcrm.SugarCRMClient.java
@Override public CursorPage<DmContact> getPage(int pageSize, String cursorKey) { LOG.debug("SugarCRM client, get contacts. Token:{}", token); // Check that we have a token if (null == this.token || null == token) { throw new RestException(ERR_SUGAR_INVALID_TOKEN, HttpStatus.FORBIDDEN, "Token missing, app must generate token first"); }/*from ww w .j ava 2 s. c o m*/ // If the cursor is null start from the beginning if (null == cursorKey) { cursorKey = "0"; } // The request // {"session":"f9psqc1rgd2iuri76u3v17aul1","module_name":"Contacts","query":"","order_by":"","offset":1,"select_fields":["id","name"],"link_name_to_fields_array":[],"max_results":2,"deleted":0,"Favorites":0} String data = String.format( "{\"session\":\"%s\",\"module_name\":\"Contacts\",\"query\":\"\",\"order_by\":\"\",\"offset\":%s,\"select_fields\":[\"id\",\"first_name\",\"last_name\",\"email\",\"phone_work\",\"primary_address_street\",\"primary_address_city\",\"primary_address_country\",\"primary_address_postalcode\"],\"link_name_to_fields_array\":[],\"max_results\":%s,\"deleted\":0,\"Favorites\":0}", this.token, cursorKey.toString(), pageSize); LOG.debug("get contacts with data:{}", data); SugarCRMContactsResponse contacts = TEMPLATE.execute(this.sugarCRMUrl + PARAM_TEMPLATE, HttpMethod.GET, new RequestCallback() { @Override public void doWithRequest(ClientHttpRequest clientHttpRequest) throws IOException { LOG.debug("Sending get contact request with url:{}", clientHttpRequest.getURI().toURL().toExternalForm()); } }, new ResponseExtractor<SugarCRMContactsResponse>() { @Override public SugarCRMContactsResponse extractData(ClientHttpResponse clientHttpResponse) throws IOException { LOG.debug("Response with http code:{}", clientHttpResponse.getStatusCode().value()); if (clientHttpResponse.getStatusCode() == HttpStatus.OK) { SugarCRMContactsResponse response = MAPPER.readValue(clientHttpResponse.getBody(), SugarCRMContactsResponse.class); LOG.debug("Response:{}", response); if (!response.hasError()) { return response; } else if (response.isTokenInvalid()) { LOG.info("Get contacts failed, invalid token"); throw new RestException(ERR_SUGAR_INVALID_TOKEN, HttpStatus.FORBIDDEN, "SugarCRM get contacts failed, invalid token"); } else { LOG.info("SugarCRM get contacts failed with unknown reason:{}", new StringHttpMessageConverter().read(String.class, clientHttpResponse)); throw new RestException(ERR_SUGAR_GET_CONTACTS_FAILED, HttpStatus.SERVICE_UNAVAILABLE, "SugarCRM get contacts failed with unknown reason"); } } else { // If the SugarCRM does not respond with 200 throw http 503 LOG.warn("SugarCRM is responding with http code:{}", clientHttpResponse.getStatusCode().value()); throw new RestException(ERR_SUGAR_NOT_AVAILABLE, HttpStatus.SERVICE_UNAVAILABLE, "SugarCRM request failed"); } } }, "get_entry_list", "json", "json", data); LOG.debug("Got number of contacts:{}", contacts.getResult_count()); CursorPage<DmContact> page = convertToPage(contacts, pageSize); return page; }
From source file:io.github.microcks.util.test.HttpTestRunner.java
@Override public List<TestReturn> runTest(Service service, Operation operation, TestResult testResult, List<Request> requests, String endpointUrl, HttpMethod method) throws URISyntaxException, IOException { if (log.isDebugEnabled()) { log.debug("Launching test run on " + endpointUrl + " for " + requests.size() + " request(s)"); }// w w w . j av a2 s . c o m // Initialize result container. List<TestReturn> result = new ArrayList<TestReturn>(); for (Request request : requests) { // Reset status code, message and request each time. int code = TestReturn.SUCCESS_CODE; String message = null; String customizedEndpointUrl = endpointUrl; if (service.getType().equals(ServiceType.REST)) { String operationName = operation.getName(); // Name may start with verb, remove it if present. if (operationName.indexOf(' ') > 0 && operationName.indexOf(' ') < operationName.length()) { operationName = operationName.split(" ")[1]; } customizedEndpointUrl += URIBuilder.buildURIFromPattern(operationName, request.getQueryParameters()); log.debug("Using customized endpoint url: " + customizedEndpointUrl); } ClientHttpRequest httpRequest = clientHttpRequestFactory.createRequest(new URI(customizedEndpointUrl), method); // Set headers to request if any. Set<Header> headers = request.getHeaders(); if (headers != null && headers.size() > 0) { for (Header header : headers) { httpRequest.getHeaders().add(header.getName(), buildValue(header.getValues())); } } // If there's input content, add it to request. if (request.getContent() != null) { httpRequest.getBody().write(request.getContent().getBytes()); } // Actually execute request. long startTime = System.currentTimeMillis(); ClientHttpResponse httpResponse = null; try { httpResponse = httpRequest.execute(); } catch (IOException ioe) { log.error("IOException while executing request " + request.getName() + " on " + endpointUrl, ioe); code = TestReturn.FAILURE_CODE; message = ioe.getMessage(); } long duration = System.currentTimeMillis() - startTime; // Extract and store response body so that stream may not be consumed more than o1 time ;-) String responseContent = null; if (httpResponse != null) { StringWriter writer = new StringWriter(); IOUtils.copy(httpResponse.getBody(), writer); responseContent = writer.toString(); } // If still in success, check if http code is out of correct ranges (20x and 30x). if (code == TestReturn.SUCCESS_CODE) { code = extractTestReturnCode(service, operation, request, httpResponse, responseContent); message = extractTestReturnMessage(service, operation, request, httpResponse); } // Create a Response object for returning. Response response = new Response(); if (httpResponse != null) { response.setContent(responseContent); response.setStatus(String.valueOf(httpResponse.getRawStatusCode())); response.setMediaType(httpResponse.getHeaders().getContentType().toString()); headers = buildHeaders(httpResponse); if (headers != null) { response.setHeaders(headers); } } result.add(new TestReturn(code, duration, message, request, response)); } return result; }
From source file:com.neiljbrown.brighttalk.channels.reportingapi.client.spring.ApiResponseErrorHandlerTest.java
/** * Creates a mock implementation of {@link ClientHttpResponse} and configures it to return supplied data. * <p>//from w w w . j a v a 2 s .c o m * ClientHttpResponse needs mocking for test fixtures which rely on setting response headers as for some reason Spring * 4.0's MockClientHttpResponse doesn't support setting response headers. * * @param httpStatus The {@link HttpStatus} which the mock should be configured to return for invocations of * {@link ClientHttpResponse#getStatusCode()}. * @param headers The {@link HttpHeaders} which the mock should be configured to return for invocations of * {@link ClientHttpResponse#getHeaders()}. * @param body A string representation of the data which the mock should be configured to return for invocations of * {@link ClientHttpResponse#getBody()}. * @return The created {@link ClientHttpResponse}. */ private ClientHttpResponse createMockClientHttpResponse(HttpStatus httpStatus, HttpHeaders headers, final String body) { ClientHttpResponse mockClientHttpResponse = EasyMock.createNiceMock(ClientHttpResponse.class); try { EasyMock.expect(mockClientHttpResponse.getStatusCode()).andReturn(httpStatus).anyTimes(); EasyMock.expect(mockClientHttpResponse.getRawStatusCode()).andReturn(httpStatus.value()).anyTimes(); EasyMock.expect(mockClientHttpResponse.getHeaders()).andReturn(headers).anyTimes(); // Return a new InputStream for each call to ClientHttpResponse.getBody() rather than an exhausted one IAnswer<InputStream> iAnswer = new IAnswer<InputStream>() { public InputStream answer() { return body != null ? new ByteArrayInputStream(body.getBytes()) : null; } }; EasyMock.expect(mockClientHttpResponse.getBody()).andAnswer(iAnswer).anyTimes(); } catch (IOException e) { throw new RuntimeException(e); } return mockClientHttpResponse; }
From source file:org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfigurationTests.java
private void assertContent(String scheme, String url, int port, Object expected) throws Exception { SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory( new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory( httpClient);/*from w ww . ja va 2s . c o m*/ ClientHttpRequest request = requestFactory.createRequest(new URI(scheme + "://localhost:" + port + url), HttpMethod.GET); try { ClientHttpResponse response = request.execute(); if (HttpStatus.NOT_FOUND.equals(response.getStatusCode())) { throw new FileNotFoundException(); } try { String actual = StreamUtils.copyToString(response.getBody(), Charset.forName("UTF-8")); if (expected instanceof Matcher) { assertThat(actual).is(Matched.by((Matcher<?>) expected)); } else { assertThat(actual).isEqualTo(expected); } } finally { response.close(); } } catch (Exception ex) { if (expected == null) { if (SocketException.class.isInstance(ex) || FileNotFoundException.class.isInstance(ex)) { return; } } throw ex; } }