Java Code Examples for org.apache.http.client.methods.CloseableHttpResponse#setEntity()
The following examples show how to use
org.apache.http.client.methods.CloseableHttpResponse#setEntity() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AuthenticationHandlerTest.java From carbon-device-mgt with Apache License 2.0 | 6 votes |
private CloseableHttpResponse getValidationResponse() throws UnsupportedEncodingException { ValidationResponce response = new ValidationResponce(); response.setDeviceId("1234"); response.setDeviceType("testdevice"); response.setJWTToken("1234567788888888"); response.setTenantId(-1234); Gson gson = new Gson(); String jsonReponse = gson.toJson(response); CloseableHttpResponse mockDCRResponse = new MockHttpResponse(); BasicHttpEntity responseEntity = new BasicHttpEntity(); responseEntity.setContent(new ByteArrayInputStream(jsonReponse.getBytes(StandardCharsets.UTF_8.name()))); responseEntity.setContentType(TestUtils.CONTENT_TYPE); mockDCRResponse.setEntity(responseEntity); mockDCRResponse.setStatusLine(new BasicStatusLine(new ProtocolVersion("http", 1, 0), 200, "OK")); return mockDCRResponse; }
Example 2
Source File: Driver.java From esigate with Apache License 2.0 | 6 votes |
/** * Performs rendering on an HttpResponse. * <p> * Rendering is only performed if page can be parsed. * * @param pageUrl * The remove url from which the body was retrieved. * @param originalRequest * The request received by esigate. * @param response * The response which will be rendered. * @param renderers * list of renderers to apply. * @return The rendered response, or the original response if if was not parsed. * @throws HttpErrorPage * @throws IOException */ private CloseableHttpResponse performRendering(String pageUrl, DriverRequest originalRequest, CloseableHttpResponse response, Renderer[] renderers) throws HttpErrorPage, IOException { if (!contentTypeHelper.isTextContentType(response)) { LOG.debug("'{}' is binary on no transformation to apply: was forwarded without modification.", pageUrl); return response; } LOG.debug("'{}' is text : will apply renderers.", pageUrl); // Get response body String currentValue = HttpResponseUtils.toString(response, this.eventManager); // Perform rendering currentValue = performRendering(pageUrl, originalRequest, response, currentValue, renderers); // Generate the new response. HttpEntity transformedHttpEntity = new StringEntity(currentValue, ContentType.get(response.getEntity())); CloseableHttpResponse transformedResponse = BasicCloseableHttpResponse.adapt(new BasicHttpResponse(response.getStatusLine())); transformedResponse.setHeaders(response.getAllHeaders()); transformedResponse.setEntity(transformedHttpEntity); return transformedResponse; }
Example 3
Source File: SignatureExec.java From wechatpay-apache-httpclient with Apache License 2.0 | 5 votes |
protected void convertToRepeatableResponseEntity(CloseableHttpResponse response) throws IOException { HttpEntity entity = response.getEntity(); if (entity != null) { response.setEntity(new BufferedHttpEntity(entity)); } }
Example 4
Source File: HttpUtilTest.java From sunbird-lms-service with MIT License | 5 votes |
@Test public void testSendPatchRequestSuccess() { Map<String, String> headers = new HashMap<>(); headers.put("Authorization", "123456"); String url = "http://localhost:8000/v1/issuer/issuers"; try { CloseableHttpResponse closeableHttpResponseMock = PowerMockito.mock(CloseableHttpResponse.class); HttpEntity httpEntity = PowerMockito.mock(HttpEntity.class); PowerMockito.when(closeableHttpResponseMock.getStatusLine()) .thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "FINE!")); PowerMockito.when(closeableHttpResponseMock.getEntity()).thenReturn(httpEntity); closeableHttpResponseMock.setEntity(httpEntity); PowerMockito.when(closeableHttpResponseMock.getEntity()).thenReturn(httpEntity); PowerMockito.when(closeableHttpResponseMock.getEntity().getContent()) .thenReturn(new ByteArrayInputStream("{\"message\":\"success\"}".getBytes())); CloseableHttpClient closeableHttpClientMocked = PowerMockito.mock(CloseableHttpClient.class); PowerMockito.mockStatic(HttpClients.class); PowerMockito.when(HttpClients.createDefault()).thenReturn(closeableHttpClientMocked); PowerMockito.when(closeableHttpClientMocked.execute(Mockito.any(HttpPost.class))) .thenReturn(closeableHttpResponseMock); String response = HttpUtil.sendPatchRequest(url, "{\"message\":\"success\"}", headers); assertTrue("SUCCESS".equals(response)); } catch (IOException e) { ProjectLogger.log(e.getMessage()); } }
Example 5
Source File: AuthenticationHandlerTest.java From carbon-device-mgt with Apache License 2.0 | 5 votes |
private CloseableHttpResponse getDCRResponse() throws IOException { CloseableHttpResponse mockDCRResponse = new MockHttpResponse(); String dcrResponseFile = TestUtils.getAbsolutePathOfConfig("dcr-response.json"); BasicHttpEntity responseEntity = new BasicHttpEntity(); responseEntity.setContent(new ByteArrayInputStream(getContent(dcrResponseFile). getBytes(StandardCharsets.UTF_8.name()))); responseEntity.setContentType(TestUtils.CONTENT_TYPE); mockDCRResponse.setEntity(responseEntity); mockDCRResponse.setStatusLine(new BasicStatusLine(new ProtocolVersion("http", 1, 0), 200, "OK")); return mockDCRResponse; }
Example 6
Source File: AuthenticationHandlerTest.java From carbon-device-mgt with Apache License 2.0 | 5 votes |
private CloseableHttpResponse getAccessTokenReponse() throws IOException { CloseableHttpResponse mockDCRResponse = new MockHttpResponse(); String dcrResponseFile = TestUtils.getAbsolutePathOfConfig("accesstoken-response.json"); BasicHttpEntity responseEntity = new BasicHttpEntity(); responseEntity.setContent(new ByteArrayInputStream(getContent(dcrResponseFile). getBytes(StandardCharsets.UTF_8.name()))); responseEntity.setContentType(TestUtils.CONTENT_TYPE); mockDCRResponse.setEntity(responseEntity); mockDCRResponse.setStatusLine(new BasicStatusLine(new ProtocolVersion("http", 1, 0), 200, "OK")); return mockDCRResponse; }
Example 7
Source File: AuthenticationHandlerTest.java From carbon-device-mgt with Apache License 2.0 | 5 votes |
private CloseableHttpResponse getInvalidResponse() throws UnsupportedEncodingException { CloseableHttpResponse mockDCRResponse = new MockHttpResponse(); BasicHttpEntity responseEntity = new BasicHttpEntity(); responseEntity.setContent(new ByteArrayInputStream("invalid response".getBytes(StandardCharsets.UTF_8.name()))); responseEntity.setContentType(TestUtils.CONTENT_TYPE); mockDCRResponse.setEntity(responseEntity); mockDCRResponse.setStatusLine(new BasicStatusLine(new ProtocolVersion("http", 1, 0), 400, "Bad Request")); return mockDCRResponse; }
Example 8
Source File: DataBridgeWebClientTest.java From herd with Apache License 2.0 | 5 votes |
@Test public void testGetBusinessObjectDataStorageFilesCreateResponse200BadContentReturnsNull() throws Exception { CloseableHttpResponse httpResponse = new MockCloseableHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "testReasonPhrase"), false); httpResponse.setEntity(new StringEntity("invalid xml")); executeWithoutLogging(DataBridgeWebClient.class, () -> { BusinessObjectDataStorageFilesCreateResponse businessObjectDataStorageFilesCreateResponse = dataBridgeWebClient.getBusinessObjectDataStorageFilesCreateResponse(httpResponse); assertNull("businessObjectDataStorageFilesCreateResponse", businessObjectDataStorageFilesCreateResponse); }); }
Example 9
Source File: DataBridgeWebClientTest.java From herd with Apache License 2.0 | 5 votes |
@Test public void testGetBusinessObjectDataStorageFilesCreateResponse200ValidResponse() throws Exception { CloseableHttpResponse httpResponse = new MockCloseableHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "testReasonPhrase"), false); httpResponse.setEntity(new StringEntity(xmlHelper.objectToXml(new BusinessObjectDataStorageFilesCreateResponse()))); BusinessObjectDataStorageFilesCreateResponse businessObjectDataStorageFilesCreateResponse = dataBridgeWebClient.getBusinessObjectDataStorageFilesCreateResponse(httpResponse); assertNotNull("businessObjectDataStorageFilesCreateResponse", businessObjectDataStorageFilesCreateResponse); }
Example 10
Source File: DataBridgeWebClientTest.java From herd with Apache License 2.0 | 5 votes |
@Test public void testGetBusinessObjectDataStorageFilesCreateResponse200ValidResponseHttpResponseThrowsExceptionOnClose() throws Exception { CloseableHttpResponse httpResponse = new MockCloseableHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "testReasonPhrase"), true); httpResponse.setEntity(new StringEntity(xmlHelper.objectToXml(new BusinessObjectDataStorageFilesCreateResponse()))); executeWithoutLogging(DataBridgeWebClient.class, () -> { BusinessObjectDataStorageFilesCreateResponse businessObjectDataStorageFilesCreateResponse = dataBridgeWebClient.getBusinessObjectDataStorageFilesCreateResponse(httpResponse); assertNotNull("businessObjectDataStorageFilesCreateResponse", businessObjectDataStorageFilesCreateResponse); }); }
Example 11
Source File: DataBridgeWebClientTest.java From herd with Apache License 2.0 | 5 votes |
@Test public void testGetBusinessObjectDataStorageFilesCreateResponse400BadContentThrows() throws Exception { int expectedStatusCode = 400; String expectedReasonPhrase = "testReasonPhrase"; String expectedErrorMessage = "invalid xml"; CloseableHttpResponse httpResponse = new MockCloseableHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, expectedStatusCode, expectedReasonPhrase), false); httpResponse.setEntity(new StringEntity(expectedErrorMessage)); try { executeWithoutLogging(DataBridgeWebClient.class, () -> { dataBridgeWebClient.getBusinessObjectDataStorageFilesCreateResponse(httpResponse); }); Assert.fail("expected HttpErrorResponseException, but no exception was thrown"); } catch (Exception e) { assertEquals("thrown exception type", HttpErrorResponseException.class, e.getClass()); HttpErrorResponseException httpErrorResponseException = (HttpErrorResponseException) e; assertEquals("httpErrorResponseException responseMessage", expectedErrorMessage, httpErrorResponseException.getResponseMessage()); assertEquals("httpErrorResponseException statusCode", expectedStatusCode, httpErrorResponseException.getStatusCode()); assertEquals("httpErrorResponseException statusDescription", expectedReasonPhrase, httpErrorResponseException.getStatusDescription()); assertEquals("httpErrorResponseException message", "Failed to add storage files", httpErrorResponseException.getMessage()); } }
Example 12
Source File: DataBridgeWebClientTest.java From herd with Apache License 2.0 | 5 votes |
@Test public void testGetBusinessObjectDataStorageFilesCreateResponse400Throws() throws Exception { int expectedStatusCode = 400; String expectedReasonPhrase = "testReasonPhrase"; String expectedErrorMessage = "testErrorMessage"; ErrorInformation errorInformation = new ErrorInformation(); errorInformation.setStatusCode(expectedStatusCode); errorInformation.setMessage(expectedErrorMessage); errorInformation.setStatusDescription(expectedReasonPhrase); String requestContent = xmlHelper.objectToXml(errorInformation); CloseableHttpResponse httpResponse = new MockCloseableHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, expectedStatusCode, expectedReasonPhrase), false); httpResponse.setEntity(new StringEntity(requestContent)); try { dataBridgeWebClient.getBusinessObjectDataStorageFilesCreateResponse(httpResponse); Assert.fail("expected HttpErrorResponseException, but no exception was thrown"); } catch (Exception e) { assertEquals("thrown exception type", HttpErrorResponseException.class, e.getClass()); HttpErrorResponseException httpErrorResponseException = (HttpErrorResponseException) e; assertEquals("httpErrorResponseException responseMessage", expectedErrorMessage, httpErrorResponseException.getResponseMessage()); assertEquals("httpErrorResponseException statusCode", expectedStatusCode, httpErrorResponseException.getStatusCode()); assertEquals("httpErrorResponseException statusDescription", expectedReasonPhrase, httpErrorResponseException.getStatusDescription()); assertEquals("httpErrorResponseException message", "Failed to add storage files", httpErrorResponseException.getMessage()); } }
Example 13
Source File: HttpErrorPage.java From esigate with Apache License 2.0 | 5 votes |
/** * Create an HTTP error page exception from an Http response. * * @param httpResponse * backend response. */ public HttpErrorPage(CloseableHttpResponse httpResponse) { super(httpResponse.getStatusLine().getStatusCode() + " " + httpResponse.getStatusLine().getReasonPhrase()); this.httpResponse = httpResponse; // Consume the entity and replace it with an in memory Entity httpResponse.setEntity(toMemoryEntity(httpResponse.getEntity())); }
Example 14
Source File: HttpErrorPage.java From esigate with Apache License 2.0 | 5 votes |
public static CloseableHttpResponse generateHttpResponse(int statusCode, String statusText) { CloseableHttpResponse result = BasicCloseableHttpResponse.adapt(new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, statusCode, statusText))); result.setEntity(toMemoryEntity(statusText)); return result; }
Example 15
Source File: ResponseSenderTest.java From esigate with Apache License 2.0 | 5 votes |
public void testSendResponseAlreadySent() throws Exception { MockHttpServletResponse httpServletResponse = new MockHttpServletResponse(); PrintWriter writer = httpServletResponse.getWriter(); writer.write("Test"); writer.close(); CloseableHttpResponse httpClientResponse = BasicCloseableHttpResponse.adapt(new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK"))); httpClientResponse.setEntity(new StringEntity("Abcdefg")); renderer.sendResponse(httpClientResponse, null, httpServletResponse); }
Example 16
Source File: Driver.java From esigate with Apache License 2.0 | 4 votes |
/** * Perform rendering on a single url content, and append result to "writer". Automatically follows redirects * * @param pageUrl * Address of the page containing the template * @param incomingRequest * originating request object * @param renderers * the renderers to use in order to transform the output * @return The resulting response * @throws IOException * If an IOException occurs while writing to the writer * @throws HttpErrorPage * If an Exception occurs while retrieving the template */ public CloseableHttpResponse render(String pageUrl, IncomingRequest incomingRequest, Renderer... renderers) throws IOException, HttpErrorPage { DriverRequest driverRequest = new DriverRequest(incomingRequest, this, pageUrl); // Replace ESI variables in URL // TODO: should be performed in the ESI extension String resultingPageUrl = VariablesResolver.replaceAllVariables(pageUrl, driverRequest); String targetUrl = ResourceUtils.getHttpUrlWithQueryString(resultingPageUrl, driverRequest, false); String currentValue; CloseableHttpResponse response; // Retrieve URL // Get from cache to prevent multiple request to the same url if // multiple fragments are used. String cacheKey = CACHE_RESPONSE_PREFIX + targetUrl; Pair<String, CloseableHttpResponse> cachedValue = incomingRequest.getAttribute(cacheKey); // content and response were not in cache if (cachedValue == null) { OutgoingRequest outgoingRequest = requestExecutor.createOutgoingRequest(driverRequest, targetUrl, false); headerManager.copyHeaders(driverRequest, outgoingRequest); response = requestExecutor.execute(outgoingRequest); int redirects = MAX_REDIRECTS; try { while (redirects > 0 && this.redirectStrategy.isRedirected(outgoingRequest, response, outgoingRequest.getContext())) { // Must consume the entity EntityUtils.consumeQuietly(response.getEntity()); redirects--; // Perform new request outgoingRequest = this.requestExecutor.createOutgoingRequest( driverRequest, this.redirectStrategy.getLocationURI(outgoingRequest, response, outgoingRequest.getContext()).toString(), false); this.headerManager.copyHeaders(driverRequest, outgoingRequest); response = requestExecutor.execute(outgoingRequest); } } catch (ProtocolException e) { throw new HttpErrorPage(HttpStatus.SC_BAD_GATEWAY, "Invalid response from server", e); } response = this.headerManager.copyHeaders(outgoingRequest, incomingRequest, response); currentValue = HttpResponseUtils.toString(response, this.eventManager); // Cache cachedValue = new ImmutablePair<>(currentValue, response); incomingRequest.setAttribute(cacheKey, cachedValue); } currentValue = cachedValue.getKey(); response = cachedValue.getValue(); logAction("render", pageUrl, renderers); // Apply renderers currentValue = performRendering(pageUrl, driverRequest, response, currentValue, renderers); response.setEntity(new StringEntity(currentValue, HttpResponseUtils.getContentType(response))); return response; }