下面列出了怎么用org.apache.http.message.BasicStatusLine的API类实例代码及写法,或者点击链接到github查看源代码。
private KylinConnection getConnectionWithMockHttp() throws SQLException, IOException {
final Properties info = new Properties();
info.setProperty("user", "ADMIN");
info.setProperty("password", "KYLIN");
// hack KylinClient
doAnswer(new Answer() {
@Override
public Object answer(InvocationOnMock invo) throws Throwable {
KylinConnectionInfo connInfo = invo.getArgument(0);
KylinClient client = new KylinClient(connInfo);
client.setHttpClient(httpClient);
return client;
}
}).when(factory).newRemoteClient(any(KylinConnectionInfo.class));
// Workaround IRemoteClient.connect()
HttpResponse response = mock(HttpResponse.class);
when(httpClient.execute(any(HttpUriRequest.class))).thenReturn(response);
when(response.getStatusLine()).thenReturn(new BasicStatusLine(HTTP_1_1, 200, "OK"));
return new KylinConnection(driver, factory, "jdbc:kylin:test_url/test_db", info);
}
private HttpEntity toApacheHttpEntity(RequestTemplate requestTemplate)
throws IOException, URISyntaxException {
final List<HttpUriRequest> request = new ArrayList<>(1);
BDDMockito.given(this.httpClient.execute(ArgumentMatchers.<HttpUriRequest>any()))
.will(new Answer<HttpResponse>() {
@Override
public HttpResponse answer(InvocationOnMock invocationOnMock)
throws Throwable {
request.add((HttpUriRequest) invocationOnMock.getArguments()[0]);
return new BasicHttpResponse(new BasicStatusLine(
new ProtocolVersion("http", 1, 1), 200, null));
}
});
new ApacheHttpClient(this.httpClient).execute(
requestTemplate.resolve(new HashMap<>()).request(),
new feign.Request.Options());
HttpUriRequest httpUriRequest = request.get(0);
return ((HttpEntityEnclosingRequestBase) httpUriRequest).getEntity();
}
@Before
public void setUp() throws Exception{
mockStatic(HttpClientBuilder.class);
mockStatic(HttpClient.class);
mockStatic(CloseableHttpClient.class);
mockStatic(HttpResponse.class);
mockStatic(CloseableHttpResponse.class);
mockStatic(HttpClients.class);
closeableHttpClient = PowerMockito.mock(CloseableHttpClient.class);
HttpClientBuilder httpClientBuilder = PowerMockito.mock(HttpClientBuilder.class);
PowerMockito.when(HttpClients.custom()).thenReturn(httpClientBuilder);
PowerMockito.when(HttpClients.custom().setSSLHostnameVerifier(anyObject())).thenReturn(httpClientBuilder);
PowerMockito.when(HttpClients.custom().setSSLHostnameVerifier(anyObject()).setSSLContext(anyObject())).thenReturn(httpClientBuilder);
PowerMockito.when(HttpClients.custom().setSSLHostnameVerifier(anyObject()).setSSLContext(anyObject()).build()).thenReturn(closeableHttpClient);
HttpGet httpGet = PowerMockito.mock(HttpGet.class);
PowerMockito.whenNew(HttpGet.class).withAnyArguments().thenReturn(httpGet);
httpResponse = PowerMockito.mock(CloseableHttpResponse.class);
HttpEntity entity = PowerMockito.mock(HttpEntity.class);
InputStream input = new ByteArrayInputStream("{\"data\":{\"puliclyaccessble\":false},\"input\":{\"endpoint\":\"http://123\"}}".getBytes() );
PowerMockito.when(httpResponse.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "FINE!"));
PowerMockito.when(entity.getContent()).thenReturn(input);
PowerMockito.when(httpResponse.getEntity()).thenReturn(entity);
}
@Before
public void setUp() throws Exception{
mockStatic(HttpClientBuilder.class);
mockStatic(HttpClient.class);
mockStatic(CloseableHttpClient.class);
mockStatic(HttpResponse.class);
mockStatic(CloseableHttpResponse.class);
closeableHttpClient = PowerMockito.mock(CloseableHttpClient.class);
HttpClientBuilder httpClientBuilder = PowerMockito.mock(HttpClientBuilder.class);
PowerMockito.when(HttpClientBuilder.create()).thenReturn(httpClientBuilder);
PowerMockito.when(HttpClientBuilder.create().setConnectionTimeToLive(anyLong(), anyObject())).thenReturn(httpClientBuilder);
PowerMockito.when(HttpClientBuilder.create().setConnectionTimeToLive(anyLong(), anyObject()).build()).thenReturn(closeableHttpClient);
HttpGet httpGet = PowerMockito.mock(HttpGet.class);
PowerMockito.whenNew(HttpGet.class).withAnyArguments().thenReturn(httpGet);
httpResponse = PowerMockito.mock(CloseableHttpResponse.class);
HttpEntity entity = PowerMockito.mock(HttpEntity.class);
InputStream input = new ByteArrayInputStream("lucene_version".getBytes() );
PowerMockito.when(httpResponse.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "FINE!"));
PowerMockito.when(entity.getContent()).thenReturn(input);
PowerMockito.when(httpResponse.getEntity()).thenReturn(entity);
}
/**
* Should return the given response if the request meets the given
* condition.
*
* @throws Exception Unexpected.
*/
@Test
public void returnResponseIfRequestMeetsCondition() throws Exception {
final HttpResponse response = new BasicHttpResponse(
new BasicStatusLine(
new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_OK, "OK"
)
);
MatcherAssert.assertThat(
new AssertRequest(
response,
new Condition(
"",
// @checkstyle LineLength (1 line)
r -> "http://some.test.com".equals(r.getRequestLine().getUri())
)
).execute(new HttpGet("http://some.test.com")),
Matchers.is(response)
);
}
@SuppressWarnings("resource")
private static OAuthRefreshTokenOnFailProcessor createProcessor(final String... grantJsons) throws IOException {
final CloseableHttpClient client = mock(CloseableHttpClient.class);
final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
when(response.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"));
final HttpEntity first = entity(grantJsons[0]);
final HttpEntity[] rest = Arrays.stream(grantJsons).skip(1).map(OAuthRefreshTokenOnFailProcessorTest::entity)
.toArray(HttpEntity[]::new);
when(response.getEntity()).thenReturn(first, rest);
when(client.execute(ArgumentMatchers.any(HttpUriRequest.class))).thenReturn(response);
final Configuration configuration = configuration("403");
final OAuthRefreshTokenOnFailProcessor processor = new OAuthRefreshTokenOnFailProcessor(OAuthState.createFrom(configuration), configuration) {
@Override
CloseableHttpClient createHttpClient() {
return client;
}
};
return processor;
}
@Test
public void testExecute_non2xx_exception() throws IOException {
HttpResponse resp = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, 404, "Not found"));
BasicHttpEntity entity = new BasicHttpEntity();
entity.setContent(new ByteArrayInputStream("{\"message\" : \"error payload\"}".getBytes()));
resp.setEntity(entity);
Mockito.doReturn(resp).when(mockClient).execute(any(HttpUriRequest.class), any(HttpContext.class));
Map<String, String> headers = new HashMap<>();
headers.put("Account-Id", "fubar");
headers.put("Content-Type", "application/json");
try {
client.execute(
new GenericApiGatewayRequestBuilder()
.withBody(new ByteArrayInputStream("test request".getBytes()))
.withHttpMethod(HttpMethodName.POST)
.withHeaders(headers)
.withResourcePath("/test/orders").build());
Assert.fail("Expected exception");
} catch (GenericApiGatewayException e) {
assertEquals("Wrong status code", 404, e.getStatusCode());
assertEquals("Wrong exception message", "{\"message\":\"error payload\"}", e.getErrorMessage());
}
}
private Segment segmentInResponseToCode(int code) {
NoOpResponseHandler responseHandler = new NoOpResponseHandler();
TracedResponseHandler<String> tracedResponseHandler = new TracedResponseHandler<>(responseHandler);
HttpResponse httpResponse = new BasicHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, code, ""));
Segment segment = AWSXRay.beginSegment("test");
AWSXRay.beginSubsegment("someHttpCall");
try {
tracedResponseHandler.handleResponse(httpResponse);
} catch (IOException e) {
throw new RuntimeException(e);
}
AWSXRay.endSubsegment();
AWSXRay.endSegment();
return segment;
}
@Before
public void initExecutor() throws IOException {
CloseableHttpClient httpMock = mock(CloseableHttpClient.class);
when(httpMock.execute(any())).thenAnswer(invocationOnMock -> {
HttpGet get = (HttpGet) invocationOnMock.getArguments()[0];
mockLog.append(get.getMethod()).append(" ").append(get.getURI()).append(" ");
switch (mockReturnCode) {
case FAIL_RETURN_CODE: throw new RuntimeException("FAIL");
case TIMEOUT_RETURN_CODE: throw new SocketTimeoutException("read timed out");
}
BasicStatusLine statusLine = new BasicStatusLine(HttpVersion.HTTP_1_1, mockReturnCode, null);
BasicHttpEntity entity = new BasicHttpEntity();
String returnMessage = "{\"foo\":\"bar\", \"no\":3, \"error-code\": " + mockReturnCode + "}";
InputStream stream = new ByteArrayInputStream(returnMessage.getBytes(StandardCharsets.UTF_8));
entity.setContent(stream);
CloseableHttpResponse response = mock(CloseableHttpResponse.class);
when(response.getEntity()).thenReturn(entity);
when(response.getStatusLine()).thenReturn(statusLine);
return response;
});
configServerApi = ConfigServerApiImpl.createForTestingWithClient(configServers, httpMock);
}
@Test
void testAsyncException() throws TelegramApiException {
final ArgumentCaptor<Exception> exceptionArgumentCaptor = ArgumentCaptor.forClass(Exception.class);
when(httpResponseMock.getStatusLine()).thenReturn(new BasicStatusLine(HTTP_1_1, 500, "emptyString"));
telegramFileDownloader.downloadFileAsync("someFilePath", downloadFileCallbackMock);
verify(downloadFileCallbackMock, timeout(100)
.times(1))
.onException(any(), exceptionArgumentCaptor.capture());
Exception e = exceptionArgumentCaptor.getValue();
assertThat(e, instanceOf(TelegramApiException.class));
assertEquals(e.getCause().getCause().getMessage(), "Unexpected Status code while downloading file. Expected 200 got 500");
}
@Test
public void testDoPost200() throws IOException {
CloseableHttpClient httpClient = Mockito.mock(CloseableHttpClient.class);
CloseableHttpResponse httpResponse = Mockito.mock(CloseableHttpResponse.class);
HttpEntity entity = Mockito.mock(HttpEntity.class);
String data = "Sample Server Response";
Mockito.when(httpResponse.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK" ));
Mockito.when(entity.getContent()).thenReturn(new ByteArrayInputStream(data.getBytes()));
Mockito.when(httpResponse.getEntity()).thenReturn(entity);
Mockito.when(httpClient.execute(Mockito.any(HttpPost.class))).thenReturn(httpResponse);
HttpDriver httpDriver = new HttpDriver.Builder("", null, "asdf".toCharArray(), null, null)
.build();
httpDriver.setHttpClient(httpClient);
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("data", "value"));
String url = "https://localhost:4443/sample";
String out = httpDriver.doPost(url, params);
Assert.assertEquals(out, data);
}
@Test
public void testDoPost404() throws IOException {
CloseableHttpClient httpClient = Mockito.mock(CloseableHttpClient.class);
CloseableHttpResponse httpResponse = Mockito.mock(CloseableHttpResponse.class);
HttpEntity entity = Mockito.mock(HttpEntity.class);
String data = "Not Found";
Mockito.when(httpResponse.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_FOUND, "Not Found" ));
Mockito.when(entity.getContent()).thenReturn(new ByteArrayInputStream(data.getBytes()));
Mockito.when(httpResponse.getEntity()).thenReturn(entity);
Mockito.when(httpClient.execute(Mockito.any(HttpPost.class))).thenReturn(httpResponse);
HttpDriver httpDriver = new HttpDriver.Builder("", null, "asdf".toCharArray(), null, null)
.build();
httpDriver.setHttpClient(httpClient);
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("data", "value"));
String url = "https://localhost:4443/sample";
String out = httpDriver.doPost(url, params);
Assert.assertEquals(out, "");
}
@Test
public void testGetBusinessObjectDataAssertNoAuthorizationHeaderWhenNoSsl() throws Exception
{
HttpClientOperations mockHttpClientOperations = mock(HttpClientOperations.class);
HttpClientOperations originalHttpClientOperations = (HttpClientOperations) ReflectionTestUtils.getField(downloaderWebClient, "httpClientOperations");
ReflectionTestUtils.setField(downloaderWebClient, "httpClientOperations", mockHttpClientOperations);
try
{
CloseableHttpResponse closeableHttpResponse = mock(CloseableHttpResponse.class);
when(mockHttpClientOperations.execute(any(), any())).thenReturn(closeableHttpResponse);
when(closeableHttpResponse.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"));
when(closeableHttpResponse.getEntity()).thenReturn(new StringEntity(xmlHelper.objectToXml(new BusinessObjectData())));
DownloaderInputManifestDto manifest = new DownloaderInputManifestDto();
downloaderWebClient.getRegServerAccessParamsDto().setUseSsl(false);
downloaderWebClient.getBusinessObjectData(manifest);
verify(mockHttpClientOperations).execute(any(), argThat(httpUriRequest -> httpUriRequest.getFirstHeader("Authorization") == null));
}
finally
{
ReflectionTestUtils.setField(downloaderWebClient, "httpClientOperations", originalHttpClientOperations);
}
}
@Test
public void happyPathWorks() throws ClientProtocolException, IOException {
String responseBodyStr = "{"
+ "\"access_token\": \"new access token\","
+ "\"token_type\": \"bearer\","
+ "\"refresh_token\": \"new refresh token\","
+ "\"expires_in\": 86399,"
+ "\"scope\": \"x:devices:* i:deviceprofiles r:devices:* w:devices:*\","
+ "\"installed_app_id\": \"installed app id\""
+ "}";
InputStream responseBodyStream =
new ByteArrayInputStream(responseBodyStr.getBytes(StandardCharsets.UTF_8));
when(httpClient.execute(any())).thenReturn(response);
when(response.getStatusLine())
.thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, null));
when(response.getEntity()).thenReturn(entity);
when(entity.getContent()).thenReturn(responseBodyStream);
Token expected = new Token()
.accessToken("new access token")
.accessTokenExpiration(now.plusSeconds(86399))
.refreshToken("new refresh token")
.refreshTokenExpiration(now.plus(Duration.ofDays(30)));
Token result = tester.refresh(token);
assertEquals(result, expected);
ArgumentCaptor<HttpUriRequest> requestCaptor =
ArgumentCaptor.forClass(HttpUriRequest.class);
verify(httpClient).execute(requestCaptor.capture());
HttpUriRequest capturedRequest = requestCaptor.getValue();
assertEquals("http://example.com/tokenRefreshUrl",
capturedRequest.getURI().toString());
}
ExecuteBuilder<T> withResponse(int code, String status, String mimeType, String body) {
BasicHttpResponse r = new BasicHttpResponse(
new BasicStatusLine(HttpVersion.HTTP_1_1, code, status)
);
StringEntity e = new StringEntity(body, ContentType.create(mimeType, Charset.forName("UTF-8")));
r.setEntity(e);
return withResponse(r);
}
@Test
public void connect() throws IOException {
HttpResponse response = mock(HttpResponse.class);
when(httpClient.execute(any(HttpUriRequest.class))).thenReturn(response);
when(response.getStatusLine()).thenReturn(new BasicStatusLine(HTTP_1_1, 200, "OK"));
client.connect();
}
/**
* Checks if is valid resource test 4.
*
* @throws ClientProtocolException the client protocol exception
* @throws IOException Signals that an I/O exception has occurred.
*/
@Test
public void isValidResourceTest4() throws ClientProtocolException, IOException {
PowerMockito.when(httpResponse.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_FORBIDDEN, "NOT FINE!"));
PowerMockito.when(httpClient.execute((HttpHead) any())).thenReturn(httpResponse);
assertFalse(CommonUtils.isValidResource("https://sample.com"));
}
/**
* Test receiving a response which has an invalid hash.
*/
@Test(expected = RealexException.class)
public void sendInvalidResponseHashTest() throws ClientProtocolException, IOException {
//get sample response XML
File file = new File(this.getClass().getResource(PAYMENT_RESPONSE_XML_PATH).getPath());
StreamSource source = new StreamSource(file);
PaymentResponse fromXmlResponse = new PaymentResponse().fromXml(source);
//add invalid hash
fromXmlResponse.setHash("invalid hash");
//mock HttpResponse
HttpResponse httpResponseMock = mock(HttpResponse.class);
when(httpResponseMock.getEntity()).thenReturn(new StringEntity(fromXmlResponse.toXml()));
when(httpResponseMock.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, null));
//create empty request
PaymentRequest request = new PaymentRequest();
//create configuration
HttpConfiguration httpConfiguration = new HttpConfiguration();
//mock HttpCLient instance
HttpClient httpClientMock = mock(HttpClient.class);
when(httpClientMock.execute(Matchers.any(HttpUriRequest.class))).thenReturn(httpResponseMock);
//execute send on client
RealexClient realexClient = new RealexClient(SampleXmlValidationUtils.SECRET, httpClientMock, httpConfiguration);
realexClient.send(request);
//shouldn't get this far
Assert.fail("RealexException should have been thrown before this point.");
}
@Before
public void setUp() throws Exception{
ec2ServiceClient = PowerMockito.mock(AmazonEC2.class);
minVersion = PowerMockito.mock(DefaultArtifactVersion.class);
url = PowerMockito.mock(URL.class);
config = PowerMockito.mock(XmlRpcClientConfigImpl.class);
annotation = PowerMockito.mock(Annotation.class);
mockStatic(HttpClientBuilder.class);
mockStatic(HttpClient.class);
mockStatic(CloseableHttpClient.class);
mockStatic(HttpResponse.class);
mockStatic(CloseableHttpResponse.class);
closeableHttpClient = PowerMockito.mock(CloseableHttpClient.class);
HttpClientBuilder httpClientBuilder = PowerMockito.mock(HttpClientBuilder.class);
PowerMockito.when(HttpClientBuilder.create()).thenReturn(httpClientBuilder);
PowerMockito.when(HttpClientBuilder.create().setConnectionTimeToLive(anyLong(), anyObject())).thenReturn(httpClientBuilder);
PowerMockito.when(HttpClientBuilder.create().setConnectionTimeToLive(anyLong(), anyObject()).build()).thenReturn(closeableHttpClient);
HttpGet httpGet = PowerMockito.mock(HttpGet.class);
PowerMockito.whenNew(HttpGet.class).withAnyArguments().thenReturn(httpGet);
httpResponse = PowerMockito.mock(CloseableHttpResponse.class);
HttpEntity entity = PowerMockito.mock(HttpEntity.class);
InputStream input = new ByteArrayInputStream("2001".getBytes() );
PowerMockito.when(httpResponse.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "FINE!"));
PowerMockito.when(entity.getContent()).thenReturn(input);
PowerMockito.when(httpResponse.getEntity()).thenReturn(entity);
}
/**
* Test sending a ThreeDSecure Verify Enrolled request and receiving a ThreeDSecure Verify Enrolled response.
*/
@Test
public void sendThreeDSecureVerifyEnrolledTest() throws ClientProtocolException, IOException {
//get sample response XML
File file = new File(this.getClass().getResource(THREE_D_SECURE_VERIFY_ENROLLED_RESPONSE_XML_PATH).getPath());
StreamSource source = new StreamSource(file);
ThreeDSecureResponse fromXmlResponse = new ThreeDSecureResponse().fromXml(source);
//mock HttpResponse
HttpResponse httpResponseMock = mock(HttpResponse.class);
when(httpResponseMock.getEntity()).thenReturn(new StringEntity(fromXmlResponse.toXml()));
when(httpResponseMock.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, null));
//create empty request
ThreeDSecureRequest request = new ThreeDSecureRequest();
//create configuration
HttpConfiguration httpConfiguration = new HttpConfiguration();
httpConfiguration.setOnlyAllowHttps(false);
//mock HttpClient instance
HttpClient httpClientMock = mock(HttpClient.class);
when(httpClientMock.execute(Matchers.any(HttpUriRequest.class))).thenReturn(httpResponseMock);
//execute send on client
RealexClient realexClient = new RealexClient(SampleXmlValidationUtils.SECRET, httpClientMock, httpConfiguration);
ThreeDSecureResponse response = realexClient.send(request);
//validate response
checkUnmarshalledThreeDSecureEnrolledResponse(response);
}
/**
* Tests creation of a web response.
* @throws Exception if the test fails
*/
@Test
public void makeWebResponse() throws Exception {
final URL url = new URL("http://htmlunit.sourceforge.net/");
final String content = "<html><head></head><body></body></html>";
final DownloadedContent downloadedContent = new DownloadedContent.InMemory(content.getBytes());
final int httpStatus = HttpStatus.SC_OK;
final long loadTime = 500L;
final ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 0);
final StatusLine statusLine = new BasicStatusLine(protocolVersion, HttpStatus.SC_OK, null);
final HttpResponse httpResponse = new BasicHttpResponse(statusLine);
final HttpEntity responseEntity = new StringEntity(content);
httpResponse.setEntity(responseEntity);
final HttpWebConnection connection = new HttpWebConnection(getWebClient());
final Method method = connection.getClass().getDeclaredMethod("makeWebResponse",
HttpResponse.class, WebRequest.class, DownloadedContent.class, long.class);
method.setAccessible(true);
final WebResponse response = (WebResponse) method.invoke(connection,
httpResponse, new WebRequest(url), downloadedContent, new Long(loadTime));
assertEquals(httpStatus, response.getStatusCode());
assertEquals(url, response.getWebRequest().getUrl());
assertEquals(loadTime, response.getLoadTime());
assertEquals(content, response.getContentAsString());
assertEquals(content.getBytes(), IOUtils.toByteArray(response.getContentAsStream()));
assertEquals(new ByteArrayInputStream(content.getBytes()), response.getContentAsStream());
}
@Override
public HttpResponse execute(HttpUriRequest request, HttpContext context) {
requestExecuted = request;
StatusLine statusLine = new BasicStatusLine(
new ProtocolVersion("HTTP", 1, 1), mStatusCode, "");
HttpResponse response = new BasicHttpResponse(statusLine);
response.setEntity(mResponseEntity);
return response;
}
protected void mockUnavailableHttpResponseWithEntity(int statusCode) throws IOException {
CloseableHttpResponse response = mock(CloseableHttpResponse.class);
Mockito.when(response.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("http", 1, 1), statusCode, "fake_reason"));
Mockito.when(response.getAllHeaders()).thenReturn(new Header[]{});
Mockito.when(response.getEntity()).thenReturn(httpEntity);
Mockito.when(httpEntity.getContent()).thenReturn(new ByteArrayInputStream("{foo}".getBytes()));
Mockito.when(response.getLocale()).thenReturn(Locale.US);
Mockito.when(mockClient.execute(any())).thenReturn(response);
}
/**
* @deprecated use {@link #executeRequest} instead to avoid a dependency on the deprecated
* Apache HTTP library. Nothing in Volley's own source calls this method. However, since
* {@link BasicNetwork#mHttpStack} is exposed to subclasses, we provide this implementation
* in case legacy client apps are dependent on that field. This method may be removed in a
* future release of Volley.
*/
@Deprecated
@Override
public final org.apache.http.HttpResponse performRequest(
Request<?> request, Map<String, String> additionalHeaders)
throws IOException, AuthFailureError {
HttpResponse response = executeRequest(request, additionalHeaders);
ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
StatusLine statusLine =
new BasicStatusLine(
protocolVersion, response.getStatusCode(), /* reasonPhrase= */ "");
BasicHttpResponse apacheResponse = new BasicHttpResponse(statusLine);
List<org.apache.http.Header> headers = new ArrayList<>();
for (Header header : response.getHeaders()) {
headers.add(new BasicHeader(header.getName(), header.getValue()));
}
apacheResponse.setHeaders(headers.toArray(new org.apache.http.Header[0]));
InputStream responseStream = response.getContent();
if (responseStream != null) {
BasicHttpEntity entity = new BasicHttpEntity();
entity.setContent(responseStream);
entity.setContentLength(response.getContentLength());
apacheResponse.setEntity(entity);
}
return apacheResponse;
}
@SuppressWarnings("resource")
private OAuthRefreshTokenProcessor createProcessor(final String grantJson) throws IOException {
final CloseableHttpClient client = mock(CloseableHttpClient.class);
final CloseableHttpResponse response = mock(CloseableHttpResponse.class);
when(response.getStatusLine()).thenReturn(new BasicStatusLine(HttpVersion.HTTP_1_1, 200, "OK"));
when(response.getEntity()).thenReturn(new ByteArrayEntity(grantJson.getBytes(StandardCharsets.US_ASCII), ContentType.APPLICATION_JSON));
when(client.execute(ArgumentMatchers.any(HttpUriRequest.class))).thenReturn(response);
final Map<String, Object> initial = new HashMap<>();
initial.put("clientId", "client-id");
initial.put("clientSecret", "client-secret");
initial.put("accessToken", "access-token");
initial.put("refreshToken", "refresh-token");
initial.put("accessTokenExpiresAt", Long.valueOf(-1));
initial.put("authorizationEndpoint", "token-endpoint");
final ComponentProxyCustomizer customizer = mock(ComponentProxyCustomizer.class);
final Configuration configuration = new Configuration(initial, customizer, null, null);
final OAuthRefreshTokenProcessor processor = new OAuthRefreshTokenProcessor(OAuthState.createFrom(configuration), configuration) {
@Override
CloseableHttpClient createHttpClient() {
return client;
}
@Override
long now() {
return currentTime;
}
};
return processor;
}
@Test
public void testLoginFailure() {
final GenericException f = new GenericException(
"message", new Header[]{}, new BasicStatusLine(new ProtocolVersion("http", 1, 1), 403, "Forbidden"));
assertTrue(new SwiftExceptionMappingService().map(f) instanceof AccessDeniedException);
assertEquals("Access denied", new SwiftExceptionMappingService().map(f).getMessage());
assertEquals("Message. 403 Forbidden. Please contact your web hosting service provider for assistance.", new SwiftExceptionMappingService().map(f).getDetail());
}
@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());
}
}
public static DummyResponseServerBehavior build(int statusCode, String statusMessage, String content) {
HttpResponse response = new BasicHttpResponse(
new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), statusCode, statusMessage));
setEntity(response, content);
response.addHeader("Content-Length", String.valueOf(content.getBytes().length));
response.addHeader("Connection", "close");
return new DummyResponseServerBehavior(response);
}
private static HttpResponseProxy createHttpResponseProxy(HttpEntity entity) {
ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1);
BasicStatusLine statusLine = new BasicStatusLine(protocolVersion, 200, "mock response");
BasicHttpResponse response = new BasicHttpResponse(statusLine);
response.setEntity(entity);
return new HttpResponseProxy(response);
}
public static DummyResponseServerBehavior build(int statusCode, String statusMessage, String content) {
HttpResponse response = new BasicHttpResponse(
new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), statusCode, statusMessage));
setEntity(response, content);
response.addHeader("Content-Length", String.valueOf(content.getBytes().length));
response.addHeader("Connection", "close");
return new DummyResponseServerBehavior(response);
}